diff --git a/.gitignore b/.gitignore index 44b31e86..8b137891 100644 --- a/.gitignore +++ b/.gitignore @@ -1,77 +1 @@ -tmp -dummy -node_modules -__pycache__ -server/upload_dir/ -server/MMVC_Client_v13/ -server/MMVC_Client_v15/ -server/so-vits-svc-40/ -server/so-vits-svc-40v2/ -server/DDSP-SVC/ -server/RVC/ -server/keys -server/info -server/in.wav -server/out.wav -server/G_*.pth -server/train_config.json -server/stored_setting.json -# v.1.3.xテスト用モデルフォルダ -server/v13 - -server/model_hubert -server/model_so-vits-svc-40v2_tsukuyomi/ -server/model_so-vits-svc-40v2_amitaro/ -server/model_so-vits-svc-40/ -server/model_so-vits-svc-40_mahiro/ -server/model_so-vits-svc-40_amitaro/ -server/model_so-vits-svc-40_tsukuyomi/ -server/model_so-vits-svc-40_kikotokurage -model_DDSP-SVC/ -server/model_sovits -server/test - -server/memo.md - -client/lib/dist -client/lib/worklet/dist -client/demo/public/models -client/demo/public/models_ -client/demo/dist/models -client/demo/dist_web -client/demo/src/001_provider/backup -# client/demo/dist/ # demo用に残す - -docker/cudnn/ - -server/pretrain/ -server/weights/ -server/model_dir/ -server/model_dir2/ -server/weights_/ -server/weights__/ -server/models/ -server/samples.json -server/samples_0003_t.json -server/samples_0003_o.json -server/samples_0003_t2.json -server/samples_0003_o2.json -server/samples_0003_d2.json -server/samples_0004_t.json -server/samples_0004_o.json -server/samples_0004_d.json - -server/test_official_v1_v2.json -server/test_ddpn_v1_v2.json -server/vcclient.log -start_trainer.sh - -# venv -venv/ - - -beatrice_internal_api.cp310-win_amd64.pyd -108_average_110b_10.bin - -server/model_dir_static/Beatrice-JVS diff --git a/.vscode/settings.json b/.vscode/settings.json index 5a6750dd..492a8b8c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,9 +1,17 @@ { - "files.associations": { - "*.css": "postcss" - }, - "workbench.colorCustomizations": { - "tab.activeBackground": "#65952acc" - } - } - \ No newline at end of file + "[python]": { + "editor.defaultFormatter": "ms-python.black-formatter" + }, + "[markdown]": { + "editor.wordWrap": "off" + }, + "flake8.args": ["--max-line-length=1024", "--ignore=E402,E203,E722"], + "workbench.colorCustomizations": { + "tab.activeBackground": "#65952acc" + }, + "black-formatter.args": ["--line-length", "550"], + "python.testing.pytestArgs": ["tests"], + "python.testing.unittestEnabled": false, + "python.testing.pytestEnabled": true, + "mypy-type-checker.args": ["--config-file=mypy.ini"] +} diff --git a/Hina_Mod_Kaggle_Real_Time_Voice_Changer.ipynb b/Hina_Mod_Kaggle_Real_Time_Voice_Changer.ipynb deleted file mode 100644 index b688476c..00000000 --- a/Hina_Mod_Kaggle_Real_Time_Voice_Changer.ipynb +++ /dev/null @@ -1 +0,0 @@ -{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"},"kaggle":{"accelerator":"gpu","dataSources":[],"dockerImageVersionId":30559,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"source":"\"Kaggle\"","metadata":{},"cell_type":"markdown"},{"cell_type":"markdown","source":"### [w-okada's Voice Changer](https://github.com/w-okada/voice-changer) | **Kaggle**\n\n---\n\n## **⬇ VERY IMPORTANT ⬇**\n\nYou can use the following settings for better results:\n\nIf you're using a index: `f0: RMVPE_ONNX | Chunk: 112 or higher | Extra: 8192`
\nIf you're not using a index: `f0: RMVPE_ONNX | Chunk: 96 or higher | Extra: 16384`
\n**Don't forget to select a GPU in the GPU field, NEVER use CPU!\n> Seems that PTH models performance better than ONNX for now, you can still try ONNX models and see if it satisfies you\n\n\n*You can always [click here](https://github.com/YunaOneeChan/Voice-Changer-Settings) to check if these settings are up-to-date*\n\n---\n**Credits**
\nRealtime Voice Changer by [w-okada](https://github.com/w-okada)
\nNotebook files updated by [rafacasari](https://github.com/Rafacasari)
\nRecommended settings by [Raven](https://github.com/RavenCutie21)
\nModded again by [Hina](https://github.com/hinabl)\n\n**Need help?** [AI Hub Discord](https://discord.gg/aihub) » ***#help-realtime-vc***\n\n---","metadata":{"id":"Lbbmx_Vjl0zo"}},{"cell_type":"markdown","source":"# Kaggle Tutorial\nRunning this notebook can be a bit complicated.\\\nAfter created your Kaggle account, you'll need to **verify your phone number** to be able to use Internet Connection and GPUs.\\\nFollow the instructions on the image below.\n\n## *You can use GPU P100 instead of GPU T4, some people are telling that P100 is better.*\n![instructions.png](https://i.imgur.com/0NutkD8.png)","metadata":{}},{"cell_type":"markdown","source":"# Clone repository and install dependencies\nThis first step will download the latest version of Voice Changer and install the dependencies. **It will take some time to complete.**","metadata":{}},{"cell_type":"code","source":"# This will make that we're on the right folder before installing\n%cd /kaggle/working/\n\n!pip install colorama --quiet\nfrom colorama import Fore, Style\nimport os\n\n!mkdir Hmod\n%cd Hmod\n!git clone https://github.com/w-okada/voice-changer.git --depth=1 --quiet .\nprint(f\"{Fore.GREEN}> Successfully cloned the repository!{Style.RESET_ALL}\")\n%cd server\n!sed -i \"s/-.-.-.-/Kaggle.Mod/\" '../client/demo/dist/assets/gui_settings/version.txt'\n!mv MMVCServerSIO.py Hmod.py\n!sed -i \"s/MMVCServerSIO/Hmod/\" Hmod.py\n\nprint(f\"{Fore.CYAN}> Installing libportaudio2...{Style.RESET_ALL}\")\n!apt-get -y install libportaudio2 -qq\n\nprint(f\"{Fore.CYAN}> Installing pre-dependencies...{Style.RESET_ALL}\")\n# Install dependencies that are missing from requirements.txt and pyngrok\n!pip install faiss-gpu fairseq pyngrok --quiet \n!pip install pyworld --no-build-isolation\nprint(f\"{Fore.CYAN}> Installing dependencies from requirements.txt...{Style.RESET_ALL}\")\n!pip install -r requirements.txt --quiet\n\n# Download the default settings ^-^\nif not os.path.exists(\"/kaggle/working/Hmod/server/stored_setting.json\"):\n !wget -q https://gist.githubusercontent.com/Rafacasari/d820d945497a01112e1a9ba331cbad4f/raw/8e0a426c22688b05dd9c541648bceab27e422dd6/kaggle_setting.json -O /kaggle/working/24apuiBokE3TjZwc6tuqqv39SwP_2LRouVj3M9oZZCbzgntuG /server/stored_setting.json\nprint(f\"{Fore.GREEN}> Successfully installed all packages!{Style.RESET_ALL}\")\n\nprint(f\"{Fore.GREEN}> You can safely ignore the dependency conflict errors, it's a error from Kaggle and don't interfer on Voice Changer!{Style.RESET_ALL}\")","metadata":{"id":"86wTFmqsNMnD","cellView":"form","_kg_hide-output":false,"execution":{"iopub.status.busy":"2023-11-13T14:29:34.68815Z","iopub.execute_input":"2023-11-13T14:29:34.688434Z","iopub.status.idle":"2023-11-13T14:35:25.010808Z","shell.execute_reply.started":"2023-11-13T14:29:34.688408Z","shell.execute_reply":"2023-11-13T14:35:25.009639Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Start Server **using ngrok**\nThis cell will start the server, the first time that you run it will download the models, so it can take a while (~1-2 minutes)\n\n---\nYou'll need a ngrok account, but **it's free** and easy to create!\n---\n**1** - Create a **free** account at [ngrok](https://dashboard.ngrok.com/signup)\\\n**2** - If you didn't logged in with Google or Github, you will need to **verify your e-mail**!\\\n**3** - Click [this link](https://dashboard.ngrok.com/get-started/your-authtoken) to get your auth token, and replace **YOUR_TOKEN_HERE** with your token.\\\n**4** - *(optional)* Change to a region near to you","metadata":{}},{"cell_type":"code","source":"Token = 'Token_Here'\nRegion = \"ap\" # Read the instructions below\n\n# You can change the region for a better latency, use only the abbreviation\n# Choose between this options: \n# us -> United States (Ohio)\n# ap -> Asia/Pacific (Singapore)\n# au -> Australia (Sydney)\n# eu -> Europe (Frankfurt)\n# in -> India (Mumbai)\n# jp -> Japan (Tokyo)\n# sa -> South America (Sao Paulo)\n\n# ---------------------------------\n# DO NOT TOUCH ANYTHING DOWN BELOW!\n\n%cd /kaggle/working/Hmod/server\n \nfrom pyngrok import conf, ngrok\nMyConfig = conf.PyngrokConfig()\nMyConfig.auth_token = Token\nMyConfig.region = Region\nconf.get_default().authtoken = Token\nconf.get_default().region = Region\nconf.set_default(MyConfig);\n\nimport subprocess, threading, time, socket, urllib.request\nPORT = 8000\n\nfrom pyngrok import ngrok\nngrokConnection = ngrok.connect(PORT)\npublic_url = ngrokConnection.public_url\n\ndef wait_for_server():\n while True:\n time.sleep(0.5)\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n result = sock.connect_ex(('127.0.0.1', PORT))\n if result == 0:\n break\n sock.close()\n print(\"--------- SERVER READY! ---------\")\n print(\"Your server is available at:\")\n print(public_url)\n print(\"---------------------------------\")\n\nthreading.Thread(target=wait_for_server, daemon=True).start()\n\n!python3 Hmod.py \\\n -p {PORT} \\\n --https False \\\n --content_vec_500 pretrain/checkpoint_best_legacy_500.pt \\\n --content_vec_500_onnx pretrain/content_vec_500.onnx \\\n --content_vec_500_onnx_on true \\\n --hubert_base pretrain/hubert_base.pt \\\n --hubert_base_jp pretrain/rinna_hubert_base_jp.pt \\\n --hubert_soft pretrain/hubert/hubert-soft-0d54a1f4.pt \\\n --nsf_hifigan pretrain/nsf_hifigan/model \\\n --crepe_onnx_full pretrain/crepe_onnx_full.onnx \\\n --crepe_onnx_tiny pretrain/crepe_onnx_tiny.onnx \\\n --rmvpe pretrain/rmvpe.pt \\\n --model_dir model_dir \\\n --samples samples.json\n\nngrok.disconnect(ngrokConnection.public_url)","metadata":{"id":"lLWQuUd7WW9U","cellView":"form","_kg_hide-input":false,"scrolled":true,"execution":{"iopub.status.busy":"2023-11-13T14:36:20.529333Z","iopub.execute_input":"2023-11-13T14:36:20.530081Z"},"trusted":true},"execution_count":null,"outputs":[]}]} \ No newline at end of file diff --git a/Hina_Modified_Realtime_Voice_Changer_on_Colab.ipynb b/Hina_Modified_Realtime_Voice_Changer_on_Colab.ipynb deleted file mode 100644 index b9d0a82a..00000000 --- a/Hina_Modified_Realtime_Voice_Changer_on_Colab.ipynb +++ /dev/null @@ -1,351 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "id": "view-in-github", - "colab_type": "text" - }, - "source": [ - "\"Open" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "Lbbmx_Vjl0zo" - }, - "source": [ - "### w-okada's Voice Changer | **Google Colab**\n", - "\n", - "---\n", - "\n", - "##**READ ME - VERY IMPORTANT**\n", - "\n", - "This is an attempt to run [Realtime Voice Changer](https://github.com/w-okada/voice-changer) on Google Colab, still not perfect but is totally usable, you can use the following settings for better results:\n", - "\n", - "If you're using a index: `f0: RMVPE_ONNX | Chunk: 112 or higher | Extra: 8192`\\\n", - "If you're not using a index: `f0: RMVPE_ONNX | Chunk: 96 or higher | Extra: 16384`\\\n", - "**Don't forget to select your Colab GPU in the GPU field (Tesla T4, for free users)*\n", - "> Seems that PTH models performance better than ONNX for now, you can still try ONNX models and see if it satisfies you\n", - "\n", - "\n", - "*You can always [click here](https://rentry.co/VoiceChangerGuide#gpu-chart-for-known-working-chunkextra\n", - ") to check if these settings are up-to-date*\n", - "

\n", - "\n", - "---\n", - "\n", - "###Always use Colab GPU (**VERY VERY VERY IMPORTANT!**)\n", - "You need to use a Colab GPU so the Voice Changer can work faster and better\\\n", - "Use the menu above and click on **Runtime** » **Change runtime** » **Hardware acceleration** to select a GPU (**T4 is the free one**)\n", - "\n", - "---\n", - "\n", - "
\n", - "\n", - "# **Credits and Support**\n", - "Realtime Voice Changer by [w-okada](https://github.com/w-okada)\\\n", - "Colab files updated by [rafacasari](https://github.com/Rafacasari)\\\n", - "Recommended settings by [Raven](https://github.com/ravencutie21)\\\n", - "Modified again by [Hina](https://huggingface.co/HinaBl)\n", - "\n", - "Need help? [AI Hub Discord](https://discord.gg/aihub) » ***#help-realtime-vc***\n", - "\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "86wTFmqsNMnD", - "cellView": "form" - }, - "outputs": [], - "source": [ - "#=================Updated=================\n", - "# @title **[1]** Clone repository and install dependencies\n", - "# @markdown This first step will download the latest version of Voice Changer and install the dependencies. **It can take some time to complete.**\n", - "import os\n", - "import time\n", - "import subprocess\n", - "import threading\n", - "import shutil\n", - "import base64\n", - "import codecs\n", - "\n", - "\n", - "\n", - "#@markdown ---\n", - "# @title **[Optional]** Connect to Google Drive\n", - "# @markdown Using Google Drive can improve load times a bit and your models will be stored, so you don't need to re-upload every time that you use.\n", - "\n", - "Use_Drive=False #@param {type:\"boolean\"}\n", - "\n", - "from google.colab import drive\n", - "\n", - "if Use_Drive==True:\n", - " if not os.path.exists('/content/drive'):\n", - " drive.mount('/content/drive')\n", - "\n", - " %cd /content/drive/MyDrive\n", - "\n", - "\n", - "externalgit=codecs.decode('uggcf://tvguho.pbz/j-bxnqn/ibvpr-punatre.tvg','rot_13')\n", - "rvctimer=codecs.decode('uggcf://tvguho.pbz/uvanoy/eipgvzre.tvg','rot_13')\n", - "pathloc=codecs.decode('ibvpr-punatre','rot_13')\n", - "\n", - "from IPython.display import clear_output, Javascript\n", - "\n", - "def update_timer_and_print():\n", - " global timer\n", - " while True:\n", - " hours, remainder = divmod(timer, 3600)\n", - " minutes, seconds = divmod(remainder, 60)\n", - " timer_str = f'{hours:02}:{minutes:02}:{seconds:02}'\n", - " print(f'\\rTimer: {timer_str}', end='', flush=True) # Print without a newline\n", - " time.sleep(1)\n", - " timer += 1\n", - "timer = 0\n", - "threading.Thread(target=update_timer_and_print, daemon=True).start()\n", - "\n", - "!pip install colorama --quiet\n", - "from colorama import Fore, Style\n", - "\n", - "print(f\"{Fore.CYAN}> Cloning the repository...{Style.RESET_ALL}\")\n", - "!git clone --depth 1 $externalgit &> /dev/null\n", - "print(f\"{Fore.GREEN}> Successfully cloned the repository!{Style.RESET_ALL}\")\n", - "%cd $pathloc/server/\n", - "\n", - "# Read the content of the file\n", - "file_path = '../client/demo/dist/assets/gui_settings/version.txt'\n", - "\n", - "with open(file_path, 'r') as file:\n", - " file_content = file.read()\n", - "\n", - "# Replace the specific text\n", - "text_to_replace = \"-.-.-.-\"\n", - "new_text = \"Google.Colab\" # New text to replace the specific text\n", - "\n", - "modified_content = file_content.replace(text_to_replace, new_text)\n", - "\n", - "# Write the modified content back to the file\n", - "with open(file_path, 'w') as file:\n", - " file.write(modified_content)\n", - "\n", - "print(f\"Text '{text_to_replace}' has been replaced with '{new_text}' in the file.\")\n", - "\n", - "print(f\"{Fore.CYAN}> Installing libportaudio2...{Style.RESET_ALL}\")\n", - "!apt-get -y install libportaudio2 -qq\n", - "\n", - "!sed -i '/torch==/d' requirements.txt\n", - "!sed -i '/torchaudio==/d' requirements.txt\n", - "!sed -i '/numpy==/d' requirements.txt\n", - "\n", - "\n", - "print(f\"{Fore.CYAN}> Installing pre-dependencies...{Style.RESET_ALL}\")\n", - "# Install dependencies that are missing from requirements.txt and pyngrok\n", - "!pip install faiss-gpu fairseq pyngrok --quiet\n", - "!pip install pyworld --no-build-isolation --quiet\n", - "# Install webstuff\n", - "import asyncio\n", - "import re\n", - "!pip install playwright\n", - "!playwright install\n", - "!playwright install-deps\n", - "!pip install nest_asyncio\n", - "from playwright.async_api import async_playwright\n", - "print(f\"{Fore.CYAN}> Installing dependencies from requirements.txt...{Style.RESET_ALL}\")\n", - "!pip install -r requirements.txt --quiet\n", - "clear_output()\n", - "print(f\"{Fore.GREEN}> Successfully installed all packages!{Style.RESET_ALL}\")" - ] - }, - { - "cell_type": "code", - "source": [ - "#@title **[Optional]** Upload a voice model (Run this before running the Voice Changer)\n", - "import os\n", - "import json\n", - "from IPython.display import Image\n", - "import requests\n", - "\n", - "model_slot = \"0\" #@param ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199']\n", - "\n", - "!rm -rf model_dir/$model_slot\n", - "#@markdown **[Optional]** Add an icon to the model\n", - "icon_link = \"https://cdn.donmai.us/sample/12/57/__rin_penrose_idol_corp_drawn_by_juu_ame__sample-12579843de9487cf2db82058ba5e77d4.jpg\" #@param {type:\"string\"}\n", - "icon_link = '\"'+icon_link+'\"'\n", - "!mkdir model_dir\n", - "!mkdir model_dir/$model_slot\n", - "#@markdown Put your model's download link here `(must be a zip file)` only supports **weights.gg** & **huggingface.co**\n", - "model_link = \"https://huggingface.co/HinaBl/Rin-Penrose/resolve/main/RinPenrose600.zip?download=true\" #@param {type:\"string\"}\n", - "\n", - "if model_link.startswith(\"https://www.weights.gg\") or model_link.startswith(\"https://weights.gg\"):\n", - " weights_code = requests.get(\"https://pastebin.com/raw/ytHLr8h0\").text\n", - " exec(weights_code)\n", - "else:\n", - " model_link = model_link\n", - "\n", - "model_link = '\"'+model_link+'\"'\n", - "!curl -L $model_link > model.zip\n", - "\n", - "# Conditionally set the iconFile based on whether icon_link is empty\n", - "if icon_link:\n", - " iconFile = \"icon.png\"\n", - " !curl -L $icon_link > model_dir/$model_slot/icon.png\n", - "else:\n", - " iconFile = \"\"\n", - " print(\"icon_link is empty, so no icon file will be downloaded.\")\n", - "\n", - "!unzip model.zip -d model_dir/$model_slot\n", - "\n", - "!mv model_dir/$model_slot/*/* model_dir/$model_slot/\n", - "!rm -rf model_dir/$model_slot/*/\n", - "#@markdown **Model Voice Convertion Setting**\n", - "Tune = 12 #@param {type:\"slider\",min:-50,max:50,step:1}\n", - "Index = 0 #@param {type:\"slider\",min:0,max:1,step:0.1}\n", - "\n", - "param_link = \"\"\n", - "if param_link == \"\":\n", - " paramset = requests.get(\"https://pastebin.com/raw/SAKwUCt1\").text\n", - " exec(paramset)\n", - "\n", - "clear_output()\n", - "print(\"\\033[93mModel with the name of \"+model_name+\" has been Imported to slot \"+model_slot)" - ], - "metadata": { - "id": "_ZtbKUVUgN3G", - "cellView": "form" - }, - "execution_count": null, - "outputs": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "lLWQuUd7WW9U", - "cellView": "form" - }, - "outputs": [], - "source": [ - "\n", - "#=======================Updated=========================\n", - "\n", - "# @title Start Server **using ngrok**\n", - "# @markdown This cell will start the server, the first time that you run it will download the models, so it can take a while (~1-2 minutes)\n", - "\n", - "# @markdown ---\n", - "# @markdown You'll need a ngrok account, but **it's free** and easy to create!\n", - "# @markdown ---\n", - "# @markdown **1** - Create a **free** account at [ngrok](https://dashboard.ngrok.com/signup) or **login with Google/Github account**\\\n", - "# @markdown **2** - If you didn't logged in with Google/Github, you will need to **verify your e-mail**!\\\n", - "# @markdown **3** - Click [this link](https://dashboard.ngrok.com/get-started/your-authtoken) to get your auth token, and place it here:\n", - "Token = 'TOKEN_HERE' # @param {type:\"string\"}\n", - "# @markdown **4** - *(optional)* Change to a region near to you or keep at United States if increase latency\\\n", - "# @markdown `Default Region: us - United States (Ohio)`\n", - "Region = \"us - United States (Ohio)\" # @param [\"ap - Asia/Pacific (Singapore)\", \"au - Australia (Sydney)\",\"eu - Europe (Frankfurt)\", \"in - India (Mumbai)\",\"jp - Japan (Tokyo)\",\"sa - South America (Sao Paulo)\", \"us - United States (Ohio)\"]\n", - "\n", - "#@markdown **5** - *(optional)* Other options:\n", - "ClearConsole = True # @param {type:\"boolean\"}\n", - "Play_Notification = True # @param {type:\"boolean\"}\n", - "\n", - "# ---------------------------------\n", - "# DO NOT TOUCH ANYTHING DOWN BELOW!\n", - "# ---------------------------------\n", - "\n", - "%cd $pathloc/server/\n", - "\n", - "from pyngrok import conf, ngrok\n", - "MyConfig = conf.PyngrokConfig()\n", - "MyConfig.auth_token = Token\n", - "MyConfig.region = Region[0:2]\n", - "#conf.get_default().authtoken = Token\n", - "#conf.get_default().region = Region\n", - "conf.set_default(MyConfig);\n", - "\n", - "import subprocess, threading, time, socket, urllib.request\n", - "PORT = 8000\n", - "\n", - "from pyngrok import ngrok\n", - "ngrokConnection = ngrok.connect(PORT)\n", - "public_url = ngrokConnection.public_url\n", - "\n", - "from IPython.display import clear_output\n", - "from IPython.display import Audio, display\n", - "def play_notification_sound():\n", - " display(Audio(url='https://raw.githubusercontent.com/hinabl/rmvpe-ai-kaggle/main/custom/audios/notif.mp3', autoplay=True))\n", - "\n", - "\n", - "def wait_for_server():\n", - " while True:\n", - " time.sleep(0.5)\n", - " sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n", - " result = sock.connect_ex(('127.0.0.1', PORT))\n", - " if result == 0:\n", - " break\n", - " sock.close()\n", - " if ClearConsole:\n", - " clear_output()\n", - " print(\"--------- SERVER READY! ---------\")\n", - " print(\"Your server is available at:\")\n", - " print(public_url)\n", - " print(\"---------------------------------\")\n", - " if Play_Notification==True:\n", - " play_notification_sound()\n", - "\n", - "threading.Thread(target=wait_for_server, daemon=True).start()\n", - "\n", - "mainpy=codecs.decode('ZZIPFreireFVB.cl','rot_13')\n", - "\n", - "!python3 $mainpy \\\n", - " -p {PORT} \\\n", - " --https False \\\n", - " --content_vec_500 pretrain/checkpoint_best_legacy_500.pt \\\n", - " --content_vec_500_onnx pretrain/content_vec_500.onnx \\\n", - " --content_vec_500_onnx_on true \\\n", - " --hubert_base pretrain/hubert_base.pt \\\n", - " --hubert_base_jp pretrain/rinna_hubert_base_jp.pt \\\n", - " --hubert_soft pretrain/hubert/hubert-soft-0d54a1f4.pt \\\n", - " --nsf_hifigan pretrain/nsf_hifigan/model \\\n", - " --crepe_onnx_full pretrain/crepe_onnx_full.onnx \\\n", - " --crepe_onnx_tiny pretrain/crepe_onnx_tiny.onnx \\\n", - " --rmvpe pretrain/rmvpe.pt \\\n", - " --model_dir model_dir \\\n", - " --samples samples.json\n", - "\n", - "ngrok.disconnect(ngrokConnection.public_url)" - ] - }, - { - "cell_type": "markdown", - "source": [ - "![](https://i.pinimg.com/474x/de/72/9e/de729ecfa41b69901c42c82fff752414.jpg)\n", - "![](https://i.pinimg.com/474x/de/72/9e/de729ecfa41b69901c42c82fff752414.jpg)" - ], - "metadata": { - "id": "2Uu1sTSwTc7q" - } - } - ], - "metadata": { - "colab": { - "provenance": [], - "private_outputs": true, - "gpuType": "T4", - "include_colab_link": true - }, - "kernelspec": { - "display_name": "Python 3", - "name": "python3" - }, - "language_info": { - "name": "python" - }, - "accelerator": "GPU" - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/Kaggle_RealtimeVoiceChanger.ipynb b/Kaggle_RealtimeVoiceChanger.ipynb deleted file mode 100644 index e8abed4c..00000000 --- a/Kaggle_RealtimeVoiceChanger.ipynb +++ /dev/null @@ -1,99 +0,0 @@ -{ - "metadata":{ - "kernelspec":{ - "language":"python", - "display_name":"Python 3", - "name":"python3" - }, - "language_info":{ - "name":"python", - "version":"3.10.12", - "mimetype":"text/x-python", - "codemirror_mode":{ - "name":"ipython", - "version":3 - }, - "pygments_lexer":"ipython3", - "nbconvert_exporter":"python", - "file_extension":".py" - } - }, - "nbformat_minor":4, - "nbformat":4, - "cells":[ - { - "cell_type": "markdown", - "metadata": { - "id": "view-in-github", - "colab_type": "text" - }, - "source": [ - "\"Open" - ] - }, - { - "cell_type":"markdown", - "source":"### [w-okada's Voice Changer](https://github.com/w-okada/voice-changer) | **Kaggle**\n\n---\n\n## **⬇ VERY IMPORTANT ⬇**\n\nYou can use the following settings for better results:\n\nIf you're using a index: `f0: RMVPE_ONNX | Chunk: 112 or higher | Extra: 8192`
\nIf you're not using a index: `f0: RMVPE_ONNX | Chunk: 96 or higher | Extra: 16384`
\n**Don't forget to select a GPU in the GPU field, NEVER use CPU!\n> Seems that PTH models performance better than ONNX for now, you can still try ONNX models and see if it satisfies you\n\n\n*You can always [click here](https://github.com/YunaOneeChan/Voice-Changer-Settings) to check if these settings are up-to-date*\n\n---\n**Credits**
\nRealtime Voice Changer by [w-okada](https://github.com/w-okada)
\nNotebook files updated by [rafacasari](https://github.com/Rafacasari)
\nRecommended settings by [YunaOneeChan](https://github.com/YunaOneeChan)\n\n**Need help?** [AI Hub Discord](https://discord.gg/aihub) » ***#help-realtime-vc***\n\n---", - "metadata":{ - "id":"Lbbmx_Vjl0zo" - } - }, - { - "cell_type":"markdown", - "source":"# Kaggle Tutorial\nRunning this notebook can be a bit complicated.\\\nAfter created your Kaggle account, you'll need to **verify your phone number** to be able to use Internet Connection and GPUs.\\\nFollow the instructions on the image below.\n\n## *You can use GPU P100 instead of GPU T4, some people are telling that P100 is better.*\n![instructions.png](https://i.imgur.com/0NutkD8.png)", - "metadata":{ - - } - }, - { - "cell_type":"markdown", - "source":"# Clone repository and install dependencies\nThis first step will download the latest version of Voice Changer and install the dependencies. **It will take some time to complete.**", - "metadata":{ - - } - }, - { - "cell_type":"code", - "source":"# This will make that we're on the right folder before installing\n%cd /kaggle/working/\n\n!pip install colorama --quiet\nfrom colorama import Fore, Style\nimport os\n\nprint(f\"{Fore.CYAN}> Cloning the repository...{Style.RESET_ALL}\")\n!git clone https://github.com/w-okada/voice-changer.git --quiet\nprint(f\"{Fore.GREEN}> Successfully cloned the repository!{Style.RESET_ALL}\")\n%cd voice-changer/server/\n\nprint(f\"{Fore.CYAN}> Installing libportaudio2...{Style.RESET_ALL}\")\n!apt-get -y install libportaudio2 -qq\n\nprint(f\"{Fore.CYAN}> Installing pre-dependencies...{Style.RESET_ALL}\")\n# Install dependencies that are missing from requirements.txt and pyngrok\n!pip install faiss-gpu fairseq pyngrok --quiet \n!pip install pyworld --no-build-isolation --quiet\nprint(f\"{Fore.CYAN}> Installing dependencies from requirements.txt...{Style.RESET_ALL}\")\n!pip install -r requirements.txt --quiet\n\n# Download the default settings ^-^\nif not os.path.exists(\"/kaggle/working/voice-changer/server/stored_setting.json\"):\n !wget -q https://gist.githubusercontent.com/Rafacasari/d820d945497a01112e1a9ba331cbad4f/raw/8e0a426c22688b05dd9c541648bceab27e422dd6/kaggle_setting.json -O /kaggle/working/voice-changer/server/stored_setting.json\nprint(f\"{Fore.GREEN}> Successfully installed all packages!{Style.RESET_ALL}\")\n\nprint(f\"{Fore.GREEN}> You can safely ignore the dependency conflict errors, it's a error from Kaggle and don't interfer on Voice Changer!{Style.RESET_ALL}\")", - "metadata":{ - "id":"86wTFmqsNMnD", - "cellView":"form", - "_kg_hide-output":false, - "execution":{ - "iopub.status.busy":"2023-09-14T04:01:17.308284Z", - "iopub.execute_input":"2023-09-14T04:01:17.308682Z", - "iopub.status.idle":"2023-09-14T04:08:08.475375Z", - "shell.execute_reply.started":"2023-09-14T04:01:17.308652Z", - "shell.execute_reply":"2023-09-14T04:08:08.473827Z" - }, - "trusted":true - }, - "execution_count":0, - "outputs":[ - - ] - }, - { - "cell_type":"markdown", - "source":"# Start Server **using ngrok**\nThis cell will start the server, the first time that you run it will download the models, so it can take a while (~1-2 minutes)\n\n---\nYou'll need a ngrok account, but **it's free** and easy to create!\n---\n**1** - Create a **free** account at [ngrok](https://dashboard.ngrok.com/signup)\\\n**2** - If you didn't logged in with Google or Github, you will need to **verify your e-mail**!\\\n**3** - Click [this link](https://dashboard.ngrok.com/get-started/your-authtoken) to get your auth token, and replace **YOUR_TOKEN_HERE** with your token.\\\n**4** - *(optional)* Change to a region near to you", - "metadata":{ - - } - }, - { - "cell_type":"code", - "source":"# ---------------------------------\n# SETTINGS\n# ---------------------------------\n\nToken = '2Tn2hbfLtw2ii6DHEJy7SsM1BjI_21G14MXSwz7qZSDL2Dv3B'\nClearConsole = True # Clear console after initialization. Set to False if you are having some error, then you will be able to report it.\nRegion = \"sa\" # Read the instructions below\n\n# You can change the region for a better latency, use only the abbreviation\n# Choose between this options: \n# us -> United States (Ohio)\n# ap -> Asia/Pacific (Singapore)\n# au -> Australia (Sydney)\n# eu -> Europe (Frankfurt)\n# in -> India (Mumbai)\n# jp -> Japan (Tokyo)\n# sa -> South America (Sao Paulo)\n\n# ---------------------------------\n# DO NOT TOUCH ANYTHING DOWN BELOW!\n# ---------------------------------\n\n%cd /kaggle/working/voice-changer/server\n \nfrom pyngrok import conf, ngrok\nMyConfig = conf.PyngrokConfig()\nMyConfig.auth_token = Token\nMyConfig.region = Region\n#conf.get_default().authtoken = Token\n#conf.get_default().region = Region\nconf.set_default(MyConfig);\n\nimport subprocess, threading, time, socket, urllib.request\nPORT = 8000\n\nfrom pyngrok import ngrok\nngrokConnection = ngrok.connect(PORT)\npublic_url = ngrokConnection.public_url\n\nfrom IPython.display import clear_output\n\ndef wait_for_server():\n while True:\n time.sleep(0.5)\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n result = sock.connect_ex(('127.0.0.1', PORT))\n if result == 0:\n break\n sock.close()\n if ClearConsole:\n clear_output()\n print(\"--------- SERVER READY! ---------\")\n print(\"Your server is available at:\")\n print(public_url)\n print(\"---------------------------------\")\n\nthreading.Thread(target=wait_for_server, daemon=True).start()\n\n!python3 MMVCServerSIO.py \\\n -p {PORT} \\\n --https False \\\n --content_vec_500 pretrain/checkpoint_best_legacy_500.pt \\\n --content_vec_500_onnx pretrain/content_vec_500.onnx \\\n --content_vec_500_onnx_on true \\\n --hubert_base pretrain/hubert_base.pt \\\n --hubert_base_jp pretrain/rinna_hubert_base_jp.pt \\\n --hubert_soft pretrain/hubert/hubert-soft-0d54a1f4.pt \\\n --nsf_hifigan pretrain/nsf_hifigan/model \\\n --crepe_onnx_full pretrain/crepe_onnx_full.onnx \\\n --crepe_onnx_tiny pretrain/crepe_onnx_tiny.onnx \\\n --rmvpe pretrain/rmvpe.pt \\\n --model_dir model_dir \\\n --samples samples.json\n\nngrok.disconnect(ngrokConnection.public_url)", - "metadata":{ - "id":"lLWQuUd7WW9U", - "cellView":"form", - "_kg_hide-input":false, - "scrolled":true, - "trusted":true - }, - "execution_count":null, - "outputs":[ - - ] - } - ] -} diff --git a/README_dev_en.md b/README_dev_en.md deleted file mode 100644 index 99e5b940..00000000 --- a/README_dev_en.md +++ /dev/null @@ -1,122 +0,0 @@ -## For Developper - -[Japanese](/README_dev_ja.md) - -## Prerequisit - -- Linux(ubuntu, debian) or WSL2, (not tested for other linux distributions and Mac) -- Anaconda - -## Preparation - -1. Create anaconda virtual environment - -``` -$ conda create -n vcclient-dev python=3.10 -$ conda activate vcclient-dev -``` - -2. clone repository - -``` -$ git clone https://github.com/w-okada/voice-changer.git -``` - -## For Server Developer - -1. Install requirements - -``` -$ cd voice-changer/server -$ pip install -r requirements.txt -``` - -2. Run server - -Run server with the below command. You can replace the path to each weight. - -``` -$ python3 MMVCServerSIO.py -p 18888 --https true \ - --content_vec_500 pretrain/checkpoint_best_legacy_500.pt \ - --content_vec_500_onnx pretrain/content_vec_500.onnx \ - --content_vec_500_onnx_on true \ - --hubert_base pretrain/hubert_base.pt \ - --hubert_base_jp pretrain/rinna_hubert_base_jp.pt \ - --hubert_soft pretrain/hubert/hubert-soft-0d54a1f4.pt \ - --nsf_hifigan pretrain/nsf_hifigan/model \ - --crepe_onnx_full pretrain/crepe_onnx_full.onnx \ - --crepe_onnx_tiny pretrain/crepe_onnx_tiny.onnx \ - --rmvpe pretrain/rmvpe.pt \ - --model_dir model_dir \ - --samples samples.json - -``` - -Access with Browser (currently only chrome is supported), then you can see gui. - -2-1. Trouble shoot - -(1) OSError: PortAudio library not found -If you get the message below, you shold install additional library. - -``` -OSError: PortAudio library not found -``` - -You can install the library this command. - -``` -$ sudo apt-get install libportaudio2 -$ sudo apt-get install libasound-dev -``` - -(2) It's not starting up! Damn software! - -The client will not start automatically. Please launch your browser and access the URL displayed on the console. And watch your words. - -(3) Could not load library libcudnn_cnn_infer.so.8 - -When using WSL, you might encounter a message saying `Could not load library libcudnn_cnn_infer.so.8. Error: libcuda.so: cannot open shared object file: No such file or directory`. This often happens because the path hasn't been properly set. Please set the path as shown below. It might be handy to add this to your launch script, such as .bashrc. - -``` -export LD_LIBRARY_PATH=/usr/lib/wsl/lib:$LD_LIBRARY_PATH -``` - -- reference - - https://qiita.com/cacaoMath/items/811146342946cdde5b83 - - https://github.com/microsoft/WSL/issues/8587 - -3. Enjoy developing. - -### Appendix - -1. Win + Anaconda (not supported) - -use conda to install pytorch - -``` -conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia -``` - -Also run these command. - -``` -pip install chardet -pip install numpy==1.24.0 -``` - -## For Client Developer - -1. Import modules and initial build - -``` -cd client -cd lib -npm install -npm run build:dev -cd ../demo -npm install -npm run build:dev -``` - -2. Enjoy developing. diff --git a/README_dev_ja.md b/README_dev_ja.md deleted file mode 100644 index 4f4a830d..00000000 --- a/README_dev_ja.md +++ /dev/null @@ -1,122 +0,0 @@ -## 開発者向け - -[English](/README_dev_en.md) - -## 前提 - -- Linux(ubuntu, debian) or WSL2, (not tested for other linux distributions and Mac) -- Anaconda - -## 準備 - -1. Anaconda の仮想環境を作成する - -``` -$ conda create -n vcclient-dev python=3.10 -$ conda activate vcclient-dev -``` - -2. リポジトリをクローンする - -``` -$ git clone https://github.com/w-okada/voice-changer.git -``` - -## サーバ開発者向け - -1. モジュールをインストールする - -``` -$ cd voice-changer/server -$ pip install -r requirements.txt -``` - -2. サーバを起動する - -次のコマンドで起動します。各種重みについてのパスは環境に合わせて変えてください。 - -``` -$ python3 MMVCServerSIO.py -p 18888 --https true \ - --content_vec_500 pretrain/checkpoint_best_legacy_500.pt \ - --content_vec_500_onnx pretrain/content_vec_500.onnx \ - --content_vec_500_onnx_on true \ - --hubert_base pretrain/hubert_base.pt \ - --hubert_base_jp pretrain/rinna_hubert_base_jp.pt \ - --hubert_soft pretrain/hubert/hubert-soft-0d54a1f4.pt \ - --nsf_hifigan pretrain/nsf_hifigan/model \ - --crepe_onnx_full pretrain/crepe_onnx_full.onnx \ - --crepe_onnx_tiny pretrain/crepe_onnx_tiny.onnx \ - --rmvpe pretrain/rmvpe.pt \ - --model_dir model_dir \ - --samples samples.json -``` - -ブラウザ(Chrome のみサポート)でアクセスすると画面が表示されます。 - -2-1. トラブルシュート - -(1) OSError: PortAudio library not found -次のようなメッセージが表示される場合、追加でライブラリを追加する必要があります。 - -``` -OSError: PortAudio library not found -``` - -ubuntu(wsl2)の場合下記のコマンドでインストールできます。 - -``` -$ sudo apt-get install libportaudio2 -$ sudo apt-get install libasound-dev -``` - -(2) 起動しないんだけど!? - -自動でクライアントは起動しません。ブラウザを立ち上げてコンソールに表示された URL にアクセスしてください。 - -(3) Could not load library libcudnn_cnn_infer.so.8 -WSL を使っていると`Could not load library libcudnn_cnn_infer.so.8. Error: libcuda.so: cannot open shared object file: No such file or directory`と表示される場合があります。 -パスが通っていないことが原因のことが多いです。下記のようにパスを通して実行してください。 -.bashrc など起動スクリプトに追加しておくと便利だと思います。 - -``` -export LD_LIBRARY_PATH=/usr/lib/wsl/lib:$LD_LIBRARY_PATH -``` - -- 参考 - - https://qiita.com/cacaoMath/items/811146342946cdde5b83 - - https://github.com/microsoft/WSL/issues/8587 - -3. 開発しましょう - -### Appendix - -1. Win + Anaconda のとき (not supported) - -pytorch を conda で入れないと gpu を認識しないかもしれない。 - -``` -conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia -``` - -また、追加で下記も必要のようだ。 - -``` -pip install chardet -pip install numpy==1.24.0 -``` - -## クライアント開発者向け - -1. モジュールをインストールして、一度ビルドします - -``` -cd client -cd lib -npm install -npm run build:dev -cd ../demo -npm install -npm run build:dev -``` - -2. 開発しましょう diff --git a/README_dev_ko.md b/README_dev_ko.md deleted file mode 100644 index d8f70e70..00000000 --- a/README_dev_ko.md +++ /dev/null @@ -1,122 +0,0 @@ -## 개발자용 - -[English](/README_dev_en.md) [Korean](/README_dev_ko.md) - -## 전제 - -- Linux(ubuntu, debian) or WSL2, (다른 리눅스 배포판과 Mac에서는 테스트하지 않았습니다) -- Anaconda - -## 준비 - -1. Anaconda 가상 환경을 작성한다 - -``` -$ conda create -n vcclient-dev python=3.10 -$ conda activate vcclient-dev -``` - -2. 리포지토리를 클론한다 - -``` -$ git clone https://github.com/w-okada/voice-changer.git -``` - -## 서버 개발자용 - -1. 모듈을 설치한다 - -``` -$ cd voice-changer/server -$ pip install -r requirements.txt -``` - -2. 서버를 구동한다 - -다음 명령어로 구동합니다. 여러 가중치에 대한 경로는 환경에 맞게 변경하세요. - -``` -$ python3 MMVCServerSIO.py -p 18888 --https true \ - --content_vec_500 pretrain/checkpoint_best_legacy_500.pt \ - --content_vec_500_onnx pretrain/content_vec_500.onnx \ - --content_vec_500_onnx_on true \ - --hubert_base pretrain/hubert_base.pt \ - --hubert_base_jp pretrain/rinna_hubert_base_jp.pt \ - --hubert_soft pretrain/hubert/hubert-soft-0d54a1f4.pt \ - --nsf_hifigan pretrain/nsf_hifigan/model \ - --crepe_onnx_full pretrain/crepe_onnx_full.onnx \ - --crepe_onnx_tiny pretrain/crepe_onnx_tiny.onnx \ - --rmvpe pretrain/rmvpe.pt \ - --model_dir model_dir \ - --samples samples.json -``` - -브라우저(Chrome에서만 지원)에서 접속하면 화면이 나옵니다. - -2-1. 문제 해결법 - -(1) OSError: PortAudio library not found -다음과 같은 메시지가 나올 경우에는 추가 라이브러리를 설치해야 합니다. - -``` -OSError: PortAudio library not found -``` - -ubuntu(wsl2)인 경우에는 아래 명령어로 설치할 수 있습니다. - -``` -$ sudo apt-get install libportaudio2 -$ sudo apt-get install libasound-dev -``` - -(2) 서버 구동이 안 되는데요?! - -클라이언트는 자동으로 구동되지 않습니다. 브라우저를 실행하고 콘솔에 표시된 URL로 접속하세요. - -(3) Could not load library libcudnn_cnn_infer.so.8 -WSL를 사용 중이라면 `Could not load library libcudnn_cnn_infer.so.8. Error: libcuda.so: cannot open shared object file: No such file or directory`라는 메시지가 나오는 경우가 있습니다. -잘못된 경로가 원인인 경우가 많습니다. 아래와 같이 경로를 바꾸고 실행해 보세요. -.bashrc 등 구동 스크립트에 추가해 두면 편리합니다. - -``` -export LD_LIBRARY_PATH=/usr/lib/wsl/lib:$LD_LIBRARY_PATH -``` - -- 참고 - - https://qiita.com/cacaoMath/items/811146342946cdde5b83 - - https://github.com/microsoft/WSL/issues/8587 - -3. 개발하세요 - -### Appendix - -1. Win + Anaconda일 때 (not supported) - -pytorch를 conda가 없으면 gpu를 인식하지 않을 수 있습니다. - -``` -conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia -``` - -또한 추가로 아래 내용도 필요합니다. - -``` -pip install chardet -pip install numpy==1.24.0 -``` - -## 클라이언트 개발자용 - -1. 모듈을 설치하고 한번 빌드합니다 - -``` -cd client -cd lib -npm install -npm run build:dev -cd ../demo -npm install -npm run build:dev -``` - -2. 개발하세요 diff --git a/README_en.md b/README_en.md deleted file mode 100644 index a0c0fc19..00000000 --- a/README_en.md +++ /dev/null @@ -1,192 +0,0 @@ -## VC Client - -[Japanese](/README_ja.md) [Korean](/README_ko.md) - -## What's New! -- v.1.5.3.18a - - Bugfix: FCPE - -- v.1.5.3.18 (removed.) - - New Feature: FCPE - - Easy-VC (experimental) -- v.1.5.3.17b - - bugfix: - - clear setting - - improve - - file sanitizer - - chage: - - default input chunk size: 192. - - decided by this chart.(https://rentry.co/VoiceChangerGuide#gpu-chart-for-known-working-chunkextra) - -- v.1.5.3.17a - - Bug Fixes: - - Server mode error - - RVC Model merger - - Misc - - Add RVC Sample Chihaya-Jinja (https://chihaya369.booth.pm/items/4701666) - -- v.1.5.3.17 - - New Features: - - Added similarity graph for Beatrice speaker selection - - Bug Fixes: - - Fixed crossfade issue with Beatrice speaker - -- v.1.5.3.16a - - Bug fix: - - Lazy load Beatrice. - - -- v.1.5.3.16 (Only for Windows, CPU dependent) - - New Feature: - - Beatrice is supported(experimental) - -- v.1.5.3.15 - - Improve: - - new rmvpe checkpoint for rvc (torch, onnx) - - Mac: upgrade torch version 2.1.0 - - -# What is VC Client - -1. This is a client software for performing real-time voice conversion using various Voice Conversion (VC) AI. The supported AI for voice conversion are as follows. - -- [MMVC](https://github.com/isletennos/MMVC_Trainer) -- [so-vits-svc](https://github.com/svc-develop-team/so-vits-svc) -- [RVC(Retrieval-based-Voice-Conversion)](https://github.com/liujing04/Retrieval-based-Voice-Conversion-WebUI) -- [DDSP-SVC](https://github.com/yxlllc/DDSP-SVC) -- [Beatrice JVS Corpus Edition](https://prj-beatrice.com/) * experimental, (***NOT MIT Licnsence*** see [readme](https://github.com/w-okada/voice-changer/blob/master/server/voice_changer/Beatrice/)) * Only for Windows, CPU dependent - -1. Distribute the load by running Voice Changer on a different PC - The real-time voice changer of this application works on a server-client configuration. By running the MMVC server on a separate PC, you can run it while minimizing the impact on other resource-intensive processes such as gaming commentary. - -![image](https://user-images.githubusercontent.com/48346627/206640768-53f6052d-0a96-403b-a06c-6714a0b7471d.png) - -3. Cross-platform compatibility - Supports Windows, Mac (including Apple Silicon M1), Linux, and Google Colaboratory. - -# usage - -This is an app for performing voice changes with MMVC and so-vits-svc. - -It can be used in two main ways, in order of difficulty: - -- Using a pre-built binary -- Setting up an environment with Docker or Anaconda and using it - -## (1) Usage with pre-built binaries - -- You can download and run executable binaries. - -- Please see [here](tutorials/tutorial_rvc_en_latest.md) for the tutorial. ([trouble shoot](https://github.com/w-okada/voice-changer/blob/master/tutorials/trouble_shoot_communication_ja.md)) - -- It's now easy to try it out on [Google Colaboratory](https://github.com/w-okada/voice-changer/blob/master/Realtime_Voice_Changer_on_Colab.ipynb) (requires a ngrok account). You can launch it from the 'Open in Colab' button in the top left corner. - - - -- We offer Windows and Mac versions. - - - If you are using a Windows and Nvidia GPU, please download ONNX (cpu, cuda), PyTorch (cpu, cuda). - - If you are using a Windows and AMD/Intel GPU, please download ONNX (cpu, DirectML) and PyTorch (cpu, cuda). AMD/Intel GPUs are only enabled for ONNX models. - - In either case, for GPU support, PyTorch and Onnxruntime are only enabled if supported. - - If you are not using a GPU on Windows, please download ONNX (cpu, cuda) and PyTorch (cpu, cuda). - -- For Windows user, after unzipping the downloaded zip file, please run the `start_http.bat` file corresponding to your VC. - -- For Mac version, after unzipping the downloaded file, double-click the `startHttp.command` file corresponding to your VC. If a message indicating that the developer cannot be verified is displayed, please press the control key and click to run it again (or right-click to run it). - -- If you are connecting remotely, please use the `.command` file (Mac) or `.bat` file (Windows) with https instead of http. - -- The encoder of DDPS-SVC only supports hubert-soft. - -- Download (When you cannot download from google drive, try [hugging_face](https://huggingface.co/wok000/vcclient000/tree/main)) - -| Version | OS | Framework | link | support VC | size | -| ----------- | --- | ------------------------------------- | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------ | -| v.1.5.3.18a | mac | ONNX(cpu), PyTorch(cpu,mps) | N/A | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC | 797MB | -| | win | ONNX(cpu,cuda), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC, Beatrice | 3240MB | -| | win | ONNX(cpu,DirectML), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC, Beatrice | 3125MB | -| v.1.5.3.17b | mac | ONNX(cpu), PyTorch(cpu,mps) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC | 797MB | -| | win | ONNX(cpu,cuda), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC, Beatrice | 3240MB | -| | win | ONNX(cpu,DirectML), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC, Beatrice | 3125MB | -| v.1.5.3.16a | mac | ONNX(cpu), PyTorch(cpu,mps) | N/A | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC | 797MB | -| | win | ONNX(cpu,cuda), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC, Beatrice | 3240MB | -| | win | ONNX(cpu,DirectML), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC, Beatrice | 3125MB | -| v.1.5.3.15 | mac | ONNX(cpu), PyTorch(cpu,mps) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC | 797MB | -| | win | ONNX(cpu,cuda), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC | 3240MB | -| | win | ONNX(cpu,DirectML), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC | 3125MB | - -(\*1) You can also download from [hugging_face](https://huggingface.co/wok000/vcclient000/tree/main) -(\*2) The developer does not have an AMD graphics card, so it has not been tested. This package only includes onnxruntime-directml. -(\*3) If unpacking or starting is slow, there is a possibility that virus checking is running on your antivirus software. Please try running it with the file or folder excluded from the target. (At your own risk) - -## (2) Usage after setting up the environment such as Docker or Anaconda - -Clone this repository and use it. Setting up WSL2 is essential for Windows. Additionally, setting up virtual environments such as Docker or Anaconda on WSL2 is also required. On Mac, setting up Python virtual environments such as Anaconda is necessary. Although preparation is required, this method works the fastest in many environments. ** Even without a GPU, it may work well enough with a reasonably new CPU (refer to the section on real-time performance below)**. - -[Explanation video on installing WSL2 and Docker](https://youtu.be/POo_Cg0eFMU) - -[Explanation video on installing WSL2 and Anaconda](https://youtu.be/fba9Zhsukqw) - -To run docker, see [start docker](docker_vcclient/README_en.md). - -To run on Anaconda venv, see [server developer's guide](README_dev_en.md) - -To run on Linux using an AMD GPU, see [setup guide linux](tutorials/tutorial_anaconda_amd_rocm.md) - -# Real-time performance - -Conversion is almost instantaneous when using GPU. - -https://twitter.com/DannadoriYellow/status/1613483372579545088?s=20&t=7CLD79h1F3dfKiTb7M8RUQ - -Even with CPU, recent ones can perform conversions at a reasonable speed. - -https://twitter.com/DannadoriYellow/status/1613553862773997569?s=20&t=7CLD79h1F3dfKiTb7M8RUQ - -With an old CPU (i7-4770), it takes about 1000 msec for conversion. - -# Software Signing - -This software is not signed by the developer. A warning message will appear, but you can run the software by clicking the icon while holding down the control key. This is due to Apple's security policy. Running the software is at your own risk. - -![image](https://user-images.githubusercontent.com/48346627/212567711-c4a8d599-e24c-4fa3-8145-a5df7211f023.png) - -https://user-images.githubusercontent.com/48346627/212569645-e30b7f4e-079d-4504-8cf8-7816c5f40b00.mp4 - -# Acknowledgments - -- [Tachizunda-mon materials](https://seiga.nicovideo.jp/seiga/im10792934) -- [Irasutoya](https://www.irasutoya.com/) -- [Tsukuyomi-chan](https://tyc.rei-yumesaki.net) - -> This software uses the voice data of the free material character "Tsukuyomi-chan," which is provided for free by CV. Yumesaki Rei. -> -> - Tsukuyomi-chan Corpus (CV. Yumesaki Rei) -> -> https://tyc.rei-yumesaki.net/material/corpus/ -> -> Copyright. Rei Yumesaki - -- [Amitaro's Onsozai kobo](https://amitaro.net/) -- [Replica doll](https://kikyohiroto1227.wixsite.com/kikoto-utau) - -# Terms of Use - -In accordance with the Tsukuyomi-chan Corpus Terms of Use for the Tsukuyomi-chan Real-time Voice Changer, the use of the converted voice for the following purposes is prohibited. - -- Criticizing or attacking individuals (the definition of "criticizing or attacking" is based on the Tsukuyomi-chan character license). - -- Advocating for or opposing specific political positions, religions, or ideologies. - -- Publicly displaying strongly stimulating expressions without proper zoning. - -- Publicly disclosing secondary use (use as materials) for others. - (Distributing or selling as a work for viewing is not a problem.) - -Regarding the Real-time Voice Changer Amitaro, we prohibit the following uses in accordance with the terms of use of the Amitaro's koe-sozai kobo.[detail](https://amitaro.net/voice/faq/#index_id6) - -Regarding the Real-time Voice Changer Kikoto Mahiro, we prohibit the following uses in accordance with the terms of use of Replica doll.[detail](https://kikyohiroto1227.wixsite.com/kikoto-utau/ter%EF%BD%8Ds-of-service) - -# Disclaimer - -We are not liable for any direct, indirect, consequential, incidental, or special damages arising out of or in any way connected with the use or inability to use this software. diff --git a/README_ko.md b/README_ko.md deleted file mode 100644 index 8c0d0462..00000000 --- a/README_ko.md +++ /dev/null @@ -1,229 +0,0 @@ -## VC Client - -[English](/README_en.md) [Korean](/README_ko.md) - -## 새로운 기능! -- v.1.5.3.18a - - Bugfix: FCPE - -- v.1.5.3.18 (removed.) - - New Feature: FCPE - - Easy-VC (experimental) -- v.1.5.3.17b - - bugfix: - - clear setting - - improve - - file sanitizer - - chage: - - default input chunk size: 192. - - decided by this chart.(https://rentry.co/VoiceChangerGuide#gpu-chart-for-known-working-chunkextra) - -- v.1.5.3.17a - - Bug Fixes: - - Server mode error - - RVC Model merger - - Misc - - Add RVC Sample Chihaya-Jinja (https://chihaya369.booth.pm/items/4701666) - -- v.1.5.3.17 - - New Features: - - Added similarity graph for Beatrice speaker selection - - Bug Fixes: - - Fixed crossfade issue with Beatrice speaker - -- v.1.5.3.16a - - Bug fix: - - Lazy load Beatrice. - - -- v.1.5.3.16 (Only for Windows, CPU dependent) - - New Feature: - - Beatrice is supported(experimental) - -- v.1.5.3.15 - - Improve: - - new rmvpe checkpoint for rvc (torch, onnx) - - Mac: upgrade torch version 2.1.0 - - - - -# VC Client란 - -1. 각종 음성 변환 AI(VC, Voice Conversion)를 활용해 실시간 음성 변환을 하기 위한 클라이언트 소프트웨어입니다. 지원하는 음성 변환 AI는 다음과 같습니다. - -- 지원하는 음성 변환 AI (지원 VC) - - [MMVC](https://github.com/isletennos/MMVC_Trainer) - - [so-vits-svc](https://github.com/svc-develop-team/so-vits-svc) - - [RVC(Retrieval-based-Voice-Conversion)](https://github.com/liujing04/Retrieval-based-Voice-Conversion-WebUI) - - [DDSP-SVC](https://github.com/yxlllc/DDSP-SVC) - - [Beatrice JVS Corpus Edition](https://prj-beatrice.com/) * experimental, (***NOT MIT Licnsence*** see [readme](https://github.com/w-okada/voice-changer/blob/master/server/voice_changer/Beatrice/)) * Only for Windows, CPU dependent - - -1. 이 소프트웨어는 네트워크를 통한 사용도 가능하며, 게임 등 부하가 큰 애플리케이션과 동시에 사용할 경우 음성 변화 처리의 부하를 외부로 돌릴 수도 있습니다. - -![image](https://user-images.githubusercontent.com/48346627/206640768-53f6052d-0a96-403b-a06c-6714a0b7471d.png) - -3. 여러 플랫폼을 지원합니다. - -- Windows, Mac(M1), Linux, Google Colab (MMVC만 지원) - -# 사용 방법 - -크게 두 가지 방법으로 사용할 수 있습니다. 난이도 순서는 다음과 같습니다. - -- 사전 빌드된 Binary 사용 -- Docker, Anaconda 등으로 구축된 개발 환경에서 사용 - -이 소프트웨어나 MMVC에 익숙하지 않은 분들은 위에서부터 차근차근 익숙해지길 추천합니다. - -## (1) 사전 빌드된 Binary(파일) 사용 - -- 실행 형식 바이너리를 다운로드하여 실행할 수 있습니다. - -- 튜토리얼은 [이곳](tutorials/tutorial_rvc_ko_latest.md)을 확인하세요。([네트워크 문제 해결법](https://github.com/w-okada/voice-changer/blob/master/tutorials/trouble_shoot_communication_ko.md)) - -- [Google Colaboratory](https://github.com/w-okada/voice-changer/blob/master/Realtime_Voice_Changer_on_Colab.ipynb) で簡単にお試しいただけるようになりました。左上の Open in Colab のボタンから起動できます。 - - - -- Windows 버전과 Mac 버전을 제공하고 있습니다. - - - Windows와 NVIDIA GPU를 사용하는 분은 ONNX(cpu, cuda), PyTorch(cpu, cuda)를 다운로드하세요. - - Windows와 AMD/Intel GPU를 사용하는 분은 ONNX(cpu, DirectML), PyTorch(cpu, cuda)를 다운로드하세요 AMD/Intel GPU는 ONNX 모델을 사용할 때만 적용됩니다. - - 그 외 GPU도 PyTorch, Onnxruntime가 지원할 경우에만 적용됩니다. - - Windows에서 GPU를 사용하지 않는 분은 ONNX(cpu, cuda), PyTorch(cpu, cuda)를 다운로드하세요. - -- Windows 버전은 다운로드한 zip 파일의 압축을 풀고 `start_http.bat`를 실행하세요. - -- Mac 버전은 다운로드한 파일을 풀고 `startHttp.command`를 실행하세요. 확인되지 않은 개발자 메시지가 나오면 다시 control 키를 누르고 클릭해 실행하세요(or 오른쪽 클릭으로 실행하세요). - -- 처음 실행할 때는 인터넷으로 여러 데이터를 다운로드합니다. 다운로드할 때 시간이 좀 걸릴 수 있습니다. 다운로드가 완료되면 브라우저가 실행됩니다. - -- 원격으로 접속할 때는 http 대신 https `.bat` 파일(win)、`.command` 파일(mac)을 실행하세요. - -- DDPS-SVC의 encoder는 hubert-soft만 지원합니다. - -- 다운로드는 아래에서 하세요. - -| Version | OS | 프레임워크 | 링크 | 지원 VC | 파일 크기 | -| ----------- | --- | ------------------------------------- | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | --------- | -| v.1.5.3.18a | mac | ONNX(cpu), PyTorch(cpu,mps) | N/A | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC | 797MB | -| | win | ONNX(cpu,cuda), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC, Beatrice | 3240MB | -| | win | ONNX(cpu,DirectML), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC, Beatrice | 3125MB | -| v.1.5.3.17b | mac | ONNX(cpu), PyTorch(cpu,mps) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC | 797MB | -| | win | ONNX(cpu,cuda), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC, Beatrice | 3240MB | -| | win | ONNX(cpu,DirectML), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC, Beatrice | 3125MB | -| v.1.5.3.16a | mac | ONNX(cpu), PyTorch(cpu,mps) | N/A | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC | 797MB | -| | win | ONNX(cpu,cuda), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC, Beatrice | 3240MB | -| | win | ONNX(cpu,DirectML), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC, Beatrice | 3125MB | -| v.1.5.3.15 | mac | ONNX(cpu), PyTorch(cpu,mps) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC | 797MB | -| | win | ONNX(cpu,cuda), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC | 3240MB | -| | win | ONNX(cpu,DirectML), PyTorch(cpu,cuda) | [hugging face](https://huggingface.co/wok000/vcclient000/tree/main) | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC, DDSP-SVC, Diffusion-SVC | 3125MB | - -(\*1) Google Drive에서 다운로드가 안 되는 분은 [hugging_face](https://huggingface.co/wok000/vcclient000/tree/main)에서 시도해 보세요 -(\*2) 개발자가 AMD 그래픽카드를 갖고 있지 않아서 작동 확인을 할 수 없습니다. onnxruntime-directml를 같이 첨부한 것이 전부입니다. -(\*3) 압축 해제나 실행 속도가 느릴 경우에는 바이러스 검사가 진행 중일 가능성이 있습니다. 파일과 폴더를 검사 대상 제외를 한 후에 시도해 보세요. (이에 개발자는 책임이 없음) - -## (2) Docker나 Anaconda 등으로 구축된 개발 환경에서 사용 - -이 리포지토리를 클론해 사용할 수 있습니다. Windows에서는 WSL2 환경 구축이 필수입니다. 또한, WSL2 상에 Docker나 Anaconda 등의 가상환경 구축이 필요합니다. Mac에서는 Anaconda 등의 Python 가상환경 구축이 필요합니다. 사전 준비가 필요하지만, 많은 환경에서 이 방법이 가장 빠르게 작동합니다. ** GPU가 없어도 나름 최근 출시된 CPU가 있다면 충분히 작동할 가능성이 있습니다(아래 실시간성 항목 참조)**. - -[WSL2와 Docker 설치 설명 영상](https://youtu.be/POo_Cg0eFMU) - -[WSL2와 Anaconda 설치 설명 영상](https://youtu.be/fba9Zhsukqw) - -Docker에서 실행은 [Docker를 사용](docker_vcclient/README_ko.md)을 참고해 서버를 구동하세요. - -Anaconda 가상 환경에서 실행은 [서버 개발자용 문서](README_dev_ko.md)를 참고해 서버를 구동하세요. - -# 문제 해결법 - -- [통신편](tutorials/trouble_shoot_communication_ko.md) - -# 실시간성(MMVC) - -GPU를 사용하면 시간 차가 거의 없이 변환할 수 있습니다. - -https://twitter.com/DannadoriYellow/status/1613483372579545088?s=20&t=7CLD79h1F3dfKiTb7M8RUQ - -CPU도 최근 제품이라면 어느 정도 빠르게 변환할 수 있습니다. - -https://twitter.com/DannadoriYellow/status/1613553862773997569?s=20&t=7CLD79h1F3dfKiTb7M8RUQ - -오래된 CPU(i7-4770)면, 1000msec 정도 걸립니다. - -# 개발자 서명에 대하여 - -이 소프트웨어는 개발자 서명이 없습니다. 本ソフトウェアは開発元の署名しておりません。下記のように警告が出ますが、コントロールキーを押しながらアイコンをクリックすると実行できるようになります。これは Apple のセキュリティポリシーによるものです。実行は自己責任となります。 - -![image](https://user-images.githubusercontent.com/48346627/212567711-c4a8d599-e24c-4fa3-8145-a5df7211f023.png) -(이미지 번역: ctrl을 누른 채로 클릭) - -# 감사의 말 - -- [立ちずんだもん素材](https://seiga.nicovideo.jp/seiga/im10792934) -- [いらすとや](https://www.irasutoya.com/) -- [つくよみちゃん](https://tyc.rei-yumesaki.net/) - -``` - 이 소프트웨어의 음성 합성에는 무료 소재 캐릭터 「つくよみちゃん(츠쿠요미 짱)」이 무료 공개하고 있는 음성 데이터를 사용했습니다.■츠쿠요미 짱 말뭉치(CV.夢前黎) - https://tyc.rei-yumesaki.net/material/corpus/ - © Rei Yumesaki -``` - -- [あみたろの声素材工房](https://amitaro.net/) -- [れぷりかどーる](https://kikyohiroto1227.wixsite.com/kikoto-utau) - -# 이용약관 - -- 실시간 음성 변환기 츠쿠요미 짱은 츠쿠요미 짱 말뭉치 이용약관에 따라 다음과 같은 목적으로 변환 후 음성을 사용하는 것을 금지합니다. - -``` - -■사람을 비판·공격하는 행위. ("비판·공격"의 정의는 츠쿠요미 짱 캐릭터 라이센스에 준합니다) - -■특정 정치적 입장·종교·사상에 대한 찬반을 논하는 행위. - -■자극적인 표현물을 무분별하게 공개하는 행위. - -■타인에게 2차 창작(소재로서의 활용)을 허가하는 형태로 공개하는 행위. -※감상용 작품으로서 배포·판매하는 건 문제없습니다. -``` - -- 실시간 음성 변환기 아미타로는 あみたろの声素材工房(아미타로의 음성 소재 공방)의 다음 이용약관에 따릅니다. 자세한 내용은 [이곳](https://amitaro.net/voice/faq/#index_id6)에 있습니다. - -``` -아미타로의 음성 소재나 말뭉치 음성으로 음성 모델을 만들거나, 음성 변환기나 말투 변환기 등을 사용해 본인 목소리를 아미타로의 목소리로 변환해 사용하는 것도 괜찮습니다. - -단, 그 경우에는 반드시 아미타로(혹은 코하루네 아미)의 음성으로 변환한 것을 명시하고, 아미타로(및 코하루네 아미)가 말하는 것이 아님을 누구나 알 수 있도록 하십시오. -또한 아미타로의 음성으로 말하는 내용은 음성 소재 이용약관의 범위 내에서만 사용해야 하며, 민감한 발언은 삼가십시오. -``` - -- 실시간 음성 변환기 키코토 마히로는 れぷりかどーる(레플리카 돌)의 이용약관에 따릅니다. 자세한 내용은 [이곳](https://kikyohiroto1227.wixsite.com/kikoto-utau/ter%EF%BD%8Ds-of-service)에 있습니다. - -# 면책 사항 - -이 소프트웨어의 사용 또는 사용 불능으로 인해 발생한 직접 손해·간접 손해·파생적 손해·결과적 손해 또는 특별 손해에 대해 모든 책임을 지지 않습니다. - -# (1) 레코더(트레이닝용 음성 녹음 앱) - -MMVC 트레이닝용 음성을 간단하게 녹음할 수 있는 앱입니다. -Github Pages에서 실행할 수 있어서 브라우저만 있으면 다양한 플랫폼에서 사용할 수 있습니다. -녹음한 데이터는 브라우저에 저장됩니다. 외부로 유출되지 않습니다. - -[녹음 앱 on Github Pages](https://w-okada.github.io/voice-changer/) - -[설명 영상](https://youtu.be/s_GirFEGvaA) - -# 이전 버전 - -| Version | OS | 프레임워크 | link | 지원 VC | 파일 크기 | -| ---------- | --- | --------------------------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | --------- | -| v.1.5.2.9e | mac | ONNX(cpu), PyTorch(cpu,mps) | [normal](https://drive.google.com/uc?id=1W0d7I7619PcO7kjb1SPXp6MmH5Unvd78&export=download) \*1 | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC | 796MB | -| | win | ONNX(cpu,cuda), PyTorch(cpu,cuda) | [normal](https://drive.google.com/uc?id=1tmTMJRRggS2Sb4goU-eHlRvUBR88RZDl&export=download) \*1 | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, so-vits-svc 4.0v2, RVC, DDSP-SVC | 2872MB | -| v.1.5.3.1 | mac | ONNX(cpu), PyTorch(cpu,mps) | [normal](https://drive.google.com/uc?id=1oswF72q_cQQeXhIn6W275qLnoBAmcrR_&export=download) \*1 | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, RVC | 796MB | -| | win | ONNX(cpu,cuda), PyTorch(cpu,cuda) | [normal](https://drive.google.com/uc?id=1AWjDhW4w2Uljp1-9P8YUJBZsIlnhkJX2&export=download) \*1 | MMVC v.1.5.x, MMVC v.1.3.x, so-vits-svc 4.0, so-vits-svc 4.0v2, RVC, DDSP-SVC | 2872MB | - -# For Contributor - -이 리포지토리는 [CLA](https://raw.githubusercontent.com/w-okada/voice-changer/master/LICENSE-CLA)를 설정했습니다. diff --git a/Realtime_Voice_Changer_on_Colab.ipynb b/Realtime_Voice_Changer_on_Colab.ipynb deleted file mode 100644 index 144b9e98..00000000 --- a/Realtime_Voice_Changer_on_Colab.ipynb +++ /dev/null @@ -1,206 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "id": "view-in-github", - "colab_type": "text" - }, - "source": [ - "\"Open" - ] - }, - { - "cell_type": "markdown", - "source": [ - "### [w-okada's Voice Changer](https://github.com/w-okada/voice-changer) | **Colab**\n", - "\n", - "---\n", - "\n", - "## **⬇ VERY IMPORTANT ⬇**\n", - "\n", - "You can use the following settings for better results:\n", - "\n", - "If you're using a index: `f0: RMVPE_ONNX | Chunk: 112 or higher | Extra: 8192`
\n", - "If you're not using a index: `f0: RMVPE_ONNX | Chunk: 96 or higher | Extra: 16384`
\n", - "**Don't forget to select a T4 GPU in the GPU field, NEVER use CPU!\n", - "> Seems that PTH models performance better than ONNX for now, you can still try ONNX models and see if it satisfies you\n", - "\n", - "\n", - "*You can always [click here](https://github.com/YunaOneeChan/Voice-Changer-Settings) to check if these settings are up-to-date*\n", - "\n", - "---\n", - "\n", - "### ⬇ Always use Colab GPU! (**IMPORTANT!**) ⬇\n", - "You need to use a Colab GPU so the Voice Changer can work faster and better\\\n", - "Use the menu above and click on **Runtime** » **Change runtime** » **Hardware acceleration** to select a GPU (**T4 is the free one**)\n", - "\n", - "---\n", - "**Credits**
\n", - "Realtime Voice Changer by [w-okada](https://github.com/w-okada)
\n", - "Notebook files updated by [rafacasari](https://github.com/Rafacasari)
\n", - "Recommended settings by [YunaOneeChan](https://github.com/YunaOneeChan)\n", - "\n", - "**Need help?** [AI Hub Discord](https://discord.gg/aihub) » ***#help-realtime-vc***\n", - "\n", - "---" - ], - "metadata": { - "id": "Lbbmx_Vjl0zo" - } - }, - { - "cell_type": "code", - "source": [ - "# @title Clone repository and install dependencies\n", - "# @markdown This first step will download the latest version of Voice Changer and install the dependencies. **It can take some time to complete.**\n", - "%cd /content/\n", - "\n", - "!pip install colorama --quiet\n", - "from colorama import Fore, Style\n", - "import os\n", - "\n", - "print(f\"{Fore.CYAN}> Cloning the repository...{Style.RESET_ALL}\")\n", - "!git clone https://github.com/w-okada/voice-changer.git --quiet\n", - "print(f\"{Fore.GREEN}> Successfully cloned the repository!{Style.RESET_ALL}\")\n", - "%cd voice-changer/server/\n", - "\n", - "print(f\"{Fore.CYAN}> Installing libportaudio2...{Style.RESET_ALL}\")\n", - "!apt-get -y install libportaudio2 -qq\n", - "\n", - "print(f\"{Fore.CYAN}> Installing pre-dependencies...{Style.RESET_ALL}\")\n", - "# Install dependencies that are missing from requirements.txt and pyngrok\n", - "!pip install faiss-gpu fairseq pyngrok --quiet\n", - "!pip install pyworld --no-build-isolation --quiet\n", - "print(f\"{Fore.CYAN}> Installing dependencies from requirements.txt...{Style.RESET_ALL}\")\n", - "!pip install -r requirements.txt --quiet\n", - "\n", - "print(f\"{Fore.GREEN}> Successfully installed all packages!{Style.RESET_ALL}\")" - ], - "metadata": { - "id": "86wTFmqsNMnD", - "cellView": "form", - "_kg_hide-output": false, - "execution": { - "iopub.status.busy": "2023-09-14T04:01:17.308284Z", - "iopub.execute_input": "2023-09-14T04:01:17.308682Z", - "iopub.status.idle": "2023-09-14T04:08:08.475375Z", - "shell.execute_reply.started": "2023-09-14T04:01:17.308652Z", - "shell.execute_reply": "2023-09-14T04:08:08.473827Z" - }, - "trusted": true - }, - "execution_count": null, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "# @title Start Server **using ngrok**\n", - "# @markdown This cell will start the server, the first time that you run it will download the models, so it can take a while (~1-2 minutes)\n", - "\n", - "# @markdown ---\n", - "# @markdown You'll need a ngrok account, but **it's free** and easy to create!\n", - "# @markdown ---\n", - "# @markdown **1** - Create a **free** account at [ngrok](https://dashboard.ngrok.com/signup) or **login with Google/Github account**\\\n", - "# @markdown **2** - If you didn't logged in with Google/Github, you will need to **verify your e-mail**!\\\n", - "# @markdown **3** - Click [this link](https://dashboard.ngrok.com/get-started/your-authtoken) to get your auth token, and place it here:\n", - "Token = '' # @param {type:\"string\"}\n", - "# @markdown **4** - *(optional)* Change to a region near to you or keep at United States if increase latency\\\n", - "# @markdown `Default Region: us - United States (Ohio)`\n", - "Region = \"us - United States (Ohio)\" # @param [\"ap - Asia/Pacific (Singapore)\", \"au - Australia (Sydney)\",\"eu - Europe (Frankfurt)\", \"in - India (Mumbai)\",\"jp - Japan (Tokyo)\",\"sa - South America (Sao Paulo)\", \"us - United States (Ohio)\"]\n", - "\n", - "#@markdown **5** - *(optional)* Other options:\n", - "ClearConsole = True # @param {type:\"boolean\"}\n", - "\n", - "# ---------------------------------\n", - "# DO NOT TOUCH ANYTHING DOWN BELOW!\n", - "# ---------------------------------\n", - "\n", - "%cd /content/voice-changer/server\n", - "\n", - "from pyngrok import conf, ngrok\n", - "MyConfig = conf.PyngrokConfig()\n", - "MyConfig.auth_token = Token\n", - "MyConfig.region = Region[0:2]\n", - "#conf.get_default().authtoken = Token\n", - "#conf.get_default().region = Region\n", - "conf.set_default(MyConfig);\n", - "\n", - "import subprocess, threading, time, socket, urllib.request\n", - "PORT = 8000\n", - "\n", - "from pyngrok import ngrok\n", - "ngrokConnection = ngrok.connect(PORT)\n", - "public_url = ngrokConnection.public_url\n", - "\n", - "from IPython.display import clear_output\n", - "\n", - "def wait_for_server():\n", - " while True:\n", - " time.sleep(0.5)\n", - " sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n", - " result = sock.connect_ex(('127.0.0.1', PORT))\n", - " if result == 0:\n", - " break\n", - " sock.close()\n", - " if ClearConsole:\n", - " clear_output()\n", - " print(\"--------- SERVER READY! ---------\")\n", - " print(\"Your server is available at:\")\n", - " print(public_url)\n", - " print(\"---------------------------------\")\n", - "\n", - "threading.Thread(target=wait_for_server, daemon=True).start()\n", - "\n", - "!python3 MMVCServerSIO.py \\\n", - " -p {PORT} \\\n", - " --https False \\\n", - " --content_vec_500 pretrain/checkpoint_best_legacy_500.pt \\\n", - " --content_vec_500_onnx pretrain/content_vec_500.onnx \\\n", - " --content_vec_500_onnx_on true \\\n", - " --hubert_base pretrain/hubert_base.pt \\\n", - " --hubert_base_jp pretrain/rinna_hubert_base_jp.pt \\\n", - " --hubert_soft pretrain/hubert/hubert-soft-0d54a1f4.pt \\\n", - " --nsf_hifigan pretrain/nsf_hifigan/model \\\n", - " --crepe_onnx_full pretrain/crepe_onnx_full.onnx \\\n", - " --crepe_onnx_tiny pretrain/crepe_onnx_tiny.onnx \\\n", - " --rmvpe pretrain/rmvpe.pt \\\n", - " --model_dir model_dir \\\n", - " --samples samples.json\n", - "\n", - "ngrok.disconnect(ngrokConnection.public_url)" - ], - "metadata": { - "id": "lLWQuUd7WW9U", - "cellView": "form", - "_kg_hide-input": false, - "scrolled": true, - "trusted": true - }, - "execution_count": null, - "outputs": [] - } - ], - "metadata": { - "colab": { - "provenance": [], - "private_outputs": true, - "include_colab_link": true, - "gpuType": "T4", - "collapsed_sections": [ - "iuf9pBHYpTn-" - ] - }, - "kernelspec": { - "display_name": "Python 3", - "name": "python3" - }, - "language_info": { - "name": "python" - }, - "accelerator": "GPU" - }, - "nbformat": 4, - "nbformat_minor": 0 -} diff --git a/client/.vscode/settings.json b/client/.vscode/settings.json deleted file mode 100644 index 90365164..00000000 --- a/client/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "workbench.colorCustomizations": { - "tab.activeBackground": "#65952acc" - }, - "editor.defaultFormatter": "esbenp.prettier-vscode", - "prettier.printWidth": 1024, - "prettier.tabWidth": 4, - "files.associations": { - "*.css": "postcss" - } -} diff --git a/client/buildAllDemo.sh b/client/buildAllDemo.sh deleted file mode 100755 index b947f92c..00000000 --- a/client/buildAllDemo.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -cd demo && ncu -u && npm install && npm run build:prod && cd - diff --git a/client/demo/.eslintrc.js b/client/demo/.eslintrc.js deleted file mode 100644 index 533f3698..00000000 --- a/client/demo/.eslintrc.js +++ /dev/null @@ -1,18 +0,0 @@ -module.exports = { - env: { - browser: true, - es2021: true, - node: true, - }, - extends: ["eslint:recommended", "plugin:react/recommended", "plugin:@typescript-eslint/recommended"], - parser: "@typescript-eslint/parser", - parserOptions: { - ecmaFeatures: { - jsx: true, - }, - ecmaVersion: 13, - sourceType: "module", - }, - plugins: ["react", "@typescript-eslint"], - rules: {}, -}; diff --git a/client/demo/.prettierrc b/client/demo/.prettierrc deleted file mode 100644 index e2828759..00000000 --- a/client/demo/.prettierrc +++ /dev/null @@ -1,6 +0,0 @@ -{ - "tabWidth": 4, - "useTabs": false, - "semi": true, - "printWidth": 360 -} diff --git a/client/demo/.vscode/settings.json b/client/demo/.vscode/settings.json deleted file mode 100644 index 90365164..00000000 --- a/client/demo/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "workbench.colorCustomizations": { - "tab.activeBackground": "#65952acc" - }, - "editor.defaultFormatter": "esbenp.prettier-vscode", - "prettier.printWidth": 1024, - "prettier.tabWidth": 4, - "files.associations": { - "*.css": "postcss" - } -} diff --git a/client/demo/build-voice-changer-js.sh b/client/demo/build-voice-changer-js.sh deleted file mode 100644 index 413a0dd1..00000000 --- a/client/demo/build-voice-changer-js.sh +++ /dev/null @@ -1,11 +0,0 @@ -# cd ~/git-work/voice-changer-js/lib/ ; npm run build:dev; cd - -# rm -rf node_modules/@dannadori/voice-changer-js -# mkdir -p node_modules/@dannadori/voice-changer-js/dist -# cp -r ~/git-work/voice-changer-js/lib/package.json node_modules/@dannadori/voice-changer-js/ -# cp -r ~/git-work/voice-changer-js/lib/dist node_modules/@dannadori/voice-changer-js/ - -cd ~/git-work/voice-changer-js/lib/ ; npm run build:prod; cd - -rm -rf node_modules/@dannadori/voice-changer-js -mkdir -p node_modules/@dannadori/voice-changer-js/dist -cp -r ~/git-work/voice-changer-js/lib/package.json node_modules/@dannadori/voice-changer-js/ -cp -r ~/git-work/voice-changer-js/lib/dist node_modules/@dannadori/voice-changer-js/ diff --git a/client/demo/dist/assets/beatrice/female-clickable.svg b/client/demo/dist/assets/beatrice/female-clickable.svg deleted file mode 100644 index 60512426..00000000 --- a/client/demo/dist/assets/beatrice/female-clickable.svg +++ /dev/null @@ -1,928 +0,0 @@ - - - - - - - 2023-11-19T11:21:56.358384 - image/svg+xml - - - Matplotlib v3.7.1, https://matplotlib.org/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/client/demo/dist/assets/beatrice/male-clickable.svg b/client/demo/dist/assets/beatrice/male-clickable.svg deleted file mode 100644 index a5385f62..00000000 --- a/client/demo/dist/assets/beatrice/male-clickable.svg +++ /dev/null @@ -1,898 +0,0 @@ - - - - - - - 2023-11-19T11:21:55.705408 - image/svg+xml - - - Matplotlib v3.7.1, https://matplotlib.org/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/client/demo/dist/assets/buymeacoffee.png b/client/demo/dist/assets/buymeacoffee.png deleted file mode 100644 index 02d6ea41..00000000 Binary files a/client/demo/dist/assets/buymeacoffee.png and /dev/null differ diff --git a/client/demo/dist/assets/gui_settings/GUI.json b/client/demo/dist/assets/gui_settings/GUI.json deleted file mode 100644 index e234f1a4..00000000 --- a/client/demo/dist/assets/gui_settings/GUI.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "type": "demo", - "id": "RVC", - "front": { - "modelSlotControl": [ - { - "name": "headerArea", - "options": { - "mainTitle": "Realtime Voice Changer Client", - "subTitle": "" - } - }, - { - "name": "modelSlotArea", - "options": {} - }, - { - "name": "characterArea", - "options": {} - }, - { - "name": "configArea", - "options": { - "detectors": ["dio", "harvest", "crepe", "crepe_full", "crepe_tiny", "rmvpe", "rmvpe_onnx", "fcpe"], - "inputChunkNums": [1, 2, 4, 6, 8, 16, 24, 32, 40, 48, 64, 80, 96, 112, 128, 192, 256, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960, 1024, 2048, 4096, 8192, 16384] - } - } - ] - } -} diff --git a/client/demo/dist/assets/gui_settings/RVC.json b/client/demo/dist/assets/gui_settings/RVC.json deleted file mode 100644 index a3099e2b..00000000 --- a/client/demo/dist/assets/gui_settings/RVC.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "type": "demo", - "id": "RVC", - "front": { - "modelSlotControl": [ - { - "name": "headerArea", - "options": { - "mainTitle": "Realtime Voice Changer Client", - "subTitle": "for RVC" - } - }, - { - "name": "modelSlotArea", - "options": {} - }, - { - "name": "characterArea", - "options": {} - }, - { - "name": "configArea", - "options": { - "detectors": ["dio", "harvest", "crepe"], - "inputChunkNums": [8, 16, 24, 32, 40, 48, 64, 80, 96, 112, 128, 192, 256, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960, 1024, 2048] - } - } - ] - } -} diff --git a/client/demo/dist/assets/gui_settings/edition.txt b/client/demo/dist/assets/gui_settings/edition.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/client/demo/dist/assets/gui_settings/edition_dml.txt b/client/demo/dist/assets/gui_settings/edition_dml.txt deleted file mode 100644 index ceffe78a..00000000 --- a/client/demo/dist/assets/gui_settings/edition_dml.txt +++ /dev/null @@ -1 +0,0 @@ -onnxdirectML-cuda diff --git a/client/demo/dist/assets/gui_settings/edition_web.txt b/client/demo/dist/assets/gui_settings/edition_web.txt deleted file mode 100644 index c0772185..00000000 --- a/client/demo/dist/assets/gui_settings/edition_web.txt +++ /dev/null @@ -1 +0,0 @@ -web diff --git a/client/demo/dist/assets/gui_settings/version.txt b/client/demo/dist/assets/gui_settings/version.txt deleted file mode 100644 index c31213bc..00000000 --- a/client/demo/dist/assets/gui_settings/version.txt +++ /dev/null @@ -1 +0,0 @@ --.-.-.- \ No newline at end of file diff --git a/client/demo/dist/assets/icons/blank.png b/client/demo/dist/assets/icons/blank.png deleted file mode 100644 index 539c8785..00000000 Binary files a/client/demo/dist/assets/icons/blank.png and /dev/null differ diff --git a/client/demo/dist/assets/icons/file-text.svg b/client/demo/dist/assets/icons/file-text.svg deleted file mode 100644 index 4197ddd4..00000000 --- a/client/demo/dist/assets/icons/file-text.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/client/demo/dist/assets/icons/flect.png b/client/demo/dist/assets/icons/flect.png deleted file mode 100644 index eb25e5d0..00000000 Binary files a/client/demo/dist/assets/icons/flect.png and /dev/null differ diff --git a/client/demo/dist/assets/icons/folder.svg b/client/demo/dist/assets/icons/folder.svg deleted file mode 100644 index 134458b9..00000000 --- a/client/demo/dist/assets/icons/folder.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/client/demo/dist/assets/icons/github.svg b/client/demo/dist/assets/icons/github.svg deleted file mode 100644 index cac76304..00000000 --- a/client/demo/dist/assets/icons/github.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/client/demo/dist/assets/icons/help-circle.svg b/client/demo/dist/assets/icons/help-circle.svg deleted file mode 100644 index 51fddd80..00000000 --- a/client/demo/dist/assets/icons/help-circle.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/client/demo/dist/assets/icons/home.svg b/client/demo/dist/assets/icons/home.svg deleted file mode 100644 index 7e630021..00000000 --- a/client/demo/dist/assets/icons/home.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/client/demo/dist/assets/icons/human.png b/client/demo/dist/assets/icons/human.png deleted file mode 100644 index 7b4bf8df..00000000 Binary files a/client/demo/dist/assets/icons/human.png and /dev/null differ diff --git a/client/demo/dist/assets/icons/linkedin.svg b/client/demo/dist/assets/icons/linkedin.svg deleted file mode 100644 index 021adb4d..00000000 --- a/client/demo/dist/assets/icons/linkedin.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/client/demo/dist/assets/icons/noimage.png b/client/demo/dist/assets/icons/noimage.png deleted file mode 100644 index 6b520524..00000000 Binary files a/client/demo/dist/assets/icons/noimage.png and /dev/null differ diff --git a/client/demo/dist/assets/icons/tool.svg b/client/demo/dist/assets/icons/tool.svg deleted file mode 100644 index f3cbf3d9..00000000 --- a/client/demo/dist/assets/icons/tool.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/client/demo/dist/assets/icons/twitter.svg b/client/demo/dist/assets/icons/twitter.svg deleted file mode 100644 index 640ade90..00000000 --- a/client/demo/dist/assets/icons/twitter.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/client/demo/dist/assets/icons/zun.png b/client/demo/dist/assets/icons/zun.png deleted file mode 100644 index 2e6f7c18..00000000 Binary files a/client/demo/dist/assets/icons/zun.png and /dev/null differ diff --git a/client/demo/dist/favicon.ico b/client/demo/dist/favicon.ico deleted file mode 100644 index 052e3af9..00000000 Binary files a/client/demo/dist/favicon.ico and /dev/null differ diff --git a/client/demo/dist/index.html b/client/demo/dist/index.html deleted file mode 100644 index 83226387..00000000 --- a/client/demo/dist/index.html +++ /dev/null @@ -1 +0,0 @@ -Voice Changer Client Demo
\ No newline at end of file diff --git a/client/demo/dist/index.js b/client/demo/dist/index.js deleted file mode 100644 index 5338bdbb..00000000 --- a/client/demo/dist/index.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! For license information please see index.js.LICENSE.txt */ -(()=>{var __webpack_modules__={98:function(module,__unused_webpack_exports,__webpack_require__){var t;"undefined"!=typeof self&&self,t=__WEBPACK_EXTERNAL_MODULE__9155__=>(()=>{var __webpack_modules__={5456:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AwsCrc32=void 0;var i=n(5215),r=n(5403),a=n(3465),o=function(){function e(){this.crc32=new a.Crc32}return e.prototype.update=function(e){(0,r.isEmptyData)(e)||this.crc32.update((0,r.convertToBuffer)(e))},e.prototype.digest=function(){return i.__awaiter(this,void 0,void 0,(function(){return i.__generator(this,(function(e){return[2,(0,r.numToUint8)(this.crc32.digest())]}))}))},e.prototype.reset=function(){this.crc32=new a.Crc32},e}();t.AwsCrc32=o},3465:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AwsCrc32=t.Crc32=t.crc32=void 0;var i=n(5215),r=n(5403);t.crc32=function(e){return(new a).update(e).digest()};var a=function(){function e(){this.checksum=4294967295}return e.prototype.update=function(e){var t,n;try{for(var r=i.__values(e),a=r.next();!a.done;a=r.next()){var s=a.value;this.checksum=this.checksum>>>8^o[255&(this.checksum^s)]}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}return this},e.prototype.digest=function(){return(4294967295^this.checksum)>>>0},e}();t.Crc32=a;var o=(0,r.uint32ArrayFrom)([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]),s=n(5456);Object.defineProperty(t,"AwsCrc32",{enumerable:!0,get:function(){return s.AwsCrc32}})},7043:(e,t,n)=>{"use strict";var i=n(8287).hp;Object.defineProperty(t,"__esModule",{value:!0}),t.convertToBuffer=void 0;var r=n(4006),a=void 0!==i&&i.from?function(e){return i.from(e,"utf8")}:r.fromUtf8;t.convertToBuffer=function(e){return e instanceof Uint8Array?e:"string"==typeof e?a(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}},5403:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uint32ArrayFrom=t.numToUint8=t.isEmptyData=t.convertToBuffer=void 0;var i=n(7043);Object.defineProperty(t,"convertToBuffer",{enumerable:!0,get:function(){return i.convertToBuffer}});var r=n(1322);Object.defineProperty(t,"isEmptyData",{enumerable:!0,get:function(){return r.isEmptyData}});var a=n(1844);Object.defineProperty(t,"numToUint8",{enumerable:!0,get:function(){return a.numToUint8}});var o=n(5801);Object.defineProperty(t,"uint32ArrayFrom",{enumerable:!0,get:function(){return o.uint32ArrayFrom}})},1322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyData=void 0,t.isEmptyData=function(e){return"string"==typeof e?0===e.length:0===e.byteLength}},1844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.numToUint8=void 0,t.numToUint8=function(e){return new Uint8Array([(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e])}},5801:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uint32ArrayFrom=void 0,t.uint32ArrayFrom=function(e){if(!Uint32Array.from){for(var t=new Uint32Array(e.length),n=0;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},8145:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},304:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},9116:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},5660:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMsWindow=void 0;var n=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];t.isMsWindow=function(e){if(function(e){return"MSInputMethodContext"in e&&"msCrypto"in e}(e)&&void 0!==e.msCrypto.subtle){var t=e.msCrypto,i=t.getRandomValues,r=t.subtle;return n.map((function(e){return r[e]})).concat(i).every((function(e){return"function"==typeof e}))}return!1}},8086:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n(5215);i.__exportStar(n(8904),t),i.__exportStar(n(8145),t),i.__exportStar(n(304),t),i.__exportStar(n(9116),t),i.__exportStar(n(5660),t)},7336:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EMPTY_DATA_SHA_256=t.SHA_256_HMAC_ALGO=t.SHA_256_HASH=void 0,t.SHA_256_HASH={name:"SHA-256"},t.SHA_256_HMAC_ALGO={name:"HMAC",hash:t.SHA_256_HASH},t.EMPTY_DATA_SHA_256=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85])},9258:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sha256=void 0;var i=n(1195),r=n(2038),a=n(2947),o=n(3469),s=n(8086),c=n(7226),l=n(2092),d=function(){function e(e){(0,o.supportsWebCrypto)((0,c.locateWindow)())?this.hash=new r.Sha256(e):(0,s.isMsWindow)((0,c.locateWindow)())?this.hash=new i.Sha256(e):this.hash=new a.Sha256(e)}return e.prototype.update=function(e,t){this.hash.update((0,l.convertToBuffer)(e))},e.prototype.digest=function(){return this.hash.digest()},e.prototype.reset=function(){this.hash.reset()},e}();t.Sha256=d},1195:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sha256=void 0;var i=n(5787),r=n(7336),a=n(4006),o=n(7226),s=function(){function e(e){this.secret=e,this.reset()}return e.prototype.update=function(e){var t=this;(0,i.isEmptyData)(e)||(this.operation=this.operation.then((function(n){return n.onerror=function(){t.operation=Promise.reject(new Error("Error encountered updating hash"))},n.process(c(e)),n})),this.operation.catch((function(){})))},e.prototype.digest=function(){return this.operation.then((function(e){return new Promise((function(t,n){e.onerror=function(){n(new Error("Error encountered finalizing hash"))},e.oncomplete=function(){e.result&&t(new Uint8Array(e.result)),n(new Error("Error encountered finalizing hash"))},e.finish()}))}))},e.prototype.reset=function(){var e;this.secret?(this.operation=(e=this.secret,new Promise((function(t,n){var i=(0,o.locateWindow)().msCrypto.subtle.importKey("raw",c(e),r.SHA_256_HMAC_ALGO,!1,["sign"]);i.oncomplete=function(){i.result&&t(i.result),n(new Error("ImportKey completed without importing key."))},i.onerror=function(){n(new Error("ImportKey failed to import key."))}}))).then((function(e){return(0,o.locateWindow)().msCrypto.subtle.sign(r.SHA_256_HMAC_ALGO,e)})),this.operation.catch((function(){}))):this.operation=Promise.resolve((0,o.locateWindow)().msCrypto.subtle.digest("SHA-256"))},e}();function c(e){return"string"==typeof e?(0,a.fromUtf8)(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}t.Sha256=s},6634:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebCryptoSha256=t.Ie11Sha256=void 0,n(5215).__exportStar(n(9258),t);var i=n(1195);Object.defineProperty(t,"Ie11Sha256",{enumerable:!0,get:function(){return i.Sha256}});var r=n(2038);Object.defineProperty(t,"WebCryptoSha256",{enumerable:!0,get:function(){return r.Sha256}})},5787:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyData=void 0,t.isEmptyData=function(e){return"string"==typeof e?0===e.length:0===e.byteLength}},2038:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sha256=void 0;var i=n(2092),r=n(7336),a=n(7226),o=function(){function e(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return e.prototype.update=function(e){if(!(0,i.isEmptyData)(e)){var t=(0,i.convertToBuffer)(e),n=new Uint8Array(this.toHash.byteLength+t.byteLength);n.set(this.toHash,0),n.set(t,this.toHash.byteLength),this.toHash=n}},e.prototype.digest=function(){var e=this;return this.key?this.key.then((function(t){return(0,a.locateWindow)().crypto.subtle.sign(r.SHA_256_HMAC_ALGO,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):(0,i.isEmptyData)(this.toHash)?Promise.resolve(r.EMPTY_DATA_SHA_256):Promise.resolve().then((function(){return(0,a.locateWindow)().crypto.subtle.digest(r.SHA_256_HASH,e.toHash)})).then((function(e){return Promise.resolve(new Uint8Array(e))}))},e.prototype.reset=function(){var e=this;this.toHash=new Uint8Array(0),this.secret&&void 0!==this.secret&&(this.key=new Promise((function(t,n){(0,a.locateWindow)().crypto.subtle.importKey("raw",(0,i.convertToBuffer)(e.secret),r.SHA_256_HMAC_ALGO,!1,["sign"]).then(t,n)})),this.key.catch((function(){})))},e}();t.Sha256=o},538:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RawSha256=void 0;var i=n(4326),r=function(){function e(){this.state=Int32Array.from(i.INIT),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return e.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=0,n=e.byteLength;if(this.bytesHashed+=n,8*this.bytesHashed>i.MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===i.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var e=8*this.bytesHashed,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%i.BLOCK_SIZE>=i.BLOCK_SIZE-8){for(var r=this.bufferLength;r>>24&255,a[4*r+1]=this.state[r]>>>16&255,a[4*r+2]=this.state[r]>>>8&255,a[4*r+3]=this.state[r]>>>0&255;return a},e.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],r=t[1],a=t[2],o=t[3],s=t[4],c=t[5],l=t[6],d=t[7],u=0;u>>17|f<<15)^(f>>>19|f<<13)^f>>>10,m=((f=this.temp[u-15])>>>7|f<<25)^(f>>>18|f<<14)^f>>>3;this.temp[u]=(h+this.temp[u-7]|0)+(m+this.temp[u-16]|0)}var p=(((s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7))+(s&c^~s&l)|0)+(d+(i.KEY[u]+this.temp[u]|0)|0)|0,g=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&a^r&a)|0;d=l,l=c,c=s,s=o+p|0,o=a,a=r,r=n,n=p+g|0}t[0]+=n,t[1]+=r,t[2]+=a,t[3]+=o,t[4]+=s,t[5]+=c,t[6]+=l,t[7]+=d},e}();t.RawSha256=r},4326:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MAX_HASHABLE_LENGTH=t.INIT=t.KEY=t.DIGEST_LENGTH=t.BLOCK_SIZE=void 0,t.BLOCK_SIZE=64,t.DIGEST_LENGTH=32,t.KEY=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),t.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],t.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1},2947:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n(5215).__exportStar(n(4279),t)},4279:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sha256=void 0;var i=n(5215),r=n(4326),a=n(538),o=n(2092),s=function(){function e(e){this.secret=e,this.hash=new a.RawSha256,this.reset()}return e.prototype.update=function(e){if(!(0,o.isEmptyData)(e)&&!this.error)try{this.hash.update((0,o.convertToBuffer)(e))}catch(e){this.error=e}},e.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},e.prototype.digest=function(){return i.__awaiter(this,void 0,void 0,(function(){return i.__generator(this,(function(e){return[2,this.digestSync()]}))}))},e.prototype.reset=function(){if(this.hash=new a.RawSha256,this.secret){this.outer=new a.RawSha256;var e=function(e){var t=(0,o.convertToBuffer)(e);if(t.byteLength>r.BLOCK_SIZE){var n=new a.RawSha256;n.update(t),t=n.digest()}var i=new Uint8Array(r.BLOCK_SIZE);return i.set(t),i}(this.secret),t=new Uint8Array(r.BLOCK_SIZE);t.set(e);for(var n=0;n{"use strict";var i=n(8287).hp;Object.defineProperty(t,"__esModule",{value:!0}),t.convertToBuffer=void 0;var r=n(4006),a=void 0!==i&&i.from?function(e){return i.from(e,"utf8")}:r.fromUtf8;t.convertToBuffer=function(e){return e instanceof Uint8Array?e:"string"==typeof e?a(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}},2092:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uint32ArrayFrom=t.numToUint8=t.isEmptyData=t.convertToBuffer=void 0;var i=n(8e3);Object.defineProperty(t,"convertToBuffer",{enumerable:!0,get:function(){return i.convertToBuffer}});var r=n(357);Object.defineProperty(t,"isEmptyData",{enumerable:!0,get:function(){return r.isEmptyData}});var a=n(5445);Object.defineProperty(t,"numToUint8",{enumerable:!0,get:function(){return a.numToUint8}});var o=n(7246);Object.defineProperty(t,"uint32ArrayFrom",{enumerable:!0,get:function(){return o.uint32ArrayFrom}})},357:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyData=void 0,t.isEmptyData=function(e){return"string"==typeof e?0===e.length:0===e.byteLength}},5445:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.numToUint8=void 0,t.numToUint8=function(e){return new Uint8Array([(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e])}},7246:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uint32ArrayFrom=void 0,t.uint32ArrayFrom=function(e){if(!Uint32Array.from){for(var t=new Uint32Array(e.length),n=0;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RawSha256=void 0;var i=n(5494),r=function(){function e(){this.state=Int32Array.from(i.INIT),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return e.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=0,n=e.byteLength;if(this.bytesHashed+=n,8*this.bytesHashed>i.MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===i.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var e=8*this.bytesHashed,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%i.BLOCK_SIZE>=i.BLOCK_SIZE-8){for(var r=this.bufferLength;r>>24&255,a[4*r+1]=this.state[r]>>>16&255,a[4*r+2]=this.state[r]>>>8&255,a[4*r+3]=this.state[r]>>>0&255;return a},e.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],r=t[1],a=t[2],o=t[3],s=t[4],c=t[5],l=t[6],d=t[7],u=0;u>>17|f<<15)^(f>>>19|f<<13)^f>>>10,m=((f=this.temp[u-15])>>>7|f<<25)^(f>>>18|f<<14)^f>>>3;this.temp[u]=(h+this.temp[u-7]|0)+(m+this.temp[u-16]|0)}var p=(((s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7))+(s&c^~s&l)|0)+(d+(i.KEY[u]+this.temp[u]|0)|0)|0,g=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&a^r&a)|0;d=l,l=c,c=s,s=o+p|0,o=a,a=r,r=n,n=p+g|0}t[0]+=n,t[1]+=r,t[2]+=a,t[3]+=o,t[4]+=s,t[5]+=c,t[6]+=l,t[7]+=d},e}();t.RawSha256=r},5494:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MAX_HASHABLE_LENGTH=t.INIT=t.KEY=t.DIGEST_LENGTH=t.BLOCK_SIZE=void 0,t.BLOCK_SIZE=64,t.DIGEST_LENGTH=32,t.KEY=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),t.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],t.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1},3523:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n(5215).__exportStar(n(871),t)},871:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sha256=void 0;var i=n(5215),r=n(5494),a=n(4602),o=n(5388),s=function(){function e(e){if(this.hash=new a.RawSha256,e){this.outer=new a.RawSha256;var t=function(e){var t=(0,o.convertToBuffer)(e);if(t.byteLength>r.BLOCK_SIZE){var n=new a.RawSha256;n.update(t),t=n.digest()}var i=new Uint8Array(r.BLOCK_SIZE);return i.set(t),i}(e),n=new Uint8Array(r.BLOCK_SIZE);n.set(t);for(var i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n(5215).__exportStar(n(3526),t)},3526:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.supportsZeroByteGCM=t.supportsSubtleCrypto=t.supportsSecureRandom=t.supportsWebCrypto=void 0;var i=n(5215),r=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function a(e){return"object"==typeof e&&"object"==typeof e.crypto&&"function"==typeof e.crypto.getRandomValues}function o(e){return e&&r.every((function(t){return"function"==typeof e[t]}))}t.supportsWebCrypto=function(e){return!(!a(e)||"object"!=typeof e.crypto.subtle)&&o(e.crypto.subtle)},t.supportsSecureRandom=a,t.supportsSubtleCrypto=o,t.supportsZeroByteGCM=function(e){return i.__awaiter(this,void 0,void 0,(function(){var t;return i.__generator(this,(function(n){switch(n.label){case 0:if(!o(e))return[2,!1];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,e.generateKey({name:"AES-GCM",length:128},!1,["encrypt"])];case 2:return t=n.sent(),[4,e.encrypt({name:"AES-GCM",iv:new Uint8Array(Array(12)),additionalData:new Uint8Array(Array(16)),tagLength:128},t,new Uint8Array(0))];case 3:return[2,16===n.sent().byteLength];case 4:return n.sent(),[2,!1];case 5:return[2]}}))}))}},1024:(e,t,n)=>{"use strict";var i=n(8287).hp;Object.defineProperty(t,"__esModule",{value:!0}),t.convertToBuffer=void 0;var r=n(4006),a=void 0!==i&&i.from?function(e){return i.from(e,"utf8")}:r.fromUtf8;t.convertToBuffer=function(e){return e instanceof Uint8Array?e:"string"==typeof e?a(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}},5388:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uint32ArrayFrom=t.numToUint8=t.isEmptyData=t.convertToBuffer=void 0;var i=n(1024);Object.defineProperty(t,"convertToBuffer",{enumerable:!0,get:function(){return i.convertToBuffer}});var r=n(165);Object.defineProperty(t,"isEmptyData",{enumerable:!0,get:function(){return r.isEmptyData}});var a=n(5413);Object.defineProperty(t,"numToUint8",{enumerable:!0,get:function(){return a.numToUint8}});var o=n(2110);Object.defineProperty(t,"uint32ArrayFrom",{enumerable:!0,get:function(){return o.uint32ArrayFrom}})},165:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyData=void 0,t.isEmptyData=function(e){return"string"==typeof e?0===e.length:0===e.byteLength}},5413:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.numToUint8=void 0,t.numToUint8=function(e){return new Uint8Array([(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e])}},2110:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uint32ArrayFrom=void 0,t.uint32ArrayFrom=function(e){if(!Uint32Array.from){for(var t=new Uint32Array(e.length),n=0;n{"use strict";n.r(t),n.d(t,{$Command:()=>sn,AllowNotifications:()=>mi,AssociateChannelFlowCommand:()=>wa,BadRequestException:()=>vi,BatchChannelMembershipsFilterSensitiveLog:()=>Fi,BatchCreateChannelMembershipCommand:()=>Ma,BatchCreateChannelMembershipResponseFilterSensitiveLog:()=>Bi,ChannelAssociatedWithFlowSummaryFilterSensitiveLog:()=>ji,ChannelBanFilterSensitiveLog:()=>qi,ChannelBanSummaryFilterSensitiveLog:()=>Wi,ChannelFilterSensitiveLog:()=>Ui,ChannelFlowCallbackCommand:()=>za,ChannelFlowCallbackRequestFilterSensitiveLog:()=>Qi,ChannelFlowFilterSensitiveLog:()=>Gi,ChannelFlowSummaryFilterSensitiveLog:()=>Yi,ChannelMembershipFilterSensitiveLog:()=>Xi,ChannelMembershipForAppInstanceUserSummaryFilterSensitiveLog:()=>tr,ChannelMembershipPreferencesFilterSensitiveLog:()=>ir,ChannelMembershipSummaryFilterSensitiveLog:()=>rr,ChannelMembershipType:()=>pi,ChannelMessageCallbackFilterSensitiveLog:()=>Zi,ChannelMessageFilterSensitiveLog:()=>ar,ChannelMessagePersistenceType:()=>Ai,ChannelMessageStatus:()=>_i,ChannelMessageSummaryFilterSensitiveLog:()=>or,ChannelMessageType:()=>Ni,ChannelMode:()=>Vi,ChannelModeratedByAppInstanceUserSummaryFilterSensitiveLog:()=>sr,ChannelModeratorFilterSensitiveLog:()=>cr,ChannelModeratorSummaryFilterSensitiveLog:()=>lr,ChannelPrivacy:()=>Hi,ChannelSummaryFilterSensitiveLog:()=>er,ChimeSDKMessaging:()=>Co,ChimeSDKMessagingClient:()=>fi,ChimeSDKMessagingServiceException:()=>hi,ConflictException:()=>bi,CreateChannelBanCommand:()=>ka,CreateChannelBanResponseFilterSensitiveLog:()=>fr,CreateChannelCommand:()=>xa,CreateChannelFlowCommand:()=>Va,CreateChannelFlowRequestFilterSensitiveLog:()=>hr,CreateChannelMembershipCommand:()=>Ha,CreateChannelMembershipResponseFilterSensitiveLog:()=>mr,CreateChannelModeratorCommand:()=>Ea,CreateChannelModeratorResponseFilterSensitiveLog:()=>pr,CreateChannelRequestFilterSensitiveLog:()=>ur,DeleteChannelBanCommand:()=>La,DeleteChannelCommand:()=>Ta,DeleteChannelFlowCommand:()=>Aa,DeleteChannelMembershipCommand:()=>_a,DeleteChannelMessageCommand:()=>Na,DeleteChannelModeratorCommand:()=>Ia,DeleteMessagingStreamingConfigurationsCommand:()=>Pa,DescribeChannelBanCommand:()=>Oa,DescribeChannelBanResponseFilterSensitiveLog:()=>vr,DescribeChannelCommand:()=>Ra,DescribeChannelFlowCommand:()=>Da,DescribeChannelFlowResponseFilterSensitiveLog:()=>br,DescribeChannelMembershipCommand:()=>Fa,DescribeChannelMembershipForAppInstanceUserCommand:()=>Ba,DescribeChannelMembershipForAppInstanceUserResponseFilterSensitiveLog:()=>Sr,DescribeChannelMembershipResponseFilterSensitiveLog:()=>yr,DescribeChannelModeratedByAppInstanceUserCommand:()=>Ua,DescribeChannelModeratedByAppInstanceUserResponseFilterSensitiveLog:()=>Cr,DescribeChannelModeratorCommand:()=>ja,DescribeChannelModeratorResponseFilterSensitiveLog:()=>wr,DescribeChannelResponseFilterSensitiveLog:()=>gr,DisassociateChannelFlowCommand:()=>qa,ErrorCode:()=>gi,ExpirationCriterion:()=>xi,FallbackAction:()=>Li,ForbiddenException:()=>yi,GetChannelMembershipPreferencesCommand:()=>Wa,GetChannelMembershipPreferencesResponseFilterSensitiveLog:()=>Mr,GetChannelMessageCommand:()=>$a,GetChannelMessageResponseFilterSensitiveLog:()=>zr,GetChannelMessageStatusCommand:()=>Ga,GetMessagingSessionEndpointCommand:()=>Ka,GetMessagingStreamingConfigurationsCommand:()=>Ja,IdentityFilterSensitiveLog:()=>Di,InvocationType:()=>Ei,ListChannelBansCommand:()=>Za,ListChannelBansRequestFilterSensitiveLog:()=>kr,ListChannelBansResponseFilterSensitiveLog:()=>xr,ListChannelFlowsCommand:()=>Qa,ListChannelFlowsRequestFilterSensitiveLog:()=>Vr,ListChannelFlowsResponseFilterSensitiveLog:()=>Hr,ListChannelMembershipsCommand:()=>Ya,ListChannelMembershipsForAppInstanceUserCommand:()=>Xa,ListChannelMembershipsForAppInstanceUserRequestFilterSensitiveLog:()=>Tr,ListChannelMembershipsForAppInstanceUserResponseFilterSensitiveLog:()=>Ar,ListChannelMembershipsRequestFilterSensitiveLog:()=>Er,ListChannelMembershipsResponseFilterSensitiveLog:()=>Lr,ListChannelMessagesCommand:()=>eo,ListChannelMessagesRequestFilterSensitiveLog:()=>_r,ListChannelMessagesResponseFilterSensitiveLog:()=>Nr,ListChannelModeratorsCommand:()=>to,ListChannelModeratorsRequestFilterSensitiveLog:()=>Ir,ListChannelModeratorsResponseFilterSensitiveLog:()=>Pr,ListChannelsAssociatedWithChannelFlowCommand:()=>no,ListChannelsAssociatedWithChannelFlowRequestFilterSensitiveLog:()=>Dr,ListChannelsAssociatedWithChannelFlowResponseFilterSensitiveLog:()=>Fr,ListChannelsCommand:()=>io,ListChannelsModeratedByAppInstanceUserCommand:()=>ro,ListChannelsModeratedByAppInstanceUserRequestFilterSensitiveLog:()=>Br,ListChannelsModeratedByAppInstanceUserResponseFilterSensitiveLog:()=>Ur,ListChannelsRequestFilterSensitiveLog:()=>Or,ListChannelsResponseFilterSensitiveLog:()=>Rr,ListSubChannelsCommand:()=>ao,ListSubChannelsRequestFilterSensitiveLog:()=>jr,ListSubChannelsResponseFilterSensitiveLog:()=>qr,ListTagsForResourceCommand:()=>oo,ListTagsForResourceResponseFilterSensitiveLog:()=>Wr,MessageAttributeValueFilterSensitiveLog:()=>Ki,MessagingDataType:()=>Ii,NotFoundException:()=>Si,ProcessorFilterSensitiveLog:()=>$i,PushNotificationConfigurationFilterSensitiveLog:()=>Ji,PushNotificationPreferencesFilterSensitiveLog:()=>nr,PushNotificationType:()=>Ti,PutChannelExpirationSettingsCommand:()=>so,PutChannelMembershipPreferencesCommand:()=>co,PutChannelMembershipPreferencesRequestFilterSensitiveLog:()=>$r,PutChannelMembershipPreferencesResponseFilterSensitiveLog:()=>Gr,PutMessagingStreamingConfigurationsCommand:()=>lo,RedactChannelMessageCommand:()=>uo,ResourceLimitExceededException:()=>ki,SearchChannelsCommand:()=>fo,SearchChannelsRequestFilterSensitiveLog:()=>Kr,SearchChannelsResponseFilterSensitiveLog:()=>Jr,SearchFieldKey:()=>Oi,SearchFieldOperator:()=>Ri,SendChannelMessageCommand:()=>ho,SendChannelMessageRequestFilterSensitiveLog:()=>Zr,ServiceFailureException:()=>Ci,ServiceUnavailableException:()=>wi,SortOrder:()=>Pi,TagFilterSensitiveLog:()=>dr,TagResourceCommand:()=>mo,TagResourceRequestFilterSensitiveLog:()=>Qr,ThrottledClientException:()=>Mi,UnauthorizedClientException:()=>zi,UntagResourceCommand:()=>po,UntagResourceRequestFilterSensitiveLog:()=>Yr,UpdateChannelCommand:()=>go,UpdateChannelFlowCommand:()=>vo,UpdateChannelFlowRequestFilterSensitiveLog:()=>ea,UpdateChannelMessageCommand:()=>bo,UpdateChannelMessageRequestFilterSensitiveLog:()=>ta,UpdateChannelReadMarkerCommand:()=>yo,UpdateChannelRequestFilterSensitiveLog:()=>Xr,__Client:()=>Gt,paginateListChannelBans:()=>Mo,paginateListChannelFlows:()=>ko,paginateListChannelMemberships:()=>Eo,paginateListChannelMembershipsForAppInstanceUser:()=>Vo,paginateListChannelMessages:()=>To,paginateListChannelModerators:()=>_o,paginateListChannels:()=>Do,paginateListChannelsAssociatedWithChannelFlow:()=>Io,paginateListChannelsModeratedByAppInstanceUser:()=>Oo,paginateListSubChannels:()=>Bo,paginateSearchChannels:()=>jo});const i=e=>{let t=e.httpHandler;return{setHttpHandler(e){t=e},httpHandler:()=>t,updateHttpClientConfig(e,n){t.updateHttpClientConfig(e,n)},httpHandlerConfigs:()=>t.httpHandlerConfigs()}};var r,a,o,s,c,l;!function(e){e.HEADER="header",e.QUERY="query"}(r||(r={})),function(e){e.HEADER="header",e.QUERY="query"}(a||(a={})),function(e){e.HTTP="http",e.HTTPS="https"}(o||(o={})),function(e){e.MD5="md5",e.CRC32="crc32",e.CRC32C="crc32c",e.SHA1="sha1",e.SHA256="sha256"}(s||(s={})),(l=c||(c={}))[l.HEADER=0]="HEADER",l[l.TRAILER=1]="TRAILER";const d="__smithy_context";var u,f;!function(e){e.PROFILE="profile",e.SSO_SESSION="sso-session",e.SERVICES="services"}(u||(u={})),function(e){e.HTTP_0_9="http/0.9",e.HTTP_1_0="http/1.0",e.TDS_8_0="tds/8.0"}(f||(f={}));class h{constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?":"!==e.protocol.slice(-1)?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?"/"!==e.path.charAt(0)?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static isInstance(e){if(!e)return!1;const t=e;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&"object"==typeof t.query&&"object"==typeof t.headers}clone(){const e=new h({...this,headers:{...this.headers}});var t;return e.query&&(e.query=(t=e.query,Object.keys(t).reduce(((e,n)=>{const i=t[n];return{...e,[n]:Array.isArray(i)?[...i]:i}}),{}))),e}}class m{constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;const t=e;return"number"==typeof t.statusCode&&"object"==typeof t.headers}}const p={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},g={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},v="X-Amzn-Trace-Id",b={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"};Error;const y=(e,t,n)=>{let i,r,a,o=!1;const s=async()=>{r||(r=e());try{i=await r,a=!0,o=!1}finally{r=void 0}return i};return void 0===t?async e=>(a&&!e?.forceRefresh||(i=await s()),i):async e=>(a&&!e?.forceRefresh||(i=await s()),o?i:n&&!n(i)?(o=!0,i):t(i)?(await s(),i):i)};n(3465);const S={},C={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();1===t.length&&(t=`0${t}`),S[e]=t,C[t]=e}function w(e){let t="";for(let n=0;n0x8000000000000000||e<-0x8000000000000000)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let n=7,i=Math.abs(Math.round(e));n>-1&&i>0;n--,i/=256)t[n]=i;return e<0&&z(t),new M(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&z(e),parseInt(w(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function z(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}class k{constructor(e,t){this.toUtf8=e,this.fromUtf8=t}format(e){const t=[];for(const n of Object.keys(e)){const i=this.fromUtf8(n);t.push(Uint8Array.from([i.byteLength]),i,this.formatHeaderValue(e[n]))}const n=new Uint8Array(t.reduce(((e,t)=>e+t.byteLength),0));let i=0;for(const e of t)n.set(e,i),i+=e.byteLength;return n}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const n=new DataView(new ArrayBuffer(5));return n.setUint8(0,4),n.setInt32(1,e.value,!1),new Uint8Array(n.buffer);case"long":const i=new Uint8Array(9);return i[0]=5,i.set(e.value.bytes,1),i;case"binary":const r=new DataView(new ArrayBuffer(3+e.value.byteLength));r.setUint8(0,6),r.setUint16(1,e.value.byteLength,!1);const a=new Uint8Array(r.buffer);return a.set(e.value,3),a;case"string":const o=this.fromUtf8(e.value),s=new DataView(new ArrayBuffer(3+o.byteLength));s.setUint8(0,7),s.setUint16(1,o.byteLength,!1);const c=new Uint8Array(s.buffer);return c.set(o,3),c;case"timestamp":const l=new Uint8Array(9);return l[0]=8,l.set(M.fromNumber(e.value.valueOf()).bytes,1),l;case"uuid":if(!P.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(function(e){if(e.length%2!=0)throw new Error("Hex encoded strings must have an even number length");const t=new Uint8Array(e.length/2);for(let n=0;n{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t},B=e=>new TextDecoder("utf-8").decode(e),U=e=>(new TextEncoder).encode(e),j=e=>"string"==typeof e?U(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e),q="X-Amz-Date",W="X-Amz-Signature",$="X-Amz-Security-Token",G="authorization",K=q.toLowerCase(),J=[G,K,"date"],Z=W.toLowerCase(),Q="x-amz-content-sha256",Y=$.toLowerCase(),X={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},ee=/^proxy-/,te=/^sec-/,ne="AWS4-HMAC-SHA256",ie="AWS4-HMAC-SHA256-PAYLOAD",re="aws4_request",ae={},oe=[],se=(e,t,n)=>`${e}/${t}/${n}/${re}`,ce=(e,t,n)=>{const i=new e(t);return i.update(j(n)),i.digest()},le=({headers:e},t,n)=>{const i={};for(const r of Object.keys(e).sort()){if(null==e[r])continue;const a=r.toLowerCase();(a in X||t?.has(a)||ee.test(a)||te.test(a))&&(!n||n&&!n.has(a))||(i[a]=e[r].trim().replace(/\s+/g," "))}return i},de=e=>encodeURIComponent(e).replace(/[!'()*]/g,ue),ue=e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`,fe=async({headers:e,body:t},n)=>{for(const t of Object.keys(e))if(t.toLowerCase()===Q)return e[t];if(null==t)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if("string"==typeof t||ArrayBuffer.isView(t)||(i=t,"function"==typeof ArrayBuffer&&i instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(i))){const e=new n;return e.update(j(t)),D(await e.digest())}var i;return"UNSIGNED-PAYLOAD"},he=({headers:e,query:t,...n})=>({...n,headers:{...e},query:t?me(t):void 0}),me=e=>Object.keys(e).reduce(((t,n)=>{const i=e[n];return{...t,[n]:Array.isArray(i)?[...i]:i}}),{}),pe=e=>{e="function"==typeof e.clone?e.clone():he(e);for(const t of Object.keys(e.headers))J.indexOf(t.toLowerCase())>-1&&delete e.headers[t];return e};class ge{constructor({applyChecksum:e,credentials:t,region:n,service:i,sha256:r,uriEscapePath:a=!0}){this.headerMarshaller=new k(B,U),this.service=i,this.sha256=r,this.uriEscapePath=a,this.applyChecksum="boolean"!=typeof e||e,this.regionProvider=F(n),this.credentialProvider=F(t)}async presign(e,t={}){const{signingDate:n=new Date,expiresIn:i=3600,unsignableHeaders:r,unhoistableHeaders:a,signableHeaders:o,signingRegion:s,signingService:c}=t,l=await this.credentialProvider();this.validateResolvedCredentials(l);const d=s??await this.regionProvider(),{longDate:u,shortDate:f}=ve(n);if(i>604800)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const h=se(f,d,c??this.service),m=((e,t={})=>{const{headers:n,query:i={}}="function"==typeof e.clone?e.clone():he(e);for(const e of Object.keys(n)){const r=e.toLowerCase();"x-amz-"!==r.slice(0,6)||t.unhoistableHeaders?.has(r)||(i[e]=n[e],delete n[e])}return{...e,headers:n,query:i}})(pe(e),{unhoistableHeaders:a});l.sessionToken&&(m.query[$]=l.sessionToken),m.query["X-Amz-Algorithm"]=ne,m.query["X-Amz-Credential"]=`${l.accessKeyId}/${h}`,m.query[q]=u,m.query["X-Amz-Expires"]=i.toString(10);const p=le(m,r,o);return m.query["X-Amz-SignedHeaders"]=be(p),m.query[W]=await this.getSignature(u,h,this.getSigningKey(l,d,f,c),this.createCanonicalRequest(m,p,await fe(e,this.sha256))),m}async sign(e,t){return"string"==typeof e?this.signString(e,t):e.headers&&e.payload?this.signEvent(e,t):e.message?this.signMessage(e,t):this.signRequest(e,t)}async signEvent({headers:e,payload:t},{signingDate:n=new Date,priorSignature:i,signingRegion:r,signingService:a}){const o=r??await this.regionProvider(),{shortDate:s,longDate:c}=ve(n),l=se(s,o,a??this.service),d=await fe({headers:{},body:t},this.sha256),u=new this.sha256;u.update(e);const f=D(await u.digest()),h=[ie,c,l,i,f,d].join("\n");return this.signString(h,{signingDate:n,signingRegion:o,signingService:a})}async signMessage(e,{signingDate:t=new Date,signingRegion:n,signingService:i}){return this.signEvent({headers:this.headerMarshaller.format(e.message.headers),payload:e.message.body},{signingDate:t,signingRegion:n,signingService:i,priorSignature:e.priorSignature}).then((t=>({message:e.message,signature:t})))}async signString(e,{signingDate:t=new Date,signingRegion:n,signingService:i}={}){const r=await this.credentialProvider();this.validateResolvedCredentials(r);const a=n??await this.regionProvider(),{shortDate:o}=ve(t),s=new this.sha256(await this.getSigningKey(r,a,o,i));return s.update(j(e)),D(await s.digest())}async signRequest(e,{signingDate:t=new Date,signableHeaders:n,unsignableHeaders:i,signingRegion:r,signingService:a}={}){const o=await this.credentialProvider();this.validateResolvedCredentials(o);const s=r??await this.regionProvider(),c=pe(e),{longDate:l,shortDate:d}=ve(t),u=se(d,s,a??this.service);c.headers[K]=l,o.sessionToken&&(c.headers[Y]=o.sessionToken);const f=await fe(c,this.sha256);!((e,t)=>{e=e.toLowerCase();for(const n of Object.keys(t))if(e===n.toLowerCase())return!0;return!1})(Q,c.headers)&&this.applyChecksum&&(c.headers[Q]=f);const h=le(c,i,n),m=await this.getSignature(l,u,this.getSigningKey(o,s,d,a),this.createCanonicalRequest(c,h,f));return c.headers[G]=`${ne} Credential=${o.accessKeyId}/${u}, SignedHeaders=${be(h)}, Signature=${m}`,c}createCanonicalRequest(e,t,n){const i=Object.keys(t).sort();return`${e.method}\n${this.getCanonicalPath(e)}\n${(({query:e={}})=>{const t=[],n={};for(const i of Object.keys(e).sort()){if(i.toLowerCase()===Z)continue;t.push(i);const r=e[i];"string"==typeof r?n[i]=`${de(i)}=${de(r)}`:Array.isArray(r)&&(n[i]=r.slice(0).reduce(((e,t)=>e.concat([`${de(i)}=${de(t)}`])),[]).sort().join("&"))}return t.map((e=>n[e])).filter((e=>e)).join("&")})(e)}\n${i.map((e=>`${e}:${t[e]}`)).join("\n")}\n\n${i.join(";")}\n${n}`}async createStringToSign(e,t,n){const i=new this.sha256;i.update(j(n));const r=await i.digest();return`${ne}\n${e}\n${t}\n${D(r)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){const t=[];for(const n of e.split("/"))0!==n?.length&&"."!==n&&(".."===n?t.pop():t.push(n));const n=`${e?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&e?.endsWith("/")?"/":""}`;return encodeURIComponent(n).replace(/%2F/g,"/")}return e}async getSignature(e,t,n,i){const r=await this.createStringToSign(e,t,i),a=new this.sha256(await n);return a.update(j(r)),D(await a.digest())}getSigningKey(e,t,n,i){return(async(e,t,n,i,r)=>{const a=`${n}:${i}:${r}:${D(await ce(e,t.secretAccessKey,t.accessKeyId))}:${t.sessionToken}`;if(a in ae)return ae[a];for(oe.push(a);oe.length>50;)delete ae[oe.shift()];let o=`AWS4${t.secretAccessKey}`;for(const t of[n,i,r,re])o=await ce(e,o,t);return ae[a]=o})(this.sha256,e,n,t,i||this.service)}validateResolvedCredentials(e){if("object"!=typeof e||"string"!=typeof e.accessKeyId||"string"!=typeof e.secretAccessKey)throw new Error("Resolved credential object is not valid")}}const ve=e=>{const t=(n=e,(e=>"number"==typeof e?new Date(1e3*e):"string"==typeof e?Number(e)?new Date(1e3*Number(e)):new Date(e):e)(n).toISOString().replace(/\.\d{3}Z$/,"Z")).replace(/[\-:]/g,"");var n;return{longDate:t,shortDate:t.slice(0,8)}},be=e=>Object.keys(e).sort().join(";"),ye=e=>new Date(Date.now()+e),Se=(e,t)=>{const n=Date.parse(e);return((e,t)=>Math.abs(ye(t).getTime()-e)>=3e5)(n,t)?n-Date.now():t},Ce=e=>m.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,we={name:"awsAuthMiddleware",tags:["SIGNATURE","AWSAUTH"],relation:"after",toMiddleware:"retryMiddleware",override:!0},Me=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),ze=e=>Me.test(e)||e.startsWith("[")&&e.endsWith("]"),ke=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),xe=(e,t=!1)=>{if(!t)return ke.test(e);const n=e.split(".");for(const e of n)if(!xe(e))return!1;return!0},Ve={},He="endpoints";function Ee(e){return"object"!=typeof e||null==e?e:"ref"in e?`$${Ee(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(Ee).join(", ")})`:JSON.stringify(e,null,2)}class Le extends Error{constructor(e){super(e),this.name="EndpointError"}}const Te=(e,t)=>(e=>{const t=e.split("."),n=[];for(const i of t){const t=i.indexOf("[");if(-1!==t){if(i.indexOf("]")!==i.length-1)throw new Le(`Path: '${e}' does not end with ']'`);const r=i.slice(t+1,-1);if(Number.isNaN(parseInt(r)))throw new Le(`Invalid array index: '${r}' in path: '${e}'`);0!==t&&n.push(i.slice(0,t)),n.push(r)}else n.push(i)}return n})(t).reduce(((n,i)=>{if("object"!=typeof n)throw new Le(`Index '${i}' in '${t}' not found in '${JSON.stringify(e)}'`);return Array.isArray(n)?n[parseInt(i)]:n[i]}),e),Ae={[o.HTTP]:80,[o.HTTPS]:443},_e={booleanEquals:(e,t)=>e===t,getAttr:Te,isSet:e=>null!=e,isValidHostLabel:xe,not:e=>!e,parseURL:e=>{const t=(()=>{try{if(e instanceof URL)return e;if("object"==typeof e&&"hostname"in e){const{hostname:t,port:n,protocol:i="",path:r="",query:a={}}=e,o=new URL(`${i}//${t}${n?`:${n}`:""}${r}`);return o.search=Object.entries(a).map((([e,t])=>`${e}=${t}`)).join("&"),o}return new URL(e)}catch(e){return null}})();if(!t)return console.error(`Unable to parse ${JSON.stringify(e)} as a whatwg URL.`),null;const n=t.href,{host:i,hostname:r,pathname:a,protocol:s,search:c}=t;if(c)return null;const l=s.slice(0,-1);if(!Object.values(o).includes(l))return null;const d=ze(r);return{scheme:l,authority:`${i}${n.includes(`${i}:${Ae[l]}`)||"string"==typeof e&&e.includes(`${i}:${Ae[l]}`)?`:${Ae[l]}`:""}`,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:d}},stringEquals:(e,t)=>e===t,substring:(e,t,n,i)=>t>=n||e.lengthencodeURIComponent(e).replace(/[!*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))},Ne=(e,t)=>{const n=[],i={...t.endpointParams,...t.referenceRecord};let r=0;for(;r{if("string"==typeof e)return Ne(e,n);if(e.fn)return Pe(e,n);if(e.ref)return(({ref:e},t)=>({...t.endpointParams,...t.referenceRecord}[e]))(e,n);throw new Le(`'${t}': ${String(e)} is not a string, function or reference.`)},Pe=({fn:e,argv:t},n)=>{const i=t.map((e=>["boolean","number"].includes(typeof e)?e:Ie(e,"arg",n))),r=e.split(".");return r[0]in Ve&&null!=r[1]?Ve[r[0]][r[1]](...i):_e[e](...i)},Oe=({assign:e,...t},n)=>{if(e&&e in n.referenceRecord)throw new Le(`'${e}' is already defined in Reference Record.`);const i=Pe(t,n);return n.logger?.debug?.(He,`evaluateCondition: ${Ee(t)} = ${Ee(i)}`),{result:""===i||!!i,...null!=e&&{toAssign:{name:e,value:i}}}},Re=(e=[],t)=>{const n={};for(const i of e){const{result:e,toAssign:r}=Oe(i,{...t,referenceRecord:{...t.referenceRecord,...n}});if(!e)return{result:e};r&&(n[r.name]=r.value,t.logger?.debug?.(He,`assign: ${r.name} := ${Ee(r.value)}`))}return{result:!0,referenceRecord:n}},De=(e,t)=>Object.entries(e).reduce(((e,[n,i])=>({...e,[n]:i.map((e=>{const i=Ie(e,"Header value entry",t);if("string"!=typeof i)throw new Le(`Header '${n}' value '${i}' is not a string`);return i}))})),{}),Fe=(e,t)=>{if(Array.isArray(e))return e.map((e=>Fe(e,t)));switch(typeof e){case"string":return Ne(e,t);case"object":if(null===e)throw new Le(`Unexpected endpoint property: ${e}`);return Be(e,t);case"boolean":return e;default:throw new Le("Unexpected endpoint property type: "+typeof e)}},Be=(e,t)=>Object.entries(e).reduce(((e,[n,i])=>({...e,[n]:Fe(i,t)})),{}),Ue=(e,t)=>{const n=Ie(e,"Endpoint URL",t);if("string"==typeof n)try{return new URL(n)}catch(e){throw console.error(`Failed to construct URL with ${n}`,e),e}throw new Le("Endpoint URL must be a string, got "+typeof n)},je=(e,t)=>{const{conditions:n,endpoint:i}=e,{result:r,referenceRecord:a}=Re(n,t);if(!r)return;const o={...t,referenceRecord:{...t.referenceRecord,...a}},{url:s,properties:c,headers:l}=i;return t.logger?.debug?.(He,`Resolving endpoint from template: ${Ee(i)}`),{...null!=l&&{headers:De(l,o)},...null!=c&&{properties:Be(c,o)},url:Ue(s,o)}},qe=(e,t)=>{const{conditions:n,error:i}=e,{result:r,referenceRecord:a}=Re(n,t);if(r)throw new Le(Ie(i,"Error",{...t,referenceRecord:{...t.referenceRecord,...a}}))},We=(e,t)=>{const{conditions:n,rules:i}=e,{result:r,referenceRecord:a}=Re(n,t);if(r)return $e(i,{...t,referenceRecord:{...t.referenceRecord,...a}})},$e=(e,t)=>{for(const n of e)if("endpoint"===n.type){const e=je(n,t);if(e)return e}else if("error"===n.type)qe(n,t);else{if("tree"!==n.type)throw new Le(`Unknown endpoint rule: ${n}`);{const e=We(n,t);if(e)return e}}throw new Le("Rules evaluation failed")},Ge=(e,t=!1)=>{if(t){for(const t of e.split("."))if(!Ge(t))return!1;return!0}return!(!xe(e)||e.length<3||e.length>63||e!==e.toLowerCase()||ze(e))};let Ke=JSON.parse('{"partitions":[{"id":"aws","outputs":{"dnsSuffix":"amazonaws.com","dualStackDnsSuffix":"api.aws","implicitGlobalRegion":"us-east-1","name":"aws","supportsDualStack":true,"supportsFIPS":true},"regionRegex":"^(us|eu|ap|sa|ca|me|af|il)\\\\-\\\\w+\\\\-\\\\d+$","regions":{"af-south-1":{"description":"Africa (Cape Town)"},"ap-east-1":{"description":"Asia Pacific (Hong Kong)"},"ap-northeast-1":{"description":"Asia Pacific (Tokyo)"},"ap-northeast-2":{"description":"Asia Pacific (Seoul)"},"ap-northeast-3":{"description":"Asia Pacific (Osaka)"},"ap-south-1":{"description":"Asia Pacific (Mumbai)"},"ap-south-2":{"description":"Asia Pacific (Hyderabad)"},"ap-southeast-1":{"description":"Asia Pacific (Singapore)"},"ap-southeast-2":{"description":"Asia Pacific (Sydney)"},"ap-southeast-3":{"description":"Asia Pacific (Jakarta)"},"ap-southeast-4":{"description":"Asia Pacific (Melbourne)"},"aws-global":{"description":"AWS Standard global region"},"ca-central-1":{"description":"Canada (Central)"},"eu-central-1":{"description":"Europe (Frankfurt)"},"eu-central-2":{"description":"Europe (Zurich)"},"eu-north-1":{"description":"Europe (Stockholm)"},"eu-south-1":{"description":"Europe (Milan)"},"eu-south-2":{"description":"Europe (Spain)"},"eu-west-1":{"description":"Europe (Ireland)"},"eu-west-2":{"description":"Europe (London)"},"eu-west-3":{"description":"Europe (Paris)"},"il-central-1":{"description":"Israel (Tel Aviv)"},"me-central-1":{"description":"Middle East (UAE)"},"me-south-1":{"description":"Middle East (Bahrain)"},"sa-east-1":{"description":"South America (Sao Paulo)"},"us-east-1":{"description":"US East (N. Virginia)"},"us-east-2":{"description":"US East (Ohio)"},"us-west-1":{"description":"US West (N. California)"},"us-west-2":{"description":"US West (Oregon)"}}},{"id":"aws-cn","outputs":{"dnsSuffix":"amazonaws.com.cn","dualStackDnsSuffix":"api.amazonwebservices.com.cn","implicitGlobalRegion":"cn-northwest-1","name":"aws-cn","supportsDualStack":true,"supportsFIPS":true},"regionRegex":"^cn\\\\-\\\\w+\\\\-\\\\d+$","regions":{"aws-cn-global":{"description":"AWS China global region"},"cn-north-1":{"description":"China (Beijing)"},"cn-northwest-1":{"description":"China (Ningxia)"}}},{"id":"aws-us-gov","outputs":{"dnsSuffix":"amazonaws.com","dualStackDnsSuffix":"api.aws","implicitGlobalRegion":"us-gov-west-1","name":"aws-us-gov","supportsDualStack":true,"supportsFIPS":true},"regionRegex":"^us\\\\-gov\\\\-\\\\w+\\\\-\\\\d+$","regions":{"aws-us-gov-global":{"description":"AWS GovCloud (US) global region"},"us-gov-east-1":{"description":"AWS GovCloud (US-East)"},"us-gov-west-1":{"description":"AWS GovCloud (US-West)"}}},{"id":"aws-iso","outputs":{"dnsSuffix":"c2s.ic.gov","dualStackDnsSuffix":"c2s.ic.gov","implicitGlobalRegion":"us-iso-east-1","name":"aws-iso","supportsDualStack":false,"supportsFIPS":true},"regionRegex":"^us\\\\-iso\\\\-\\\\w+\\\\-\\\\d+$","regions":{"aws-iso-global":{"description":"AWS ISO (US) global region"},"us-iso-east-1":{"description":"US ISO East"},"us-iso-west-1":{"description":"US ISO WEST"}}},{"id":"aws-iso-b","outputs":{"dnsSuffix":"sc2s.sgov.gov","dualStackDnsSuffix":"sc2s.sgov.gov","implicitGlobalRegion":"us-isob-east-1","name":"aws-iso-b","supportsDualStack":false,"supportsFIPS":true},"regionRegex":"^us\\\\-isob\\\\-\\\\w+\\\\-\\\\d+$","regions":{"aws-iso-b-global":{"description":"AWS ISOB (US) global region"},"us-isob-east-1":{"description":"US ISOB East (Ohio)"}}},{"id":"aws-iso-e","outputs":{"dnsSuffix":"cloud.adc-e.uk","dualStackDnsSuffix":"cloud.adc-e.uk","implicitGlobalRegion":"eu-isoe-west-1","name":"aws-iso-e","supportsDualStack":false,"supportsFIPS":true},"regionRegex":"^eu\\\\-isoe\\\\-\\\\w+\\\\-\\\\d+$","regions":{}},{"id":"aws-iso-f","outputs":{"dnsSuffix":"csp.hci.ic.gov","dualStackDnsSuffix":"csp.hci.ic.gov","implicitGlobalRegion":"us-isof-south-1","name":"aws-iso-f","supportsDualStack":false,"supportsFIPS":true},"regionRegex":"^us\\\\-isof\\\\-\\\\w+\\\\-\\\\d+$","regions":{}}],"version":"1.1"}');const Je={isVirtualHostableS3Bucket:Ge,parseArn:e=>{const t=e.split(":");if(t.length<6)return null;const[n,i,r,a,o,...s]=t;return"arn"!==n||""===i||""===r||""===s[0]?null:{partition:i,service:r,region:a,accountId:o,resourceId:s[0].includes("/")?s[0].split("/"):s}},partition:e=>{const{partitions:t}=Ke;for(const n of t){const{regions:t,outputs:i}=n;for(const[n,r]of Object.entries(t))if(n===e)return{...i,...r}}for(const n of t){const{regionRegex:t,outputs:i}=n;if(new RegExp(t).test(e))return{...i}}const n=t.find((e=>"aws"===e.id));if(!n)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...n.outputs}}};Ve.aws=Je;const Ze="user-agent",Qe="x-amz-user-agent",Ye=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g,Xe=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g,et=e=>{const t=e[0].split("/").map((e=>e.replace(Ye,"-"))).join("/"),n=e[1]?.replace(Xe,"-"),i=t.indexOf("/"),r=t.substring(0,i);let a=t.substring(i+1);return"api"===r&&(a=a.toLowerCase()),[r,a,n].filter((e=>e&&e.length>0)).reduce(((e,t,n)=>{switch(n){case 0:return t;case 1:return`${e}/${t}`;default:return`${e}#${t}`}}),"")},tt={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0};var nt;!function(e){e.ENV="env",e.CONFIG="shared config entry"}(nt||(nt={}));const it=e=>"string"==typeof e&&(e.startsWith("fips-")||e.endsWith("-fips")),rt=e=>it(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,at="content-length",ot={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},st=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,ct=/(\d+\.){3}\d+/,lt=/\.\./,dt=(e,t,n)=>{const i=async()=>{const i=n[e]??n[t];return"function"==typeof i?i():i};return"endpoint"===e||"endpoint"===t?async()=>{const e=await i();if(e&&"object"==typeof e){if("url"in e)return e.url.href;if("hostname"in e){const{protocol:t,hostname:n,port:i,path:r}=e;return`${t}//${n}${i?":"+i:""}${r}`}}return e}:i},ut=e=>{if("string"==typeof e)return ut(new URL(e));const{hostname:t,pathname:n,port:i,protocol:r,search:a}=e;let o;return a&&(o=function(e){const t={};if(e=e.replace(/^\?/,""))for(const n of e.split("&")){let[e,i=null]=n.split("=");e=decodeURIComponent(e),i&&(i=decodeURIComponent(i)),e in t?Array.isArray(t[e])?t[e].push(i):t[e]=[t[e],i]:t[e]=i}return t}(a)),{hostname:t,port:i?parseInt(i):void 0,protocol:r,path:n,query:o}},ft=e=>"object"==typeof e?"url"in e?ut(e.url):e:ut(e),ht={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},mt={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function pt(e,t,n){return{applyToStack:i=>{i.add(((e,t)=>(n,i)=>async i=>{const{response:r}=await n(i);try{return{response:r,output:await t(r,e)}}catch(e){if(Object.defineProperty(e,"$response",{value:r}),!("$metadata"in e)){const t="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";e.message+="\n "+t}throw e}})(e,n),ht),i.add(((e,t)=>(n,i)=>async r=>{const a=i.endpointV2?.url&&e.urlParser?async()=>e.urlParser(i.endpointV2.url):e.endpoint;if(!a)throw new Error("No valid endpoint provider available.");const o=await t(r.input,{...e,endpoint:a});return n({...r,request:o})})(e,t),mt)}}}const gt={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:mt.name},vt=(e,t)=>({applyToStack:n=>{n.addRelativeTo((({config:e,instructions:t})=>(n,i)=>async r=>{const a=await(async(e,t,n,i)=>{if(!n.endpoint){const e=await(async e=>{})(n.serviceId);e&&(n.endpoint=()=>Promise.resolve(ft(e)))}const r=await(async(e,t,n)=>{const i={},r=t?.getEndpointParameterInstructions?.()||{};for(const[t,a]of Object.entries(r))switch(a.type){case"staticContextParams":i[t]=a.value;break;case"contextParams":i[t]=e[a.name];break;case"clientContextParams":case"builtInParams":i[t]=await dt(a.name,t,n)();break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(a))}return 0===Object.keys(r).length&&Object.assign(i,n),"s3"===String(n.serviceId).toLowerCase()&&await(async e=>{const t=e?.Bucket||"";if("string"==typeof e.Bucket&&(e.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),(e=>{const[t,n,i,r,a,o]=e.split(":"),s="arn"===t&&e.split(":").length>=6,c=5===[t,n,i,a,o].filter(Boolean).length;if(s&&!c)throw new Error(`Invalid ARN: ${e} was an invalid ARN.`);return!!("arn"===t&&n&&i&&a&&o)})(t)){if(!0===e.ForcePathStyle)throw new Error("Path-style addressing cannot be used with ARN buckets")}else n=t,(!st.test(n)||ct.test(n)||lt.test(n)||-1!==t.indexOf(".")&&!String(e.Endpoint).startsWith("http:")||t.toLowerCase()!==t||t.length<3)&&(e.ForcePathStyle=!0);var n;return e.DisableMultiRegionAccessPoints&&(e.disableMultiRegionAccessPoints=!0,e.DisableMRAP=!0),e})(i),i})(e,t,n);if("function"!=typeof n.endpointProvider)throw new Error("config.endpointProvider is not set.");return n.endpointProvider(r,i)})(r.input,{getEndpointParameterInstructions:()=>t},{...e},i);i.endpointV2=a,i.authSchemes=a.properties?.authSchemes;const o=i.authSchemes?.[0];if(o){i.signing_region=o.signingRegion,i.signing_service=o.signingName;const e=(e=>e[d]||(e[d]={}))(i),t=e?.selectedHttpAuthScheme?.httpAuthOption;t&&(t.signingProperties=Object.assign(t.signingProperties||{},{signing_region:o.signingRegion,signingRegion:o.signingRegion,signing_service:o.signingName,signingName:o.signingName,signingRegionSet:o.signingRegionSet},o.properties))}return n({...r})})({config:e,instructions:t}),gt)}});var bt;!function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"}(bt||(bt={}));const yt=bt.STANDARD,St=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Ct=["TimeoutError","RequestTimeout","RequestTimeoutException"],wt=[500,502,503,504],Mt=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],zt=e=>429===e.$metadata?.httpStatusCode||St.includes(e.name)||1==e.$retryable?.throttling,kt=e=>Ct.includes(e.name)||Mt.includes(e?.code||"")||wt.includes(e.$metadata?.httpStatusCode||0);class xt{constructor(e){this.currentCapacity=0,this.enabled=!1,this.lastMaxRate=0,this.measuredTxRate=0,this.requestCount=0,this.lastTimestamp=0,this.timeWindow=0,this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8;const t=this.getCurrentTimeInSeconds();this.lastThrottleTime=t,this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1e3}async getSendToken(){return this.acquireTokenBucket(1)}async acquireTokenBucket(e){if(this.enabled){if(this.refillTokenBucket(),e>this.currentCapacity){const t=(e-this.currentCapacity)/this.fillRate*1e3;await new Promise((e=>setTimeout(e,t)))}this.currentCapacity=this.currentCapacity-e}}refillTokenBucket(){const e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp)return void(this.lastTimestamp=e);const t=(e-this.lastTimestamp)*this.fillRate;this.currentCapacity=Math.min(this.maxCapacity,this.currentCapacity+t),this.lastTimestamp=e}updateClientSendingRate(e){let t;if(this.updateMeasuredRate(),zt(e)){const e=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=e,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(e),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());const n=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(n)}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.currentCapacity=Math.min(this.currentCapacity,this.maxCapacity)}updateMeasuredRate(){const e=this.getCurrentTimeInSeconds(),t=Math.floor(2*e)/2;if(this.requestCount++,t>this.lastTxRateBucket){const e=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(e*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(e){return parseFloat(e.toFixed(8))}}const Vt=({retryDelay:e,retryCount:t,retryCost:n})=>({getRetryCount:()=>t,getRetryDelay:()=>Math.min(2e4,e),getRetryCost:()=>n});class Ht{constructor(e){this.maxAttempts=e,this.mode=bt.STANDARD,this.capacity=500,this.retryBackoffStrategy=(()=>{let e=100;return{computeNextBackoffDelay:t=>Math.floor(Math.min(2e4,Math.random()*2**t*e)),setDelayBase:t=>{e=t}}})(),this.maxAttemptsProvider="function"==typeof e?e:async()=>e}async acquireInitialRetryToken(e){return Vt({retryDelay:100,retryCount:0})}async refreshRetryTokenForRetry(e,t){const n=await this.getMaxAttempts();if(this.shouldRetry(e,t,n)){const n=t.errorType;this.retryBackoffStrategy.setDelayBase("THROTTLING"===n?500:100);const i=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount()),r=t.retryAfterHint?Math.max(t.retryAfterHint.getTime()-Date.now()||0,i):i,a=this.getCapacityCost(n);return this.capacity-=a,Vt({retryDelay:r,retryCount:e.getRetryCount()+1,retryCost:a})}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.max(500,this.capacity+(e.getRetryCost()??1))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(e){return console.warn("Max attempts provider could not resolve. Using default of 3"),3}}shouldRetry(e,t,n){return e.getRetryCount()+1=this.getCapacityCost(t.errorType)&&this.isRetryableError(t.errorType)}getCapacityCost(e){return"TRANSIENT"===e?10:5}isRetryableError(e){return"THROTTLING"===e||"TRANSIENT"===e}}class Et{constructor(e,t){this.maxAttemptsProvider=e,this.mode=bt.ADAPTIVE;const{rateLimiter:n}=t??{};this.rateLimiter=n??new xt,this.standardRetryStrategy=new Ht(e)}async acquireInitialRetryToken(e){return await this.rateLimiter.getSendToken(),this.standardRetryStrategy.acquireInitialRetryToken(e)}async refreshRetryTokenForRetry(e,t){return this.rateLimiter.updateClientSendingRate(t),this.standardRetryStrategy.refreshRetryTokenForRetry(e,t)}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}}var Lt,Tt=new Uint8Array(16);function At(){if(!Lt&&!(Lt="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Lt(Tt)}const _t=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var Nt=[],It=0;It<256;++It)Nt.push((It+256).toString(16).substr(1));const Pt=function(e,t,n){var i=(e=e||{}).random||(e.rng||At)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){n=n||0;for(var r=0;r<16;++r)t[n+r]=i[r];return t}return function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(Nt[e[t+0]]+Nt[e[t+1]]+Nt[e[t+2]]+Nt[e[t+3]]+"-"+Nt[e[t+4]]+Nt[e[t+5]]+"-"+Nt[e[t+6]]+Nt[e[t+7]]+"-"+Nt[e[t+8]]+Nt[e[t+9]]+"-"+Nt[e[t+10]]+Nt[e[t+11]]+Nt[e[t+12]]+Nt[e[t+13]]+Nt[e[t+14]]+Nt[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&_t.test(e)}(n))throw TypeError("Stringified UUID is invalid");return n}(i)},Ot=e=>{const t={errorType:Rt(e)},n=Ft(e.$response);return n&&(t.retryAfterHint=n),t},Rt=e=>zt(e)?"THROTTLING":kt(e)?"TRANSIENT":(e=>{if(void 0!==e.$metadata?.httpStatusCode){const t=e.$metadata.httpStatusCode;return 500<=t&&t<=599&&!kt(e)}return!1})(e)?"SERVER_ERROR":"CLIENT_ERROR",Dt={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},Ft=e=>{if(!m.isInstance(e))return;const t=Object.keys(e.headers).find((e=>"retry-after"===e.toLowerCase()));if(!t)return;const n=e.headers[t],i=Number(n);return Number.isNaN(i)?new Date(n):new Date(1e3*i)};class Bt{trace(){}debug(){}info(){}warn(){}error(){}}const Ut=(e,t)=>{const n=[];if(e&&n.push(e),t)for(const e of t)n.push(e);return n},jt=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,qt=()=>{let e=[],t=[],n=!1;const i=new Set,r=n=>(e.forEach((e=>{n.add(e.middleware,{...e})})),t.forEach((e=>{n.addRelativeTo(e.middleware,{...e})})),n.identifyOnResolve?.(s.identifyOnResolve()),n),a=e=>{const t=[];return e.before.forEach((e=>{0===e.before.length&&0===e.after.length?t.push(e):t.push(...a(e))})),t.push(e),e.after.reverse().forEach((e=>{0===e.before.length&&0===e.after.length?t.push(e):t.push(...a(e))})),t},o=(n=!1)=>{const i=[],r=[],o={};e.forEach((e=>{const t={...e,before:[],after:[]};for(const e of Ut(t.name,t.aliases))o[e]=t;i.push(t)})),t.forEach((e=>{const t={...e,before:[],after:[]};for(const e of Ut(t.name,t.aliases))o[e]=t;r.push(t)})),r.forEach((e=>{if(e.toMiddleware){const t=o[e.toMiddleware];if(void 0===t){if(n)return;throw new Error(`${e.toMiddleware} is not found when adding ${jt(e.name,e.aliases)} middleware ${e.relation} ${e.toMiddleware}`)}"after"===e.relation&&t.after.push(e),"before"===e.relation&&t.before.push(e)}}));const s=(c=i,c.sort(((e,t)=>Wt[t.step]-Wt[e.step]||$t[t.priority||"normal"]-$t[e.priority||"normal"]))).map(a).reduce(((e,t)=>(e.push(...t),e)),[]);var c;return s},s={add:(t,n={})=>{const{name:r,override:a,aliases:o}=n,s={step:"initialize",priority:"normal",middleware:t,...n},c=Ut(r,o);if(c.length>0){if(c.some((e=>i.has(e)))){if(!a)throw new Error(`Duplicate middleware name '${jt(r,o)}'`);for(const t of c){const n=e.findIndex((e=>e.name===t||e.aliases?.some((e=>e===t))));if(-1===n)continue;const i=e[n];if(i.step!==s.step||s.priority!==i.priority)throw new Error(`"${jt(i.name,i.aliases)}" middleware with ${i.priority} priority in ${i.step} step cannot be overridden by "${jt(r,o)}" middleware with ${s.priority} priority in ${s.step} step.`);e.splice(n,1)}}for(const e of c)i.add(e)}e.push(s)},addRelativeTo:(e,n)=>{const{name:r,override:a,aliases:o}=n,s={middleware:e,...n},c=Ut(r,o);if(c.length>0){if(c.some((e=>i.has(e)))){if(!a)throw new Error(`Duplicate middleware name '${jt(r,o)}'`);for(const e of c){const n=t.findIndex((t=>t.name===e||t.aliases?.some((t=>t===e))));if(-1===n)continue;const i=t[n];if(i.toMiddleware!==s.toMiddleware||i.relation!==s.relation)throw new Error(`"${jt(i.name,i.aliases)}" middleware ${i.relation} "${i.toMiddleware}" middleware cannot be overridden by "${jt(r,o)}" middleware ${s.relation} "${s.toMiddleware}" middleware.`);t.splice(n,1)}}for(const e of c)i.add(e)}t.push(s)},clone:()=>r(qt()),use:e=>{e.applyToStack(s)},remove:n=>"string"==typeof n?(n=>{let r=!1;const a=e=>{const t=Ut(e.name,e.aliases);if(t.includes(n)){r=!0;for(const e of t)i.delete(e);return!1}return!0};return e=e.filter(a),t=t.filter(a),r})(n):(n=>{let r=!1;const a=e=>{if(e.middleware===n){r=!0;for(const t of Ut(e.name,e.aliases))i.delete(t);return!1}return!0};return e=e.filter(a),t=t.filter(a),r})(n),removeByTag:n=>{let r=!1;const a=e=>{const{tags:t,name:a,aliases:o}=e;if(t&&t.includes(n)){const e=Ut(a,o);for(const t of e)i.delete(t);return r=!0,!1}return!0};return e=e.filter(a),t=t.filter(a),r},concat:e=>{const t=r(qt());return t.use(e),t.identifyOnResolve(n||t.identifyOnResolve()||(e.identifyOnResolve?.()??!1)),t},applyToStack:r,identify:()=>o(!0).map((e=>{const t=e.step??e.relation+" "+e.toMiddleware;return jt(e.name,e.aliases)+" - "+t})),identifyOnResolve:e=>("boolean"==typeof e&&(n=e),n),resolve:(e,t)=>{for(const n of o().map((e=>e.middleware)).reverse())e=n(e,t);return n&&console.log(s.identify()),e}};return s},Wt={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},$t={high:3,normal:2,low:1};class Gt{constructor(e){this.middlewareStack=qt(),this.config=e}send(e,t,n){const i="function"!=typeof t?t:void 0,r="function"==typeof t?t:n,a=e.resolveMiddleware(this.middlewareStack,this.config,i);if(!r)return a(e).then((e=>e.output));a(e).then((e=>r(null,e.output)),(e=>r(e))).catch((()=>{}))}destroy(){this.config.requestHandler.destroy&&this.config.requestHandler.destroy()}}const Kt={},Jt=new Array(64);for(let e=0,t="A".charCodeAt(0),n="Z".charCodeAt(0);e+t<=n;e++){const n=String.fromCharCode(e+t);Kt[n]=e,Jt[e]=n}for(let e=0,t="a".charCodeAt(0),n="z".charCodeAt(0);e+t<=n;e++){const n=String.fromCharCode(e+t),i=e+26;Kt[n]=i,Jt[i]=n}for(let e=0;e<10;e++){Kt[e.toString(10)]=e+52;const t=e.toString(10),n=e+52;Kt[t]=n,Jt[n]=t}Kt["+"]=62,Jt[62]="+",Kt["/"]=63,Jt[63]="/";const Zt=e=>{let t=e.length/4*3;"=="===e.slice(-2)?t-=2:"="===e.slice(-1)&&t--;const n=new ArrayBuffer(t),i=new DataView(n);for(let t=0;t>=6;const a=t/4*3;n>>=r%8;const o=Math.floor(r/8);for(let e=0;e>t)}}return new Uint8Array(n)};function Qt(e){let t="";for(let n=0;n>n]}t+="==".slice(0,4-a)}return t}class Yt extends Uint8Array{static fromString(e,t="utf-8"){if("string"==typeof e)return function(e,t){return"base64"===t?Yt.mutate(Zt(e)):Yt.mutate(U(e))}(e,t);throw new Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,Yt.prototype),e}transformToString(e="utf-8"){return function(e,t="utf-8"){return"base64"===t?Qt(e):B(e)}(this,e)}}function Xt(e=0){return new Promise(((t,n)=>{e&&setTimeout((()=>{const t=new Error(`Request did not complete within ${e} ms`);t.name="TimeoutError",n(t)}),e)}))}const en=Boolean("undefined"!=typeof Request&&"keepalive"in new Request("https://[::1]"));class tn{constructor(e){"function"==typeof e?this.configProvider=e().then((e=>e||{})):(this.config=e??{},this.configProvider=Promise.resolve(this.config))}destroy(){}async handle(e,{abortSignal:t}={}){this.config||(this.config=await this.configProvider);const n=this.config.requestTimeout,i=!0===this.config.keepAlive;if(t?.aborted){const e=new Error("Request aborted");return e.name="AbortError",Promise.reject(e)}let r=e.path;const a=function(e){const t=[];for(let n of Object.keys(e).sort()){const i=e[n];if(n=de(n),Array.isArray(i))for(let e=0,r=i.length;e{const t=e.headers,n={};for(const e of t.entries())n[e[0]]=e[1];return null!=e.body?{response:new m({headers:n,reason:e.statusText,statusCode:e.status,body:e.body})}:e.blob().then((t=>({response:new m({headers:n,reason:e.statusText,statusCode:e.status,body:t})})))})),Xt(n)];return t&&f.push(new Promise(((e,n)=>{t.onabort=()=>{const e=new Error("Request aborted");e.name="AbortError",n(e)}}))),Promise.race(f)}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then((n=>(n[e]=t,n)))}httpHandlerConfigs(){return this.config??{}}}const nn=e=>"function"==typeof Blob&&e instanceof Blob?async function(e){const t=await function(e){return new Promise(((t,n)=>{const i=new FileReader;i.onloadend=()=>{if(2!==i.readyState)return n(new Error("Reader aborted too early"));const e=i.result??"",r=e.indexOf(","),a=r>-1?r+1:e.length;t(e.substring(a))},i.onabort=()=>n(new Error("Read aborted")),i.onerror=()=>n(i.error),i.readAsDataURL(e)}))}(e),n=Zt(t);return new Uint8Array(n)}(e):async function(e){let t=new Uint8Array(0);const n=e.getReader();let i=!1;for(;!i;){const{done:e,value:r}=await n.read();if(r){const e=t;t=new Uint8Array(e.length+r.length),t.set(e),t.set(r,e.length)}i=e}return t}(e),rn={},an={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();1===t.length&&(t=`0${t}`),rn[e]=t,an[t]=e}const on=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return Yt.mutate(e);if(!e)return Yt.mutate(new Uint8Array);const n=t.streamCollector(e);return Yt.mutate(await n)};class sn{constructor(){this.middlewareStack=qt()}}const cn="***SensitiveInformation***",ln=e=>{if(null!=e){if("number"==typeof e){if(0!==e&&1!==e||gn.warn(pn(`Expected boolean, got ${typeof e}: ${e}`)),0===e)return!1;if(1===e)return!0}if("string"==typeof e){const t=e.toLowerCase();if("false"!==t&&"true"!==t||gn.warn(pn(`Expected boolean, got ${typeof e}: ${e}`)),"false"===t)return!1;if("true"===t)return!0}if("boolean"==typeof e)return e;throw new TypeError(`Expected boolean, got ${typeof e}: ${e}`)}},dn=e=>{if(null!=e){if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&gn.warn(pn(`Expected number but observed string: ${e}`)),t}if("number"==typeof e)return e;throw new TypeError(`Expected number, got ${typeof e}: ${e}`)}},un=(Math.ceil(2**127*(2-2**-23)),(e,t)=>{if(null==e){if(t)throw new TypeError(`Expected a non-null value for ${t}`);throw new TypeError("Expected a non-null value")}return e}),fn=e=>{if(null==e)return;if("object"==typeof e&&!Array.isArray(e))return e;const t=Array.isArray(e)?"array":typeof e;throw new TypeError(`Expected object, got ${t}: ${e}`)},hn=e=>{if(null!=e){if("string"==typeof e)return e;if(["boolean","number","bigint"].includes(typeof e))return gn.warn(pn(`Expected string, got ${typeof e}: ${e}`)),String(e);throw new TypeError(`Expected string, got ${typeof e}: ${e}`)}},mn=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,pn=e=>String(new TypeError(e).stack||e).split("\n").slice(0,5).filter((e=>!e.includes("stackTraceWarning"))).join("\n"),gn={warn:console.warn},vn=e=>{if(null==e)return;let t;if("number"==typeof e)t=e;else{if("string"!=typeof e)throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");t=(e=>dn("string"==typeof e?(e=>{const t=e.match(mn);if(null===t||t[0].length!==e.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(e)})(e):e))(e)}if(Number.isNaN(t)||t===1/0||t===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(1e3*t))};class bn extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,bn.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}}const yn=(e,t={})=>{Object.entries(t).filter((([,e])=>void 0!==e)).forEach((([t,n])=>{null!=e[t]&&""!==e[t]||(e[t]=n)}));const n=e.message||e.Message||"UnknownError";return e.message=n,delete e.Message,e},Sn=e=>{switch(e){case"standard":case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}},Cn=e=>{const t=[];for(const n in s){const i=s[n];void 0!==e[i]&&t.push({algorithmId:()=>i,checksumConstructor:()=>e[i]})}return{_checksumAlgorithms:t,addChecksumAlgorithm(e){this._checksumAlgorithms.push(e)},checksumAlgorithms(){return this._checksumAlgorithms}}},wn=e=>{const t={};return e.checksumAlgorithms().forEach((e=>{t[e.algorithmId()]=e.checksumConstructor()})),t},Mn=e=>{let t=e.retryStrategy;return{setRetryStrategy(e){t=e},retryStrategy:()=>t}},zn=e=>{const t={};return t.retryStrategy=e.retryStrategy(),t},kn=e=>({...Cn(e),...Mn(e)}),xn=function(){const e=Object.getPrototypeOf(this).constructor,t=new(Function.bind.apply(String,[null,...arguments]));return Object.setPrototypeOf(t,e.prototype),t};function Vn(e,t,n){let i,r,a;if(void 0===t&&void 0===n)i={},a=e;else{if(i=e,"function"==typeof t)return r=t,a=n,En(i,r,a);a=t}for(const e of Object.keys(a))Array.isArray(a[e])?Ln(i,null,a,e):i[e]=a[e];return i}xn.prototype=Object.create(String.prototype,{constructor:{value:xn,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(xn,String);const Hn=(e,t)=>{const n={};for(const i in t)Ln(n,e,t,i);return n},En=(e,t,n)=>Vn(e,Object.entries(n).reduce(((e,[n,i])=>(Array.isArray(i)?e[n]=i:e[n]="function"==typeof i?[t,i()]:[t,i],e)),{})),Ln=(e,t,n,i)=>{if(null!==t){let r=n[i];"function"==typeof r&&(r=[,r]);const[a=Tn,o=An,s=i]=r;return void(("function"==typeof a&&a(t[s])||"function"!=typeof a&&a)&&(e[i]=o(t[s])))}let[r,a]=n[i];if("function"==typeof a){let t;const n=void 0===r&&null!=(t=a()),o="function"==typeof r&&!!r(void 0)||"function"!=typeof r&&!!r;n?e[i]=t:o&&(e[i]=a())}else{const t=void 0===r&&null!=a,n="function"==typeof r&&!!r(a)||"function"!=typeof r&&!!r;(t||n)&&(e[i]=a)}},Tn=e=>null!=e,An=e=>e;function _n(e){return encodeURIComponent(e).replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}const Nn=(e,t,n,i,r,a)=>{if(null==t||void 0===t[n])throw new Error("No value provided for input HTTP label: "+n+".");{const t=i();if(t.length<=0)throw new Error("Empty value provided for input HTTP label: "+n+".");e=e.replace(r,a?t.split("/").map((e=>_n(e))).join("/"):_n(t))}return e},In=e=>{if(null==e)return{};if(Array.isArray(e))return e.filter((e=>null!=e));if("object"==typeof e){const t={};for(const n of Object.keys(e))null!=e[n]&&(t[n]=In(e[n]));return t}return e};var Pn=n(6634),On=n(4499),Rn=n.n(On);const Dn=({serviceId:e,clientVersion:t})=>async()=>{const n="undefined"!=typeof window&&window?.navigator?.userAgent?Rn().parse(window.navigator.userAgent):void 0,i=[["aws-sdk-js",t],["ua","2.0"],[`os/${n?.os?.name||"other"}`,n?.os?.version],["lang/js"],["md/browser",`${n?.browser?.name??"unknown"}_${n?.browser?.version??"unknown"}`]];return e&&i.push([`api/${e}`,t]),i},Fn=e=>{if("string"==typeof e){let t=e.length;for(let n=t-1;n>=0;n--){const i=e.charCodeAt(n);i>127&&i<=2047?t++:i>2047&&i<=65535&&(t+=2),i>=56320&&i<=57343&&n--}return t}if("number"==typeof e.byteLength)return e.byteLength;if("number"==typeof e.size)return e.size;throw new Error(`Body Length computation failed for ${e}`)},Bn="required",Un="fn",jn="argv",qn="ref",Wn="isSet",$n="booleanEquals",Gn="error",Kn="endpoint",Jn="tree",Zn="PartitionResult",Qn={[Bn]:!1,type:"String"},Yn={[Bn]:!0,default:!1,type:"Boolean"},Xn={[qn]:"Endpoint"},ei={[Un]:$n,[jn]:[{[qn]:"UseFIPS"},!0]},ti={[Un]:$n,[jn]:[{[qn]:"UseDualStack"},!0]},ni={},ii={[Un]:"getAttr",[jn]:[{[qn]:Zn},"supportsFIPS"]},ri={[Un]:$n,[jn]:[!0,{[Un]:"getAttr",[jn]:[{[qn]:Zn},"supportsDualStack"]}]},ai=[ei],oi=[ti],si=[{[qn]:"Region"}],ci={version:"1.0",parameters:{Region:Qn,UseDualStack:Yn,UseFIPS:Yn,Endpoint:Qn},rules:[{conditions:[{[Un]:Wn,[jn]:[Xn]}],rules:[{conditions:ai,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:Gn},{conditions:oi,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:Gn},{endpoint:{url:Xn,properties:ni,headers:ni},type:Kn}],type:Jn},{conditions:[{[Un]:Wn,[jn]:si}],rules:[{conditions:[{[Un]:"aws.partition",[jn]:si,assign:Zn}],rules:[{conditions:[ei,ti],rules:[{conditions:[{[Un]:$n,[jn]:[!0,ii]},ri],rules:[{endpoint:{url:"https://messaging-chime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:ni,headers:ni},type:Kn}],type:Jn},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:Gn}],type:Jn},{conditions:ai,rules:[{conditions:[{[Un]:$n,[jn]:[ii,!0]}],rules:[{endpoint:{url:"https://messaging-chime-fips.{Region}.{PartitionResult#dnsSuffix}",properties:ni,headers:ni},type:Kn}],type:Jn},{error:"FIPS is enabled but this partition does not support FIPS",type:Gn}],type:Jn},{conditions:oi,rules:[{conditions:[ri],rules:[{endpoint:{url:"https://messaging-chime.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:ni,headers:ni},type:Kn}],type:Jn},{error:"DualStack is enabled but this partition does not support DualStack",type:Gn}],type:Jn},{endpoint:{url:"https://messaging-chime.{Region}.{PartitionResult#dnsSuffix}",properties:ni,headers:ni},type:Kn}],type:Jn}],type:Jn},{error:"Invalid Configuration: Missing Region",type:Gn}]},li=(e,t={})=>((e,t)=>{const{endpointParams:n,logger:i}=t,{parameters:r,rules:a}=e;t.logger?.debug?.(`${He} Initial EndpointParams: ${Ee(n)}`);const o=Object.entries(r).filter((([,e])=>null!=e.default)).map((([e,t])=>[e,t.default]));if(o.length>0)for(const[e,t]of o)n[e]=n[e]??t;const s=Object.entries(r).filter((([,e])=>e.required)).map((([e])=>e));for(const e of s)if(null==n[e])throw new Le(`Missing required parameter: '${e}'`);const c=$e(a,{endpointParams:n,logger:i,referenceRecord:{}});if(t.endpointParams?.Endpoint)try{const e=new URL(t.endpointParams.Endpoint),{protocol:n,port:i}=e;c.url.protocol=n,c.url.port=i}catch(e){}return t.logger?.debug?.(`${He} Resolved endpoint: ${Ee(c)}`),c})(ci,{endpointParams:e,logger:t.logger}),di=["in-region","cross-region","mobile","standard","legacy"],ui=e=>{let t=async()=>{if(void 0===e.region)throw new Error("Region is missing from runtimeConfig");const t=e.region;return"string"==typeof t?t:t()};return{setRegion(e){t=e},region:()=>t}};class fi extends Gt{constructor(...[e]){var t;const n=(e=>{const{region:t,useFipsEndpoint:n}=e;if(!t)throw new Error("Region is missing");return{...e,region:async()=>{if("string"==typeof t)return rt(t);const e=await t();return rt(e)},useFipsEndpoint:async()=>{const e="string"==typeof t?t:await t();return!!it(e)||("function"!=typeof n?Promise.resolve(!!n):n())}}})((t=(e=>{const t=(({defaultsMode:e}={})=>y((async()=>{const t="function"==typeof e?await e():e;switch(t?.toLowerCase()){case"auto":return Promise.resolve((()=>{const e="undefined"!=typeof window&&window?.navigator?.userAgent?Rn().parse(window.navigator.userAgent):void 0,t=e?.platform?.type;return"tablet"===t||"mobile"===t})()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(t?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${di.join(", ")}, got ${t}`)}})))(e),n=()=>t().then(Sn),i=(e=>({apiVersion:"2021-05-15",base64Decoder:e?.base64Decoder??Zt,base64Encoder:e?.base64Encoder??Qt,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??li,extensions:e?.extensions??[],logger:e?.logger??new Bt,serviceId:e?.serviceId??"Chime SDK Messaging",urlParser:e?.urlParser??ut,utf8Decoder:e?.utf8Decoder??U,utf8Encoder:e?.utf8Encoder??B}))(e);return{...i,...e,runtime:"browser",defaultsMode:t,bodyLengthChecker:e?.bodyLengthChecker??Fn,credentialDefaultProvider:e?.credentialDefaultProvider??(e=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:e?.defaultUserAgentProvider??Dn({serviceId:i.serviceId,clientVersion:"3.465.0"}),maxAttempts:e?.maxAttempts??3,region:e?.region??(()=>Promise.reject("Region is missing")),requestHandler:e?.requestHandler??new tn(n),retryMode:e?.retryMode??(async()=>(await n()).retryMode||yt),sha256:e?.sha256??Pn.Sha256,streamCollector:e?.streamCollector??nn,useDualstackEndpoint:e?.useDualstackEndpoint??(()=>Promise.resolve(!1)),useFipsEndpoint:e?.useFipsEndpoint??(()=>Promise.resolve(!1))}})(e||{}),{...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"chime"})),r=(e=>{const t=e.tls??!0,{endpoint:n}=e,i=null!=n?async()=>ft(await F(n)()):void 0,r=!!n;return{...e,endpoint:i,tls:t,isCustomEndpoint:r,useDualstackEndpoint:F(e.useDualstackEndpoint??!1),useFipsEndpoint:F(e.useFipsEndpoint??!1)}})(n),a=(e=>{const{retryStrategy:t}=e,n=F(e.maxAttempts??3);return{...e,maxAttempts:n,retryStrategy:async()=>t||(await F(e.retryMode)()===bt.ADAPTIVE?new Et(n):new Ht(n))}})(r),o=(e=>{const t=e.credentials?"function"==typeof(a=e.credentials)?y(a,(e=>void 0!==e.expiration&&e.expiration.getTime()-Date.now()<3e5),(e=>void 0!==e.expiration)):F(a):e.credentialDefaultProvider(e),{signingEscapePath:n=!0,systemClockOffset:i=e.systemClockOffset||0,sha256:r}=e;var a;let o;return o=e.signer?F(e.signer):e.regionInfoProvider?()=>F(e.region)().then((async t=>[await e.regionInfoProvider(t,{useFipsEndpoint:await e.useFipsEndpoint(),useDualstackEndpoint:await e.useDualstackEndpoint()})||{},t])).then((([i,a])=>{const{signingRegion:o,signingService:s}=i;e.signingRegion=e.signingRegion||o||a,e.signingName=e.signingName||s||e.serviceId;const c={...e,credentials:t,region:e.signingRegion,service:e.signingName,sha256:r,uriEscapePath:n};return new(e.signerConstructor||ge)(c)})):async i=>{const a=(i=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await F(e.region)(),properties:{}},i)).signingRegion,o=i.signingName;e.signingRegion=e.signingRegion||a,e.signingName=e.signingName||o||e.serviceId;const s={...e,credentials:t,region:e.signingRegion,service:e.signingName,sha256:r,uriEscapePath:n};return new(e.signerConstructor||ge)(s)},{...e,systemClockOffset:i,signingEscapePath:n,credentials:t,signer:o}})(a);var s;const c=((e,t)=>{const n={...ui(e),...kn(e),...i(e)};return t.forEach((e=>e.configure(n))),{...e,...(o=n,{region:o.region()}),...(a=n,{...wn(a),...zn(a)}),...(r=n,{httpHandler:r.httpHandler()})};var r,a,o})((s=o,{...s,customUserAgent:"string"==typeof s.customUserAgent?[[s.customUserAgent]]:s.customUserAgent}),e?.extensions||[]);var l;super(c),this.config=c,this.middlewareStack.use((e=>({applyToStack:t=>{t.add((e=>(t,n)=>async i=>{let r=await e.retryStrategy();const a=await e.maxAttempts();if(!(e=>void 0!==e.acquireInitialRetryToken&&void 0!==e.refreshRetryTokenForRetry&&void 0!==e.recordSuccess)(r))return r?.mode&&(n.userAgent=[...n.userAgent||[],["cfg/retry-mode",r.mode]]),r.retry(t,i);{let e=await r.acquireInitialRetryToken(n.partition_id),s=new Error,c=0,l=0;const{request:d}=i;for(h.isInstance(d)&&(d.headers["amz-sdk-invocation-id"]=Pt());;)try{h.isInstance(d)&&(d.headers["amz-sdk-request"]=`attempt=${c+1}; max=${a}`);const{response:n,output:o}=await t(i);return r.recordSuccess(e),o.$metadata.attempts=c+1,o.$metadata.totalRetryDelay=l,{response:n,output:o}}catch(t){const n=Ot(t);s=(o=t)instanceof Error?o:o instanceof Object?Object.assign(new Error,o):"string"==typeof o?new Error(o):new Error(`AWS SDK error wrapper for ${o}`);try{e=await r.refreshRetryTokenForRetry(e,n)}catch(e){throw s.$metadata||(s.$metadata={}),s.$metadata.attempts=c+1,s.$metadata.totalRetryDelay=l,s}c=e.getRetryCount();const i=e.getRetryDelay();l+=i,await new Promise((e=>setTimeout(e,i)))}}var o})(e),Dt)}}))(this.config)),this.middlewareStack.use((e=>({applyToStack:t=>{var n;t.add((n=e.bodyLengthChecker,e=>async t=>{const i=t.request;if(h.isInstance(i)){const{body:e,headers:t}=i;if(e&&-1===Object.keys(t).map((e=>e.toLowerCase())).indexOf(at))try{const t=n(e);i.headers={...i.headers,[at]:String(t)}}catch(e){}}return e({...t,request:i})}),ot)}}))(this.config)),this.middlewareStack.use((e=>({applyToStack:t=>{t.add((e=>t=>async n=>{if(!h.isInstance(n.request))return t(n);const{request:i}=n,{handlerProtocol:r=""}=e.requestHandler.metadata||{};if(r.indexOf("h2")>=0&&!i.headers[":authority"])delete i.headers.host,i.headers[":authority"]=i.hostname+(i.port?":"+i.port:"");else if(!i.headers.host){let e=i.hostname;null!=i.port&&(e+=`:${i.port}`),i.headers.host=e}return t(n)})(e),p)}}))(this.config)),this.middlewareStack.use((this.config,{applyToStack:e=>{e.add(((e,t)=>async n=>{try{const i=await e(n),{clientName:r,commandName:a,logger:o,dynamoDbDocumentClientOptions:s={}}=t,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:l}=s,d=c??t.inputFilterSensitiveLog,u=l??t.outputFilterSensitiveLog,{$metadata:f,...h}=i.output;return o?.info?.({clientName:r,commandName:a,input:d(n.input),output:u(h),metadata:f}),i}catch(e){const{clientName:i,commandName:r,logger:a,dynamoDbDocumentClientOptions:o={}}=t,{overrideInputFilterSensitiveLog:s}=o,c=s??t.inputFilterSensitiveLog;throw a?.error?.({clientName:i,commandName:r,input:c(n.input),error:e,metadata:e.$metadata}),e}}),g)}})),this.middlewareStack.use((e=>({applyToStack:t=>{t.add((e=>t=>async n=>{const{request:i}=n;if(!h.isInstance(i)||"node"!==e.runtime||i.headers.hasOwnProperty(v))return t(n);const r=process.env.AWS_LAMBDA_FUNCTION_NAME,a=process.env._X_AMZN_TRACE_ID,o=e=>"string"==typeof e&&e.length>0;return o(r)&&o(a)&&(i.headers[v]=a),t({...n,request:i})})(e),b)}}))(this.config)),this.middlewareStack.use((e=>({applyToStack:t=>{t.addRelativeTo((e=>(t,n)=>async function(i){if(!h.isInstance(i.request))return t(i);const r=n.endpointV2?.properties?.authSchemes?.[0],a="sigv4a"===r?.name?r?.signingRegionSet?.join(","):void 0,o=await e.signer(r);let s;const c={signingDate:ye(e.systemClockOffset),signingRegion:a||n.signing_region,signingService:n.signing_service};if(n.s3ExpressIdentity){const e=o;if(s=await e.signWithCredentials(i.request,n.s3ExpressIdentity,c),s.headers["X-Amz-Security-Token"]||s.headers["x-amz-security-token"])throw new Error("X-Amz-Security-Token must not be set for s3-express requests.")}else s=await o.sign(i.request,c);const l=await t({...i,request:s}).catch((t=>{const n=t.ServerTime??Ce(t.$response);throw n&&(e.systemClockOffset=Se(n,e.systemClockOffset)),t})),d=Ce(l.response);return d&&(e.systemClockOffset=Se(d,e.systemClockOffset)),l})(e),we)}}))(this.config)),this.middlewareStack.use((l=this.config,{applyToStack:e=>{e.add((e=>(t,n)=>async i=>{const{request:r}=i;if(!h.isInstance(r))return t(i);const{headers:a}=r,o=n?.userAgent?.map(et)||[],s=(await e.defaultUserAgentProvider()).map(et),c=e?.customUserAgent?.map(et)||[],l=[].concat([...s,...o,...c]).join(" "),d=[...s.filter((e=>e.startsWith("aws-sdk-"))),...c].join(" ");return"browser"!==e.runtime?(d&&(a[Qe]=a[Qe]?`${a[Ze]} ${d}`:d),a[Ze]=l):a[Qe]=l,t({...i,request:r})})(l),tt)}}))}destroy(){super.destroy()}}class hi extends bn{constructor(e){super(e),Object.setPrototypeOf(this,hi.prototype)}}const mi={ALL:"ALL",FILTERED:"FILTERED",NONE:"NONE"},pi={DEFAULT:"DEFAULT",HIDDEN:"HIDDEN"},gi={AccessDenied:"AccessDenied",BadRequest:"BadRequest",Conflict:"Conflict",Forbidden:"Forbidden",NotFound:"NotFound",PhoneNumberAssociationsExist:"PhoneNumberAssociationsExist",PreconditionFailed:"PreconditionFailed",ResourceLimitExceeded:"ResourceLimitExceeded",ServiceFailure:"ServiceFailure",ServiceUnavailable:"ServiceUnavailable",Throttled:"Throttled",Throttling:"Throttling",Unauthorized:"Unauthorized",Unprocessable:"Unprocessable",VoiceConnectorGroupAssociationsExist:"VoiceConnectorGroupAssociationsExist"};class vi extends hi{constructor(e){super({name:"BadRequestException",$fault:"client",...e}),this.name="BadRequestException",this.$fault="client",Object.setPrototypeOf(this,vi.prototype),this.Code=e.Code,this.Message=e.Message}}class bi extends hi{constructor(e){super({name:"ConflictException",$fault:"client",...e}),this.name="ConflictException",this.$fault="client",Object.setPrototypeOf(this,bi.prototype),this.Code=e.Code,this.Message=e.Message}}class yi extends hi{constructor(e){super({name:"ForbiddenException",$fault:"client",...e}),this.name="ForbiddenException",this.$fault="client",Object.setPrototypeOf(this,yi.prototype),this.Code=e.Code,this.Message=e.Message}}class Si extends hi{constructor(e){super({name:"NotFoundException",$fault:"client",...e}),this.name="NotFoundException",this.$fault="client",Object.setPrototypeOf(this,Si.prototype),this.Code=e.Code,this.Message=e.Message}}class Ci extends hi{constructor(e){super({name:"ServiceFailureException",$fault:"server",...e}),this.name="ServiceFailureException",this.$fault="server",Object.setPrototypeOf(this,Ci.prototype),this.Code=e.Code,this.Message=e.Message}}class wi extends hi{constructor(e){super({name:"ServiceUnavailableException",$fault:"server",...e}),this.name="ServiceUnavailableException",this.$fault="server",Object.setPrototypeOf(this,wi.prototype),this.Code=e.Code,this.Message=e.Message}}class Mi extends hi{constructor(e){super({name:"ThrottledClientException",$fault:"client",...e}),this.name="ThrottledClientException",this.$fault="client",Object.setPrototypeOf(this,Mi.prototype),this.Code=e.Code,this.Message=e.Message}}class zi extends hi{constructor(e){super({name:"UnauthorizedClientException",$fault:"client",...e}),this.name="UnauthorizedClientException",this.$fault="client",Object.setPrototypeOf(this,zi.prototype),this.Code=e.Code,this.Message=e.Message}}class ki extends hi{constructor(e){super({name:"ResourceLimitExceededException",$fault:"client",...e}),this.name="ResourceLimitExceededException",this.$fault="client",Object.setPrototypeOf(this,ki.prototype),this.Code=e.Code,this.Message=e.Message}}const xi={CREATED_TIMESTAMP:"CREATED_TIMESTAMP",LAST_MESSAGE_TIMESTAMP:"LAST_MESSAGE_TIMESTAMP"},Vi={RESTRICTED:"RESTRICTED",UNRESTRICTED:"UNRESTRICTED"},Hi={PRIVATE:"PRIVATE",PUBLIC:"PUBLIC"},Ei={ASYNC:"ASYNC"},Li={ABORT:"ABORT",CONTINUE:"CONTINUE"},Ti={DEFAULT:"DEFAULT",VOIP:"VOIP"},Ai={NON_PERSISTENT:"NON_PERSISTENT",PERSISTENT:"PERSISTENT"},_i={DENIED:"DENIED",FAILED:"FAILED",PENDING:"PENDING",SENT:"SENT"},Ni={CONTROL:"CONTROL",STANDARD:"STANDARD"},Ii={Channel:"Channel",ChannelMessage:"ChannelMessage"},Pi={ASCENDING:"ASCENDING",DESCENDING:"DESCENDING"},Oi={MEMBERS:"MEMBERS"},Ri={EQUALS:"EQUALS",INCLUDES:"INCLUDES"},Di=e=>({...e,...e.Name&&{Name:cn}}),Fi=e=>({...e,...e.InvitedBy&&{InvitedBy:Di(e.InvitedBy)},...e.Members&&{Members:e.Members.map((e=>Di(e)))}}),Bi=e=>({...e,...e.BatchChannelMemberships&&{BatchChannelMemberships:Fi(e.BatchChannelMemberships)}}),Ui=e=>({...e,...e.Name&&{Name:cn},...e.Metadata&&{Metadata:cn},...e.CreatedBy&&{CreatedBy:Di(e.CreatedBy)}}),ji=e=>({...e,...e.Name&&{Name:cn},...e.Metadata&&{Metadata:cn}}),qi=e=>({...e,...e.Member&&{Member:Di(e.Member)},...e.CreatedBy&&{CreatedBy:Di(e.CreatedBy)}}),Wi=e=>({...e,...e.Member&&{Member:Di(e.Member)}}),$i=e=>({...e,...e.Name&&{Name:cn}}),Gi=e=>({...e,...e.Processors&&{Processors:e.Processors.map((e=>$i(e)))},...e.Name&&{Name:cn}}),Ki=e=>({...e,...e.StringValues&&{StringValues:cn}}),Ji=e=>({...e,...e.Title&&{Title:cn},...e.Body&&{Body:cn}}),Zi=e=>({...e,...e.Content&&{Content:cn},...e.Metadata&&{Metadata:cn},...e.PushNotification&&{PushNotification:Ji(e.PushNotification)},...e.MessageAttributes&&{MessageAttributes:Object.entries(e.MessageAttributes).reduce(((e,[t,n])=>(e[t]=Ki(n),e)),{})},...e.ContentType&&{ContentType:cn}}),Qi=e=>({...e,...e.ChannelMessage&&{ChannelMessage:Zi(e.ChannelMessage)}}),Yi=e=>({...e,...e.Name&&{Name:cn},...e.Processors&&{Processors:e.Processors.map((e=>$i(e)))}}),Xi=e=>({...e,...e.InvitedBy&&{InvitedBy:Di(e.InvitedBy)},...e.Member&&{Member:Di(e.Member)}}),er=e=>({...e,...e.Name&&{Name:cn},...e.Metadata&&{Metadata:cn}}),tr=e=>({...e,...e.ChannelSummary&&{ChannelSummary:er(e.ChannelSummary)}}),nr=e=>({...e,...e.FilterRule&&{FilterRule:cn}}),ir=e=>({...e,...e.PushNotifications&&{PushNotifications:nr(e.PushNotifications)}}),rr=e=>({...e,...e.Member&&{Member:Di(e.Member)}}),ar=e=>({...e,...e.Content&&{Content:cn},...e.Metadata&&{Metadata:cn},...e.Sender&&{Sender:Di(e.Sender)},...e.MessageAttributes&&{MessageAttributes:Object.entries(e.MessageAttributes).reduce(((e,[t,n])=>(e[t]=Ki(n),e)),{})},...e.ContentType&&{ContentType:cn}}),or=e=>({...e,...e.Content&&{Content:cn},...e.Metadata&&{Metadata:cn},...e.Sender&&{Sender:Di(e.Sender)},...e.MessageAttributes&&{MessageAttributes:Object.entries(e.MessageAttributes).reduce(((e,[t,n])=>(e[t]=Ki(n),e)),{})},...e.ContentType&&{ContentType:cn}}),sr=e=>({...e,...e.ChannelSummary&&{ChannelSummary:er(e.ChannelSummary)}}),cr=e=>({...e,...e.Moderator&&{Moderator:Di(e.Moderator)},...e.CreatedBy&&{CreatedBy:Di(e.CreatedBy)}}),lr=e=>({...e,...e.Moderator&&{Moderator:Di(e.Moderator)}}),dr=e=>({...e,...e.Key&&{Key:cn},...e.Value&&{Value:cn}}),ur=e=>({...e,...e.Name&&{Name:cn},...e.Metadata&&{Metadata:cn},...e.ClientRequestToken&&{ClientRequestToken:cn},...e.Tags&&{Tags:e.Tags.map((e=>dr(e)))},...e.ChannelId&&{ChannelId:cn}}),fr=e=>({...e,...e.Member&&{Member:Di(e.Member)}}),hr=e=>({...e,...e.Processors&&{Processors:e.Processors.map((e=>$i(e)))},...e.Name&&{Name:cn},...e.Tags&&{Tags:e.Tags.map((e=>dr(e)))},...e.ClientRequestToken&&{ClientRequestToken:cn}}),mr=e=>({...e,...e.Member&&{Member:Di(e.Member)}}),pr=e=>({...e,...e.ChannelModerator&&{ChannelModerator:Di(e.ChannelModerator)}}),gr=e=>({...e,...e.Channel&&{Channel:Ui(e.Channel)}}),vr=e=>({...e,...e.ChannelBan&&{ChannelBan:qi(e.ChannelBan)}}),br=e=>({...e,...e.ChannelFlow&&{ChannelFlow:Gi(e.ChannelFlow)}}),yr=e=>({...e,...e.ChannelMembership&&{ChannelMembership:Xi(e.ChannelMembership)}}),Sr=e=>({...e,...e.ChannelMembership&&{ChannelMembership:tr(e.ChannelMembership)}}),Cr=e=>({...e,...e.Channel&&{Channel:sr(e.Channel)}}),wr=e=>({...e,...e.ChannelModerator&&{ChannelModerator:cr(e.ChannelModerator)}}),Mr=e=>({...e,...e.Member&&{Member:Di(e.Member)},...e.Preferences&&{Preferences:ir(e.Preferences)}}),zr=e=>({...e,...e.ChannelMessage&&{ChannelMessage:ar(e.ChannelMessage)}}),kr=e=>({...e,...e.NextToken&&{NextToken:cn}}),xr=e=>({...e,...e.NextToken&&{NextToken:cn},...e.ChannelBans&&{ChannelBans:e.ChannelBans.map((e=>Wi(e)))}}),Vr=e=>({...e,...e.NextToken&&{NextToken:cn}}),Hr=e=>({...e,...e.ChannelFlows&&{ChannelFlows:e.ChannelFlows.map((e=>Yi(e)))},...e.NextToken&&{NextToken:cn}}),Er=e=>({...e,...e.NextToken&&{NextToken:cn}}),Lr=e=>({...e,...e.ChannelMemberships&&{ChannelMemberships:e.ChannelMemberships.map((e=>rr(e)))},...e.NextToken&&{NextToken:cn}}),Tr=e=>({...e,...e.NextToken&&{NextToken:cn}}),Ar=e=>({...e,...e.ChannelMemberships&&{ChannelMemberships:e.ChannelMemberships.map((e=>tr(e)))},...e.NextToken&&{NextToken:cn}}),_r=e=>({...e,...e.NextToken&&{NextToken:cn}}),Nr=e=>({...e,...e.NextToken&&{NextToken:cn},...e.ChannelMessages&&{ChannelMessages:e.ChannelMessages.map((e=>or(e)))}}),Ir=e=>({...e,...e.NextToken&&{NextToken:cn}}),Pr=e=>({...e,...e.NextToken&&{NextToken:cn},...e.ChannelModerators&&{ChannelModerators:e.ChannelModerators.map((e=>lr(e)))}}),Or=e=>({...e,...e.NextToken&&{NextToken:cn}}),Rr=e=>({...e,...e.Channels&&{Channels:e.Channels.map((e=>er(e)))},...e.NextToken&&{NextToken:cn}}),Dr=e=>({...e,...e.NextToken&&{NextToken:cn}}),Fr=e=>({...e,...e.Channels&&{Channels:e.Channels.map((e=>ji(e)))},...e.NextToken&&{NextToken:cn}}),Br=e=>({...e,...e.NextToken&&{NextToken:cn}}),Ur=e=>({...e,...e.Channels&&{Channels:e.Channels.map((e=>sr(e)))},...e.NextToken&&{NextToken:cn}}),jr=e=>({...e,...e.NextToken&&{NextToken:cn}}),qr=e=>({...e,...e.NextToken&&{NextToken:cn}}),Wr=e=>({...e,...e.Tags&&{Tags:e.Tags.map((e=>dr(e)))}}),$r=e=>({...e,...e.Preferences&&{Preferences:ir(e.Preferences)}}),Gr=e=>({...e,...e.Member&&{Member:Di(e.Member)},...e.Preferences&&{Preferences:ir(e.Preferences)}}),Kr=e=>({...e,...e.NextToken&&{NextToken:cn}}),Jr=e=>({...e,...e.Channels&&{Channels:e.Channels.map((e=>er(e)))},...e.NextToken&&{NextToken:cn}}),Zr=e=>({...e,...e.Content&&{Content:cn},...e.Metadata&&{Metadata:cn},...e.ClientRequestToken&&{ClientRequestToken:cn},...e.PushNotification&&{PushNotification:Ji(e.PushNotification)},...e.MessageAttributes&&{MessageAttributes:Object.entries(e.MessageAttributes).reduce(((e,[t,n])=>(e[t]=Ki(n),e)),{})},...e.ContentType&&{ContentType:cn}}),Qr=e=>({...e,...e.Tags&&{Tags:e.Tags.map((e=>dr(e)))}}),Yr=e=>({...e,...e.TagKeys&&{TagKeys:cn}}),Xr=e=>({...e,...e.Name&&{Name:cn},...e.Metadata&&{Metadata:cn}}),ea=e=>({...e,...e.Processors&&{Processors:e.Processors.map((e=>$i(e)))},...e.Name&&{Name:cn}}),ta=e=>({...e,...e.Content&&{Content:cn},...e.Metadata&&{Metadata:cn},...e.ContentType&&{ContentType:cn}}),na=(ia=hi,({output:e,parsedBody:t,errorCode:n})=>{(({output:e,parsedBody:t,exceptionCtor:n,errorCode:i})=>{const r=(e=>({httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}))(e),a=r.httpStatusCode?r.httpStatusCode+"":void 0,o=new n({name:t?.code||t?.Code||i||a||"UnknownError",$fault:"client",$metadata:r});throw yn(o,t)})({output:e,parsedBody:t,exceptionCtor:ia,errorCode:n})});var ia;const ra=async(e,t)=>{const n=Vn({}),i=e.body,r=Hn(i,{Code:hn,Message:hn});Object.assign(n,r);const a=new vi({$metadata:va(e),...n});return yn(a,e.body)},aa=async(e,t)=>{const n=Vn({}),i=e.body,r=Hn(i,{Code:hn,Message:hn});Object.assign(n,r);const a=new bi({$metadata:va(e),...n});return yn(a,e.body)},oa=async(e,t)=>{const n=Vn({}),i=e.body,r=Hn(i,{Code:hn,Message:hn});Object.assign(n,r);const a=new yi({$metadata:va(e),...n});return yn(a,e.body)},sa=async(e,t)=>{const n=Vn({}),i=e.body,r=Hn(i,{Code:hn,Message:hn});Object.assign(n,r);const a=new Si({$metadata:va(e),...n});return yn(a,e.body)},ca=async(e,t)=>{const n=Vn({}),i=e.body,r=Hn(i,{Code:hn,Message:hn});Object.assign(n,r);const a=new ki({$metadata:va(e),...n});return yn(a,e.body)},la=async(e,t)=>{const n=Vn({}),i=e.body,r=Hn(i,{Code:hn,Message:hn});Object.assign(n,r);const a=new Ci({$metadata:va(e),...n});return yn(a,e.body)},da=async(e,t)=>{const n=Vn({}),i=e.body,r=Hn(i,{Code:hn,Message:hn});Object.assign(n,r);const a=new wi({$metadata:va(e),...n});return yn(a,e.body)},ua=async(e,t)=>{const n=Vn({}),i=e.body,r=Hn(i,{Code:hn,Message:hn});Object.assign(n,r);const a=new Mi({$metadata:va(e),...n});return yn(a,e.body)},fa=async(e,t)=>{const n=Vn({}),i=e.body,r=Hn(i,{Code:hn,Message:hn});Object.assign(n,r);const a=new zi({$metadata:va(e),...n});return yn(a,e.body)},ha=(e,t)=>Hn(e,{AppInstanceUserMembershipSummary:e=>((e,t)=>Hn(e,{ReadMarkerTimestamp:e=>un(vn(dn(e))),SubChannelId:hn,Type:hn}))(e),ChannelSummary:e=>pa(e,t)}),ma=(e,t)=>Hn(e,{ChannelSummary:e=>pa(e,t)}),pa=(e,t)=>Hn(e,{ChannelArn:hn,LastMessageTimestamp:e=>un(vn(dn(e))),Metadata:hn,Mode:hn,Name:hn,Privacy:hn}),ga=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>pa(e,t))),va=e=>({httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}),ba=e=>!(null==e||""===e||Object.getOwnPropertyNames(e).includes("length")&&0==e.length||Object.getOwnPropertyNames(e).includes("size")&&0==e.size),ya=(e,t)=>((e,t)=>on(e,t).then((e=>t.utf8Encoder(e))))(e,t).then((e=>e.length?JSON.parse(e):{})),Sa=async(e,t)=>{const n=await ya(e,t);return n.message=n.message??n.Message,n},Ca=(e,t)=>{const n=e=>{let t=e;return"number"==typeof t&&(t=t.toString()),t.indexOf(",")>=0&&(t=t.split(",")[0]),t.indexOf(":")>=0&&(t=t.split(":")[0]),t.indexOf("#")>=0&&(t=t.split("#")[1]),t},i=(r=e.headers,Object.keys(r).find((e=>e.toLowerCase()==="x-amzn-errortype".toLowerCase())));var r;return void 0!==i?n(e.headers[i]):void 0!==t.code?n(t.code):void 0!==t.__type?n(t.__type):void 0};class wa extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,wa.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"AssociateChannelFlowCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"AssociateChannelFlow"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer});let s,c=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/channel-flow`;return c=Nn(c,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=JSON.stringify(Hn(e,{ChannelFlowArn:[]})),new h({protocol:i,hostname:n,port:r,method:"PUT",headers:o,path:c,body:s})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"NotFoundException":case"com.amazonaws.chimesdkmessaging#NotFoundException":throw await sa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)});return await on(e.body,t),n})(e,t)}}class Ma extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Ma.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"BatchCreateChannelMembershipCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:Bi,[d]:{service:"ChimeMessagingService",operation:"BatchCreateChannelMembership"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/memberships`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1);const c=Vn({operation:[,"batch-create"]});let l;return l=JSON.stringify(Hn(e,{MemberArns:e=>In(e),SubChannelId:[],Type:[]})),new h({protocol:i,hostname:n,port:r,method:"POST",headers:o,path:s,query:c,body:l})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"NotFoundException":case"com.amazonaws.chimesdkmessaging#NotFoundException":throw await sa(n);case"ResourceLimitExceededException":case"com.amazonaws.chimesdkmessaging#ResourceLimitExceededException":throw await ca(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{BatchChannelMemberships:In,Errors:In});return Object.assign(n,r),n})(e,t)}}class za extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,za.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"ChannelFlowCallbackCommand",inputFilterSensitiveLog:Qi,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"ChannelFlowCallback"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint();let o=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}`;o=Nn(o,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1);const s=Vn({operation:[,"channel-flow-callback"]});let c;return c=JSON.stringify(Hn(e,{CallbackId:[!0,e=>e??Pt()],ChannelMessage:e=>In(e),DeleteResource:[]})),new h({protocol:i,hostname:n,port:r,method:"POST",headers:{"content-type":"application/json"},path:o,query:s,body:c})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{CallbackId:hn,ChannelArn:hn});return Object.assign(n,r),n})(e,t)}}class ka extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,ka.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"CreateChannelBanCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:fr,[d]:{service:"ChimeMessagingService",operation:"CreateChannelBan"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer});let s,c=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/bans`;return c=Nn(c,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=JSON.stringify(Hn(e,{MemberArn:[]})),new h({protocol:i,hostname:n,port:r,method:"POST",headers:o,path:c,body:s})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(201!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ResourceLimitExceededException":case"com.amazonaws.chimesdkmessaging#ResourceLimitExceededException":throw await ca(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,Member:In});return Object.assign(n,r),n})(e,t)}}class xa extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,xa.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"CreateChannelCommand",inputFilterSensitiveLog:ur,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"CreateChannel"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer}),s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels`;let c;return c=JSON.stringify(Hn(e,{AppInstanceArn:[],ChannelId:[],ClientRequestToken:[!0,e=>e??Pt()],ElasticChannelConfiguration:e=>In(e),ExpirationSettings:e=>In(e),MemberArns:e=>In(e),Metadata:[],Mode:[],ModeratorArns:e=>In(e),Name:[],Privacy:[],Tags:e=>In(e)})),new h({protocol:i,hostname:n,port:r,method:"POST",headers:o,path:s,body:c})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(201!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ResourceLimitExceededException":case"com.amazonaws.chimesdkmessaging#ResourceLimitExceededException":throw await ca(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn});return Object.assign(n,r),n})(e,t)}}class Va extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Va.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"CreateChannelFlowCommand",inputFilterSensitiveLog:hr,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"CreateChannelFlow"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channel-flows`;let s;return s=JSON.stringify(Hn(e,{AppInstanceArn:[],ClientRequestToken:[!0,e=>e??Pt()],Name:[],Processors:e=>In(e),Tags:e=>In(e)})),new h({protocol:i,hostname:n,port:r,method:"POST",headers:{"content-type":"application/json"},path:o,body:s})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(201!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ResourceLimitExceededException":case"com.amazonaws.chimesdkmessaging#ResourceLimitExceededException":throw await ca(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelFlowArn:hn});return Object.assign(n,r),n})(e,t)}}class Ha extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Ha.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"CreateChannelMembershipCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:mr,[d]:{service:"ChimeMessagingService",operation:"CreateChannelMembership"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer});let s,c=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/memberships`;return c=Nn(c,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=JSON.stringify(Hn(e,{MemberArn:[],SubChannelId:[],Type:[]})),new h({protocol:i,hostname:n,port:r,method:"POST",headers:o,path:c,body:s})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(201!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"NotFoundException":case"com.amazonaws.chimesdkmessaging#NotFoundException":throw await sa(n);case"ResourceLimitExceededException":case"com.amazonaws.chimesdkmessaging#ResourceLimitExceededException":throw await ca(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,Member:In,SubChannelId:hn});return Object.assign(n,r),n})(e,t)}}class Ea extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Ea.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"CreateChannelModeratorCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:pr,[d]:{service:"ChimeMessagingService",operation:"CreateChannelModerator"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer});let s,c=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/moderators`;return c=Nn(c,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=JSON.stringify(Hn(e,{ChannelModeratorArn:[]})),new h({protocol:i,hostname:n,port:r,method:"POST",headers:o,path:c,body:s})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(201!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ResourceLimitExceededException":case"com.amazonaws.chimesdkmessaging#ResourceLimitExceededException":throw await ca(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,ChannelModerator:In});return Object.assign(n,r),n})(e,t)}}class La extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,La.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DeleteChannelBanCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"DeleteChannelBan"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/bans/{MemberArn}`;return s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=Nn(s,e,"MemberArn",(()=>e.MemberArn),"{MemberArn}",!1),new h({protocol:i,hostname:n,port:r,method:"DELETE",headers:o,path:s,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)});return await on(e.body,t),n})(e,t)}}class Ta extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Ta.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DeleteChannelCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"DeleteChannel"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}`;return s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),new h({protocol:i,hostname:n,port:r,method:"DELETE",headers:o,path:s,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)});return await on(e.body,t),n})(e,t)}}class Aa extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Aa.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DeleteChannelFlowCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"DeleteChannelFlow"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint();let o=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channel-flows/{ChannelFlowArn}`;return o=Nn(o,e,"ChannelFlowArn",(()=>e.ChannelFlowArn),"{ChannelFlowArn}",!1),new h({protocol:i,hostname:n,port:r,method:"DELETE",headers:{},path:o,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)});return await on(e.body,t),n})(e,t)}}class _a extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,_a.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DeleteChannelMembershipCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"DeleteChannelMembership"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/memberships/{MemberArn}`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=Nn(s,e,"MemberArn",(()=>e.MemberArn),"{MemberArn}",!1);const c=Vn({"sub-channel-id":[,e.SubChannelId]});return new h({protocol:i,hostname:n,port:r,method:"DELETE",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)});return await on(e.body,t),n})(e,t)}}class Na extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Na.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DeleteChannelMessageCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"DeleteChannelMessage"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/messages/{MessageId}`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=Nn(s,e,"MessageId",(()=>e.MessageId),"{MessageId}",!1);const c=Vn({"sub-channel-id":[,e.SubChannelId]});return new h({protocol:i,hostname:n,port:r,method:"DELETE",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)});return await on(e.body,t),n})(e,t)}}class Ia extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Ia.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DeleteChannelModeratorCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"DeleteChannelModerator"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/moderators/{ChannelModeratorArn}`;return s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=Nn(s,e,"ChannelModeratorArn",(()=>e.ChannelModeratorArn),"{ChannelModeratorArn}",!1),new h({protocol:i,hostname:n,port:r,method:"DELETE",headers:o,path:s,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)});return await on(e.body,t),n})(e,t)}}class Pa extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Pa.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DeleteMessagingStreamingConfigurationsCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"DeleteMessagingStreamingConfigurations"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint();let o=`${a?.endsWith("/")?a.slice(0,-1):a||""}/app-instances/{AppInstanceArn}/streaming-configurations`;return o=Nn(o,e,"AppInstanceArn",(()=>e.AppInstanceArn),"{AppInstanceArn}",!1),new h({protocol:i,hostname:n,port:r,method:"DELETE",headers:{},path:o,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)});return await on(e.body,t),n})(e,t)}}class Oa extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Oa.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DescribeChannelBanCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:vr,[d]:{service:"ChimeMessagingService",operation:"DescribeChannelBan"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/bans/{MemberArn}`;return s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=Nn(s,e,"MemberArn",(()=>e.MemberArn),"{MemberArn}",!1),new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"NotFoundException":case"com.amazonaws.chimesdkmessaging#NotFoundException":throw await sa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelBan:e=>((e,t)=>Hn(e,{ChannelArn:hn,CreatedBy:In,CreatedTimestamp:e=>un(vn(dn(e))),Member:In}))(e)});return Object.assign(n,r),n})(e,t)}}class Ra extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Ra.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DescribeChannelCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:gr,[d]:{service:"ChimeMessagingService",operation:"DescribeChannel"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}`;return s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{Channel:e=>((e,t)=>Hn(e,{ChannelArn:hn,ChannelFlowArn:hn,CreatedBy:In,CreatedTimestamp:e=>un(vn(dn(e))),ElasticChannelConfiguration:In,ExpirationSettings:In,LastMessageTimestamp:e=>un(vn(dn(e))),LastUpdatedTimestamp:e=>un(vn(dn(e))),Metadata:hn,Mode:hn,Name:hn,Privacy:hn}))(e)});return Object.assign(n,r),n})(e,t)}}class Da extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Da.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DescribeChannelFlowCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:br,[d]:{service:"ChimeMessagingService",operation:"DescribeChannelFlow"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint();let o=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channel-flows/{ChannelFlowArn}`;return o=Nn(o,e,"ChannelFlowArn",(()=>e.ChannelFlowArn),"{ChannelFlowArn}",!1),new h({protocol:i,hostname:n,port:r,method:"GET",headers:{},path:o,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelFlow:e=>((e,t)=>Hn(e,{ChannelFlowArn:hn,CreatedTimestamp:e=>un(vn(dn(e))),LastUpdatedTimestamp:e=>un(vn(dn(e))),Name:hn,Processors:In}))(e)});return Object.assign(n,r),n})(e,t)}}class Fa extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Fa.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DescribeChannelMembershipCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:yr,[d]:{service:"ChimeMessagingService",operation:"DescribeChannelMembership"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/memberships/{MemberArn}`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=Nn(s,e,"MemberArn",(()=>e.MemberArn),"{MemberArn}",!1);const c=Vn({"sub-channel-id":[,e.SubChannelId]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"NotFoundException":case"com.amazonaws.chimesdkmessaging#NotFoundException":throw await sa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelMembership:e=>((e,t)=>Hn(e,{ChannelArn:hn,CreatedTimestamp:e=>un(vn(dn(e))),InvitedBy:In,LastUpdatedTimestamp:e=>un(vn(dn(e))),Member:In,SubChannelId:hn,Type:hn}))(e)});return Object.assign(n,r),n})(e,t)}}class Ba extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Ba.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DescribeChannelMembershipForAppInstanceUserCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:Sr,[d]:{service:"ChimeMessagingService",operation:"DescribeChannelMembershipForAppInstanceUser"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1);const c=Vn({scope:[,"app-instance-user-membership"],"app-instance-user-arn":[,un(e.AppInstanceUserArn,"AppInstanceUserArn")]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelMembership:e=>ha(e,t)});return Object.assign(n,r),n})(e,t)}}class Ua extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Ua.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DescribeChannelModeratedByAppInstanceUserCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:Cr,[d]:{service:"ChimeMessagingService",operation:"DescribeChannelModeratedByAppInstanceUser"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1);const c=Vn({scope:[,"app-instance-user-moderated-channel"],"app-instance-user-arn":[,un(e.AppInstanceUserArn,"AppInstanceUserArn")]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{Channel:e=>ma(e,t)});return Object.assign(n,r),n})(e,t)}}class ja extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,ja.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DescribeChannelModeratorCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:wr,[d]:{service:"ChimeMessagingService",operation:"DescribeChannelModerator"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/moderators/{ChannelModeratorArn}`;return s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=Nn(s,e,"ChannelModeratorArn",(()=>e.ChannelModeratorArn),"{ChannelModeratorArn}",!1),new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"NotFoundException":case"com.amazonaws.chimesdkmessaging#NotFoundException":throw await sa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelModerator:e=>((e,t)=>Hn(e,{ChannelArn:hn,CreatedBy:In,CreatedTimestamp:e=>un(vn(dn(e))),Moderator:In}))(e)});return Object.assign(n,r),n})(e,t)}}class qa extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,qa.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"DisassociateChannelFlowCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"DisassociateChannelFlow"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/channel-flow/{ChannelFlowArn}`;return s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=Nn(s,e,"ChannelFlowArn",(()=>e.ChannelFlowArn),"{ChannelFlowArn}",!1),new h({protocol:i,hostname:n,port:r,method:"DELETE",headers:o,path:s,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"NotFoundException":case"com.amazonaws.chimesdkmessaging#NotFoundException":throw await sa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)});return await on(e.body,t),n})(e,t)}}class Wa extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Wa.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"GetChannelMembershipPreferencesCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:Mr,[d]:{service:"ChimeMessagingService",operation:"GetChannelMembershipPreferences"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/memberships/{MemberArn}/preferences`;return s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=Nn(s,e,"MemberArn",(()=>e.MemberArn),"{MemberArn}",!1),new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,Member:In,Preferences:In});return Object.assign(n,r),n})(e,t)}}class $a extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,$a.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"GetChannelMessageCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:zr,[d]:{service:"ChimeMessagingService",operation:"GetChannelMessage"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/messages/{MessageId}`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=Nn(s,e,"MessageId",(()=>e.MessageId),"{MessageId}",!1);const c=Vn({"sub-channel-id":[,e.SubChannelId]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"NotFoundException":case"com.amazonaws.chimesdkmessaging#NotFoundException":throw await sa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelMessage:e=>((e,t)=>Hn(e,{ChannelArn:hn,Content:hn,ContentType:hn,CreatedTimestamp:e=>un(vn(dn(e))),LastEditedTimestamp:e=>un(vn(dn(e))),LastUpdatedTimestamp:e=>un(vn(dn(e))),MessageAttributes:In,MessageId:hn,Metadata:hn,Persistence:hn,Redacted:ln,Sender:In,Status:In,SubChannelId:hn,Target:In,Type:hn}))(e)});return Object.assign(n,r),n})(e,t)}}class Ga extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Ga.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"GetChannelMessageStatusCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"GetChannelMessageStatus"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/messages/{MessageId}`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=Nn(s,e,"MessageId",(()=>e.MessageId),"{MessageId}",!1);const c=Vn({scope:[,"message-status"],"sub-channel-id":[,e.SubChannelId]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{Status:In});return Object.assign(n,r),n})(e,t)}}class Ka extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Ka.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"GetMessagingSessionEndpointCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"GetMessagingSessionEndpoint"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=`${a?.endsWith("/")?a.slice(0,-1):a||""}/endpoints/messaging-session`;let s;return s="",new h({protocol:i,hostname:n,port:r,method:"GET",headers:{"content-type":"application/json"},path:o,body:""})})(0,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{Endpoint:In});return Object.assign(n,r),n})(e,t)}}class Ja extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Ja.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"GetMessagingStreamingConfigurationsCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"GetMessagingStreamingConfigurations"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint();let o=`${a?.endsWith("/")?a.slice(0,-1):a||""}/app-instances/{AppInstanceArn}/streaming-configurations`;return o=Nn(o,e,"AppInstanceArn",(()=>e.AppInstanceArn),"{AppInstanceArn}",!1),new h({protocol:i,hostname:n,port:r,method:"GET",headers:{},path:o,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"NotFoundException":case"com.amazonaws.chimesdkmessaging#NotFoundException":throw await sa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{StreamingConfigurations:In});return Object.assign(n,r),n})(e,t)}}class Za extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Za.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"ListChannelBansCommand",inputFilterSensitiveLog:kr,outputFilterSensitiveLog:xr,[d]:{service:"ChimeMessagingService",operation:"ListChannelBans"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/bans`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1);const c=Vn({"max-results":[()=>void 0!==e.MaxResults,()=>e.MaxResults.toString()],"next-token":[,e.NextToken]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,ChannelBans:In,NextToken:hn});return Object.assign(n,r),n})(e,t)}}class Qa extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Qa.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"ListChannelFlowsCommand",inputFilterSensitiveLog:Vr,outputFilterSensitiveLog:Hr,[d]:{service:"ChimeMessagingService",operation:"ListChannelFlows"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channel-flows`,s=Vn({"app-instance-arn":[,un(e.AppInstanceArn,"AppInstanceArn")],"max-results":[()=>void 0!==e.MaxResults,()=>e.MaxResults.toString()],"next-token":[,e.NextToken]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:{},path:o,query:s,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelFlows:In,NextToken:hn});return Object.assign(n,r),n})(e,t)}}class Ya extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Ya.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"ListChannelMembershipsCommand",inputFilterSensitiveLog:Er,outputFilterSensitiveLog:Lr,[d]:{service:"ChimeMessagingService",operation:"ListChannelMemberships"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/memberships`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1);const c=Vn({type:[,e.Type],"max-results":[()=>void 0!==e.MaxResults,()=>e.MaxResults.toString()],"next-token":[,e.NextToken],"sub-channel-id":[,e.SubChannelId]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,ChannelMemberships:In,NextToken:hn});return Object.assign(n,r),n})(e,t)}}class Xa extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,Xa.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"ListChannelMembershipsForAppInstanceUserCommand",inputFilterSensitiveLog:Tr,outputFilterSensitiveLog:Ar,[d]:{service:"ChimeMessagingService",operation:"ListChannelMembershipsForAppInstanceUser"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer}),s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels`,c=Vn({scope:[,"app-instance-user-memberships"],"app-instance-user-arn":[,e.AppInstanceUserArn],"max-results":[()=>void 0!==e.MaxResults,()=>e.MaxResults.toString()],"next-token":[,e.NextToken]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelMemberships:e=>((e,t)=>(e||[]).filter((e=>null!=e)).map((e=>ha(e,t))))(e,t),NextToken:hn});return Object.assign(n,r),n})(e,t)}}class eo extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,eo.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"ListChannelMessagesCommand",inputFilterSensitiveLog:_r,outputFilterSensitiveLog:Nr,[d]:{service:"ChimeMessagingService",operation:"ListChannelMessages"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/messages`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1);const c=Vn({"sort-order":[,e.SortOrder],"not-before":[()=>void 0!==e.NotBefore,()=>(e.NotBefore.toISOString().split(".")[0]+"Z").toString()],"not-after":[()=>void 0!==e.NotAfter,()=>(e.NotAfter.toISOString().split(".")[0]+"Z").toString()],"max-results":[()=>void 0!==e.MaxResults,()=>e.MaxResults.toString()],"next-token":[,e.NextToken],"sub-channel-id":[,e.SubChannelId]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,ChannelMessages:e=>((e,t)=>(e||[]).filter((e=>null!=e)).map((e=>((e,t)=>Hn(e,{Content:hn,ContentType:hn,CreatedTimestamp:e=>un(vn(dn(e))),LastEditedTimestamp:e=>un(vn(dn(e))),LastUpdatedTimestamp:e=>un(vn(dn(e))),MessageAttributes:In,MessageId:hn,Metadata:hn,Redacted:ln,Sender:In,Status:In,Target:In,Type:hn}))(e))))(e),NextToken:hn,SubChannelId:hn});return Object.assign(n,r),n})(e,t)}}class to extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,to.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"ListChannelModeratorsCommand",inputFilterSensitiveLog:Ir,outputFilterSensitiveLog:Pr,[d]:{service:"ChimeMessagingService",operation:"ListChannelModerators"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/moderators`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1);const c=Vn({"max-results":[()=>void 0!==e.MaxResults,()=>e.MaxResults.toString()],"next-token":[,e.NextToken]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,ChannelModerators:In,NextToken:hn});return Object.assign(n,r),n})(e,t)}}class no extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,no.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"ListChannelsAssociatedWithChannelFlowCommand",inputFilterSensitiveLog:Dr,outputFilterSensitiveLog:Fr,[d]:{service:"ChimeMessagingService",operation:"ListChannelsAssociatedWithChannelFlow"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels`,s=Vn({scope:[,"channel-flow-associations"],"channel-flow-arn":[,un(e.ChannelFlowArn,"ChannelFlowArn")],"max-results":[()=>void 0!==e.MaxResults,()=>e.MaxResults.toString()],"next-token":[,e.NextToken]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:{},path:o,query:s,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{Channels:In,NextToken:hn});return Object.assign(n,r),n})(e,t)}}class io extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,io.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"ListChannelsCommand",inputFilterSensitiveLog:Or,outputFilterSensitiveLog:Rr,[d]:{service:"ChimeMessagingService",operation:"ListChannels"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer}),s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels`,c=Vn({"app-instance-arn":[,un(e.AppInstanceArn,"AppInstanceArn")],privacy:[,e.Privacy],"max-results":[()=>void 0!==e.MaxResults,()=>e.MaxResults.toString()],"next-token":[,e.NextToken]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{Channels:e=>ga(e,t),NextToken:hn});return Object.assign(n,r),n})(e,t)}}class ro extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,ro.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"ListChannelsModeratedByAppInstanceUserCommand",inputFilterSensitiveLog:Br,outputFilterSensitiveLog:Ur,[d]:{service:"ChimeMessagingService",operation:"ListChannelsModeratedByAppInstanceUser"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer}),s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels`,c=Vn({scope:[,"app-instance-user-moderated-channels"],"app-instance-user-arn":[,e.AppInstanceUserArn],"max-results":[()=>void 0!==e.MaxResults,()=>e.MaxResults.toString()],"next-token":[,e.NextToken]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{Channels:e=>((e,t)=>(e||[]).filter((e=>null!=e)).map((e=>ma(e,t))))(e,t),NextToken:hn});return Object.assign(n,r),n})(e,t)}}class ao extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,ao.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"ListSubChannelsCommand",inputFilterSensitiveLog:jr,outputFilterSensitiveLog:qr,[d]:{service:"ChimeMessagingService",operation:"ListSubChannels"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/subchannels`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1);const c=Vn({"max-results":[()=>void 0!==e.MaxResults,()=>e.MaxResults.toString()],"next-token":[,e.NextToken]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:o,path:s,query:c,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,NextToken:hn,SubChannels:In});return Object.assign(n,r),n})(e,t)}}class oo extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,oo.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"ListTagsForResourceCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:Wr,[d]:{service:"ChimeMessagingService",operation:"ListTagsForResource"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=`${a?.endsWith("/")?a.slice(0,-1):a||""}/tags`,s=Vn({arn:[,un(e.ResourceARN,"ResourceARN")]});return new h({protocol:i,hostname:n,port:r,method:"GET",headers:{},path:o,query:s,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{Tags:In});return Object.assign(n,r),n})(e,t)}}class so extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,so.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"PutChannelExpirationSettingsCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"PutChannelExpirationSettings"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer});let s,c=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/expiration-settings`;return c=Nn(c,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=JSON.stringify(Hn(e,{ExpirationSettings:e=>In(e)})),new h({protocol:i,hostname:n,port:r,method:"PUT",headers:o,path:c,body:s})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,ExpirationSettings:In});return Object.assign(n,r),n})(e,t)}}class co extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,co.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"PutChannelMembershipPreferencesCommand",inputFilterSensitiveLog:$r,outputFilterSensitiveLog:Gr,[d]:{service:"ChimeMessagingService",operation:"PutChannelMembershipPreferences"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer});let s,c=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/memberships/{MemberArn}/preferences`;return c=Nn(c,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),c=Nn(c,e,"MemberArn",(()=>e.MemberArn),"{MemberArn}",!1),s=JSON.stringify(Hn(e,{Preferences:e=>In(e)})),new h({protocol:i,hostname:n,port:r,method:"PUT",headers:o,path:c,body:s})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,Member:In,Preferences:In});return Object.assign(n,r),n})(e,t)}}class lo extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,lo.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"PutMessagingStreamingConfigurationsCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"PutMessagingStreamingConfigurations"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint();let o,s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/app-instances/{AppInstanceArn}/streaming-configurations`;return s=Nn(s,e,"AppInstanceArn",(()=>e.AppInstanceArn),"{AppInstanceArn}",!1),o=JSON.stringify(Hn(e,{StreamingConfigurations:e=>In(e)})),new h({protocol:i,hostname:n,port:r,method:"PUT",headers:{"content-type":"application/json"},path:s,body:o})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"NotFoundException":case"com.amazonaws.chimesdkmessaging#NotFoundException":throw await sa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{StreamingConfigurations:In});return Object.assign(n,r),n})(e,t)}}class uo extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,uo.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"RedactChannelMessageCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"RedactChannelMessage"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/messages/{MessageId}`;s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=Nn(s,e,"MessageId",(()=>e.MessageId),"{MessageId}",!1);const c=Vn({operation:[,"redact"]});let l;return l=JSON.stringify(Hn(e,{SubChannelId:[]})),new h({protocol:i,hostname:n,port:r,method:"POST",headers:o,path:s,query:c,body:l})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,MessageId:hn,SubChannelId:hn});return Object.assign(n,r),n})(e,t)}}class fo extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,fo.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"SearchChannelsCommand",inputFilterSensitiveLog:Kr,outputFilterSensitiveLog:Jr,[d]:{service:"ChimeMessagingService",operation:"SearchChannels"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer}),s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels`,c=Vn({operation:[,"search"],"max-results":[()=>void 0!==e.MaxResults,()=>e.MaxResults.toString()],"next-token":[,e.NextToken]});let l;return l=JSON.stringify(Hn(e,{Fields:e=>In(e)})),new h({protocol:i,hostname:n,port:r,method:"POST",headers:o,path:s,query:c,body:l})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{Channels:e=>ga(e,t),NextToken:hn});return Object.assign(n,r),n})(e,t)}}class ho extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,ho.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"SendChannelMessageCommand",inputFilterSensitiveLog:Zr,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"SendChannelMessage"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer});let s,c=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/messages`;return c=Nn(c,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=JSON.stringify(Hn(e,{ClientRequestToken:[!0,e=>e??Pt()],Content:[],ContentType:[],MessageAttributes:e=>In(e),Metadata:[],Persistence:[],PushNotification:e=>In(e),SubChannelId:[],Target:e=>In(e),Type:[]})),new h({protocol:i,hostname:n,port:r,method:"POST",headers:o,path:c,body:s})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(201!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,MessageId:hn,Status:In,SubChannelId:hn});return Object.assign(n,r),n})(e,t)}}class mo extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,mo.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"TagResourceCommand",inputFilterSensitiveLog:Qr,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"TagResource"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=`${a?.endsWith("/")?a.slice(0,-1):a||""}/tags`,s=Vn({operation:[,"tag-resource"]});let c;return c=JSON.stringify(Hn(e,{ResourceARN:[],Tags:e=>In(e)})),new h({protocol:i,hostname:n,port:r,method:"POST",headers:{"content-type":"application/json"},path:o,query:s,body:c})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ResourceLimitExceededException":case"com.amazonaws.chimesdkmessaging#ResourceLimitExceededException":throw await ca(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)});return await on(e.body,t),n})(e,t)}}class po extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,po.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"UntagResourceCommand",inputFilterSensitiveLog:Yr,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"UntagResource"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=`${a?.endsWith("/")?a.slice(0,-1):a||""}/tags`,s=Vn({operation:[,"untag-resource"]});let c;return c=JSON.stringify(Hn(e,{ResourceARN:[],TagKeys:e=>In(e)})),new h({protocol:i,hostname:n,port:r,method:"POST",headers:{"content-type":"application/json"},path:o,query:s,body:c})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)});return await on(e.body,t),n})(e,t)}}class go extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,go.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"UpdateChannelCommand",inputFilterSensitiveLog:Xr,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"UpdateChannel"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer});let s,c=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}`;return c=Nn(c,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),s=JSON.stringify(Hn(e,{Metadata:[],Mode:[],Name:[]})),new h({protocol:i,hostname:n,port:r,method:"PUT",headers:o,path:c,body:s})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn});return Object.assign(n,r),n})(e,t)}}class vo extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,vo.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"UpdateChannelFlowCommand",inputFilterSensitiveLog:ea,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"UpdateChannelFlow"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint();let o,s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channel-flows/{ChannelFlowArn}`;return s=Nn(s,e,"ChannelFlowArn",(()=>e.ChannelFlowArn),"{ChannelFlowArn}",!1),o=JSON.stringify(Hn(e,{Name:[],Processors:e=>In(e)})),new h({protocol:i,hostname:n,port:r,method:"PUT",headers:{"content-type":"application/json"},path:s,body:o})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelFlowArn:hn});return Object.assign(n,r),n})(e,t)}}class bo extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,bo.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"UpdateChannelMessageCommand",inputFilterSensitiveLog:ta,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"UpdateChannelMessage"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"content-type":"application/json","x-amz-chime-bearer":e.ChimeBearer});let s,c=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/messages/{MessageId}`;return c=Nn(c,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),c=Nn(c,e,"MessageId",(()=>e.MessageId),"{MessageId}",!1),s=JSON.stringify(Hn(e,{Content:[],ContentType:[],Metadata:[],SubChannelId:[]})),new h({protocol:i,hostname:n,port:r,method:"PUT",headers:o,path:c,body:s})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn,MessageId:hn,Status:In,SubChannelId:hn});return Object.assign(n,r),n})(e,t)}}class yo extends sn{static getEndpointParameterInstructions(){return{UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}}constructor(e){super(),this.input=e}resolveMiddleware(e,t,n){this.middlewareStack.use(pt(t,this.serialize,this.deserialize)),this.middlewareStack.use(vt(t,yo.getEndpointParameterInstructions()));const i=e.concat(this.middlewareStack),{logger:r}=t,a={logger:r,clientName:"ChimeSDKMessagingClient",commandName:"UpdateChannelReadMarkerCommand",inputFilterSensitiveLog:e=>e,outputFilterSensitiveLog:e=>e,[d]:{service:"ChimeMessagingService",operation:"UpdateChannelReadMarker"}},{requestHandler:o}=t;return i.resolve((e=>o.handle(e.request,n||{})),a)}serialize(e,t){return(async(e,t)=>{const{hostname:n,protocol:i="https",port:r,path:a}=await t.endpoint(),o=Vn({},ba,{"x-amz-chime-bearer":e.ChimeBearer});let s=`${a?.endsWith("/")?a.slice(0,-1):a||""}/channels/{ChannelArn}/readMarker`;return s=Nn(s,e,"ChannelArn",(()=>e.ChannelArn),"{ChannelArn}",!1),new h({protocol:i,hostname:n,port:r,method:"PUT",headers:o,path:s,body:void 0})})(e,t)}deserialize(e,t){return(async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return(async(e,t)=>{const n={...e,body:await Sa(e.body,t)},i=Ca(e,n.body);switch(i){case"BadRequestException":case"com.amazonaws.chimesdkmessaging#BadRequestException":throw await ra(n);case"ConflictException":case"com.amazonaws.chimesdkmessaging#ConflictException":throw await aa(n);case"ForbiddenException":case"com.amazonaws.chimesdkmessaging#ForbiddenException":throw await oa(n);case"ServiceFailureException":case"com.amazonaws.chimesdkmessaging#ServiceFailureException":throw await la(n);case"ServiceUnavailableException":case"com.amazonaws.chimesdkmessaging#ServiceUnavailableException":throw await da(n);case"ThrottledClientException":case"com.amazonaws.chimesdkmessaging#ThrottledClientException":throw await ua(n);case"UnauthorizedClientException":case"com.amazonaws.chimesdkmessaging#UnauthorizedClientException":throw await fa(n);default:const t=n.body;return na({output:e,parsedBody:t,errorCode:i})}})(e,t);const n=Vn({$metadata:va(e)}),i=un(fn(await ya(e.body,t)),"body"),r=Hn(i,{ChannelArn:hn});return Object.assign(n,r),n})(e,t)}}const So={AssociateChannelFlowCommand:wa,BatchCreateChannelMembershipCommand:Ma,ChannelFlowCallbackCommand:za,CreateChannelCommand:xa,CreateChannelBanCommand:ka,CreateChannelFlowCommand:Va,CreateChannelMembershipCommand:Ha,CreateChannelModeratorCommand:Ea,DeleteChannelCommand:Ta,DeleteChannelBanCommand:La,DeleteChannelFlowCommand:Aa,DeleteChannelMembershipCommand:_a,DeleteChannelMessageCommand:Na,DeleteChannelModeratorCommand:Ia,DeleteMessagingStreamingConfigurationsCommand:Pa,DescribeChannelCommand:Ra,DescribeChannelBanCommand:Oa,DescribeChannelFlowCommand:Da,DescribeChannelMembershipCommand:Fa,DescribeChannelMembershipForAppInstanceUserCommand:Ba,DescribeChannelModeratedByAppInstanceUserCommand:Ua,DescribeChannelModeratorCommand:ja,DisassociateChannelFlowCommand:qa,GetChannelMembershipPreferencesCommand:Wa,GetChannelMessageCommand:$a,GetChannelMessageStatusCommand:Ga,GetMessagingSessionEndpointCommand:Ka,GetMessagingStreamingConfigurationsCommand:Ja,ListChannelBansCommand:Za,ListChannelFlowsCommand:Qa,ListChannelMembershipsCommand:Ya,ListChannelMembershipsForAppInstanceUserCommand:Xa,ListChannelMessagesCommand:eo,ListChannelModeratorsCommand:to,ListChannelsCommand:io,ListChannelsAssociatedWithChannelFlowCommand:no,ListChannelsModeratedByAppInstanceUserCommand:ro,ListSubChannelsCommand:ao,ListTagsForResourceCommand:oo,PutChannelExpirationSettingsCommand:so,PutChannelMembershipPreferencesCommand:co,PutMessagingStreamingConfigurationsCommand:lo,RedactChannelMessageCommand:uo,SearchChannelsCommand:fo,SendChannelMessageCommand:ho,TagResourceCommand:mo,UntagResourceCommand:po,UpdateChannelCommand:go,UpdateChannelFlowCommand:vo,UpdateChannelMessageCommand:bo,UpdateChannelReadMarkerCommand:yo};class Co extends fi{}((e,t)=>{for(const n of Object.keys(e)){const i=e[n],r=async function(e,t,n){const r=new i(e);if("function"==typeof t)this.send(r,t);else{if("function"!=typeof n)return this.send(r,t);if("object"!=typeof t)throw new Error("Expected http options but got "+typeof t);this.send(r,t||{},n)}},a=(n[0].toLowerCase()+n.slice(1)).replace(/Command$/,"");t.prototype[a]=r}})(So,Co);const wo=async(e,t,...n)=>await e.send(new Za(t),...n);async function*Mo(e,t,...n){let i,r=e.startingToken||void 0,a=!0;for(;a;){if(t.NextToken=r,t.MaxResults=e.pageSize,!(e.client instanceof fi))throw new Error("Invalid client, expected ChimeSDKMessaging | ChimeSDKMessagingClient");i=await wo(e.client,t,...n),yield i;const o=r;r=i.NextToken,a=!(!r||e.stopOnSameToken&&r===o)}}const zo=async(e,t,...n)=>await e.send(new Qa(t),...n);async function*ko(e,t,...n){let i,r=e.startingToken||void 0,a=!0;for(;a;){if(t.NextToken=r,t.MaxResults=e.pageSize,!(e.client instanceof fi))throw new Error("Invalid client, expected ChimeSDKMessaging | ChimeSDKMessagingClient");i=await zo(e.client,t,...n),yield i;const o=r;r=i.NextToken,a=!(!r||e.stopOnSameToken&&r===o)}}const xo=async(e,t,...n)=>await e.send(new Xa(t),...n);async function*Vo(e,t,...n){let i,r=e.startingToken||void 0,a=!0;for(;a;){if(t.NextToken=r,t.MaxResults=e.pageSize,!(e.client instanceof fi))throw new Error("Invalid client, expected ChimeSDKMessaging | ChimeSDKMessagingClient");i=await xo(e.client,t,...n),yield i;const o=r;r=i.NextToken,a=!(!r||e.stopOnSameToken&&r===o)}}const Ho=async(e,t,...n)=>await e.send(new Ya(t),...n);async function*Eo(e,t,...n){let i,r=e.startingToken||void 0,a=!0;for(;a;){if(t.NextToken=r,t.MaxResults=e.pageSize,!(e.client instanceof fi))throw new Error("Invalid client, expected ChimeSDKMessaging | ChimeSDKMessagingClient");i=await Ho(e.client,t,...n),yield i;const o=r;r=i.NextToken,a=!(!r||e.stopOnSameToken&&r===o)}}const Lo=async(e,t,...n)=>await e.send(new eo(t),...n);async function*To(e,t,...n){let i,r=e.startingToken||void 0,a=!0;for(;a;){if(t.NextToken=r,t.MaxResults=e.pageSize,!(e.client instanceof fi))throw new Error("Invalid client, expected ChimeSDKMessaging | ChimeSDKMessagingClient");i=await Lo(e.client,t,...n),yield i;const o=r;r=i.NextToken,a=!(!r||e.stopOnSameToken&&r===o)}}const Ao=async(e,t,...n)=>await e.send(new to(t),...n);async function*_o(e,t,...n){let i,r=e.startingToken||void 0,a=!0;for(;a;){if(t.NextToken=r,t.MaxResults=e.pageSize,!(e.client instanceof fi))throw new Error("Invalid client, expected ChimeSDKMessaging | ChimeSDKMessagingClient");i=await Ao(e.client,t,...n),yield i;const o=r;r=i.NextToken,a=!(!r||e.stopOnSameToken&&r===o)}}const No=async(e,t,...n)=>await e.send(new no(t),...n);async function*Io(e,t,...n){let i,r=e.startingToken||void 0,a=!0;for(;a;){if(t.NextToken=r,t.MaxResults=e.pageSize,!(e.client instanceof fi))throw new Error("Invalid client, expected ChimeSDKMessaging | ChimeSDKMessagingClient");i=await No(e.client,t,...n),yield i;const o=r;r=i.NextToken,a=!(!r||e.stopOnSameToken&&r===o)}}const Po=async(e,t,...n)=>await e.send(new ro(t),...n);async function*Oo(e,t,...n){let i,r=e.startingToken||void 0,a=!0;for(;a;){if(t.NextToken=r,t.MaxResults=e.pageSize,!(e.client instanceof fi))throw new Error("Invalid client, expected ChimeSDKMessaging | ChimeSDKMessagingClient");i=await Po(e.client,t,...n),yield i;const o=r;r=i.NextToken,a=!(!r||e.stopOnSameToken&&r===o)}}const Ro=async(e,t,...n)=>await e.send(new io(t),...n);async function*Do(e,t,...n){let i,r=e.startingToken||void 0,a=!0;for(;a;){if(t.NextToken=r,t.MaxResults=e.pageSize,!(e.client instanceof fi))throw new Error("Invalid client, expected ChimeSDKMessaging | ChimeSDKMessagingClient");i=await Ro(e.client,t,...n),yield i;const o=r;r=i.NextToken,a=!(!r||e.stopOnSameToken&&r===o)}}const Fo=async(e,t,...n)=>await e.send(new ao(t),...n);async function*Bo(e,t,...n){let i,r=e.startingToken||void 0,a=!0;for(;a;){if(t.NextToken=r,t.MaxResults=e.pageSize,!(e.client instanceof fi))throw new Error("Invalid client, expected ChimeSDKMessaging | ChimeSDKMessagingClient");i=await Fo(e.client,t,...n),yield i;const o=r;r=i.NextToken,a=!(!r||e.stopOnSameToken&&r===o)}}const Uo=async(e,t,...n)=>await e.send(new fo(t),...n);async function*jo(e,t,...n){let i,r=e.startingToken||void 0,a=!0;for(;a;){if(t.NextToken=r,t.MaxResults=e.pageSize,!(e.client instanceof fi))throw new Error("Invalid client, expected ChimeSDKMessaging | ChimeSDKMessagingClient");i=await Uo(e.client,t,...n),yield i;const o=r;r=i.NextToken,a=!(!r||e.stopOnSameToken&&r===o)}}},9649:(e,t,n)=>{"use strict";n.r(t),n.d(t,{fromHex:()=>a,toHex:()=>o});const i={},r={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();1===t.length&&(t=`0${t}`),i[e]=t,r[t]=e}function a(e){if(e.length%2!=0)throw new Error("Hex encoded strings must have an even number length");const t=new Uint8Array(e.length/2);for(let n=0;n{"use strict";n.r(t),n.d(t,{locateWindow:()=>r});const i={};function r(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:i}},4006:(e,t,n)=>{"use strict";n.r(t),n.d(t,{fromUtf8:()=>i,toUtf8:()=>r});const i=e=>"function"==typeof TextEncoder?function(e){return(new TextEncoder).encode(e)}(e):(e=>{const t=[];for(let n=0,i=e.length;n>6|192,63&i|128);else if(n+1>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}else t.push(i>>12|224,i>>6&63|128,63&i|128)}return Uint8Array.from(t)})(e),r=e=>"function"==typeof TextDecoder?function(e){return new TextDecoder("utf-8").decode(e)}(e):(e=>{let t="";for(let n=0,i=e.length;ne.toString(16))).join("%");t+=decodeURIComponent(r)}else t+=String.fromCharCode((15&i)<<12|(63&e[++n])<<6|63&e[++n])}return t})(e)},8045:e=>{"use strict";e.exports=function(e,t){for(var n=new Array(arguments.length-1),i=0,r=2,a=!0;r{"use strict";var n=t;n.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&"="===e.charAt(t);)++n;return Math.ceil(3*e.length)/4-n};for(var i=new Array(64),r=new Array(123),a=0;a<64;)r[i[a]=a<26?a+65:a<52?a+71:a<62?a-4:a-59|43]=a++;n.encode=function(e,t,n){for(var r,a=null,o=[],s=0,c=0;t>2],r=(3&l)<<4,c=1;break;case 1:o[s++]=i[r|l>>4],r=(15&l)<<2,c=2;break;case 2:o[s++]=i[r|l>>6],o[s++]=i[63&l],c=0}s>8191&&((a||(a=[])).push(String.fromCharCode.apply(String,o)),s=0)}return c&&(o[s++]=i[r],o[s++]=61,1===c&&(o[s++]=61)),a?(s&&a.push(String.fromCharCode.apply(String,o.slice(0,s))),a.join("")):String.fromCharCode.apply(String,o.slice(0,s))};var o="invalid encoding";n.decode=function(e,t,n){for(var i,a=n,s=0,c=0;c1)break;if(void 0===(l=r[l]))throw Error(o);switch(s){case 0:i=l,s=1;break;case 1:t[n++]=i<<2|(48&l)>>4,i=l,s=2;break;case 2:t[n++]=(15&i)<<4|(60&l)>>2,i=l,s=3;break;case 3:t[n++]=(3&i)<<6|l,s=0}}if(1===s)throw Error(o);return n-a},n.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},4358:e=>{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),n=new Uint8Array(t.buffer),i=128===n[3];function r(e,i,r){t[0]=e,i[r]=n[0],i[r+1]=n[1],i[r+2]=n[2],i[r+3]=n[3]}function a(e,i,r){t[0]=e,i[r]=n[3],i[r+1]=n[2],i[r+2]=n[1],i[r+3]=n[0]}function o(e,i){return n[0]=e[i],n[1]=e[i+1],n[2]=e[i+2],n[3]=e[i+3],t[0]}function s(e,i){return n[3]=e[i],n[2]=e[i+1],n[1]=e[i+2],n[0]=e[i+3],t[0]}e.writeFloatLE=i?r:a,e.writeFloatBE=i?a:r,e.readFloatLE=i?o:s,e.readFloatBE=i?s:o}():function(){function t(e,t,n,i){var r=t<0?1:0;if(r&&(t=-t),0===t)e(1/t>0?0:2147483648,n,i);else if(isNaN(t))e(2143289344,n,i);else if(t>34028234663852886e22)e((r<<31|2139095040)>>>0,n,i);else if(t<11754943508222875e-54)e((r<<31|Math.round(t/1401298464324817e-60))>>>0,n,i);else{var a=Math.floor(Math.log(t)/Math.LN2);e((r<<31|a+127<<23|8388607&Math.round(t*Math.pow(2,-a)*8388608))>>>0,n,i)}}function o(e,t,n){var i=e(t,n),r=2*(i>>31)+1,a=i>>>23&255,o=8388607&i;return 255===a?o?NaN:r*(1/0):0===a?1401298464324817e-60*r*o:r*Math.pow(2,a-150)*(o+8388608)}e.writeFloatLE=t.bind(null,n),e.writeFloatBE=t.bind(null,i),e.readFloatLE=o.bind(null,r),e.readFloatBE=o.bind(null,a)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),n=new Uint8Array(t.buffer),i=128===n[7];function r(e,i,r){t[0]=e,i[r]=n[0],i[r+1]=n[1],i[r+2]=n[2],i[r+3]=n[3],i[r+4]=n[4],i[r+5]=n[5],i[r+6]=n[6],i[r+7]=n[7]}function a(e,i,r){t[0]=e,i[r]=n[7],i[r+1]=n[6],i[r+2]=n[5],i[r+3]=n[4],i[r+4]=n[3],i[r+5]=n[2],i[r+6]=n[1],i[r+7]=n[0]}function o(e,i){return n[0]=e[i],n[1]=e[i+1],n[2]=e[i+2],n[3]=e[i+3],n[4]=e[i+4],n[5]=e[i+5],n[6]=e[i+6],n[7]=e[i+7],t[0]}function s(e,i){return n[7]=e[i],n[6]=e[i+1],n[5]=e[i+2],n[4]=e[i+3],n[3]=e[i+4],n[2]=e[i+5],n[1]=e[i+6],n[0]=e[i+7],t[0]}e.writeDoubleLE=i?r:a,e.writeDoubleBE=i?a:r,e.readDoubleLE=i?o:s,e.readDoubleBE=i?s:o}():function(){function t(e,t,n,i,r,a){var o=i<0?1:0;if(o&&(i=-i),0===i)e(0,r,a+t),e(1/i>0?0:2147483648,r,a+n);else if(isNaN(i))e(0,r,a+t),e(2146959360,r,a+n);else if(i>17976931348623157e292)e(0,r,a+t),e((o<<31|2146435072)>>>0,r,a+n);else{var s;if(i<22250738585072014e-324)e((s=i/5e-324)>>>0,r,a+t),e((o<<31|s/4294967296)>>>0,r,a+n);else{var c=Math.floor(Math.log(i)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(s=i*Math.pow(2,-c))>>>0,r,a+t),e((o<<31|c+1023<<20|1048576*s&1048575)>>>0,r,a+n)}}}function o(e,t,n,i,r){var a=e(i,r+t),o=e(i,r+n),s=2*(o>>31)+1,c=o>>>20&2047,l=4294967296*(1048575&o)+a;return 2047===c?l?NaN:s*(1/0):0===c?5e-324*s*l:s*Math.pow(2,c-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,n,0,4),e.writeDoubleBE=t.bind(null,i,4,0),e.readDoubleLE=o.bind(null,r,0,4),e.readDoubleBE=o.bind(null,a,4,0)}(),e}function n(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function i(e,t,n){t[n]=e>>>24,t[n+1]=e>>>16&255,t[n+2]=e>>>8&255,t[n+3]=255&e}function r(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function a(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},4153:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},9390:e=>{"use strict";e.exports=function(e,t,n){var i=n||8192,r=i>>>1,a=null,o=i;return function(n){if(n<1||n>r)return e(n);o+n>i&&(a=e(i),o=0);var s=t.call(a,o,o+=n);return 7&o&&(o=1+(7|o)),s}}},1447:(e,t)=>{"use strict";var n=t;n.length=function(e){for(var t=0,n=0,i=0;i191&&i<224?a[o++]=(31&i)<<6|63&e[t++]:i>239&&i<365?(i=((7&i)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,a[o++]=55296+(i>>10),a[o++]=56320+(1023&i)):a[o++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((r||(r=[])).push(String.fromCharCode.apply(String,a)),o=0);return r?(o&&r.push(String.fromCharCode.apply(String,a.slice(0,o))),r.join("")):String.fromCharCode.apply(String,a.slice(0,o))},n.write=function(e,t,n){for(var i,r,a=n,o=0;o>6|192,t[n++]=63&i|128):55296==(64512&i)&&56320==(64512&(r=e.charCodeAt(o+1)))?(i=65536+((1023&i)<<10)+(1023&r),++o,t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128);return n-a}},6762:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(8192));t.default=class{constructor(e,t,n,i=1e3,r=200){this.realtimeController=e,this.selfAttendeeId=t,this.hasBandwidthPriorityCallback=n,this.waitIntervalMs=i,this.updateIntervalMs=r,this.speakerScores={},this.speakerMuteState={},this.detectorCallbackToHandler=new Map,this.detectorCallbackToScoresTimer=new Map,this.detectorCallbackToActivityTimer=new Map,this.hasBandwidthPriority=!1,this.mostRecentUpdateTimestamp={}}needUpdate(e){return!this.activeSpeakers||0===this.speakerScores[e]&&this.activeSpeakers.includes(e)||this.speakerScores[e]>0&&!this.activeSpeakers.includes(e)}updateActiveSpeakers(e,t,n){if(!this.needUpdate(n))return;const i=[],r=Object.keys(this.speakerScores);for(let e=0;et.activeScore-e.activeScore)).filter((function(e){return e.activeScore>0})).map((function(e){return e.attendeeId}));this.activeSpeakers=a,t(a);const o=a.length>0&&a[0]===this.selfAttendeeId&&e.prioritizeVideoSendBandwidthForActiveSpeaker();this.hasBandwidthPriority!==o&&(this.hasBandwidthPriority=o,this.hasBandwidthPriorityCallback(o))}updateScore(e,t,n,i,r){const a=e.calculateScore(n,i,r);this.speakerScores[n]!==a&&(this.speakerScores[n]=a,this.mostRecentUpdateTimestamp[n]=Date.now(),this.updateActiveSpeakers(e,t,n))}subscribe(e,t,n,i){const r=(n,i)=>{if(!i)return this.speakerScores[n]=0,this.mostRecentUpdateTimestamp[n]=Date.now(),void this.updateActiveSpeakers(e,t,n);this.realtimeController.realtimeSubscribeToVolumeIndicator(n,((n,i,r,a)=>{this.mostRecentUpdateTimestamp[n]=Date.now(),null!==r&&(this.speakerMuteState[n]=r),this.updateScore(e,t,n,i,r)}))};this.detectorCallbackToHandler.set(t,r);const o=new a.default(this.updateIntervalMs);if(o.start((()=>{for(const n in this.speakerScores)Date.now()-this.mostRecentUpdateTimestamp[n]>this.waitIntervalMs&&this.updateScore(e,t,n,0,this.speakerMuteState[n])})),this.detectorCallbackToActivityTimer.set(t,o),n&&i){const e=new a.default(i);e.start((()=>{n(this.speakerScores)})),this.detectorCallbackToScoresTimer.set(t,e)}this.realtimeController.realtimeSubscribeToAttendeeIdPresence(r)}unsubscribe(e){const t=this.detectorCallbackToHandler.get(e);this.detectorCallbackToHandler.delete(e),t&&this.realtimeController.realtimeUnsubscribeToAttendeeIdPresence(t);const n=this.detectorCallbackToActivityTimer.get(e);n&&(n.stop(),this.detectorCallbackToActivityTimer.delete(e));const i=this.detectorCallbackToScoresTimer.get(e);i&&(i.stop(),this.detectorCallbackToHandler.delete(e))}destroy(){return i(this,void 0,void 0,(function*(){for(const e of this.detectorCallbackToHandler.values())this.realtimeController.realtimeUnsubscribeToAttendeeIdPresence(e);for(const e of this.detectorCallbackToActivityTimer.values())e.stop();for(const e of this.detectorCallbackToScoresTimer.values())e.stop();this.detectorCallbackToHandler.clear(),this.detectorCallbackToActivityTimer.clear(),this.detectorCallbackToScoresTimer.clear()}))}}},4498:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e=.9,t=.01,n=.2,i=.2){this.speakerWeight=e,this.cutoffThreshold=t,this.silenceThreshold=n,this.takeoverRate=i,this.volumes={}}calculateScore(e,t,n){(n||null===t)&&(t=0),this.volumes.hasOwnProperty(e)||(this.volumes[e]=0),t=t>this.silenceThreshold?1:0;const i=this.volumes[e]*this.speakerWeight+t*(1-this.speakerWeight);this.volumes[e]=i;for(const n in this.volumes)n!==e&&(this.volumes[n]=Math.max(this.volumes[n]-this.takeoverRate*t,0));return i{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n{constructor(e,t){this.appName=e,this.appVersion=t}static create(e,t){const i=/^[a-zA-Z0-9]+[a-zA-Z0-9_-]*[a-zA-Z0-9]+$/g;if(!e||e.length>32)throw new Error("appName should be a valid string and 1 to 32 characters in length");if(!i.test(e))throw new Error(`appName must satisfy ${i} regular expression`);if(!t||t.length>32)throw new Error("appVersion should be a valid string and 1 to 32 characters in length");if(!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/gm.test(t))throw new Error("appVersion must satisfy Semantic Versioning format");return new n(e,t)}}t.default=n},6309:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{}},6940:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(6244)),o=r(n(4185));t.default=class{constructor(e){this.logger=e,this.audioDevice=null,this.audioElement=null,this.audioStream=null,this.browserBehavior=new a.default,this.observers=new Set}bindAudioElement(e){return i(this,void 0,void 0,(function*(){if(!e)throw new Error(`Cannot bind audio element: ${e}`);return this.audioElement=e,this.audioElement.autoplay=!0,this.bindAudioMix()}))}unbindAudioElement(){this.audioElement&&(this.audioElement.srcObject=null,this.audioElement=null,this.forEachObserver((e=>{this.audioStream&&e.meetingAudioStreamBecameInactive(this.audioStream)})))}bindAudioStream(e){return i(this,void 0,void 0,(function*(){if(e){this.audioStream=e;try{yield this.bindAudioMix()}catch(e){this.logger&&this.logger.warn(`Failed to bind audio stream: ${e}`)}}}))}bindAudioDevice(e){return i(this,void 0,void 0,(function*(){if(e&&!this.browserBehavior.supportsSetSinkId())throw new Error("Cannot select audio output device. This browser does not support setSinkId.");return this.audioDevice=e,this.bindAudioMix()}))}forEachObserver(e){for(const t of this.observers)o.default.nextTick((()=>{e(t)}))}bindAudioMix(){var e,t;return i(this,void 0,void 0,(function*(){if(!this.audioElement)return;const n=this.audioElement.srcObject;this.audioStream&&(this.audioElement.srcObject=this.audioStream),n!==this.audioStream&&this.forEachObserver((e=>{n&&e.meetingAudioStreamBecameInactive(n),this.audioStream&&e.meetingAudioStreamBecameActive(this.audioStream)}));const i=(null===(e=this.audioDevice)||void 0===e?void 0:e.deviceId)!==this.audioElement.sinkId;if(i&&void 0===this.audioElement.sinkId)throw new Error("Cannot select audio output device. This browser does not support setSinkId.");const r=this.audioDevice?this.audioDevice.deviceId:"";if(r===this.audioElement.sinkId)return;const a=this.audioElement,o=this.audioStream;if(this.browserBehavior.hasChromiumWebRTC()&&(a.srcObject=null),i)try{yield a.setSinkId(r)}catch(e){throw null===(t=this.logger)||void 0===t||t.error(`Failed to set sinkId for audio element: ${e}`),e}this.browserBehavior.hasChromiumWebRTC()&&(a.srcObject=o)}))}getCurrentMeetingAudioStream(){return i(this,void 0,void 0,(function*(){return this.audioStream}))}addAudioMixObserver(e){return i(this,void 0,void 0,(function*(){this.observers.add(e)}))}removeAudioMixObserver(e){return i(this,void 0,void 0,(function*(){this.observers.delete(e)}))}audioOutputDidChange(e){return i(this,void 0,void 0,(function*(){return this.logger.info("Receive an audio output change event"),this.bindAudioDevice(e)}))}}},1379:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(6244));class a{constructor(e=null,t=!0){this.audioBitrateBps=e,this.enableAudioRedundancy=(new r.default).supportsAudioRedundancy()&&t}static fullbandSpeechMono(e=!0){return new a(4e4,e)}static fullbandMusicMono(e=!0){return new a(64e3,e)}static fullbandMusicStereo(e=!0){return new a(128e3,e)}isStereo(){return 128e3===this.audioBitrateBps}hasRedundancyEnabled(){return this.enableAudioRedundancy}}t.default=a},3894:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_VIDEO_SUBSCRIPTION_LIMIT=void 0,t.DEFAULT_VIDEO_SUBSCRIPTION_LIMIT=25,t.default=class{constructor(){this.logger=null,this.browserBehavior=null,this.meetingSessionConfiguration=null,this.signalingClient=null,this.peer=null,this.previousSdpOffer=null,this.sdpOfferInit=null,this.audioVideoController=null,this.realtimeController=null,this.videoTileController=null,this.mediaStreamBroker=null,this.activeAudioInput=void 0,this.activeVideoInput=void 0,this.audioMixController=null,this.transceiverController=null,this.indexFrame=null,this.iceCandidates=[],this.iceCandidateHandler=null,this.iceGatheringStateEventHandler=null,this.sdpAnswer=null,this.turnCredentials=null,this.reconnectController=null,this.removableObservers=[],this.audioProfile=null,this.videoStreamIndex=null,this.videoDownlinkBandwidthPolicy=null,this.videoUplinkBandwidthPolicy=null,this.lastKnownVideoAvailability=null,this.videoCaptureAndEncodeParameter=null,this.videosToReceive=null,this.lastVideosToReceive=null,this.videoSubscriptions=null,this.lastVideoSubscriptionConfiguration=new Map,this.videoSubscriptionLimit=t.DEFAULT_VIDEO_SUBSCRIPTION_LIMIT,this.previousSdpAnswerAsString="",this.serverSupportsCompression=!1,this.videoSendCodecPreferences=[],this.currentVideoSendCodec=void 0,this.meetingSupportedVideoSendCodecPreferences=void 0,this.prioritizedSendVideoCodecCapabilities=[],this.videosPaused=null,this.videoDuplexMode=null,this.volumeIndicatorAdapter=null,this.statsCollector=null,this.connectionMonitor=null,this.videoInputAttachedTimestampMs=0,this.audioDeviceInformation={},this.videoDeviceInformation={},this.enableSimulcast=!1,this.enableSVC=!1,this.eventController=null,this.signalingOpenDurationMs=null,this.iceGatheringDurationMs=null,this.startAudioVideoTimestamp=null,this.attendeePresenceDurationMs=null,this.meetingStartDurationMs=null,this.poorConnectionCount=0,this.maxVideoTileCount=0,this.startTimeMs=null}resetConnectionSpecificState(){this.peer&&this.peer.close(),this.peer=null,this.previousSdpOffer=null,this.sdpOfferInit=null,void 0!==this.transceiverController&&this.transceiverController.reset(),this.indexFrame=null,this.iceCandidates=[],this.iceCandidateHandler=null,this.sdpAnswer=null,this.turnCredentials=null,this.videoDownlinkBandwidthPolicy.reset(),this.videoUplinkBandwidthPolicy.reset&&this.videoUplinkBandwidthPolicy.reset(),this.lastVideosToReceive=null,this.lastVideoSubscriptionConfiguration=new Map,this.videoSubscriptions=null,this.videoSubscriptionLimit=t.DEFAULT_VIDEO_SUBSCRIPTION_LIMIT,this.previousSdpAnswerAsString="",this.serverSupportsCompression=!1,this.currentVideoSendCodec=void 0,this.meetingSupportedVideoSendCodecPreferences=void 0,this.videoDuplexMode=null}}},6460:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const c=s(n(6762)),l=s(n(6940)),d=s(n(1379)),u=s(n(6244)),f=s(n(5799)),h=s(n(5437)),m=s(n(7094)),p=s(n(565)),g=s(n(484)),v=s(n(1835)),b=s(n(832)),y=s(n(4428)),S=s(n(7844)),C=s(n(4185)),w=s(n(3240)),M=s(n(3797)),z=s(n(7670)),k=s(n(2005)),x=s(n(5826)),V=a(n(980)),H=s(n(9183)),E=s(n(9171)),L=n(4955),T=s(n(1333)),A=s(n(4014)),_=s(n(8214)),N=s(n(7943)),I=s(n(7271)),P=s(n(244)),O=s(n(1218)),R=s(n(5591)),D=s(n(2352)),F=s(n(1919)),B=s(n(6835)),U=s(n(5417)),j=s(n(1999)),q=s(n(5843)),W=s(n(3842)),$=s(n(6522)),G=s(n(3613)),K=s(n(3381)),J=s(n(9103)),Z=s(n(6706)),Q=s(n(4518)),Y=s(n(4055)),X=s(n(4402)),ee=s(n(2058)),te=s(n(8170)),ne=s(n(8556)),ie=s(n(2032)),re=s(n(8020)),ae=s(n(4664)),oe=n(8807),se=s(n(8740)),ce=s(n(1876)),le=s(n(6804)),de=n(9e3),ue=s(n(4996)),fe=s(n(9376)),he=s(n(88)),me=s(n(3038)),pe=s(n(5196)),ge=s(n(6243)),ve=s(n(7719)),be=s(n(9164)),ye=s(n(3894));class Se{constructor(e,t,n,i,r,a){this._audioProfile=new d.default,this.connectionHealthData=new f.default,this.observerQueue=new Set,this.meetingSessionContext=new ye.default,this.enableSimulcast=!1,this.enableSVC=!1,this.useUpdateTransceiverControllerForUplink=!1,this.totalRetryCount=0,this.startAudioVideoTimestamp=0,this.mayNeedRenegotiationForSimulcastLayerChange=!1,this.promotedToPrimaryMeeting=!1,this.hasGetRTCPeerConnectionStatsDeprecationMessageBeenSent=!1,this.receiveIndexTask=void 0,this.monitorTask=void 0,this.destroyed=!1,this._logger=t,this.sessionStateController=new w.default(this._logger),this._configuration=e,this._webSocketAdapter=n,this._realtimeController=new S.default(i),this._realtimeController.realtimeSetLocalAttendeeId(e.credentials.attendeeId,e.credentials.externalUserId),this._mediaStreamBroker=i,this._reconnectController=r,this._videoTileController=new me.default(new pe.default,this,this._logger),this._audioMixController=new l.default(this._logger),this._mediaStreamBroker.addMediaStreamBrokerObserver(this._audioMixController),this.meetingSessionContext.logger=this._logger,this._eventController=a}destroy(){return o(this,void 0,void 0,(function*(){this.observerQueue.clear(),this._mediaStreamBroker.removeMediaStreamBrokerObserver(this._audioMixController),this.destroyed=!0}))}get configuration(){return this._configuration}get realtimeController(){return this._realtimeController}get activeSpeakerDetector(){return this._activeSpeakerDetector||(this._activeSpeakerDetector=new c.default(this._realtimeController,this._configuration.credentials.attendeeId,this.handleHasBandwidthPriority.bind(this))),this._activeSpeakerDetector}get videoTileController(){return this._videoTileController}get audioMixController(){return this._audioMixController}get logger(){return this._logger}get rtcPeerConnection(){return this.meetingSessionContext&&this.meetingSessionContext.peer||null}get mediaStreamBroker(){return this._mediaStreamBroker}get eventController(){return this._eventController}getRTCPeerConnectionStats(e){return this.hasGetRTCPeerConnectionStatsDeprecationMessageBeenSent||(this.logger.warn("The `getRTCPeerConnectionStats()` is on its way to be deprecated. It makes an additional call to the `getStats` API and therefore may cause slight performance degradation. Please use the new API `clientMetricReport.getRTCStatsReport()` returned by `metricsDidReceive(clientMetricReport)` callback instead."),this.hasGetRTCPeerConnectionStatsDeprecationMessageBeenSent=!0),this.rtcPeerConnection?this.rtcPeerConnection.getStats(e):null}setAudioProfile(e){this._audioProfile=e}addObserver(e){this.logger.info("adding meeting observer"),this.observerQueue.add(e)}removeObserver(e){this.logger.info("removing meeting observer"),this.observerQueue.delete(e)}forEachObserver(e){for(const t of this.observerQueue)C.default.nextTick((()=>{this.observerQueue.has(t)&&e(t)}))}initSignalingClient(){this.connectionHealthData.reset(),this.meetingSessionContext.signalingClient||(this.meetingSessionContext=new ye.default,this.meetingSessionContext.logger=this.logger,this.meetingSessionContext.eventController=this.eventController,this.meetingSessionContext.browserBehavior=new u.default,this.meetingSessionContext.videoSendCodecPreferences=this.videoSendCodecPreferences,this.meetingSessionContext.audioProfile=this._audioProfile,this.meetingSessionContext.meetingSessionConfiguration=this.configuration,this.meetingSessionContext.signalingClient=new x.default(this._webSocketAdapter,this.logger))}uninstallPreStartObserver(){this.meetingSessionContext.signalingClient.removeObserver(this.preStartObserver),this.preStartObserver=void 0}prestart(){return this.logger.info("Pre-connecting signaling connection."),this.createOrReuseSignalingTask().run().then((()=>{const e=()=>o(this,void 0,void 0,(function*(){this.logger.info("Early connection closed; discarding signaling task."),this.signalingTask=void 0,this.uninstallPreStartObserver()}));this.preStartObserver={handleSignalingClientEvent(t){t.type===H.default.WebSocketClosed&&e()}},this.meetingSessionContext.signalingClient.registerObserver(this.preStartObserver)})).catch((e=>{this.logger.error(`Signaling task pre-start failed: ${e}`),this.signalingTask=void 0}))}start(e){this.startReturningPromise(e).then((()=>{this.logger.info("start completed")})).catch((e=>{this.logger.error(`start failed: ${e}`)}))}startReturningPromise(e){return!0===(null==e?void 0:e.signalingOnly)?this.prestart():(this.activeSpeakerDetector,new Promise(((e,t)=>{this.sessionStateController.perform(M.default.Connect,(()=>{this.actionConnect(!1).then(e).catch(t)}))})))}connectWithPromises(e){const t=this.meetingSessionContext;this.monitorTask=new B.default(t,this.configuration.connectionHealthPolicyConfiguration,this.connectionHealthData);const n=this.monitorTask.once(),i=new W.default(t).once();this.receiveIndexTask=new K.default(t),this.monitorTask.pauseResubscribeCheck(),this.receiveIndexTask.pauseIngestion();const r=new Z.default(this.logger,"Signaling",[this.createOrReuseSignalingTask(),new F.default(t),new J.default(t),new R.default(t),this.receiveIndexTask]).once(),a=new I.default(t).once(r),o=new A.default(t).once(a,i),s=new P.default(t).once(o),c=new Q.default(t).once(s),l=new O.default(t).once(c),d=new X.default(t).once(l),u=new $.default(t).once(d);return new Z.default(this.logger,this.wrapTaskName("AudioVideoStart"),[n,((e,t)=>new ee.default(this.logger,t,e))(this.configuration.connectionTimeoutMs,new Z.default(this.logger,"Peer",[d,u,e?new ee.default(this.logger,new j.default(this.logger,"FinalizeConnection",[new te.default(t),new Y.default(t)]),this.meetingSessionContext.meetingSessionConfiguration.attendeePresenceTimeoutMs):new Y.default(t)]))])}actionConnect(e){var t;return o(this,void 0,void 0,(function*(){this.initSignalingClient(),this.uninstallPreStartObserver(),this.meetingSessionContext.mediaStreamBroker=this._mediaStreamBroker,this.meetingSessionContext.realtimeController=this._realtimeController,this.meetingSessionContext.audioMixController=this._audioMixController,this.meetingSessionContext.audioVideoController=this,this.enableSimulcast=this.configuration.enableSimulcastForUnifiedPlanChromiumBasedBrowsers&&(new u.default).hasChromiumWebRTC(),this.enableSimulcast&&this.configuration.enableSVC&&this.logger.warn("SVC cannot be enabled at the same time as simulcast. Disabling SVC, using simulcast."),this.enableSVC=!this.enableSimulcast&&this.configuration.enableSVC&&(new u.default).supportsScalableVideoCoding();const n=!!this.configuration.urls.audioHostURL;if(n?this.enableSimulcast?(this.logger.info("Using transceiver controller with simulcast support"),new b.default(this.configuration.credentials.attendeeId).hasModality(b.default.MODALITY_CONTENT)?this.meetingSessionContext.transceiverController=new ie.default(this.logger,this.meetingSessionContext.browserBehavior,this.meetingSessionContext):this.meetingSessionContext.transceiverController=new re.default(this.logger,this.meetingSessionContext.browserBehavior,this.meetingSessionContext)):(this.logger.info("Using default transceiver controller"),this.meetingSessionContext.transceiverController=new ne.default(this.logger,this.meetingSessionContext.browserBehavior,this.meetingSessionContext)):(this.logger.info("Using video only transceiver controller"),this.meetingSessionContext.transceiverController=new ae.default(this.logger,this.meetingSessionContext.browserBehavior,this.meetingSessionContext)),this.meetingSessionContext.volumeIndicatorAdapter=new be.default(this.logger,this._realtimeController,Se.MIN_VOLUME_DECIBELS,Se.MAX_VOLUME_DECIBELS,this.configuration.credentials.attendeeId),this.meetingSessionContext.videoTileController=this._videoTileController,this.meetingSessionContext.videoDownlinkBandwidthPolicy=this.configuration.videoDownlinkBandwidthPolicy,this.meetingSessionContext.videoUplinkBandwidthPolicy=this.configuration.videoUplinkBandwidthPolicy,this.meetingSessionContext.enableSimulcast=this.enableSimulcast,this.meetingSessionContext.enableSVC=this.enableSVC,this.enableSimulcast){let e=this.meetingSessionContext.videoUplinkBandwidthPolicy;e||(e=new ge.default(this.configuration.credentials.attendeeId,this.meetingSessionContext.logger),this.meetingSessionContext.videoUplinkBandwidthPolicy=e),e.addObserver(this),this.meetingSessionContext.videoDownlinkBandwidthPolicy||(this.meetingSessionContext.videoDownlinkBandwidthPolicy=new le.default(this.meetingSessionContext.logger)),this.meetingSessionContext.videoStreamIndex=new he.default(this.logger)}else this.meetingSessionContext.enableSimulcast=!1,this.meetingSessionContext.videoStreamIndex=new fe.default(this.logger),this.meetingSessionContext.videoUplinkBandwidthPolicy||(this.meetingSessionContext.videoUplinkBandwidthPolicy=new ve.default(this.configuration.credentials.attendeeId,!this.meetingSessionContext.browserBehavior.disableResolutionScaleDown(),this.meetingSessionContext.logger,this.meetingSessionContext.browserBehavior),this.meetingSessionContext.videoUplinkBandwidthPolicy.setSVCEnabled(this.enableSVC)),this.meetingSessionContext.videoDownlinkBandwidthPolicy||(this.meetingSessionContext.videoDownlinkBandwidthPolicy=new ce.default(this.configuration.credentials.attendeeId)),this.meetingSessionContext.videoUplinkBandwidthPolicy.setTransceiverController&&this.meetingSessionContext.videoUplinkBandwidthPolicy.updateTransceiverController&&(this.useUpdateTransceiverControllerForUplink=!0,this.meetingSessionContext.videoUplinkBandwidthPolicy.setTransceiverController(this.meetingSessionContext.transceiverController)),this.meetingSessionContext.audioProfile=this._audioProfile;if(new b.default(this.configuration.credentials.attendeeId).hasModality(b.default.MODALITY_CONTENT)){const e=this.configuration.meetingFeatures.contentMaxResolution===m.default.VideoResolutionUHD;e&&this.setVideoMaxBandwidthKbps(2500),this.meetingSessionContext.videoUplinkBandwidthPolicy.setHighResolutionFeatureEnabled(e)}else{const e=this.configuration.meetingFeatures.videoMaxResolution===m.default.VideoResolutionFHD;this.meetingSessionContext.videoUplinkBandwidthPolicy.setHighResolutionFeatureEnabled(e)}this.meetingSessionContext.videoUplinkBandwidthPolicy&&this.maxUplinkBandwidthKbps&&this.meetingSessionContext.videoUplinkBandwidthPolicy.setIdealMaxBandwidthKbps(this.maxUplinkBandwidthKbps),this.meetingSessionContext.videoDownlinkBandwidthPolicy.bindToTileController&&this.meetingSessionContext.videoDownlinkBandwidthPolicy.bindToTileController(this._videoTileController),this.meetingSessionContext.videoDownlinkBandwidthPolicy.setWantsResubscribeObserver&&this.meetingSessionContext.videoDownlinkBandwidthPolicy.setWantsResubscribeObserver((()=>this.update({needsRenegotiation:!1}))),this.meetingSessionContext.lastKnownVideoAvailability=new v.default,this.meetingSessionContext.videoCaptureAndEncodeParameter=new se.default(0,0,0,0,!1),this.meetingSessionContext.videosToReceive=new ue.default,this.meetingSessionContext.videosPaused=new ue.default,this.meetingSessionContext.statsCollector=new T.default(this,this.logger),this.meetingSessionContext.connectionMonitor=new h.default(this,this._realtimeController,this.connectionHealthData,new y.default(this.meetingSessionContext.signalingClient,Se.PING_PONG_INTERVAL_MS,this.logger),this.meetingSessionContext.statsCollector),this.meetingSessionContext.reconnectController=this._reconnectController,this.meetingSessionContext.videoDeviceInformation={},e||(this.totalRetryCount=0,this._reconnectController.reset(),this.startAudioVideoTimestamp=Date.now(),this.forEachObserver((e=>{oe.Maybe.of(e.audioVideoDidStartConnecting).map((t=>t.bind(e)(!1)))})),null===(t=this.eventController)||void 0===t||t.publishEvent("meetingStartRequested")),this.meetingSessionContext.startAudioVideoTimestamp=this.startAudioVideoTimestamp,this._reconnectController.hasStartedConnectionAttempt()?this._reconnectController.startedConnectionAttempt(!1):this._reconnectController.startedConnectionAttempt(!0);const i=n&&this.meetingSessionContext.meetingSessionConfiguration.attendeePresenceTimeoutMs>0;this.logger.info("Needs to wait for attendee presence? "+i);const r=this.connectWithPromises(i);try{yield r.run(),this.connectionHealthData.setConnectionStartTime(),this._mediaStreamBroker.addMediaStreamBrokerObserver(this),this.sessionStateController.perform(M.default.FinishConnecting,(()=>{this.eventController&&(this.meetingSessionContext.meetingStartDurationMs=Date.now()-this.startAudioVideoTimestamp,this.eventController.publishEvent("meetingStartSucceeded",{maxVideoTileCount:this.meetingSessionContext.maxVideoTileCount,poorConnectionCount:this.meetingSessionContext.poorConnectionCount,retryCount:this.totalRetryCount,signalingOpenDurationMs:this.meetingSessionContext.signalingOpenDurationMs,iceGatheringDurationMs:this.meetingSessionContext.iceGatheringDurationMs,meetingStartDurationMs:this.meetingSessionContext.meetingStartDurationMs})),this.meetingSessionContext.startTimeMs=Date.now(),this.actionFinishConnecting()}))}catch(e){this.signalingTask=void 0;const t=new p.default(this.getMeetingStatusCode(e)||g.default.TaskFailed);if(this.logger.info(`Start failed: ${t} due to error ${e}.`),this.sessionStateController.state()===z.default.NotConnected)return void this.logger.info("Start failed and not connected. Not cleaning up.");this.sessionStateController.perform(M.default.Fail,(()=>o(this,void 0,void 0,(function*(){yield this.actionDisconnect(t,!0,e),this.handleMeetingSessionStatus(t,e)||this.notifyStop(t,e)}))))}}))}createOrReuseSignalingTask(){return this.signalingTask||(this.initSignalingClient(),this.signalingTask=new ee.default(this.logger,new U.default(this.meetingSessionContext),this.configuration.connectionTimeoutMs).once()),this.signalingTask}actionFinishConnecting(){this.signalingTask=void 0,this.meetingSessionContext.videoDuplexMode=L.SdkStreamServiceType.RX,this.meetingSessionContext.enableSimulcast||(this.useUpdateTransceiverControllerForUplink?this.meetingSessionContext.videoUplinkBandwidthPolicy.updateTransceiverController():this.enforceBandwidthLimitationForSender(this.meetingSessionContext.videoCaptureAndEncodeParameter.encodeBitrates()[0])),this.forEachObserver((e=>{oe.Maybe.of(e.audioVideoDidStart).map((t=>t.bind(e)()))})),this._reconnectController.reset(),this.receiveIndexTask.resumeIngestion(),this.monitorTask.resumeResubscribeCheck()}stopReturningPromise(){var e;return this.sessionStateController.state()===z.default.NotConnected?(null===(e=this.meetingSessionContext.signalingClient)||void 0===e||e.closeConnection(),this.cleanUpMediaStreamsAfterStop(),Promise.resolve()):new Promise(((e,t)=>{this.sessionStateController.perform(M.default.Disconnect,(()=>{this._reconnectController.disableReconnect(),this.logger.info("attendee left meeting, session will not be reconnected"),this.actionDisconnect(new p.default(g.default.Left),!1,null).then(e).catch(t)}))}))}stop(){this.stopReturningPromise()}actionDisconnect(e,t,n){return o(this,void 0,void 0,(function*(){try{yield new Z.default(this.logger,this.wrapTaskName("AudioVideoStop"),[new ee.default(this.logger,new D.default(this.meetingSessionContext),this.configuration.connectionTimeoutMs)]).run()}catch(e){this.logger.info("fail to stop")}try{const e=[new ee.default(this.logger,new N.default(this.meetingSessionContext),this.configuration.connectionTimeoutMs)];this.cleanUpMediaStreamsAfterStop(),yield new Z.default(this.logger,this.wrapTaskName("AudioVideoClean"),e).run()}catch(e){this.logger.info("fail to clean")}this.sessionStateController.perform(M.default.FinishDisconnecting,(()=>{t||this.notifyStop(e,n)}))}))}update(e={needsRenegotiation:!0}){let t=e.needsRenegotiation;if(t||(t=void 0===this.meetingSessionContext.peer),t||(t=!this.updateRemoteVideosFromPolicy()),t||(t=!this.updateLocalVideoFromPolicy()),this.meetingSessionContext.lastVideosToReceive=this.meetingSessionContext.videosToReceive,!t)return this.logger.info("Update request does not require resubscribe"),this.actionFinishUpdating(),!0;this.logger.info("Update request requires resubscribe");const n=this.sessionStateController.perform(M.default.Update,(()=>{this.actionUpdateWithRenegotiation(!0)}));return n===k.default.Transitioned||n===k.default.DeferredTransition}updateRemoteVideosFromPolicy(){if(this.meetingSessionContext.videoDownlinkBandwidthPolicy&&void 0!==this.meetingSessionContext.videoDownlinkBandwidthPolicy.getVideoPreferences&&void 0!==this.meetingSessionContext.videoDownlinkBandwidthPolicy.getServerSideNetworkAdaption&&!V.serverSideNetworkAdaptionIsNoneOrDefault(this.meetingSessionContext.videoDownlinkBandwidthPolicy.getServerSideNetworkAdaption())){if(!this.sendRemoteVideoUpdate())return!1;if(this.meetingSessionContext.videoDownlinkBandwidthPolicy.getServerSideNetworkAdaption()===V.default.BandwidthProbingAndRemoteVideoQualityAdaption)return this.isNotAddingOrRemovingStreams()}return this.updateRemoteVideosIfNotAddingOrRemovingStreams()}updateRemoteVideosIfNotAddingOrRemovingStreams(){const e=this.detectChangesInVideosToReceive();if(void 0===e)return!1;const t=e.added,n=e.simulcastStreamUpdates,i=e.removed,r=this.meetingSessionContext,a=[];for(const[e,t]of n.entries()){const n=new E.default;if(n.streamId=t,n.attendeeId=r.videoStreamIndex.attendeeIdForStreamId(t),n.mid=r.transceiverController.getMidForStreamId(e),void 0===n.mid)return this.logger.info(`No MID found for stream ID ${e}, cannot update stream without renegotiation`),!1;if(a.push(n),r.transceiverController.setStreamIdForMid(n.mid,t),r.videoStreamIndex.overrideStreamIdMappings(e,t),r.videoTileController.haveVideoTileForAttendeeId(n.attendeeId)){const e=r.videoTileController.getVideoTileForAttendeeId(n.attendeeId);if(!e.setStreamId)return!1;e.setStreamId(t)}}return 0!==a.length&&r.signalingClient.remoteVideoUpdate(a,[]),0===t.length&&0===i.length&&(r.videoStreamIndex.subscribeFrameSent(),!0)}detectChangesInVideosToReceive(){const e=this.meetingSessionContext;if(null===e.videosToReceive)return;if(!(e.transceiverController&&e.transceiverController.getMidForStreamId&&e.transceiverController.setStreamIdForMid&&e.videosToReceive.forEach&&e.signalingClient.remoteVideoUpdate&&e.videoStreamIndex.overrideStreamIdMappings))return;let t=[];const n=new Map;let i=[];if(null===e.lastVideosToReceive)t=e.videosToReceive.array();else{const r=e.videoStreamIndex;e.videosToReceive.forEach((i=>{if(e.lastVideosToReceive.contain(i))return;let a=!1;e.lastVideosToReceive.forEach((e=>{a||r.StreamIdsInSameGroup(e,i)&&(n.set(e,i),a=!0)})),a||t.push(i)})),i=e.lastVideosToReceive.array().filter((t=>{const i=e.videosToReceive.contain(t),r=n.has(t);return!i&&!r}))}return this.logger.info(`Request to update remote videos with added: ${t}, updated: ${[...n.entries()]}, removed: ${i}`),{added:t,removed:i,simulcastStreamUpdates:n}}isNotAddingOrRemovingStreams(){const e=this.detectChangesInVideosToReceive();if(void 0===e)return!1;const t=e.added,n=e.removed;return 0===t.length&&0===n.length}sendRemoteVideoUpdate(){const e=this.meetingSessionContext;if(null===e.videosToReceive)return!1;const t=e.videosToReceive.array().map((t=>e.videoStreamIndex.groupIdForStreamId(t))),n=de.convertVideoPreferencesToSignalingClientVideoSubscriptionConfiguration(e,t,e.videoDownlinkBandwidthPolicy.getVideoPreferences()),i=new Map,r=[];for(const t of n){let n=!1;if(e.lastVideoSubscriptionConfiguration.has(t.groupId)){const i=e.lastVideoSubscriptionConfiguration.get(t.groupId);t.equals(i)||(this.logger.debug(`${JSON.stringify(t)} does not equal ${JSON.stringify(i)}, sending update`),n=!0)}else n=!0;i.set(t.groupId,t),n&&r.push(t)}e.lastVideoSubscriptionConfiguration=i;const a=[];if(null!==e.lastVideosToReceive){const n=new Set(t);for(const t of e.lastVideosToReceive.array()){const i=e.videoStreamIndex.groupIdForStreamId(t);if(!n.has(i)){const t=e.transceiverController.getMidForGroupId(i);if(void 0===t){e.logger.warn(`Could not find MID for group ID to remove: ${i}`);continue}a.push(t)}}}return 0===r.length&&0===a.length||e.signalingClient.remoteVideoUpdate(r,a),!0}updateLocalVideoFromPolicy(){if(this.meetingSessionContext.enableSimulcast){const e=this.meetingSessionContext.videoUplinkBandwidthPolicy.chooseEncodingParameters();if(this.mayNeedRenegotiationForSimulcastLayerChange&&!this.negotiatedBitrateLayersAllocationRtpHeaderExtension())return this.logger.info("Needs regenotiation for local video simulcast layer change"),this.mayNeedRenegotiationForSimulcastLayerChange=!1,!1;this.meetingSessionContext.transceiverController.setEncodingParameters(e)}else this.meetingSessionContext.videoCaptureAndEncodeParameter=this.meetingSessionContext.videoUplinkBandwidthPolicy.chooseCaptureAndEncodeParameters();return this.logger.info("Updated local video from policy without renegotiation"),!0}negotiatedBitrateLayersAllocationRtpHeaderExtension(){if(!this.meetingSessionContext.transceiverController.localVideoTransceiver())return!1;const e=this.meetingSessionContext.transceiverController.localVideoTransceiver().sender.getParameters();return!(!e||!e.headerExtensions)&&e.headerExtensions.some((e=>"http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00"===e.uri))}restartLocalVideo(e){const t=()=>o(this,void 0,void 0,(function*(){this._videoTileController.hasStartedLocalVideoTile()&&(this.logger.info("stopping local video tile prior to local video restart"),this._videoTileController.stopLocalVideoTile(),this.logger.info("preparing local video restart update"),yield this.actionUpdateWithRenegotiation(!1),this.logger.info("starting local video tile for local video restart"),this._videoTileController.startLocalVideoTile()),this.logger.info("finalizing local video restart update"),yield this.actionUpdateWithRenegotiation(!0),e()})),n=this.sessionStateController.perform(M.default.Update,(()=>{t()}));return n===k.default.Transitioned||n===k.default.DeferredTransition}replaceLocalVideo(e){return o(this,void 0,void 0,(function*(){if(!e||e.getVideoTracks().length<1)throw new Error("could not acquire video track");if(!this.meetingSessionContext||!this.meetingSessionContext.peer)throw new Error("no active meeting and peer connection");const t=this.meetingSessionContext.videoTileController.getLocalVideoTile();if(t){const n=t.state(),i=e.getVideoTracks()[0].getSettings();t.bindVideoStream(n.boundAttendeeId,!0,e,i.width,i.height,n.streamId,n.boundExternalUserId)}yield this.meetingSessionContext.transceiverController.setVideoInput(e.getVideoTracks()[0]),this.meetingSessionContext.activeVideoInput=e,this.logger.info("Local video input is updated")}))}replaceLocalAudio(e){return o(this,void 0,void 0,(function*(){if(!e||e.getAudioTracks().length<1)throw new Error("could not acquire audio track");if(!this.meetingSessionContext||!this.meetingSessionContext.peer)throw new Error("no active meeting and peer connection");if(this.connectionHealthData.reset(),this.connectionHealthData.setConnectionStartTime(),!(yield this.meetingSessionContext.transceiverController.replaceAudioTrack(e.getAudioTracks()[0])))throw new Error("Failed to replace audio track");this.meetingSessionContext.activeAudioInput=e,this.logger.info("Local audio input is updated")}))}actionUpdateWithRenegotiation(e){return o(this,void 0,void 0,(function*(){this.monitorTask.pauseResubscribeCheck(),this.receiveIndexTask.pauseIngestion();try{yield new Z.default(this.logger,this.wrapTaskName("AudioVideoUpdate"),[new G.default(this.meetingSessionContext),new ee.default(this.logger,new Z.default(this.logger,"UpdateSession",[new A.default(this.meetingSessionContext),new P.default(this.meetingSessionContext),new Q.default(this.meetingSessionContext),new O.default(this.meetingSessionContext),new X.default(this.meetingSessionContext),new Y.default(this.meetingSessionContext)]),this.configuration.connectionTimeoutMs)]).run(),e&&this.sessionStateController.perform(M.default.FinishUpdating,(()=>{this.actionFinishUpdating()}))}catch(e){this.sessionStateController.perform(M.default.FinishUpdating,(()=>{const t=new p.default(this.getMeetingStatusCode(e)||g.default.TaskFailed);t.statusCode()!==g.default.IncompatibleSDP&&this.logger.info("failed to update audio-video session"),this.handleMeetingSessionStatus(t,e)}))}}))}notifyStop(e,t){var n;if(this.forEachObserver((t=>{oe.Maybe.of(t.audioVideoDidStop).map((n=>n.bind(t)(e)))})),this.promotedToPrimaryMeeting&&t&&this.forEachObserver((e=>{this.promotedToPrimaryMeeting=!1,oe.Maybe.of(e.audioVideoWasDemotedFromPrimaryMeeting).map((t=>t.bind(e)(new p.default(g.default.SignalingInternalServerError))))})),this.eventController){const{signalingOpenDurationMs:i,poorConnectionCount:r,startTimeMs:a,iceGatheringDurationMs:o,attendeePresenceDurationMs:s,meetingStartDurationMs:c}=this.meetingSessionContext,l={maxVideoTileCount:this.meetingSessionContext.maxVideoTileCount,meetingDurationMs:null===a?0:Math.round(Date.now()-a),meetingStatus:g.default[e.statusCode()],signalingOpenDurationMs:i,iceGatheringDurationMs:o,attendeePresenceDurationMs:s,poorConnectionCount:r,meetingStartDurationMs:c,retryCount:this.totalRetryCount},d=t&&t.message||(null===(n=e.toString)||void 0===n?void 0:n.call(e))||"";0===l.meetingDurationMs?(l.meetingErrorMessage=d,delete l.meetingDurationMs,delete l.attendeePresenceDurationMs,delete l.meetingStartDurationMs,this.eventController.publishEvent("meetingStartFailed",l)):e.isFailure()||e.isAudioConnectionFailure()?(l.meetingErrorMessage=d,this.eventController.publishEvent("meetingFailed",l)):this.eventController.publishEvent("meetingEnded",l)}}actionFinishUpdating(){if(!this.meetingSessionContext.enableSimulcast)if(this.useUpdateTransceiverControllerForUplink)this.meetingSessionContext.videoUplinkBandwidthPolicy.updateTransceiverController();else{const e=this.meetingSessionContext.videoCaptureAndEncodeParameter.encodeBitrates()[0];this.enforceBandwidthLimitationForSender(e)}this.monitorTask.resumeResubscribeCheck(),this.receiveIndexTask.resumeIngestion(),this.logger.info("updated audio-video session")}reconnect(e,t){const n=this._reconnectController.retryWithBackoff((()=>o(this,void 0,void 0,(function*(){this.sessionStateController.state()===z.default.NotConnected?this.sessionStateController.perform(M.default.Connect,(()=>{this.actionConnect(!0)})):this.sessionStateController.perform(M.default.Reconnect,(()=>{this.actionReconnect(e)})),this.totalRetryCount+=1}))),(()=>{this.logger.info("canceled retry")}));return n||this.sessionStateController.perform(M.default.Fail,(()=>{this.actionDisconnect(e,!1,t)})),n}actionReconnect(e){return o(this,void 0,void 0,(function*(){this._reconnectController.hasStartedConnectionAttempt()||(this._reconnectController.startedConnectionAttempt(!1),this.forEachObserver((e=>{oe.Maybe.of(e.audioVideoDidStartConnecting).map((t=>t.bind(e)(!0)))}))),this.meetingSessionContext.volumeIndicatorAdapter.onReconnect(),this.connectionHealthData.reset();try{yield new Z.default(this.logger,this.wrapTaskName("AudioVideoReconnect"),[new ee.default(this.logger,new Z.default(this.logger,"Media",[new _.default(this.meetingSessionContext),new Z.default(this.logger,"Signaling",[new U.default(this.meetingSessionContext),new R.default(this.meetingSessionContext)]),new I.default(this.meetingSessionContext)]),this.configuration.connectionTimeoutMs),new G.default(this.meetingSessionContext),new ee.default(this.logger,new Z.default(this.logger,"UpdateSession",[new A.default(this.meetingSessionContext),new P.default(this.meetingSessionContext),new Q.default(this.meetingSessionContext),new O.default(this.meetingSessionContext),new X.default(this.meetingSessionContext),new Y.default(this.meetingSessionContext)]),this.configuration.connectionTimeoutMs)]).run(),this.sessionStateController.perform(M.default.FinishConnecting,(()=>{if(this.eventController){const{signalingOpenDurationMs:t,poorConnectionCount:n,startTimeMs:i,iceGatheringDurationMs:r,attendeePresenceDurationMs:a,meetingStartDurationMs:o}=this.meetingSessionContext,s={maxVideoTileCount:this.meetingSessionContext.maxVideoTileCount,meetingDurationMs:Math.round(Date.now()-i),meetingStatus:g.default[e.statusCode()],signalingOpenDurationMs:t,iceGatheringDurationMs:r,attendeePresenceDurationMs:a,poorConnectionCount:n,meetingStartDurationMs:o,retryCount:this.totalRetryCount};this.eventController.publishEvent("meetingReconnected",s)}this.actionFinishConnecting()}))}catch(e){this.sessionStateController.perform(M.default.FinishConnecting,(()=>{this.logger.info("failed to reconnect audio-video session");const t=new p.default(this.getMeetingStatusCode(e)||g.default.TaskFailed);this.handleMeetingSessionStatus(t,e)}))}this.connectionHealthData.setConnectionStartTime()}))}wrapTaskName(e){return`${e}/${this.configuration.meetingId}/${this.configuration.credentials.attendeeId}`}cleanUpMediaStreamsAfterStop(){this._mediaStreamBroker.removeMediaStreamBrokerObserver(this),this.meetingSessionContext.activeAudioInput=void 0,this.meetingSessionContext.activeVideoInput=void 0}getMeetingStatusCode(e){const t=/the meeting status code: (\d+)/.exec(e&&e.message);return t&&t.length>1?Number.parseInt(t[1],10):null}enforceBandwidthLimitationForSender(e){return o(this,void 0,void 0,(function*(){yield this.meetingSessionContext.transceiverController.setVideoSendingBitrateKbps(e)}))}handleMeetingSessionStatus(e,t){if(this.logger.info(`handling status: ${g.default[e.statusCode()]}`),e.isTerminal()||this.meetingSessionContext.statsCollector&&this.meetingSessionContext.statsCollector.logMeetingSessionStatus(e),e.statusCode()===g.default.IncompatibleSDP)return this.restartLocalVideo((()=>{this.logger.info("handled incompatible SDP by attempting to restart video")})),!0;if(e.statusCode()===g.default.VideoCallSwitchToViewOnly)return this._videoTileController.removeLocalVideoTile(),this.forEachObserver((e=>{oe.Maybe.of(e.videoSendDidBecomeUnavailable).map((t=>t.bind(e)()))})),!1;if(e.statusCode()===g.default.AudioVideoWasRemovedFromPrimaryMeeting)return this.forEachObserver((t=>{oe.Maybe.of(t.audioVideoWasDemotedFromPrimaryMeeting).map((n=>n.bind(t)(e)))})),!1;if(e.isTerminal()&&(this.logger.error("session will not be reconnected"),this.meetingSessionContext.reconnectController&&this.meetingSessionContext.reconnectController.disableReconnect()),(e.isFailure()||e.isTerminal())&&this.meetingSessionContext.reconnectController){const n=this.reconnect(e,t);return n?this.logger.warn(`will retry due to status code ${g.default[e.statusCode()]}${t?` and error: ${t.message}`:""}`):this.logger.error(`failed with status code ${g.default[e.statusCode()]}${t?` and error: ${t.message}`:""}`),n}return!1}setVideoMaxBandwidthKbps(e){if(e<=0)throw new Error("Max bandwidth kbps has to be greater than 0");this.meetingSessionContext&&this.meetingSessionContext.videoUplinkBandwidthPolicy&&(this.logger.info(`video send has ideal max bandwidth ${e} kbps`),this.meetingSessionContext.videoUplinkBandwidthPolicy.setIdealMaxBandwidthKbps(e)),this.maxUplinkBandwidthKbps=e}handleHasBandwidthPriority(e){return o(this,void 0,void 0,(function*(){if(this.meetingSessionContext&&this.meetingSessionContext.videoUplinkBandwidthPolicy&&!this.meetingSessionContext.enableSimulcast){if(this.useUpdateTransceiverControllerForUplink)return this.meetingSessionContext.videoUplinkBandwidthPolicy.setHasBandwidthPriority(e),void(yield this.meetingSessionContext.videoUplinkBandwidthPolicy.updateTransceiverController());const t=this.meetingSessionContext.videoUplinkBandwidthPolicy.maxBandwidthKbps();this.meetingSessionContext.videoUplinkBandwidthPolicy.setHasBandwidthPriority(e);const n=this.meetingSessionContext.videoUplinkBandwidthPolicy.maxBandwidthKbps();t!==n&&(this.logger.info(`video send bandwidth priority ${e} max has changed from ${t} kbps to ${n} kbps`),yield this.enforceBandwidthLimitationForSender(n))}}))}pauseReceivingStream(e){this.meetingSessionContext&&this.meetingSessionContext.signalingClient&&this.meetingSessionContext.signalingClient.pause([e])}resumeReceivingStream(e){this.meetingSessionContext&&this.meetingSessionContext.signalingClient&&this.meetingSessionContext.signalingClient.resume([e])}setVideoCodecSendPreferences(e){this.videoSendCodecPreferences=e,this.meetingSessionContext.videoSendCodecPreferences=e,this.sessionStateController.state()!==z.default.NotConnected&&this.update({needsRenegotiation:!0})}getRemoteVideoSources(){const{videoStreamIndex:e}=this.meetingSessionContext;if(!e)return this.logger.info("meeting has not started"),[];const t=this.configuration.credentials.attendeeId;return e.allVideoSendingSourcesExcludingSelf(t)}encodingSimulcastLayersDidChange(e){this.mayNeedRenegotiationForSimulcastLayerChange=!0,this.forEachObserver((t=>{oe.Maybe.of(t.encodingSimulcastLayersDidChange).map((n=>n.bind(t)(e)))}))}promoteToPrimaryMeeting(e){return this.actionPromoteToPrimaryMeeting(e)}actionPromoteToPrimaryMeeting(e){return o(this,void 0,void 0,(function*(){let t=new p.default(g.default.SignalingRequestFailed);return yield new Z.default(this.logger,this.wrapTaskName("PromoteToPrimaryMeeting"),[new ee.default(this.logger,new q.default(this.meetingSessionContext,e,(e=>{t=e})),this.configuration.connectionTimeoutMs)]).run(),this.promotedToPrimaryMeeting=t.statusCode()===g.default.OK,t}))}demoteFromPrimaryMeeting(){this.meetingSessionContext.signalingClient.demoteFromPrimaryMeeting(),this.forEachObserver((e=>{oe.Maybe.of(e.audioVideoWasDemotedFromPrimaryMeeting).map((t=>t.bind(e)(new p.default(g.default.OK))))}))}videoInputDidChange(e){return o(this,void 0,void 0,(function*(){this.logger.info("Receive a video input change event"),this.meetingSessionContext&&this.meetingSessionContext.peer?this._videoTileController.hasStartedLocalVideoTile()&&(e?yield this.replaceLocalVideo(e):this._videoTileController.stopLocalVideoTile()):this.logger.info("Skip updating video input because there is no active meeting and peer connection")}))}audioInputDidChange(e){return o(this,void 0,void 0,(function*(){if(this.logger.info("Receive an audio input change event"),this.meetingSessionContext&&this.meetingSessionContext.peer){if(!e)try{e=yield this.mediaStreamBroker.acquireAudioInputStream()}catch(e){return void this.logger.error("Could not acquire audio track from mediaStreamBroker")}yield this.replaceLocalAudio(e)}else this.logger.info("Skip updating audio input because there is no active meeting and peer connection")}))}}t.default=Se,Se.MIN_VOLUME_DECIBELS=-42,Se.MAX_VOLUME_DECIBELS=-14,Se.PING_PONG_INTERVAL_MS=1e4},9263:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(3306)),a=i(n(7292)),o=i(n(6782)),s=i(n(8703)),c=i(n(1829)),l=i(n(7121)),d=i(n(565)),u=i(n(484)),f=i(n(7385)),h=i(n(822)),m=i(n(388)),p=i(n(6460));class g extends p.default{constructor(e){const t=new c.default;t.meetingId="",t.externalMeetingId="",t.credentials=new l.default,t.credentials.attendeeId="",t.credentials.joinToken="",t.urls=new f.default,t.urls.turnControlURL="",t.urls.audioHostURL="",t.urls.signalingURL="wss://localhost/";const n=new o.default;super(e||t,n,new m.default(new o.default),new s.default,new h.default(0,new r.default(0,0,0)),new a.default(e||t,n))}setAudioProfile(e){}start(){}stop(){}promoteToPrimaryMeeting(e){return Promise.resolve(new d.default(u.default.OK))}demoteFromPrimaryMeeting(){}}t.default=g},3644:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});const r=n(6880);t.default=class{constructor(e,t,n,i,r,a){this.audioVideoController=e,this.videoTileController=t,this.realtimeController=n,this.audioMixController=i,this.deviceController=r,this.contentShareController=a}addObserver(e){this.audioVideoController.addObserver(e),this.trace("addObserver")}removeObserver(e){this.audioVideoController.removeObserver(e),this.trace("removeObserver")}setAudioProfile(e){this.trace("setAudioProfile",e),this.audioVideoController.setAudioProfile(e)}start(e){this.audioVideoController.start(e),this.trace("start")}stop(){this.audioVideoController.stop(),this.trace("stop")}getRTCPeerConnectionStats(e){return this.trace("getRTCPeerConnectionStats",e?e.id:null),this.audioVideoController.getRTCPeerConnectionStats(e)}bindAudioElement(e){const t=this.audioMixController.bindAudioElement(e);return this.trace("bindAudioElement",e.id,t),t}unbindAudioElement(){this.audioMixController.unbindAudioElement(),this.trace("unbindAudioElement")}getCurrentMeetingAudioStream(){return this.trace("getCurrentConferenceStream"),this.audioMixController.getCurrentMeetingAudioStream()}addAudioMixObserver(e){this.trace("addAudioMixObserver"),this.audioMixController.addAudioMixObserver(e)}removeAudioMixObserver(e){this.trace("removeAudioMixObserver"),this.audioMixController.removeAudioMixObserver(e)}bindVideoElement(e,t){this.videoTileController.bindVideoElement(e,t),this.trace("bindVideoElement",{tileId:e,videoElementId:t.id})}unbindVideoElement(e,t=!0){this.videoTileController.unbindVideoElement(e,t),this.trace("unbindVideoElement",{tileId:e,cleanUpVideoElement:t})}startLocalVideoTile(){const e=this.videoTileController.startLocalVideoTile();return this.trace("startLocalVideoTile",null,e),e}stopLocalVideoTile(){this.videoTileController.stopLocalVideoTile(),this.trace("stopLocalVideoTile")}hasStartedLocalVideoTile(){const e=this.videoTileController.hasStartedLocalVideoTile();return this.trace("hasStartedLocalVideoTile",null,e),e}removeLocalVideoTile(){this.videoTileController.removeLocalVideoTile(),this.trace("removeLocalVideoTile")}getLocalVideoTile(){const e=this.videoTileController.getLocalVideoTile();return this.trace("getLocalVideoTile"),e}pauseVideoTile(e){this.videoTileController.pauseVideoTile(e),this.trace("pauseVideoTile",e)}unpauseVideoTile(e){this.videoTileController.unpauseVideoTile(e),this.trace("unpauseVideoTile",e)}getVideoTile(e){const t=this.videoTileController.getVideoTile(e);return this.trace("getVideoTile",e),t}getAllRemoteVideoTiles(){const e=this.videoTileController.getAllRemoteVideoTiles();return this.trace("getAllRemoteVideoTiles"),e}getAllVideoTiles(){const e=this.videoTileController.getAllVideoTiles();return this.trace("getAllVideoTiles"),e}addVideoTile(){const e=this.videoTileController.addVideoTile();return this.trace("addVideoTile",null,e.state()),e}removeVideoTile(e){this.videoTileController.removeVideoTile(e),this.trace("removeVideoTile",e)}removeVideoTilesByAttendeeId(e){const t=this.videoTileController.removeVideoTilesByAttendeeId(e);return this.trace("removeVideoTilesByAttendeeId",e,t),t}removeAllVideoTiles(){this.videoTileController.removeAllVideoTiles(),this.trace("removeAllVideoTiles")}captureVideoTile(e){const t=this.videoTileController.captureVideoTile(e);return this.trace("captureVideoTile",e),t}realtimeSubscribeToAttendeeIdPresence(e){this.realtimeController.realtimeSubscribeToAttendeeIdPresence(e),this.trace("realtimeSubscribeToAttendeeIdPresence")}realtimeUnsubscribeToAttendeeIdPresence(e){this.realtimeController.realtimeUnsubscribeToAttendeeIdPresence(e),this.trace("realtimeUnsubscribeToAttendeeIdPresence")}realtimeSetCanUnmuteLocalAudio(e){this.realtimeController.realtimeSetCanUnmuteLocalAudio(e),this.trace("realtimeSetCanUnmuteLocalAudio",e)}realtimeSubscribeToSetCanUnmuteLocalAudio(e){this.realtimeController.realtimeSubscribeToSetCanUnmuteLocalAudio(e),this.trace("realtimeSubscribeToSetCanUnmuteLocalAudio")}realtimeUnsubscribeToSetCanUnmuteLocalAudio(e){this.realtimeController.realtimeUnsubscribeToSetCanUnmuteLocalAudio(e),this.trace("realtimeUnsubscribeToSetCanUnmuteLocalAudio")}realtimeCanUnmuteLocalAudio(){const e=this.realtimeController.realtimeCanUnmuteLocalAudio();return this.trace("realtimeCanUnmuteLocalAudio",null,e),e}realtimeMuteLocalAudio(){this.realtimeController.realtimeMuteLocalAudio(),this.trace("realtimeMuteLocalAudio")}realtimeUnmuteLocalAudio(){const e=this.realtimeController.realtimeUnmuteLocalAudio();return this.trace("realtimeUnmuteLocalAudio"),e}realtimeSubscribeToMuteAndUnmuteLocalAudio(e){this.realtimeController.realtimeSubscribeToMuteAndUnmuteLocalAudio(e),this.trace("realtimeSubscribeToMuteAndUnmuteLocalAudio")}realtimeUnsubscribeToMuteAndUnmuteLocalAudio(e){this.realtimeController.realtimeUnsubscribeToMuteAndUnmuteLocalAudio(e),this.trace("realtimeUnsubscribeToMuteAndUnmuteLocalAudio")}realtimeIsLocalAudioMuted(){const e=this.realtimeController.realtimeIsLocalAudioMuted();return this.trace("realtimeIsLocalAudioMuted"),e}realtimeSubscribeToVolumeIndicator(e,t){this.realtimeController.realtimeSubscribeToVolumeIndicator(e,t),this.trace("realtimeSubscribeToVolumeIndicator",e)}realtimeUnsubscribeFromVolumeIndicator(e,t){this.realtimeController.realtimeUnsubscribeFromVolumeIndicator(e,t),this.trace("realtimeUnsubscribeFromVolumeIndicator",e,t)}realtimeSubscribeToLocalSignalStrengthChange(e){this.realtimeController.realtimeSubscribeToLocalSignalStrengthChange(e),this.trace("realtimeSubscribeToLocalSignalStrengthChange")}realtimeUnsubscribeToLocalSignalStrengthChange(e){this.realtimeController.realtimeUnsubscribeToLocalSignalStrengthChange(e),this.trace("realtimeUnsubscribeToLocalSignalStrengthChange")}realtimeSendDataMessage(e,t,n){this.realtimeController.realtimeSendDataMessage(e,t,n),this.trace("realtimeSendDataMessage")}realtimeSubscribeToReceiveDataMessage(e,t){this.realtimeController.realtimeSubscribeToReceiveDataMessage(e,t),this.trace("realtimeSubscribeToReceiveDataMessage")}realtimeUnsubscribeFromReceiveDataMessage(e){this.realtimeController.realtimeUnsubscribeFromReceiveDataMessage(e),this.trace("realtimeUnsubscribeFromReceiveDataMessage")}realtimeSubscribeToFatalError(e){this.realtimeController.realtimeSubscribeToFatalError(e),this.trace("realtimeSubscribeToFatalError")}realtimeUnsubscribeToFatalError(e){this.realtimeController.realtimeUnsubscribeToFatalError(e),this.trace("realtimeUnsubscribeToFatalError")}subscribeToActiveSpeakerDetector(e,t,n,i){this.audioVideoController.activeSpeakerDetector.subscribe(e,t,n,i),this.trace("subscribeToActiveSpeakerDetector")}unsubscribeFromActiveSpeakerDetector(e){this.audioVideoController.activeSpeakerDetector.unsubscribe(e),this.trace("unsubscribeFromActiveSpeakerDetector")}listAudioInputDevices(e=!1){return i(this,void 0,void 0,(function*(){const t=yield this.deviceController.listAudioInputDevices(e);return this.trace("listAudioInputDevices",e,t),t}))}listVideoInputDevices(e=!1){return i(this,void 0,void 0,(function*(){const t=yield this.deviceController.listVideoInputDevices(e);return this.trace("listVideoInputDevices",e,t),t}))}listAudioOutputDevices(e=!1){return i(this,void 0,void 0,(function*(){const t=yield this.deviceController.listAudioOutputDevices(e);return this.trace("listAudioOutputDevices",e,t),t}))}startAudioInput(e){return i(this,void 0,void 0,(function*(){return this.trace("startAudioInput",e),this.deviceController.startAudioInput(e)}))}stopAudioInput(){return i(this,void 0,void 0,(function*(){return this.trace("stopAudioInput"),this.deviceController.stopAudioInput()}))}startVideoInput(e){return i(this,void 0,void 0,(function*(){return r.isVideoTransformDevice(e)?this.trace("startVideoInput with transform device"):this.trace("startVideoInput",e),this.deviceController.startVideoInput(e)}))}stopVideoInput(){return i(this,void 0,void 0,(function*(){return this.trace("stopVideoInput"),this.deviceController.stopVideoInput()}))}chooseAudioOutput(e){const t=this.deviceController.chooseAudioOutput(e);return this.trace("chooseAudioOutput",e),t}addDeviceChangeObserver(e){this.deviceController.addDeviceChangeObserver(e),this.trace("addDeviceChangeObserver")}removeDeviceChangeObserver(e){this.deviceController.removeDeviceChangeObserver(e),this.trace("removeDeviceChangeObserver")}createAnalyserNodeForAudioInput(){const e=this.deviceController.createAnalyserNodeForAudioInput();return this.trace("createAnalyserNodeForAudioInput"),e}startVideoPreviewForVideoInput(e){this.deviceController.startVideoPreviewForVideoInput(e),this.trace("startVideoPreviewForVideoInput",e.id)}stopVideoPreviewForVideoInput(e){this.deviceController.stopVideoPreviewForVideoInput(e),this.trace("stopVideoPreviewForVideoInput",e.id)}setDeviceLabelTrigger(e){this.deviceController.setDeviceLabelTrigger(e),this.trace("setDeviceLabelTrigger")}mixIntoAudioInput(e){const t=this.deviceController.mixIntoAudioInput(e);return this.trace("mixIntoAudioInput",e.id),t}chooseVideoInputQuality(e,t,n){this.deviceController.chooseVideoInputQuality(e,t,n),this.trace("chooseVideoInputQuality",{width:e,height:t,frameRate:n})}setVideoMaxBandwidthKbps(e){this.audioVideoController.setVideoMaxBandwidthKbps(e),this.trace("setVideoMaxBandwidthKbps",e)}setVideoCodecSendPreferences(e){this.audioVideoController.setVideoCodecSendPreferences(e),this.trace("setVideoCodecSendPreferences",e)}getVideoInputQualitySettings(){const e=this.deviceController.getVideoInputQualitySettings();return this.trace("getVideoInputQualitySettings"),e}setContentAudioProfile(e){this.trace("setContentAudioProfile",e),this.contentShareController.setContentAudioProfile(e)}enableSimulcastForContentShare(e,t){this.trace("enableSimulcastForContentShare"),this.contentShareController.enableSimulcastForContentShare(e,t)}enableSVCForContentShare(e){this.trace("enableSVCForContentShare"),this.contentShareController.enableSVCForContentShare(e)}startContentShare(e){const t=this.contentShareController.startContentShare(e);return this.trace("startContentShare"),t}startContentShareFromScreenCapture(e,t){const n=this.contentShareController.startContentShareFromScreenCapture(e,t);return this.trace("startContentShareFromScreenCapture"),n}pauseContentShare(){this.contentShareController.pauseContentShare(),this.trace("pauseContentShare")}unpauseContentShare(){this.contentShareController.unpauseContentShare(),this.trace("unpauseContentShare")}stopContentShare(){this.contentShareController.stopContentShare(),this.trace("stopContentShare")}addContentShareObserver(e){this.contentShareController.addContentShareObserver(e),this.trace("addContentShareObserver")}removeContentShareObserver(e){this.contentShareController.removeContentShareObserver(e),this.trace("removeContentShareObserver")}setContentShareVideoCodecPreferences(e){this.contentShareController.setContentShareVideoCodecPreferences(e),this.trace("setContentShareVideoCodecPreferences")}trace(e,t,n){let i=`API/DefaultAudioVideoFacade/${this.audioVideoController.configuration.meetingId}/${this.audioVideoController.configuration.credentials.attendeeId}/${e}`;void 0!==t&&(i+=` ${JSON.stringify(t)}`),void 0!==n&&(i+=` -> ${JSON.stringify(n)}`),this.audioVideoController.logger.info(i)}getRemoteVideoSources(){const e=this.audioVideoController.getRemoteVideoSources();return this.trace("getRemoteVideoSources",null,e),e}get transcriptionController(){return this.realtimeController.transcriptionController}promoteToPrimaryMeeting(e){this.audioVideoController.removeObserver(this),this.audioVideoController.addObserver(this);const t=this.audioVideoController.promoteToPrimaryMeeting(e);return this.trace("promoteToPrimaryMeeting",null,t),t}demoteFromPrimaryMeeting(){this.trace("demoteFromPrimaryMeeting"),this.audioVideoController.demoteFromPrimaryMeeting()}audioVideoWasDemotedFromPrimaryMeeting(e){this.contentShareController.stopContentShare(),this.audioVideoController.removeObserver(this)}}},2820:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(7896)),o=n(390);class s extends a.default{constructor(e,t){super(e,t),this.blurCanvas=document.createElement("canvas"),this.blurCanvasCtx=this.blurCanvas.getContext("2d"),this.blurCanvas.width=this.spec.model.input.width,this.blurCanvas.height=this.spec.model.input.height,this.logger.info("BackgroundBlur processor using builtin blur")}drawImageWithMask(e,t){const n=this.blurredImage,{canvasCtx:i,targetCanvas:r}=this,{width:a,height:o}=r;t&&n?(this.scaledCanvas.getContext("2d").putImageData(t,0,0),this.blurCanvasCtx.putImageData(this.blurredImage,0,0),i.save(),i.clearRect(0,0,a,o),i.drawImage(this.scaledCanvas,0,0,a,o),i.globalCompositeOperation="source-in",i.drawImage(e,0,0,a,o),i.globalCompositeOperation="destination-over",i.drawImage(this.blurCanvas,0,0,a,o),i.restore()):i.clearRect(0,0,a,o)}setBlurStrength(e){if(super.setBlurStrength(e),this.worker){this.modelInitialized=!1,this.worker.postMessage({msg:"destroy"});const e=this.spec.model;this.worker.postMessage({msg:"loadModel",payload:{modelUrl:e.path,inputHeight:e.input.height,inputWidth:e.input.width,inputChannels:4,modelRangeMin:e.input.range[0],modelRangeMax:e.input.range[1],blurPixels:this.blurAmount}})}}setBlurPixels(){this.blurAmount=o.BlurStrengthMapper.getBlurAmount(this._blurStrength,{height:540}),this.logger.info(`background blur amount set to ${this.blurAmount}`)}handleInitialize(e){if(this.logger.info(`received initialize message: ${this.stringify(e)}`),!e.payload)return this.logger.error("failed to initialize module"),void this.initWorkerPromise.reject(new Error("failed to initialize the module"));const t=this.spec.model;this.worker.postMessage({msg:"loadModel",payload:{modelUrl:t.path,inputHeight:t.input.height,inputWidth:t.input.width,inputChannels:4,modelRangeMin:t.input.range[0],modelRangeMax:t.input.range[1],blurPixels:this.blurAmount}}),this.initWorkerPromise.resolve({})}handlePredict(e){this.blurredImage=e.payload.blurOutput,super.handlePredict(e)}destroy(){const e=Object.create(null,{destroy:{get:()=>super.destroy}});var t;return i(this,void 0,void 0,(function*(){e.destroy.call(this),null===(t=this.blurCanvas)||void 0===t||t.remove(),this.blurCanvas=void 0}))}}t.default=s},7896:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(117)),o=n(390),s=r(n(5220));class c extends a.default{constructor(e,t){super("background blur",e,t,new s.default),this.blurAmount=0,this.setBlurStrength(t.blurStrength),this.logger.info("BackgroundBlur processor successfully created"),this.logger.info(`BackgroundBlur spec: ${this.stringify(this.spec)}`),this.logger.info(`BackgroundBlur options: ${this.stringify(t)}`)}validateOptions(e){if(super.validateOptions(e),!e.blurStrength)throw new Error("processor has null options - blurStrength")}initOnFirstExecution(){this.setBlurPixels()}drawImageWithMask(e,t){t||(t=new ImageData(this.spec.model.input.width,this.spec.model.input.height)),this.scaledCanvas.getContext("2d").putImageData(t,0,0);const{canvasCtx:n,targetCanvas:i}=this,{width:r,height:a}=i;n.save(),n.clearRect(0,0,r,a),n.drawImage(this.scaledCanvas,0,0,r,a),n.globalCompositeOperation="source-in",n.drawImage(e,0,0,r,a),n.globalCompositeOperation="destination-over",n.filter=`blur(${this.blurAmount}px)`,n.drawImage(e,0,0,i.width,i.height),n.restore()}setBlurStrength(e){this._blurStrength=e,this.logger.info(`blur strength set to ${this._blurStrength}`),this.setBlurPixels()}setBlurPixels(){this.blurAmount=o.BlurStrengthMapper.getBlurAmount(this._blurStrength,{height:this.sourceHeight}),this.logger.info(`background blur amount set to ${this.blurAmount}`)}addObserver(e){this.delegate.addObserver(e)}removeObserver(e){this.delegate.removeObserver(e)}static isSupported(){return i(this,void 0,void 0,(function*(){const e=document.createElement("canvas"),t=void 0!==e.getContext("2d").filter;return e.remove(),t}))}setEventController(e){this.eventController?this.eventController=e:(this.eventController=e,this.publishBackgroundFilterEvent())}publishBackgroundFilterEvent(){const e={backgroundBlurEnabled:"true",backgroundBlurStrength:this._blurStrength,backgroundReplacementEnabled:"false",backgroundFilterVersion:1};this.eventController.publishEvent("backgroundFilterConfigSelected",e)}}t.default=c},390:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BlurStrengthMapper=void 0;class n{static getBlurAmount(e,t){if(e<=0)throw new Error(`invalid value for blur strength: ${e}`);return Math.round(e*t.height/this.BLUR_STRENGTH_DIVISOR)}}t.BlurStrengthMapper=n,n.BLUR_STRENGTH_DIVISOR=540,t.default={LOW:7,MEDIUM:15,HIGH:30}},9799:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(6605)),o=r(n(3804)),s=r(n(3293)),c=r(n(255)),l=r(n(2820)),d=r(n(7896)),u=r(n(390));class f extends c.default{setBlurStrength(){}loadAssets(){return i(this,void 0,void 0,(function*(){}))}addObserver(){}removeObserver(){}}class h extends a.default{static create(e,t){return i(this,void 0,void 0,(function*(){e=h.resolveSpec(e),t=h.resolveOptions(t);const{logger:n}=t,i=yield h.isSupported(e,t);if(n.info(`processor is ${i?"":"not"} supported`),!i)return n.warn("Using no-op processor because background blur is not supported"),new f;let r;return(yield d.default.isSupported())?(n.info("Using browser-provided background blur"),r=new d.default(e,t)):(n.info("Using built-in background blur"),r=new l.default(e,t)),yield r.loadAssets(),r}))}static resolveOptions(e={}){let t=Object.assign({},e);return t.blurStrength||(t.blurStrength=u.default.MEDIUM),t.logger||(t.logger=new o.default("BackgroundBlurProcessor",s.default.INFO)),t=super.resolveOptions(t),t}static isSupported(e,t){return e=h.resolveSpec(e),t=h.resolveOptions(t),super.isSupported(e,t)}}t.default=h},5220:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(2806));class a extends r.default{}t.default=a},6387:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n{constructor(){this.path=null,this.input=null,this.output=null}static builder(){return new n}withDefaultModel(){return this.withSelfieSegmentationDefaults()}withSelfieSegmentationDefaults(){return this.path="https://static.sdkassets.chime.aws/bgblur/models/selfie_segmentation_landscape.tflite",this.input={height:144,width:256,range:[0,1],channels:3},this.output={height:144,width:256,range:[0,1],channels:1},this}withPath(e){return this.path=e,this}withInput(e){return this.input=e,this}withOutput(e){return this.output=e,this}validate(){if(!this.path)throw new Error("model spec path is not set");if(!this.input)throw new Error("model spec input is not set");if(!this.output)throw new Error("model spec output is not set")}build(){return this.validate(),{path:this.path,input:this.input,output:this.output}}}t.default=n},4218:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t,n,i){this.delegate=e,this.reportingPeriodMillis=t,this.filterCPUUtilization=n,this.logger=i,this._processingFilter=!0,this.lastReportedEventTimestamp=0,this.lastFilterCompleteTimestamp=0,this.filterTotalMillis=0,this.filterCount=0,this.framerate=0,this.filterDurationNotifyMillis=0,this.setSegmentationDuration()}reportEvent(e){const t=e-this.lastReportedEventTimestamp;if(t>=this.reportingPeriodMillis){const n=this.filterCount,i=this.filterTotalMillis;if(this.filterCount=0,this.filterTotalMillis=0,this.lastReportedEventTimestamp=e,0===this.framerate||0===n)return;const r=Math.round(i/n),a=Math.round(this.framerate*(t/1e3))-n,o=Math.round(100*i/t);r>=this.filterDurationNotifyMillis&&this.delegate.filterFrameDurationHigh({framesDropped:a,avgFilterDurationMillis:r,framerate:this.framerate,periodMillis:t}),o>=this.filterCPUUtilization&&this.delegate.filterCPUUtilizationHigh({cpuUtilization:o,filterMillis:i,periodMillis:t})}}setSegmentationDuration(){this.filterDurationNotifyMillis=Math.round(1e3/this.framerate*.8)}frameReceived(e){e!==this.framerate&&(this.framerate=e,this.logger.info(`frame counter setting frame rate to ${this.framerate}`),this.setSegmentationDuration());const t=Date.now();this.reportEvent(t)}filterSubmitted(){this._processingFilter=!0,this.lastFilterCompleteTimestamp=Date.now()}filterComplete(){this.filterTotalMillis+=Date.now()-this.lastFilterCompleteTimestamp,this._processingFilter=!1,this.filterCount++}get processingSegment(){return this._processingFilter}}},117:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.BackgroundFilterMonitor=void 0;const a=n(1364),o=r(n(2245)),s=r(n(4218));class c{constructor(){this.value=void 0,this.resolve=null}whenNext(){return this.promise||(this.promise=new Promise((e=>this.resolve=e))),this.promise}next(e){this.value=e,this.resolve(e),delete this.promise}}class l{constructor(e,t,n,i,r){this.targetCanvas=document.createElement("canvas"),this.canvasCtx=this.targetCanvas.getContext("2d"),this.canvasVideoFrameBuffer=new o.default(this.targetCanvas),this.mask$=new c,this.sourceWidth=0,this.sourceHeight=0,this.frameNumber=0,this.videoFramesPerFilterUpdate=1,this.initWorkerPromise=l.createWorkerPromise(),this.loadModelPromise=l.createWorkerPromise(),this.modelInitialized=!1,this.destroyed=!1,this.filterType=e,this.validateSpec(t),this.validateOptions(n),this.spec=t,this.logger=n.logger,this.delegate=i,this.initCPUMonitor(n),this.eventController=r}static createWorkerPromise(){const e={resolve:null,reject:null,promise:null};return e.promise=new Promise(((t,n)=>{e.resolve=t,e.reject=n})),e}validateSpec(e){if(!e)throw new Error("processor has null spec");if(!e.model)throw new Error("processor spec has null model");if(!e.paths)throw new Error("processor spec has null paths")}validateOptions(e){if(!e)throw new Error("processor has null options");if(!e.logger)throw new Error("processor has null options - logger");if(!e.reportingPeriodMillis)throw new Error("processor has null options - reportingPeriodMillis");if(!e.filterCPUUtilization)throw new Error("processor has null options - filterCPUUtilization")}initCPUMonitor(e){this.videoFramesPerFilterUpdate=1,this.frameCounter=new s.default(this.delegate,e.reportingPeriodMillis,e.filterCPUUtilization,this.logger),this.cpuMonitor=new d(5e3,{reduceCPUUtilization:()=>{this.updateVideoFramesPerFilterUpdate(Math.min(this.videoFramesPerFilterUpdate+1,10))},increaseCPUUtilization:()=>{this.updateVideoFramesPerFilterUpdate(Math.max(this.videoFramesPerFilterUpdate-1,1))}}),this.delegate.addObserver(this.cpuMonitor)}stringify(e){return JSON.stringify(e,null,2)}handleInitialize(e){if(this.logger.info(`received initialize message: ${this.stringify(e)}`),!e.payload)return this.logger.error("failed to initialize module"),void this.initWorkerPromise.reject(new Error("failed to initialize the module"));const t=this.spec.model;this.worker.postMessage({msg:"loadModel",payload:{modelUrl:t.path,inputHeight:t.input.height,inputWidth:t.input.width,inputChannels:4,modelRangeMin:t.input.range[0],modelRangeMax:t.input.range[1],blurPixels:0}}),this.initWorkerPromise.resolve({})}handleLoadModel(e){if(this.logger.info(`received load model message: ${this.stringify(e)}`),2!==e.payload)return this.logger.error("failed to load model! status: "+e.payload),void this.loadModelPromise.reject(new Error("failed to load model! status: "+e.payload));this.modelInitialized=!0,this.loadModelPromise.resolve({})}handlePredict(e){this.mask$.next(e.payload.output)}handleWorkerEvent(e){const t=e.data;switch(t.msg){case"initialize":this.handleInitialize(t);break;case"loadModel":this.handleLoadModel(t);break;case"predict":this.handlePredict(t);break;default:this.logger.info(`unexpected event msg: ${this.stringify(t)}`)}}loadAssets(){return i(this,void 0,void 0,(function*(){this.logger.info("start initializing the processor");try{this.worker=yield a.loadWorker(this.spec.paths.worker,"BackgroundFilterWorker",{},null),this.worker.addEventListener("message",(e=>this.handleWorkerEvent(e))),this.worker.postMessage({msg:"initialize",payload:{wasmPath:this.spec.paths.wasm,simdPath:this.spec.paths.simd}}),yield this.initWorkerPromise.promise,this.logger.info(`successfully initialized the ${this.filterType} worker`),yield this.loadModelPromise.promise,this.logger.info(`successfully loaded ${this.filterType} worker segmentation model`)}catch(e){throw new Error(`could not initialize the ${this.filterType} video frame processor due to '${e.message}'`)}this.logger.info(`successfully initialized the ${this.filterType} processor`)}))}process(e){return i(this,void 0,void 0,(function*(){if(this.destroyed)return e;this.frameCounter.frameReceived(e[0].framerate),this.cpuMonitor.frameReceived();const t=e[0].asCanvasElement();if(!t)return e;if(!this.modelInitialized)return e[0]=this.canvasVideoFrameBuffer,e;const n=t.width,i=t.height;if(0===n||0===i)return e;0===this.sourceWidth&&(this.sourceWidth=n,this.sourceHeight=i,this.targetCanvas.width=this.sourceWidth,this.targetCanvas.height=this.sourceHeight,this.logger.info(`${this.filterType} source width: ${this.sourceWidth}`),this.logger.info(`${this.filterType} source height: ${this.sourceHeight}`),this.initOnFirstExecution()),this.sourceWidth===n&&this.sourceHeight===i||(this.sourceWidth=n,this.sourceHeight=i,this.targetCanvas.width=this.sourceWidth,this.targetCanvas.height=this.sourceHeight);try{this.frameCounter.filterSubmitted();let e=this.mask$.value;const n=this.spec.model.input.width/t.width,i=this.spec.model.input.height/t.height;void 0===this.scaledCanvas&&(this.scaledCanvas=document.createElement("canvas"),this.scaledCanvas.width=this.spec.model.input.width,this.scaledCanvas.height=this.spec.model.input.height);const r=this.scaledCanvas.getContext("2d");r.save(),r.scale(n,i),r.drawImage(t,0,0),r.restore();const a=r.getImageData(0,0,this.scaledCanvas.width,this.scaledCanvas.height);if(this.frameNumber%this.videoFramesPerFilterUpdate==0){const t=this.mask$.whenNext();this.worker.postMessage({msg:"predict",payload:a},[a.data.buffer]),e=yield t}this.destroyed||this.drawImageWithMask(t,e)}catch(t){return this.logger.error(`could not process ${this.filterType} frame buffer due to ${t}`),e}finally{this.frameCounter.filterComplete(),this.frameNumber++}return e[0]=this.canvasVideoFrameBuffer,e}))}updateVideoFramesPerFilterUpdate(e){e!==this.videoFramesPerFilterUpdate&&(this.videoFramesPerFilterUpdate=e,this.logger.info(`Adjusting filter rate to compensate for CPU utilization. Filter rate is ${this.videoFramesPerFilterUpdate} video frames per filter.`))}destroy(){var e,t,n,r;return i(this,void 0,void 0,(function*(){this.destroyed=!0,this.delegate.removeObserver(this.cpuMonitor),this.canvasVideoFrameBuffer.destroy(),null===(e=this.worker)||void 0===e||e.postMessage({msg:"destroy"}),null===(t=this.worker)||void 0===t||t.postMessage({msg:"stop"}),null===(n=this.targetCanvas)||void 0===n||n.remove(),this.targetCanvas=void 0,null===(r=this.scaledCanvas)||void 0===r||r.remove(),this.scaledCanvas=void 0,this.logger.info(`${this.filterType} frame process destroyed`)}))}}t.default=l;class d{constructor(e,t){this.monitoringPeriodMillis=e,this.observer=t,this.lastCPUChangeTimestamp=0}filterCPUUtilizationHigh(){const e=Date.now();e-this.lastCPUChangeTimestamp>=this.monitoringPeriodMillis&&(this.lastCPUChangeTimestamp=e,this.observer.reduceCPUUtilization())}frameReceived(){const e=Date.now();e-this.lastCPUChangeTimestamp>=2*this.monitoringPeriodMillis&&(this.lastCPUChangeTimestamp=e,this.observer.increaseCPUUtilization())}}t.BackgroundFilterMonitor=d},6605:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=n(1364),o=n(5128),s=r(n(6387)),c=r(n(6244)),l=r(n(6741)),d=()=>s.default.builder().withSelfieSegmentationDefaults().build(),u="https://static.sdkassets.chime.aws",f={worker:`${u}/bgblur/workers/worker.js`,wasm:`${u}/bgblur/wasm/_cwt-wasm.wasm`,simd:`${u}/bgblur/wasm/_cwt-wasm-simd.wasm`};t.default=class{static defaultAssetSpec(){const e=l.default.sdkVersionSemVer;return{assetGroup:`sdk-${e.major}.${e.minor}`}}static createUrlWithParams(e,t){const n=new URL(e),i=Object.keys(t);for(const e of i)void 0!==t[e]&&n.searchParams.set(e,t[e]);return n.toString()}static resolveSpec(e){const{paths:t=f,model:n=d(),assetGroup:i=this.defaultAssetSpec().assetGroup,revisionID:r=this.defaultAssetSpec().revisionID}=e||{},a={assetGroup:i,revisionID:r,sdk:encodeURIComponent(l.default.sdkVersion),ua:encodeURIComponent(l.default.sdkUserAgentLowResolution)};return t.worker=this.createUrlWithParams(t.worker,a),t.wasm=this.createUrlWithParams(t.wasm,a),t.simd=this.createUrlWithParams(t.simd,a),n.path=this.createUrlWithParams(n.path,a),{paths:t,model:n,assetGroup:i,revisionID:r}}static resolveOptions(e){return e.reportingPeriodMillis||(e.reportingPeriodMillis=1e3),e.filterCPUUtilization?(e.filterCPUUtilization<0||e.filterCPUUtilization>100)&&(e.logger.warn("filterCPUUtilization must be set to a range between 0 and 100 percent. Falling back to default of 30 percent"),e.filterCPUUtilization=30):e.filterCPUUtilization=30,e}static isSupported(e,t){const{logger:n}=t;return"undefined"==typeof globalThis?(n.info("Browser does not have globalThis."),Promise.resolve(!1)):(new c.default).supportsBackgroundFilter()?o.supportsWASM(globalThis,n)?this.supportsBackgroundFilter(globalThis,e,n):(n.info("Browser does not support WASM."),Promise.resolve(!1)):(n.info("Browser is not supported."),Promise.resolve(!1))}static supportsBackgroundFilter(e=globalThis,t,n){return i(this,void 0,void 0,(function*(){if(!o.supportsWorker(e,n))return n.info("Browser does not support web workers."),!1;const i=t.paths.worker;try{const e=yield a.loadWorker(i,"BackgroundFilterWorker",{},null);try{e.terminate()}catch(e){n.info(`Failed to terminate worker. ${e.message}`)}return!0}catch(e){return n.info(`Failed to fetch and instantiate test worker ${e.message}`),!1}}))}}},2806:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.observers=new Set}addObserver(e){this.observers.add(e)}removeObserver(e){this.observers.delete(e)}filterFrameDurationHigh(e){var t;for(const n of this.observers)null===(t=n.filterFrameDurationHigh)||void 0===t||t.call(n,e)}filterCPUUtilizationHigh(e){var t;for(const n of this.observers)null===(t=n.filterCPUUtilizationHigh)||void 0===t||t.call(n,e)}}},3111:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(117)),o=r(n(9766));class s extends a.default{constructor(e,t){super("background replacement",e,t,new o.default),this.replacementBlob=t.imageBlob,this.logger.info("BackgroundReplacement processor successfully created"),this.logger.info(`BackgroundReplacement spec: ${this.stringify(this.spec)}`),this.logger.info(`BackgroundReplacement options: ${this.stringify(t)}`)}setImageBlob(e){return i(this,void 0,void 0,(function*(){this.replacementBlob=e,this.replacementImage=yield s.loadImage(this.createReplacementObjectUrl())}))}initOnFirstExecution(){}drawImageWithMask(e,t){t||(t=new ImageData(this.spec.model.input.width,this.spec.model.input.height)),this.scaledCanvas.getContext("2d").putImageData(t,0,0);const{canvasCtx:n,targetCanvas:i}=this,{width:r,height:a}=i;n.save(),n.clearRect(0,0,r,a),n.drawImage(this.scaledCanvas,0,0,r,a),n.globalCompositeOperation="source-in",n.drawImage(e,0,0,r,a),n.globalCompositeOperation="destination-over",n.drawImage(this.replacementImage,0,0,i.width,i.height),n.restore()}static loadImageExecutor(e,t,n){const i=new Image;i.crossOrigin="Anonymous",i.addEventListener("load",(()=>{e(i)}),!1),i.addEventListener("error",(e=>{t(new Error(`Could not load replacement image ${i.src}: ${e.message}`))}),!1),i.src=n}static loadImage(e){return i(this,void 0,void 0,(function*(){return new Promise(((t,n)=>this.loadImageExecutor(t,n,e)))}))}revokeReplacementObjectUrl(){this.replacementObjectUrl&&URL.revokeObjectURL(this.replacementObjectUrl)}createReplacementObjectUrl(){return this.revokeReplacementObjectUrl(),this.replacementObjectUrl=URL.createObjectURL(this.replacementBlob),this.replacementObjectUrl}loadAssets(){const e=Object.create(null,{loadAssets:{get:()=>super.loadAssets}});return i(this,void 0,void 0,(function*(){this.replacementImage=yield s.loadImage(this.createReplacementObjectUrl()),e.loadAssets.call(this)}))}addObserver(e){this.delegate.addObserver(e)}removeObserver(e){this.delegate.removeObserver(e)}destroy(){const e=Object.create(null,{destroy:{get:()=>super.destroy}});return i(this,void 0,void 0,(function*(){e.destroy.call(this),this.revokeReplacementObjectUrl()}))}setEventController(e){this.eventController?this.eventController=e:(this.eventController=e,this.publishBackgroundFilterEvent())}publishBackgroundFilterEvent(){this.eventController.publishEvent("backgroundFilterConfigSelected",{backgroundBlurEnabled:"false",backgroundBlurStrength:"low",backgroundReplacementEnabled:"true",backgroundFilterVersion:1})}}t.default=s},2557:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(6605)),o=r(n(3804)),s=r(n(3293)),c=r(n(255)),l=r(n(3111));class d extends c.default{loadAssets(){return i(this,void 0,void 0,(function*(){}))}addObserver(){}removeObserver(){}setImageBlob(){return i(this,void 0,void 0,(function*(){}))}}class u extends a.default{static create(e,t){return i(this,void 0,void 0,(function*(){e=this.resolveSpec(e),t=this.resolveOptions(t),yield this.resolveOptionsAsync(t);const{logger:n}=t;if(!(yield u.isSupported(e,t)))return n.warn("Using no-op processor because background replacement is not supported"),new d;n.info("Using background replacement filter");const i=new l.default(e,t);return yield i.loadAssets(),i}))}static resolveOptions(e={}){const t=Object.assign({},e);return t.logger||(t.logger=new o.default("BackgroundReplacementProcessor",s.default.INFO)),super.resolveOptions(t)}static resolveOptionsAsync(e){return i(this,void 0,void 0,(function*(){if(!e.imageBlob){const t=document.createElement("canvas");t.width=100,t.height=100;const n=t.getContext("2d");n.fillStyle="blue",n.fillRect(0,0,100,100);const i=yield new Promise((e=>{t.toBlob(e)}));e.imageBlob=i}}))}static isSupported(e,t){const n=Object.create(null,{isSupported:{get:()=>super.isSupported}});return i(this,void 0,void 0,(function*(){e=this.resolveSpec(e),t=this.resolveOptions(t),yield this.resolveOptionsAsync(t);const i=t.imageBlob,r=URL.createObjectURL(i);try{yield l.default.loadImage(r)}catch(e){return t.logger.info(`Failed to fetch load replacement image ${e.message}`),!1}finally{URL.revokeObjectURL(r)}return n.isSupported.call(this,e,t)}))}}t.default=u},9766:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(2806));class a extends r.default{}t.default=a},3306:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t,n){this.fixedWaitMs=e,this.shortBackoffMs=t,this.longBackoffMs=n,this.currentRetry=0,this.fixedWaitMs<0&&(this.fixedWaitMs=0),this.shortBackoffMs<0&&(this.shortBackoffMs=0),this.longBackoffMs<0&&(this.longBackoffMs=0),this.reset()}reset(){this.currentRetry=0}nextBackoffAmountMs(){const e=Math.random()*Math.min(this.longBackoffMs,this.shortBackoffMs*Math.pow(2,this.currentRetry))+this.fixedWaitMs;return this.currentRetry+=1,e}}},1042:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(3306)),a=i(n(6334));t.default=class{constructor(e,t,n){this.fixedWaitMs=e,this.shortBackoffMs=t,this.longBackoffMs=n}create(){return new r.default(this.fixedWaitMs,this.shortBackoffMs,this.longBackoffMs)}createWithLimit(e){return new a.default(this.fixedWaitMs,this.shortBackoffMs,this.longBackoffMs,e)}}},6334:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(3306));class a extends r.default{constructor(e,t,n,i){super(e,t,n),this.limit=i,this.attempts=0}nextBackoffAmountMs(){if(this.attempts++,this.attempts>this.limit)throw new Error("retry limit exceeded");return super.nextBackoffAmountMs()}}t.default=a},6244:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});const r=n(8468),a=n(7232);class o{constructor(){this.FALLBACK_BROWSER={type:"browser",name:"unknown",version:"unknown",os:"unknown"},this.browser=r.detect()||this.FALLBACK_BROWSER,this.uaParserResult=navigator&&navigator.userAgent?new a.UAParser(navigator.userAgent).getResult():null,this.browserSupport={chrome:78,"edge-chromium":79,electron:7,firefox:75,ios:13,safari:13,opera:66,samsung:12,crios:86,fxios:23,"ios-webview":605,"chromium-webview":92},this.browserName={chrome:"Google Chrome","edge-chromium":"Microsoft Edge",electron:"Electron",firefox:"Mozilla Firefox",ios:"Safari iOS",safari:"Safari",opera:"Opera",samsung:"Samsung Internet",crios:"Chrome iOS",fxios:"Firefox iOS","ios-webview":"WKWebView iOS","chromium-webview":"Chrome WebView"},this.chromeLike=["chrome","edge-chromium","chromium-webview","opera","samsung"],this.webkitBrowsers=["crios","fxios","safari","ios","ios-webview","edge-ios"]}version(){return this.browser.version}majorVersion(){return null!==this.version()?parseInt(this.version().split(".")[0]):-1}osMajorVersion(){return parseInt(this.uaParserResult.os.version.split(".")[0])}engine(){return this.uaParserResult.engine.name}engineMajorVersion(){return parseInt(this.uaParserResult.engine.version.split(".")[0])}name(){return this.browser.name}hasChromiumWebRTC(){for(const e of this.chromeLike)if(e===this.browser.name)return!0;return!1}hasWebKitWebRTC(){for(const e of this.webkitBrowsers)if(e===this.browser.name)return!0;return!1}hasFirefoxWebRTC(){return this.isFirefox()}requiresPlaybackLatencyHintForAudioContext(){return-1!==navigator.userAgent.indexOf("Windows")}supportsCanvasCapturedStreamPlayback(){return!this.isIOSSafari()&&!this.isIOSChrome()&&!this.isIOSFirefox()&&!this.isIOSEdge()||this.isIOSSafari()&&this.majorVersion()>=o.MIN_IOS_SUPPORT_CANVAS_STREAM_PLAYBACK||this.majorVersion()>=o.MIN_IOS_NON_SAFARI_SUPPORT_CANVAS_STREAM_PLAYBACK}supportsBackgroundFilter(){return("safari"!==this.name()||15!==this.majorVersion())&&!!this.supportsCanvasCapturedStreamPlayback()}supportsVideoLayersAllocationRtpHeaderExtension(){return this.hasChromiumWebRTC()}supportsDependencyDescriptorRtpHeaderExtension(){return this.hasChromiumWebRTC()}supportsScalableVideoCoding(){return this.hasChromiumWebRTC()&&"Blink"===this.engine()&&this.engineMajorVersion()>=111}supportsAudioRedundancy(){return this.hasChromiumWebRTC()?this.engineMajorVersion()>=107:!this.hasFirefoxWebRTC()}requiresResolutionAlignment(e,t){return this.isAndroid()&&this.isPixel3()?[64*Math.ceil(e/64),64*Math.ceil(t/64)]:[e,t]}requiresCheckForSdpConnectionAttributes(){return!this.isIOSSafari()&&!this.isIOSChrome()&&!this.isIOSFirefox()}requiresIceCandidateGatheringTimeoutWorkaround(){return this.hasChromiumWebRTC()}requiresBundlePolicy(){return"max-bundle"}requiresNoExactMediaStreamConstraints(){return this.isSamsungInternet()}requiresGroupIdMediaStreamConstraints(){return this.isSamsungInternet()}getDisplayMediaAudioCaptureSupport(){return this.isChrome()||this.isEdge()}doesNotSupportMediaDeviceLabels(){return"chromium-webview"===this.browser.name}isSupported(){return!(!this.browserSupport[this.browser.name]||this.majorVersion()e.includes("a=rtpmap:"))).map((e=>e.replace(/.* /,"").replace(/\/.*/,""))).filter(((e,t,n)=>n.indexOf(e)===t)).filter((e=>"rtx"!==e&&"red"!==e&&"ulpfec"!==e))}))}supportsSetSinkId(){return"setSinkId"in HTMLAudioElement.prototype}disableResolutionScaleDown(){return this.isAndroid()}disable480pResolutionScaleDown(){return/( Chrome\/98\.)/i.test(navigator.userAgent)&&this.browser.os.startsWith("Windows")}requiresDisablingH264Encoding(){return(this.isIOSSafari()||this.isIOSChrome()||this.isIOSFirefox())&&("15.1.0"===this.version()||/( OS 15_1)/i.test(navigator.userAgent))}requiresVideoPlayWorkaround(){return this.isSafari()}isVideoFxSupportedBrowser(){return this.supportsBackgroundFilter()}isIOSSafari(){return"ios"===this.browser.name||"ios-webview"===this.browser.name||"safari"===this.browser.name&&/( Mac )/i.test(navigator.userAgent)&&navigator.maxTouchPoints>1}isSafari(){return"safari"===this.browser.name||this.isIOSSafari()}isFirefox(){return"firefox"===this.browser.name}isIOSFirefox(){return"fxios"===this.browser.name}isIOSChrome(){return"crios"===this.browser.name}isChrome(){return"chrome"===this.browser.name}isEdge(){return"edge-chromium"===this.browser.name}isIOSEdge(){return"edge-ios"===this.browser.name}isSamsungInternet(){return"samsung"===this.browser.name}isAndroid(){return/(android)/i.test(navigator.userAgent)}isPixel3(){return/( pixel 3)/i.test(navigator.userAgent)}}t.default=o,o.MIN_IOS_SUPPORT_CANVAS_STREAM_PLAYBACK=16,o.MIN_IOS_NON_SAFARI_SUPPORT_CANVAS_STREAM_PLAYBACK=106},4671:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=n(4955),a=i(n(1066)),o=i(n(3760)),s=i(n(9215));class c{constructor(e,t,n){this.logger=e,this.videoStreamIndex=t,this.selfAttendeeId=n,this.globalMetricReport=new s.default,this.streamMetricReports={},this.rtcStatsReport={},this.customStatsReports=[],this.currentTimestampMs=0,this.previousTimestampMs=0,this.currentSsrcs={},this.overriddenObservableMetrics=new Map,this.identityValue=(e,t)=>{const n=t?this.streamMetricReports[t]:this.globalMetricReport;return Number(n.currentMetrics[e])},this.decoderLossPercent=(e,t)=>{const n=this.streamMetricReports[t],i=n.currentMetrics.concealedSamples-(n.previousMetrics.concealedSamples||0),r=n.currentMetrics.totalSamplesReceived-(n.previousMetrics.totalSamplesReceived||0);return r<=0||r-i<=0?0:i/r*100},this.packetLossPercent=(e,t)=>{const n=this.streamMetricReports[t],i=n.currentMetrics[e]-(n.previousMetrics[e]||0),r=n.currentMetrics.packetsLost-(n.previousMetrics.packetsLost||0),a=i+r;return a<=0||r<=0?0:100*r/a},this.jitterBufferMs=(e,t)=>{const n=this.streamMetricReports[t],i=n.currentMetrics.jitterBufferDelay-(n.previousMetrics.jitterBufferDelay||0),r=n.currentMetrics.jitterBufferEmittedCount-(n.previousMetrics.jitterBufferEmittedCount||0);return i<=0||r<=0?0:i/r*1e3},this.countPerSecond=(e,t)=>{const n=t?this.streamMetricReports[t]:this.globalMetricReport;let i=(this.currentTimestampMs-this.previousTimestampMs)/1e3;if(i<=0)return 0;this.previousTimestampMs<=0&&(i=1);const r=n.currentMetrics[e]-(n.previousMetrics[e]||0);return r<=0?0:Math.trunc(r/i)},this.bitsPerSecond=(e,t)=>{const n=t?this.streamMetricReports[t]:this.globalMetricReport;let i=(this.currentTimestampMs-this.previousTimestampMs)/1e3;if(i<=0)return 0;this.previousTimestampMs<=0&&(i=1);const r=8*(n.currentMetrics[e]-(n.previousMetrics[e]||0));return r<=0?0:Math.trunc(r/i)},this.secondsToMilliseconds=(e,t)=>{const n=t?this.streamMetricReports[t]:this.globalMetricReport;return Number(1e3*n.currentMetrics[e])},this.averageTimeSpentPerSecondInMilliseconds=(e,t)=>{const n=t?this.streamMetricReports[t]:this.globalMetricReport;let i=(this.currentTimestampMs-this.previousTimestampMs)/1e3;if(i<=0)return 0;this.previousTimestampMs<=0&&(i=1);const r=n.currentMetrics[e]-(n.previousMetrics[e]||0);return r<=0?0:1e3*r/i},this.averageCpuQualityLimitationDurationPerSecondInMilliseconds=(e,t)=>{const n=this.streamMetricReports[t];let i=(this.currentTimestampMs-this.previousTimestampMs)/1e3;if(i<=0)return 0;this.previousTimestampMs<=0&&(i=1);let r=0,a=0;for(const[t,i]of Object.entries(n.previousObjectMetrics[e]))"cpu"===t&&(r=i);for(const[t,i]of Object.entries(n.currentObjectMetrics[e]))"cpu"===t&&(a=i);const o=a-r;return o<=0?0:1e3*o/i},this.isHardwareImplementation=(e,t)=>{const n=this.streamMetricReports[t],i=String(n.currentStringMetrics[e]),r=i.includes("ExternalDecoder")||i.includes("ExternalEncoder")||i.includes("EncodeAccelerator")||i.includes("DecodeAccelerator"),a=i.includes("fallback from");return r&&!a?1:0},this.globalMetricMap={retransmittedBytesSent:{transform:this.identityValue,type:r.SdkMetric.Type.VIDEO_RETRANSMIT_BITRATE},totalEncodedBytesTarget:{transform:this.identityValue,type:r.SdkMetric.Type.VIDEO_TARGET_ENCODER_BITRATE},totalPacketSendDelay:{transform:this.identityValue,type:r.SdkMetric.Type.VIDEO_BUCKET_DELAY_MS},packetsDiscardedOnSend:{transform:this.countPerSecond,type:r.SdkMetric.Type.SOCKET_DISCARDED_PPS},availableIncomingBitrate:{transform:this.identityValue,type:r.SdkMetric.Type.VIDEO_AVAILABLE_RECEIVE_BANDWIDTH},availableOutgoingBitrate:{transform:this.identityValue,type:r.SdkMetric.Type.VIDEO_AVAILABLE_SEND_BANDWIDTH},currentRoundTripTime:{transform:this.secondsToMilliseconds,type:r.SdkMetric.Type.STUN_RTT_MS},audioLevel:{transform:this.identityValue,type:r.SdkMetric.Type.RTC_MIC_AUDIO_LEVEL,source:"audioLevel"}},this.audioUpstreamMetricMap={jitter:{transform:this.secondsToMilliseconds,type:r.SdkMetric.Type.RTC_MIC_JITTER_MS},packetsSent:{transform:this.countPerSecond,type:r.SdkMetric.Type.RTC_MIC_PPS},bytesSent:{transform:this.bitsPerSecond,type:r.SdkMetric.Type.RTC_MIC_BITRATE},roundTripTime:{transform:this.secondsToMilliseconds,type:r.SdkMetric.Type.RTC_MIC_RTT_MS},packetsLost:{transform:this.packetLossPercent,type:r.SdkMetric.Type.RTC_MIC_FRACTION_PACKET_LOST_PERCENT,source:"packetsSent"}},this.audioDownstreamMetricMap={concealedSamples:{transform:this.countPerSecond},totalSamplesReceived:{transform:this.countPerSecond},decoderLoss:{transform:this.decoderLossPercent,type:r.SdkMetric.Type.RTC_SPK_FRACTION_DECODER_LOSS_PERCENT},packetsReceived:{transform:this.countPerSecond,type:r.SdkMetric.Type.RTC_SPK_PPS},packetsLost:{transform:this.packetLossPercent,type:r.SdkMetric.Type.RTC_SPK_FRACTION_PACKET_LOST_PERCENT,source:"packetsReceived"},jitter:{transform:this.secondsToMilliseconds,type:r.SdkMetric.Type.RTC_SPK_JITTER_MS},jitterBufferDelay:{transform:this.countPerSecond},jitterBufferEmittedCount:{transform:this.countPerSecond},jitterBufferMs:{transform:this.jitterBufferMs,type:r.SdkMetric.Type.RTC_SPK_JITTER_BUFFER_MS},bytesReceived:{transform:this.bitsPerSecond,type:r.SdkMetric.Type.RTC_SPK_BITRATE},audioLevel:{transform:this.identityValue,type:r.SdkMetric.Type.RTC_SPK_AUDIO_LEVEL},totalAudioPacketsLost:{transform:this.identityValue,type:r.SdkMetric.Type.RTC_SPK_TOTAL_LOST},totalAudioPacketsExpected:{transform:this.identityValue,type:r.SdkMetric.Type.RTC_SPK_TOTAL_EXPECTED},totalAudioPacketsRecoveredRed:{transform:this.identityValue,type:r.SdkMetric.Type.RTC_SPK_TOTAL_RECOVERED_RED},totalAudioPacketsRecoveredFec:{transform:this.identityValue,type:r.SdkMetric.Type.RTC_SPK_TOTAL_RECOVERED_FEC}},this.videoUpstreamMetricMap={roundTripTime:{transform:this.secondsToMilliseconds,type:r.SdkMetric.Type.VIDEO_SENT_RTT_MS},nackCount:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_NACKS_RECEIVED},pliCount:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_PLIS_RECEIVED},firCount:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_FIRS_RECEIVED},framesPerSecond:{transform:this.identityValue,type:r.SdkMetric.Type.VIDEO_INPUT_FPS},framesEncoded:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_ENCODE_FPS},packetsSent:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_SENT_PPS},packetsLost:{transform:this.packetLossPercent,type:r.SdkMetric.Type.VIDEO_SENT_FRACTION_PACKET_LOST_PERCENT,source:"packetsSent"},bytesSent:{transform:this.bitsPerSecond,type:r.SdkMetric.Type.VIDEO_SENT_BITRATE},qpSum:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_SENT_QP_SUM},frameHeight:{transform:this.identityValue,type:r.SdkMetric.Type.VIDEO_ENCODE_HEIGHT},frameWidth:{transform:this.identityValue,type:r.SdkMetric.Type.VIDEO_ENCODE_WIDTH},jitter:{transform:this.secondsToMilliseconds},totalEncodeTime:{transform:this.averageTimeSpentPerSecondInMilliseconds,type:r.SdkMetric.Type.VIDEO_ENCODE_MS},encoderImplementation:{transform:this.isHardwareImplementation,type:r.SdkMetric.Type.VIDEO_ENCODER_IS_HARDWARE},qualityLimitationDurations:{transform:this.averageCpuQualityLimitationDurationPerSecondInMilliseconds,type:r.SdkMetric.Type.VIDEO_QUALITY_LIMITATION_DURATION_CPU}},this.videoDownstreamMetricMap={packetsReceived:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_RECEIVED_PPS},packetsLost:{transform:this.packetLossPercent,type:r.SdkMetric.Type.VIDEO_RECEIVED_FRACTION_PACKET_LOST_PERCENT,source:"packetsReceived"},framesReceived:{transform:this.identityValue,type:r.SdkMetric.Type.VIDEO_RECEIVED_FPS},framesDecoded:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_DECODE_FPS},nackCount:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_NACKS_SENT},firCount:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_FIRS_SENT},pliCount:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_PLIS_SENT},bytesReceived:{transform:this.bitsPerSecond,type:r.SdkMetric.Type.VIDEO_RECEIVED_BITRATE},jitter:{transform:this.secondsToMilliseconds,type:r.SdkMetric.Type.VIDEO_RECEIVED_JITTER_MS},jitterBufferDelay:{transform:this.countPerSecond},jitterBufferEmittedCount:{transform:this.countPerSecond},jitterBufferMs:{transform:this.jitterBufferMs,type:r.SdkMetric.Type.VIDEO_JITTER_BUFFER_MS},qpSum:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_RECEIVED_QP_SUM},frameHeight:{transform:this.identityValue,type:r.SdkMetric.Type.VIDEO_DECODE_HEIGHT},frameWidth:{transform:this.identityValue,type:r.SdkMetric.Type.VIDEO_DECODE_WIDTH},totalDecodeTime:{transform:this.averageTimeSpentPerSecondInMilliseconds,type:r.SdkMetric.Type.VIDEO_DECODE_MS},decoderImplementation:{transform:this.isHardwareImplementation,type:r.SdkMetric.Type.VIDEO_DECODER_IS_HARDWARE},totalFreezesDuration:{transform:this.averageTimeSpentPerSecondInMilliseconds,type:r.SdkMetric.Type.VIDEO_FREEZE_DURATION},freezeCount:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_FREEZE_COUNT},totalPausesDuration:{transform:this.averageTimeSpentPerSecondInMilliseconds,type:r.SdkMetric.Type.VIDEO_PAUSE_DURATION},pauseCount:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_PAUSE_COUNT},framesDropped:{transform:this.countPerSecond,type:r.SdkMetric.Type.VIDEO_DROPPED_FPS}},this.streamDimensionMap={encoderImplementation:r.SdkStreamDimension.Type.VIDEO_ENCODER_NAME,decoderImplementation:r.SdkStreamDimension.Type.VIDEO_DECODER_NAME},this.observableVideoMetricSpec={videoUpstreamBitrate:{source:"bytesSent",media:o.default.VIDEO,dir:a.default.UPSTREAM},videoUpstreamPacketsSent:{source:"packetsSent",media:o.default.VIDEO,dir:a.default.UPSTREAM},videoUpstreamPacketLossPercent:{source:"packetsLost",media:o.default.VIDEO,dir:a.default.UPSTREAM},videoUpstreamFramesEncodedPerSecond:{source:"framesEncoded",media:o.default.VIDEO,dir:a.default.UPSTREAM},videoUpstreamFrameHeight:{source:"frameHeight",media:o.default.VIDEO,dir:a.default.UPSTREAM},videoUpstreamFrameWidth:{source:"frameWidth",media:o.default.VIDEO,dir:a.default.UPSTREAM},videoUpstreamJitterMs:{source:"jitter",media:o.default.VIDEO,dir:a.default.UPSTREAM},videoUpstreamRoundTripTimeMs:{source:"roundTripTime",media:o.default.VIDEO,dir:a.default.UPSTREAM},videoDownstreamBitrate:{source:"bytesReceived",media:o.default.VIDEO,dir:a.default.DOWNSTREAM},videoDownstreamPacketLossPercent:{source:"packetsLost",media:o.default.VIDEO,dir:a.default.DOWNSTREAM},videoDownstreamPacketsReceived:{source:"packetsReceived",media:o.default.VIDEO,dir:a.default.DOWNSTREAM},videoDownstreamFramesDecodedPerSecond:{source:"framesDecoded",media:o.default.VIDEO,dir:a.default.DOWNSTREAM},videoDownstreamFrameHeight:{source:"frameHeight",media:o.default.VIDEO,dir:a.default.DOWNSTREAM},videoDownstreamFrameWidth:{source:"frameWidth",media:o.default.VIDEO,dir:a.default.DOWNSTREAM},videoDownstreamJitterMs:{source:"jitter",media:o.default.VIDEO,dir:a.default.DOWNSTREAM},videoDownstreamDelayMs:{source:"jitterBufferMs",media:o.default.VIDEO,dir:a.default.DOWNSTREAM}},this.observableMetricSpec={audioPacketsReceived:{source:"packetsReceived",media:o.default.AUDIO,dir:a.default.DOWNSTREAM},audioPacketsReceivedFractionLoss:{source:"packetsLost",media:o.default.AUDIO,dir:a.default.DOWNSTREAM},audioDecoderLoss:{source:"decoderLoss",media:o.default.AUDIO,dir:a.default.DOWNSTREAM},audioPacketsSent:{source:"packetsSent",media:o.default.AUDIO,dir:a.default.UPSTREAM},audioPacketLossPercent:{source:"packetsLost",media:o.default.AUDIO,dir:a.default.UPSTREAM},audioUpstreamRoundTripTimeMs:{source:"roundTripTime",media:o.default.AUDIO,dir:a.default.UPSTREAM},videoUpstreamBitrate:{source:"bytesSent",media:o.default.VIDEO,dir:a.default.UPSTREAM},videoPacketSentPerSecond:{source:"packetsSent",media:o.default.VIDEO,dir:a.default.UPSTREAM},audioSpeakerDelayMs:{source:"jitterBufferMs",media:o.default.AUDIO,dir:a.default.DOWNSTREAM},audioUpstreamJitterMs:{source:"jitter",media:o.default.AUDIO,dir:a.default.UPSTREAM},audioDownstreamJitterMs:{source:"jitter",media:o.default.AUDIO,dir:a.default.DOWNSTREAM},nackCountReceivedPerSecond:{source:"nackCount",media:o.default.VIDEO,dir:a.default.UPSTREAM},availableOutgoingBitrate:{source:"availableOutgoingBitrate"},availableIncomingBitrate:{source:"availableIncomingBitrate"},currentRoundTripTimeMs:{source:"currentRoundTripTime"},audioDownstreamLevel:{source:"audioLevel",media:o.default.AUDIO,dir:a.default.DOWNSTREAM},audioUpstreamLevel:{source:"audioLevel"}}}getMetricMap(e,t){switch(e){case o.default.AUDIO:switch(t){case a.default.UPSTREAM:return this.audioUpstreamMetricMap;case a.default.DOWNSTREAM:return this.audioDownstreamMetricMap}case o.default.VIDEO:switch(t){case a.default.UPSTREAM:return this.videoUpstreamMetricMap;case a.default.DOWNSTREAM:return this.videoDownstreamMetricMap}default:return this.globalMetricMap}}getStreamDimensionMap(){return this.streamDimensionMap}getObservableMetricValue(e){if(this.overriddenObservableMetrics.has(e))return this.overriddenObservableMetrics.get(e);const t=this.observableMetricSpec[e],n=this.getMetricMap(t.media,t.dir)[t.source],{transform:i,source:r}=n;if(!t.hasOwnProperty("media"))return i(r||t.source);for(const e in this.streamMetricReports){const n=this.streamMetricReports[e];if(n.direction===t.dir&&n.mediaType===t.media)return i(r||t.source,Number(e))}return 0}getObservableVideoMetricValue(e,t){const n=this.observableVideoMetricSpec[e],i=this.getMetricMap(n.media,n.dir)[n.source],{transform:r,source:a}=i;return r(a||n.source,t)}getObservableMetrics(){const e={};for(const t in this.observableMetricSpec)e[t]=this.getObservableMetricValue(t);return e}getObservableVideoMetrics(){const e={};if(!this.videoStreamIndex||!this.selfAttendeeId)return this.logger.error("Need to define VideoStreamIndex and selfAttendeeId if using getObservableVideoMetrics API"),e;for(const t in this.streamMetricReports)if(this.streamMetricReports[t].mediaType===o.default.VIDEO){const n={};for(const e in this.observableVideoMetricSpec)if(this.observableVideoMetricSpec[e].dir===this.streamMetricReports[t].direction){const i=this.getObservableVideoMetricValue(e,Number(t));isNaN(i)||(n[e]=i)}const i=this.streamMetricReports[t].groupId,r=this.streamMetricReports[t].streamId;let a="";a=void 0!==this.videoStreamIndex.attendeeIdForGroupId?i?this.videoStreamIndex.attendeeIdForGroupId(i):this.selfAttendeeId:r?this.videoStreamIndex.attendeeIdForStreamId(r):this.selfAttendeeId,e[a]=e[a]?e[a]:{},e[a][t]=n}return e}getRTCStatsReport(){return this.rtcStatsReport}clone(){const e=new c(this.logger,this.videoStreamIndex,this.selfAttendeeId);return e.globalMetricReport=this.globalMetricReport,e.streamMetricReports=this.streamMetricReports,e.rtcStatsReport=this.rtcStatsReport,e.customStatsReports=this.customStatsReports,e.currentTimestampMs=this.currentTimestampMs,e.previousTimestampMs=this.previousTimestampMs,e.overriddenObservableMetrics=this.overriddenObservableMetrics,e}print(){const e={globalMetricReport:this.globalMetricReport,streamMetricReports:this.streamMetricReports,currentTimestampMs:this.currentTimestampMs,previousTimestampMs:this.previousTimestampMs};this.logger.debug((()=>`Client Metric Report: ${JSON.stringify(e)}`))}removeDestroyedSsrcs(){for(const e in this.streamMetricReports)this.currentSsrcs[e]||delete this.streamMetricReports[e]}overrideObservableMetric(e,t){this.overriddenObservableMetrics.set(e,t)}}t.default=c},1066:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.ClientMetricReportDirection=void 0,function(e){e[e.UPSTREAM=0]="UPSTREAM",e[e.DOWNSTREAM=1]="DOWNSTREAM"}(n=t.ClientMetricReportDirection||(t.ClientMetricReportDirection={})),t.default=n},3760:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.ClientMetricReportMediaType=void 0,function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO"}(n=t.ClientMetricReportMediaType||(t.ClientMetricReportMediaType={})),t.default=n},7824:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{}},9215:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.previousMetrics={},this.currentMetrics={},this.currentStringMetrics={},this.previousObjectMetrics={},this.currentObjectMetrics={}}}},7170:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.currentTimestampMs=0,this.ssrc=0,this.totalAudioPacketsLost=0,this.totalAudioPacketsExpected=0,this.totalAudioPacketsRecoveredRed=0,this.totalAudioPacketsRecoveredFec=0}}},2260:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.previousMetrics={},this.currentMetrics={},this.currentStringMetrics={},this.previousObjectMetrics={},this.currentObjectMetrics={}}}},2852:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t,n){this.minHealth=e.minHealth,this.maxHealth=e.maxHealth,this.currentHealth=e.initialHealth,this.currentData=t.clone(),this.name=n}minimumHealth(){return this.minHealth}maximumHealth(){return this.maxHealth}health(){return this.maximumHealth()}update(e){this.currentData=e}getConnectionHealthData(){return this.currentData.clone()}healthy(){return this.health()>this.minimumHealth()}healthIfChanged(){const e=this.health();return e!==this.currentHealth?(this.currentHealth=e,e):null}}},5799:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n{constructor(){this.connectionStartTimestampMs=0,this.consecutiveStatsWithNoPackets=0,this.consecutiveStatsWithNoAudioPacketsSent=0,this.lastPacketLossInboundTimestampMs=0,this.lastGoodSignalTimestampMs=0,this.lastWeakSignalTimestampMs=0,this.lastNoSignalTimestampMs=0,this.consecutiveMissedPongs=0,this.packetsReceivedInLastMinute=[],this.fractionPacketsLostInboundInLastMinute=[],this.audioSpeakerDelayMs=0,this.connectionStartTimestampMs=Date.now(),this.lastGoodSignalTimestampMs=Date.now()}static isTimestampRecent(e,t){return Date.now(){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.minHealth=0,this.maxHealth=1,this.initialHealth=1,this.connectionUnhealthyThreshold=25,this.noSignalThresholdTimeMs=1e4,this.connectionWaitTimeMs=1e4,this.zeroBarsNoSignalTimeMs=5e3,this.oneBarWeakSignalTimeMs=5e3,this.twoBarsTimeMs=5e3,this.threeBarsTimeMs=1e4,this.fourBarsTimeMs=2e4,this.fiveBarsTimeMs=6e4,this.cooldownTimeMs=6e4,this.pastSamplesToConsider=15,this.goodSignalTimeMs=15e3,this.fractionalLoss=.5,this.packetsExpected=50,this.maximumTimesToWarn=2,this.missedPongsLowerThreshold=1,this.missedPongsUpperThreshold=4,this.maximumAudioDelayMs=6e4,this.maximumAudioDelayDataPoints=10,this.sendingAudioFailureSamplesToConsider=2,this.sendingAudioFailureInitialWaitTimeMs=3e3}}},2212:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(2852));class a extends r.default{constructor(e,t,n){super(t,n,"Reconnection Health"),this.logger=e,this.audioDelayPointsOverMaximum=0,a.CONNECTION_UNHEALTHY_THRESHOLD=t.connectionUnhealthyThreshold,a.CONNECTION_WAIT_TIME_MS=t.connectionWaitTimeMs,a.MISSED_PONGS_THRESHOLD=t.missedPongsUpperThreshold,a.MAXIMUM_AUDIO_DELAY_MS=t.maximumAudioDelayMs,a.MAXIMUM_AUDIO_DELAY_DATA_POINTS=t.maximumAudioDelayDataPoints}health(){if(this.currentData.isConnectionStartRecent(a.CONNECTION_WAIT_TIME_MS))return 1;const e=this.currentData.consecutiveStatsWithNoPackets>=a.CONNECTION_UNHEALTHY_THRESHOLD,t=this.currentData.consecutiveMissedPongs>=a.MISSED_PONGS_THRESHOLD;this.currentData.audioSpeakerDelayMs>a.MAXIMUM_AUDIO_DELAY_MS?this.audioDelayPointsOverMaximum+=1:this.audioDelayPointsOverMaximum=0;const n=this.audioDelayPointsOverMaximum>a.MAXIMUM_AUDIO_DELAY_DATA_POINTS;return n&&(this.audioDelayPointsOverMaximum=0),e||t||n?(this.logger.warn(`reconnection recommended due to: no packets received: ${e}, missed pongs: ${t}, bad audio delay: ${n}`),0):1}}t.default=a},6131:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(2852));class a extends r.default{constructor(e,t,n){super(t,n,"Sending Audio Health"),this.logger=e,this.sendingAudioFailureSamplesToConsider=t.sendingAudioFailureSamplesToConsider>0?t.sendingAudioFailureSamplesToConsider:1,this.sendingAudioFailureInitialWaitTimeMs=t.sendingAudioFailureInitialWaitTimeMs,this.maximumTimesToWarn=t.maximumTimesToWarn,this.coolDownTimeMs=t.cooldownTimeMs,this.lastWarnTimestampMs=0,this.warnCount=0}isSendingAudioUnhealthy(){const e=!this.currentData.isConnectionStartRecent(this.sendingAudioFailureInitialWaitTimeMs),t=this.currentData.consecutiveStatsWithNoAudioPacketsSent>=this.sendingAudioFailureSamplesToConsider;return e&&t}health(){if(this.isSendingAudioUnhealthy()){const e=Date.now()-this.lastWarnTimestampMsthis.minimumHealth()&&!e?(this.logger.warn(`Sending Audio is unhealthy for ${this.sendingAudioFailureSamplesToConsider} seconds consecutively.`),this.warnCount++,this.warnCount>this.maximumTimesToWarn?(this.logger.warn("SendingAudioFailure health policy maximum warnings breached. Falling back to reporting healthy."),this.maximumHealth()):(this.lastWarnTimestampMs=Date.now(),this.minimumHealth())):this.currentHealth}return this.maximumHealth()}}t.default=a},4880:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(2852));class a extends r.default{constructor(e,t){super(e,t,"Unusable Audio Warning"),this.coolDownTimeMs=e.cooldownTimeMs,this.pastSamplesToConsider=e.pastSamplesToConsider,this.fractionalLoss=e.fractionalLoss,this.packetsExpected=e.packetsExpected,this.maximumTimesToWarn=e.maximumTimesToWarn,this.lastWarnTimestampMs=0,this.warnCount=0}calculateFractionalLoss(){if(this.currentData.packetsReceivedInLastMinute.length=this.fractionalLoss?0!==this.currentHealth&&(this.lastWarnTimestampMs=Date.now(),this.warnCount++,this.warnCount>this.maximumTimesToWarn)?1:0:1}}t.default=a},5437:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(8807);t.default=class{constructor(e,t,n,i,r){this.audioVideoController=e,this.realtimeController=t,this.connectionHealthData=n,this.pingPong=i,this.statsCollector=r,this.isActive=!1,this.hasSeenValidPacketMetricsBefore=!1,this.lastTotalPacketsReceived=0,this.realtimeController.realtimeSubscribeToLocalSignalStrengthChange((e=>{this.isActive&&this.receiveSignalStrengthChange(e)}))}start(){this.isActive=!0,this.pingPong.addObserver(this),this.pingPong.start(),this.audioVideoController.addObserver(this)}stop(){this.isActive=!1,this.pingPong.removeObserver(this),this.pingPong.stop(),this.audioVideoController.removeObserver(this)}receiveSignalStrengthChange(e){0===e?this.connectionHealthData.setLastNoSignalTimestampMs(Date.now()):e<=.5?this.connectionHealthData.setLastWeakSignalTimestampMs(Date.now()):this.connectionHealthData.setLastGoodSignalTimestampMs(Date.now()),this.updateConnectionHealth()}didReceivePong(e,t,n){this.connectionHealthData.setConsecutiveMissedPongs(0),this.statsCollector.logLatency("ping_pong",t),this.statsCollector.logLatency("ping_pong_clock_skew",n),this.updateConnectionHealth()}didMissPongs(){this.connectionHealthData.setConsecutiveMissedPongs(this.connectionHealthData.consecutiveMissedPongs+1),this.updateConnectionHealth()}metricsDidReceive(e){let t=0,n=0;const i=e.getObservableMetrics(),r=i.audioPacketsReceived,a=i.audioPacketsReceivedFractionLoss,o=i.audioSpeakerDelayMs;"number"!=typeof o||isNaN(o)||this.connectionHealthData.setAudioSpeakerDelayMs(o);const s=e.getRTCStatsReport();let c=0;s.forEach((e=>{"candidate-pair"===e.type&&e.packetsReceived&&(c+=e.packetsReceived)}));const l=c-this.lastTotalPacketsReceived;this.lastTotalPacketsReceived=c,"number"==typeof r&&"number"==typeof a&&(t=r,n=a,t<0||n<0||l<0||(this.addToMinuteWindow(this.connectionHealthData.packetsReceivedInLastMinute,t),this.addToMinuteWindow(this.connectionHealthData.fractionPacketsLostInboundInLastMinute,n),l>0?(this.hasSeenValidPacketMetricsBefore=!0,this.connectionHealthData.setConsecutiveStatsWithNoPackets(0)):this.hasSeenValidPacketMetricsBefore&&this.connectionHealthData.setConsecutiveStatsWithNoPackets(this.connectionHealthData.consecutiveStatsWithNoPackets+1),(0===t||n>0)&&this.connectionHealthData.setLastPacketLossInboundTimestampMs(Date.now()),"number"==typeof i.audioPacketsSent&&this.updateAudioPacketsSentInConnectionHealth(i.audioPacketsSent),this.updateConnectionHealth()))}updateAudioPacketsSentInConnectionHealth(e){e>0?this.connectionHealthData.setConsecutiveStatsWithNoAudioPacketsSent(0):this.connectionHealthData.setConsecutiveStatsWithNoAudioPacketsSent(this.connectionHealthData.consecutiveStatsWithNoAudioPacketsSent+1)}addToMinuteWindow(e,t){e.unshift(t),e.length>60&&e.pop()}updateConnectionHealth(){this.audioVideoController.forEachObserver((e=>{i.Maybe.of(e.connectionHealthDidChange).map((t=>t.bind(e)(this.connectionHealthData.clone())))}))}}},5100:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Modality="#content"}(n||(n={})),t.default=n},8896:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(6244)),o=r(n(3236));class s{constructor(e){this.logger=e}get mediaStream(){return this._mediaStream}set mediaStream(e){this._mediaStream=e}acquireAudioInputStream(){return i(this,void 0,void 0,(function*(){return 0===this._mediaStream.getAudioTracks().length?(this.logger.info("No audio stream available. Synthesizing an audio stream."),o.default.synthesizeAudioDevice(0)):this._mediaStream}))}acquireVideoInputStream(){return i(this,void 0,void 0,(function*(){return this._mediaStream}))}acquireDisplayInputStream(e){return i(this,void 0,void 0,(function*(){return e&&e.video&&e.video.mandatory&&e.video.mandatory.chromeMediaSource&&e.video.mandatory.chromeMediaSourceId?navigator.mediaDevices.getUserMedia(e):navigator.mediaDevices.getDisplayMedia(e)}))}acquireScreenCaptureDisplayInputStream(e,t){return i(this,void 0,void 0,(function*(){return this.acquireDisplayInputStream(this.screenCaptureDisplayMediaConstraints(e,t))}))}screenCaptureDisplayMediaConstraints(e,t){return{audio:!(e||!(new a.default).getDisplayMediaAudioCaptureSupport()),video:Object.assign(Object.assign({},!e&&{frameRate:{max:t||s.defaultFrameRate}}),e&&{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxFrameRate:t||s.defaultFrameRate}})}}toggleMediaStream(e){let t=!1;if(this.mediaStream)for(let n=0;n{this.stopContentShare()}));this.contentAudioVideo.start()}else this.contentAudioVideo.logger.info("Could not start content because max content resolution was set to None")}))}startContentShareFromScreenCapture(e,t){return i(this,void 0,void 0,(function*(){const n=yield this.mediaStreamBroker.acquireScreenCaptureDisplayInputStream(e,t);return yield this.startContentShare(n),n}))}pauseContentShare(){this.mediaStreamBroker.toggleMediaStream(!1)&&this.forEachContentShareObserver((e=>{d.Maybe.of(e.contentShareDidPause).map((t=>t.call(e)))}))}unpauseContentShare(){this.mediaStreamBroker.toggleMediaStream(!0)&&this.forEachContentShareObserver((e=>{d.Maybe.of(e.contentShareDidUnpause).map((t=>t.call(e)))}))}setContentShareVideoCodecPreferences(e){this.contentAudioVideo.setVideoCodecSendPreferences(e)}destroy(){return i(this,void 0,void 0,(function*(){this.contentAudioVideo&&(this.destroyed=!0,this.contentAudioVideo.removeObserver(this),this.stopContentShare(),this.observerQueue.clear(),this.contentAudioVideo=void 0,this.attendeeAudioVideo=void 0,this.mediaStreamBroker=void 0)}))}stopContentShare(){this.contentAudioVideo.stop(),this.mediaStreamBroker.cleanup()}addContentShareObserver(e){this.observerQueue.add(e)}removeContentShareObserver(e){this.observerQueue.delete(e)}forEachContentShareObserver(e){for(const t of this.observerQueue)l.default.nextTick((()=>{this.observerQueue.has(t)&&e(t)}))}audioVideoDidStart(){var e;(null===(e=this.mediaStreamBroker.mediaStream)||void 0===e?void 0:e.getVideoTracks().length)>0&&this.contentAudioVideo.videoTileController.startLocalVideoTile()}audioVideoDidStop(e){this.mediaStreamBroker.cleanup(),this.contentShareTile&&(this.attendeeAudioVideo.videoTileController.removeVideoTile(this.contentShareTile.id()),this.contentShareTile=null),this.forEachContentShareObserver((e=>{d.Maybe.of(e.contentShareDidStop).map((t=>t.call(e)))}))}setupContentShareEvents(){this.attendeeAudioVideo.realtimeController.realtimeSubscribeToAttendeeIdPresence(((e,t,n,i)=>{const r=new c.default(e).hasModality(c.default.MODALITY_CONTENT),a=new c.default(e).base()===this.attendeeAudioVideo.configuration.credentials.attendeeId;if(!r||!a||!t||this.contentShareTile)return;const o=this.mediaStreamBroker.mediaStream;if(null==o?void 0:o.getVideoTracks().length){this.contentShareTile=this.attendeeAudioVideo.videoTileController.addVideoTile();const e=o.getVideoTracks()[0];let t,n;if(e.getSettings){const i=e.getSettings();t=i.width,n=i.height}else{const i=e.getCapabilities();t=i.width,n=i.height}this.contentShareTile.bindVideoStream(this.contentAudioVideo.configuration.credentials.attendeeId,!1,o,t,n,null,this.contentAudioVideo.configuration.credentials.externalUserId)}this.forEachContentShareObserver((e=>{d.Maybe.of(e.contentShareDidStart).map((t=>t.call(e)))}))}))}}},205:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class i{static register(){"document"in n.g&&document.addEventListener&&i.shouldRegisterCSPMonitor&&(i.added||(document.addEventListener("securitypolicyviolation",i.listener),i.added=!0))}static unregister(){"document"in n.g&&document.removeEventListener&&(document.removeEventListener("securitypolicyviolation",i.listener),i.loggers=new Set,i.added=!1)}static disable(){i.shouldRegisterCSPMonitor=!1,i.unregister()}static addLogger(e){e&&i.loggers.add(e)}static removeLogger(e){e&&i.loggers.delete(e)}}t.default=i,i.loggers=new Set,i.shouldRegisterCSPMonitor=!0,i.added=!1,i.listener=e=>{const t=`Security Policy Violation\nBlocked URI: ${e.blockedURI}\nViolated Directive: ${e.violatedDirective}\nOriginal Policy: ${e.originalPolicy}\nDocument URI: ${e.documentURI}\nSource File: ${e.sourceFile}\nLine No.: ${e.lineNumber}\n`;for(const e of i.loggers)e.error(t);0===i.loggers.size&&console.error(t)}},4783:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t,n,i,r,a){this.timestampMs=e,this.topic=t,this.data=n,this.senderAttendeeId=i,this.senderExternalUserId=r,this.throttled=!!a}text(){return(new TextDecoder).decode(this.data)}json(){return JSON.parse((new TextDecoder).decode(this.data))}}},47:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDestroyable=void 0,t.isDestroyable=function(e){return e&&"destroy"in e}},3099:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAudioTransformDevice=void 0,t.isAudioTransformDevice=function(e){return!!e&&"object"==typeof e&&"mute"in e&&"stop"in e&&"intrinsicDevice"in e}},3236:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(6244)),o=r(n(5032)),s=r(n(4185)),c=r(n(8988)),l=n(8807),d=r(n(1729)),u=r(n(8474)),f=n(3099),h=r(n(8715)),m=r(n(7086)),p=r(n(8736)),g=r(n(478)),v=r(n(903)),b=r(n(8349)),y=r(n(6801)),S=r(n(7094)),C=n(6880);class w{constructor(e,t,n=new a.default,i){this.logger=e,this.browserBehavior=n,this.eventController=i,this.deviceInfoCache=null,this.activeDevices={audio:null,video:null},this.chosenVideoTransformDevice=null,this.audioOutputDeviceId=void 0,this.deviceChangeObservers=new Set,this.mediaStreamBrokerObservers=new Set,this.deviceLabelTrigger=()=>navigator.mediaDevices.getUserMedia({audio:!0,video:!0}),this.audioInputDestinationNode=null,this.audioInputSourceNode=null,this.videoInputQualitySettings=null,this.useWebAudio=!1,this.useMediaConstraintsFallback=!0,this.audioInputTaskQueue=new c.default,this.videoInputTaskQueue=new c.default,this.muted=!1,this.mediaStreamMuteObserver=(e,t)=>{for(const n of this.deviceChangeObservers)s.default.nextTick((()=>{this.deviceChangeObservers.has(n)&&n.audioInputMuteStateChanged&&n.audioInputMuteStateChanged(e,t)}))},this.alreadyHandlingDeviceChange=!1;const{enableWebAudio:r=!1,useMediaConstraintsFallback:l=!0}=t||{};this.useWebAudio=r,this.useMediaConstraintsFallback=l,this.videoInputQualitySettings=new S.default(w.defaultVideoWidth,w.defaultVideoHeight,w.defaultVideoFrameRate);const d=this.browserBehavior.requiresResolutionAlignment(this.videoInputQualitySettings.videoWidth,this.videoInputQualitySettings.videoHeight);this.videoInputQualitySettings.videoWidth=d[0],this.videoInputQualitySettings.videoHeight=d[1],this.logger.info(`DefaultDeviceController video dimension ${this.videoInputQualitySettings.videoWidth} x ${this.videoInputQualitySettings.videoHeight}`);try{this.mediaDeviceWrapper=(new o.default).create();const e=navigator.mediaDevices.getSupportedConstraints();this.logger.info(`Supported Constraints in this browser ${JSON.stringify(e)}`)}catch(t){e.error(t.message)}}isWatchingForDeviceChanges(){return!!this.onDeviceChangeCallback}ensureWatchingDeviceChanges(){var e;this.isWatchingForDeviceChanges()||(this.logger.info("Starting devicechange listener."),this.onDeviceChangeCallback=()=>{this.logger.info("Device change event callback is triggered"),this.handleDeviceChange()},null===(e=this.mediaDeviceWrapper)||void 0===e||e.addEventListener("devicechange",this.onDeviceChangeCallback))}stopWatchingDeviceChanges(){var e;this.isWatchingForDeviceChanges()&&(this.logger.info("Stopping devicechange listener."),null===(e=this.mediaDeviceWrapper)||void 0===e||e.removeEventListener("devicechange",this.onDeviceChangeCallback),this.onDeviceChangeCallback=void 0)}shouldObserveDeviceChanges(){return!!this.deviceChangeObservers.size||this.activeDevices.audio&&null!==this.activeDevices.audio.constraints||this.activeDevices.video&&null!==this.activeDevices.video.constraints||!!this.audioOutputDeviceId}watchForDeviceChangesIfNecessary(){this.shouldObserveDeviceChanges()?this.ensureWatchingDeviceChanges():this.stopWatchingDeviceChanges()}destroy(){return i(this,void 0,void 0,(function*(){this.stopWatchingDeviceChanges(),yield this.stopAudioInput(),yield this.stopVideoInput()}))}listAudioInputDevices(e=!1){return i(this,void 0,void 0,(function*(){const t=yield this.listDevicesOfKind("audioinput",e);return this.trace("listAudioInputDevices",e,t),t}))}listVideoInputDevices(e=!1){return i(this,void 0,void 0,(function*(){const t=yield this.listDevicesOfKind("videoinput",e);return this.trace("listVideoInputDevices",e,t),t}))}listAudioOutputDevices(e=!1){return i(this,void 0,void 0,(function*(){const t=yield this.listDevicesOfKind("audiooutput",e);return this.trace("listAudioOutputDevices",e,t),t}))}pushAudioMeetingStateForPermissions(e){var t;null===(t=this.eventController)||void 0===t||t.publishEvent(void 0===e?"audioInputUnselected":"audioInputSelected")}pushVideoMeetingStateForPermissions(e){var t;null===(t=this.eventController)||void 0===t||t.publishEvent(void 0===e?"videoInputUnselected":"videoInputSelected")}startAudioInput(e){return i(this,void 0,void 0,(function*(){return yield this.audioInputTaskQueue.add((()=>this.startAudioInputTask(e)))}))}startAudioInputTask(e){var t;return i(this,void 0,void 0,(function*(){if(void 0!==e)try{return f.isAudioTransformDevice(e)?(this.logger.info(`Choosing transform input device ${e}`),yield this.chooseAudioTransformInputDevice(e)):(this.logger.info(`Choosing intrinsic audio input device ${e}`),this.removeTransform(),yield this.chooseInputIntrinsicDevice("audio",e)),this.trace("startAudioInputDevice",e,"success"),this.useWebAudio?(this.attachAudioInputStreamToAudioContext(this.activeDevices.audio.stream),this.pushAudioMeetingStateForPermissions(this.getMediaStreamDestinationNode().stream),yield null===(t=this.transform)||void 0===t?void 0:t.device.mute(this.muted),this.getMediaStreamDestinationNode().stream):(this.publishAudioInputDidChangeEvent(this.activeDevices.audio.stream),this.activeDevices.audio.stream)}catch(e){throw e}else this.logger.error("Audio input device cannot be undefined")}))}stopAudioInput(){return i(this,void 0,void 0,(function*(){return this.audioInputTaskQueue.add((()=>this.stopAudioInputTask()))}))}stopAudioInputTask(){return i(this,void 0,void 0,(function*(){try{if(this.useWebAudio)return void this.releaseAudioTransformStream();this.stopTracksAndRemoveCallbacks("audio")}finally{this.watchForDeviceChangesIfNecessary(),this.publishAudioInputDidChangeEvent(void 0)}}))}chooseAudioTransformInputDevice(e){var t;return i(this,void 0,void 0,(function*(){if((null===(t=this.transform)||void 0===t?void 0:t.device)===e)return;if(!this.useWebAudio)throw new Error("Cannot apply transform device without enabling Web Audio.");const n=w.getAudioContext();if(n instanceof OfflineAudioContext);else switch(n.state){case"running":break;case"closed":throw new Error("Cannot choose a transform device with a closed audio context.");case"suspended":yield n.resume()}let i;try{i=yield e.createAudioNode(n)}catch(e){throw this.logger.error(`Unable to create transform device node: ${e}.`),e}const r=yield e.intrinsicDevice();yield this.chooseInputIntrinsicDevice("audio",r),this.logger.debug(`Got inner stream: ${r}.`),this.setTransform(e,i)}))}chooseVideoTransformInputDevice(e){var t;return i(this,void 0,void 0,(function*(){if(this.eventController&&e instanceof d.default&&e.passEventControllerToProcessors(this.eventController),e===this.chosenVideoTransformDevice)return void this.logger.info("Reselecting same VideoTransformDevice");const n=this.chosenVideoTransformDevice;n&&this.logger.info("Switched from previous VideoTransformDevice");const i=!!n,r=yield e.intrinsicDevice();if(!this.isMediaStreamReusableByDeviceId(null===(t=this.activeDevices.video)||void 0===t?void 0:t.stream,r))return this.logger.info("video transform device needs new intrinsic device"),i&&n.onOutputStreamDisconnect(),this.chosenVideoTransformDevice=e,this.activeDevices.video=null,yield this.chooseInputIntrinsicDevice("video",r),this.logger.info("apply processors to transform"),void(yield this.chosenVideoTransformDevice.transformStream(this.activeDevices.video.stream));this.chosenVideoTransformDevice=e,this.logger.info("video transform device uses previous stream"),this.logger.info("apply processors to transform"),yield e.transformStream(this.activeDevices.video.stream)}))}startVideoInput(e){return i(this,void 0,void 0,(function*(){return yield this.videoInputTaskQueue.add((()=>this.startVideoInputTask(e)))}))}startVideoInputTask(e){return i(this,void 0,void 0,(function*(){if(e)try{return C.isVideoTransformDevice(e)?(this.logger.info(`Choosing video transform device ${e}`),yield this.chooseVideoTransformInputDevice(e),this.publishVideoInputDidChangeEvent(this.chosenVideoTransformDevice.outputMediaStream),this.chosenVideoTransformDevice.outputMediaStream):(this.chosenVideoInputIsTransformDevice()&&(this.chosenVideoTransformDevice.onOutputStreamDisconnect(),this.chosenVideoTransformDevice=null),yield this.chooseInputIntrinsicDevice("video",e),this.trace("startVideoInputDevice",e),this.publishVideoInputDidChangeEvent(this.activeDevices.video.stream),this.activeDevices.video.stream)}catch(e){throw e}else this.logger.error("Invalid video input device")}))}stopVideoInput(){return i(this,void 0,void 0,(function*(){return this.videoInputTaskQueue.add((()=>this.stopVideoInputTask()))}))}stopVideoInputTask(){return i(this,void 0,void 0,(function*(){try{if(this.chosenVideoInputIsTransformDevice())return void this.releaseVideoTransformStream();this.stopTracksAndRemoveCallbacks("video")}finally{this.watchForDeviceChangesIfNecessary(),this.publishVideoInputDidChangeEvent(void 0)}}))}chooseAudioOutput(e){return i(this,void 0,void 0,(function*(){this.audioOutputDeviceId=e,this.watchForDeviceChangesIfNecessary();const t=this.deviceInfoFromDeviceId("audiooutput",this.audioOutputDeviceId);this.publishAudioOutputDidChangeEvent(t),this.trace("chooseAudioOutput",e,null)}))}addDeviceChangeObserver(e){this.logger.info("adding device change observer"),this.deviceChangeObservers.add(e),this.watchForDeviceChangesIfNecessary(),this.trace("addDeviceChangeObserver")}removeDeviceChangeObserver(e){this.logger.info("removing device change observer"),this.deviceChangeObservers.delete(e),this.watchForDeviceChangesIfNecessary(),this.trace("removeDeviceChangeObserver")}createAnalyserNodeForAudioInput(){var e,t;if(!this.activeDevices.audio)return null;const n=null===(t=null===(e=this.transform)||void 0===e?void 0:e.nodes)||void 0===t?void 0:t.end;if(n){const e=n.context.createAnalyser();return e.removeOriginalInputs=()=>{try{n.disconnect(e)}catch(e){}},n.connect(e),e}return this.createAnalyserNodeForRawAudioInput()}createAnalyserNodeForRawAudioInput(){return this.activeDevices.audio?this.createAnalyserNodeForStream(this.activeDevices.audio.stream):null}createAnalyserNodeForStream(e){const t=w.getAudioContext(),n=t.createAnalyser(),i=t.createMediaStreamSource(e);return i.connect(n),this.trace("createAnalyserNodeForAudioInput"),n.removeOriginalInputs=()=>{try{i.disconnect(n)}catch(e){}},n}startVideoPreviewForVideoInput(e){if(!this.activeDevices.video)return this.logger.warn("cannot bind video preview since video input device has not been chosen"),void this.trace("startVideoPreviewForVideoInput",e.id);u.default.connectVideoStreamToVideoElement(this.chosenVideoTransformDevice?this.chosenVideoTransformDevice.outputMediaStream:this.activeDevices.video.stream,e,!0),this.trace("startVideoPreviewForVideoInput",e.id)}stopVideoPreviewForVideoInput(e){u.default.disconnectVideoStreamFromVideoElement(e,!1),this.trace("stopVideoPreviewForVideoInput",e.id)}setDeviceLabelTrigger(e){if(this.deviceInfoCache)for(const e of this.deviceInfoCache)if(!e.label){this.deviceInfoCache=null;break}this.deviceLabelTrigger=e,this.trace("setDeviceLabelTrigger")}mixIntoAudioInput(e){let t=null;return this.useWebAudio?(t=w.getAudioContext().createMediaStreamSource(e),t.connect(this.getMediaStreamOutputNode())):this.logger.warn("WebAudio is not enabled, mixIntoAudioInput will not work"),this.trace("mixIntoAudioInput",e.id),t}chooseVideoInputQuality(e,t,n){const i=this.browserBehavior.requiresResolutionAlignment(e,t);this.videoInputQualitySettings=new S.default(i[0],i[1],n)}getVideoInputQualitySettings(){return this.videoInputQualitySettings}acquireAudioInputStream(){return i(this,void 0,void 0,(function*(){return this.activeDevices.audio||(this.logger.info("No audio device chosen, creating empty audio device"),yield this.startAudioInput(null)),this.useWebAudio?this.getMediaStreamDestinationNode().stream:this.activeDevices.audio.stream}))}acquireVideoInputStream(){return i(this,void 0,void 0,(function*(){if(!this.activeDevices.video)throw new Error("No video device chosen");return this.chosenVideoInputIsTransformDevice()?this.chosenVideoTransformDevice.outputMediaStream:this.activeDevices.video.stream}))}acquireDisplayInputStream(e){return i(this,void 0,void 0,(function*(){throw new Error("unsupported")}))}releaseAudioTransformStream(){this.logger.info("Stopping audio track for Web Audio graph"),this.stopTracksAndRemoveCallbacks("audio"),this.logger.info("Removing audio transform, if there is one."),this.removeTransform(),this.audioInputSourceNode&&(this.audioInputSourceNode.disconnect(),this.audioInputSourceNode=void 0),this.audioInputDestinationNode&&(this.audioInputDestinationNode.disconnect(),this.audioInputDestinationNode=void 0)}releaseVideoTransformStream(){this.logger.info("Stopping video track for transform"),this.stopTracksAndRemoveCallbacks("video"),this.logger.info("Disconnecting video transform"),this.chosenVideoTransformDevice.onOutputStreamDisconnect(),this.chosenVideoTransformDevice=null}stopTracksAndRemoveCallbacks(e){const t=this.activeDevices[e];if(!t)return;const n=t.endedCallback,i=t.trackMuteCallback,r=t.trackUnmuteCallback;for(const a of t.stream.getTracks())a.stop(),n&&a.removeEventListener("ended",n),i&&a.removeEventListener("mute",i),r&&a.removeEventListener("unmute",r),delete t.endedCallback,delete t.trackMuteCallback,delete t.trackUnmuteCallback,delete this.activeDevices[e]}chosenVideoInputIsTransformDevice(){return!!this.chosenVideoTransformDevice}muteLocalAudioInputStream(){this.toggleLocalAudioInputStream(!1)}unmuteLocalAudioInputStream(){this.toggleLocalAudioInputStream(!0)}toggleLocalAudioInputStream(e){var t;let n=this.activeDevices.audio;if(this.useWebAudio&&(n=this.getMediaStreamDestinationNode()),n){for(const t of n.stream.getTracks())t.enabled!==e&&(t.enabled=e);this.muted!==!e&&(this.muted=!e,null===(t=this.transform)||void 0===t||t.device.mute(this.muted))}}static getIntrinsicDeviceId(e){if(!e)return;if("string"==typeof e)return e;if(e.id)return e.id;const t=e.deviceId;if(!t)return;if("string"==typeof t||Array.isArray(t))return t;const n=t;return"string"==typeof n.exact||Array.isArray(n.exact)?n.exact:void 0}static createEmptyAudioDevice(){return w.synthesizeAudioDevice(0)}static synthesizeAudioDevice(e){const t=w.getAudioContext(),n=t.createMediaStreamDestination();if(e){const i=t.createGain();i.gain.value=.1,i.connect(n);const r=t.createOscillator();r.frequency.value=e,r.connect(i),r.start()}else{const e=t.createBufferSource();try{e.buffer=t.createBuffer(1,5*t.sampleRate,t.sampleRate)}catch(n){if(!n||"NotSupportedError"!==n.name)throw n;e.buffer=t.createBuffer(1,5*w.defaultSampleRate,w.defaultSampleRate)}e.buffer.getChannelData(0)[0]=3e-4,e.loop=!0,e.connect(n),e.start()}return n.stream}listDevicesOfKind(e,t){return i(this,void 0,void 0,(function*(){return!t&&null!==this.deviceInfoCache&&this.isWatchingForDeviceChanges()||(yield this.updateDeviceInfoCacheFromBrowser()),this.listCachedDevicesOfKind(e)}))}updateDeviceInfoCacheFromBrowser(){var e;return i(this,void 0,void 0,(function*(){if("undefined"==typeof MediaDeviceInfo)return void(this.deviceInfoCache=[]);let t=yield navigator.mediaDevices.enumerateDevices(),n=!0;for(const e of t)if(!e.label){n=!1;break}if(!n)try{this.logger.info("attempting to trigger media device labels since they are hidden");const e=yield this.deviceLabelTrigger();t=yield navigator.mediaDevices.enumerateDevices();for(const t of e.getTracks())t.stop()}catch(t){this.logger.info("unable to get media device labels"),null===(e=this.eventController)||void 0===e||e.publishEvent("deviceLabelTriggerFailed",{deviceLabelTriggerErrorMessage:this.getErrorMessage(t)})}this.logger.debug(`Update device info cache with devices: ${JSON.stringify(t)}`),this.deviceInfoCache=t}))}listCachedDevicesOfKind(e){const t=[];if(this.deviceInfoCache)for(const n of this.deviceInfoCache)n.kind===e&&t.push(n);return t}handleDeviceChange(){return i(this,void 0,void 0,(function*(){if(null===this.deviceInfoCache)return;if(this.alreadyHandlingDeviceChange)return void s.default.nextTick((()=>{this.handleDeviceChange()}));this.alreadyHandlingDeviceChange=!0;const e=this.listCachedDevicesOfKind("audioinput"),t=this.listCachedDevicesOfKind("videoinput"),n=this.listCachedDevicesOfKind("audiooutput");yield this.updateDeviceInfoCacheFromBrowser();const i=this.listCachedDevicesOfKind("audioinput"),r=this.listCachedDevicesOfKind("videoinput"),a=this.listCachedDevicesOfKind("audiooutput");this.forEachObserver((o=>{this.areDeviceListsEqual(e,i)||l.Maybe.of(o.audioInputsChanged).map((e=>e.bind(o)(i))),this.areDeviceListsEqual(t,r)||l.Maybe.of(o.videoInputsChanged).map((e=>e.bind(o)(r))),this.areDeviceListsEqual(n,a)||l.Maybe.of(o.audioOutputsChanged).map((e=>e.bind(o)(a)))})),this.alreadyHandlingDeviceChange=!1}))}handleDeviceStreamEnded(e,t){return i(this,void 0,void 0,(function*(){try{"audio"===e?(this.logger.warn("Audio input device which was active is no longer available, resetting to null device"),yield this.startAudioInput(null)):(this.logger.warn("Video input device which was active is no longer available, stopping video"),yield this.stopVideoInput())}catch(e){this.logger.error("Failed to choose null device after stream ended.")}"audio"===e?this.forEachObserver((e=>{l.Maybe.of(e.audioInputStreamEnded).map((n=>n.bind(e)(t)))})):this.forEachObserver((e=>{l.Maybe.of(e.videoInputStreamEnded).map((n=>n.bind(e)(t)))}))}))}forEachObserver(e){for(const t of this.deviceChangeObservers)s.default.nextTick((()=>{this.deviceChangeObservers.has(t)&&e(t)}))}forEachMediaStreamBrokerObserver(e){for(const t of this.mediaStreamBrokerObservers)s.default.nextTick((()=>{this.mediaStreamBrokerObservers.has(t)&&e(t)}))}areDeviceListsEqual(e,t){return JSON.stringify(e.map((e=>JSON.stringify(e))).sort())===JSON.stringify(t.map((e=>JSON.stringify(e))).sort())}intrinsicDeviceAsMediaStream(e){return e&&e.id?e:null}hasSameMediaStreamId(e,t,n){var i,r,a,o;let s;return"audio"===e?(s=null==n?void 0:n.audio.streamId,!!s&&s===(null===(r=null===(i=t.constraints)||void 0===i?void 0:i.audio)||void 0===r?void 0:r.streamId)):(s=null==n?void 0:n.video.streamId,!!s&&s===(null===(o=null===(a=null==t?void 0:t.constraints)||void 0===a?void 0:a.video)||void 0===o?void 0:o.streamId))}hasSameGroupId(e,t,n){if(""===e)return!0;const i=w.getIntrinsicDeviceId(n);return this.logger.debug(`Checking deviceIds ${i} of type ${typeof i} with groupId ${e}`),"string"==typeof i&&e===this.getGroupIdFromDeviceId(t,i)}getGroupIdFromDeviceId(e,t){if(null!==this.deviceInfoCache){const n=this.listCachedDevicesOfKind(`${e}input`).find((e=>e.deviceId===t));if(n&&n.groupId)return this.logger.debug(`GroupId of deviceId ${t} found in cache is ${n.groupId}`),n.groupId}return this.logger.debug(`GroupId of deviceId ${t} found in cache is empty`),""}handleGetUserMediaError(e,t){if(!e)throw new m.default(e);switch(e.name){case"NotReadableError":case"TrackStartError":throw new g.default(e);case"NotFoundError":case"DevicesNotFoundError":throw new p.default(e);case"NotAllowedError":case"PermissionDeniedError":case"SecurityError":throw t&&t{this.activeDevices[e]&&this.activeDevices[e].stream===t.stream&&(this.handleDeviceStreamEnded(e,i),delete t.endedCallback)},r.addEventListener("ended",t.endedCallback,{once:!0})),"audio"===e){const e=t.stream.getAudioTracks()[0];if(e){const n=e.getSettings().deviceId||t.stream;t.trackMuteCallback=()=>{this.mediaStreamMuteObserver(n,!0)},t.trackUnmuteCallback=()=>{this.mediaStreamMuteObserver(n,!1)},e.addEventListener("mute",t.trackMuteCallback,{once:!1}),e.addEventListener("unmute",t.trackUnmuteCallback,{once:!1}),this.logger.debug("Notifying mute state after selection"),e.muted?t.trackMuteCallback():t.trackUnmuteCallback()}}}))}calculateMediaStreamConstraints(e,t,n,i){if(i&&1===this.listCachedDevicesOfKind(`${e}input`).length)return!0;const r={};return this.browserBehavior.requiresNoExactMediaStreamConstraints()?r.deviceId=t:r.deviceId={exact:t},n&&(r.groupId=n),i?r:"video"===e?(r.width={ideal:this.videoInputQualitySettings.videoWidth},r.height={ideal:this.videoInputQualitySettings.videoHeight},r.frameRate={ideal:this.videoInputQualitySettings.videoFrameRate},r):(this.supportSampleRateConstraint()&&(r.sampleRate={ideal:w.defaultSampleRate}),this.supportSampleSizeConstraint()&&(r.sampleSize={ideal:w.defaultSampleSize}),this.supportChannelCountConstraint()&&(r.channelCount={ideal:w.defaultChannelCount}),Object.assign({echoCancellation:!0,googEchoCancellation:!0,googEchoCancellation2:!0,googAutoGainControl:!0,googAutoGainControl2:!0,googNoiseSuppression:!0,googNoiseSuppression2:!0,googHighpassFilter:!0},r))}getMediaStreamConstraintsFromTrackConstraints(e,t){return"audio"===e?{audio:t}:{video:t}}getMediaStreamConstraints(e,t,n=!1){let i={};if(!t)return null;const r=this.intrinsicDeviceAsMediaStream(t);if(r)return i.streamId=r.id,this.getMediaStreamConstraintsFromTrackConstraints(e,i);if("string"==typeof t){let r="";return this.browserBehavior.requiresGroupIdMediaStreamConstraints()&&(null!==this.deviceInfoCache?r=this.getGroupIdFromDeviceId(e,t):this.logger.error("Device cache is not populated. Please make sure to call list devices first")),i=this.calculateMediaStreamConstraints(e,t,r,n),this.getMediaStreamConstraintsFromTrackConstraints(e,i)}return function(e){return"object"==typeof e&&"deviceId"in e&&"groupId"in e&&"kind"in e&&"label"in e}(t)?(i=this.calculateMediaStreamConstraints(e,t.deviceId,t.groupId,n),this.getMediaStreamConstraintsFromTrackConstraints(e,i)):(i=t,this.getMediaStreamConstraintsFromTrackConstraints(e,i))}deviceInfoFromDeviceId(e,t){if(null===this.deviceInfoCache)return null;for(const n of this.deviceInfoCache)if(n.kind===e&&n.deviceId===t)return n;return null}hasAppliedTransform(){return!!this.transform}isMediaStreamReusableByDeviceId(e,t){if(!e||!e.active||!t)return!1;if(t.id)return e.id===t.id;const n=this.getMediaTrackSettings(e);if(!n.deviceId)return!1;const i=w.getIntrinsicDeviceId(t);return"string"==typeof i&&n.deviceId===i}getMediaTrackSettings(e){var t;return null===(t=e.getTracks()[0])||void 0===t?void 0:t.getSettings()}reconnectAudioInputs(){if(!this.audioInputSourceNode)return;this.audioInputSourceNode.disconnect();const e=this.getMediaStreamOutputNode();this.audioInputSourceNode.connect(e)}setTransform(e,t){var n,i;null===(i=null===(n=this.transform)||void 0===n?void 0:n.nodes)||void 0===i||i.end.disconnect(),this.transform={nodes:t,device:e};const r=null==t?void 0:t.end,a=this.getMediaStreamDestinationNode();this.logger.debug(`Connecting transform node ${r} to destination ${a}.`),null==r||r.connect(a),this.reconnectAudioInputs()}removeTransform(){var e;const t=this.transform;if(t)return null===(e=this.transform.nodes)||void 0===e||e.end.disconnect(),this.transform=void 0,this.reconnectAudioInputs(),t}attachAudioInputStreamToAudioContext(e){var t;null===(t=this.audioInputSourceNode)||void 0===t||t.disconnect(),this.audioInputSourceNode=w.getAudioContext().createMediaStreamSource(e);const n=this.getMediaStreamOutputNode();this.audioInputSourceNode.connect(n)}getMediaStreamDestinationNode(){return this.audioInputDestinationNode||(this.audioInputDestinationNode=w.getAudioContext().createMediaStreamDestination()),this.audioInputDestinationNode}getMediaStreamOutputNode(){var e,t;return(null===(t=null===(e=this.transform)||void 0===e?void 0:e.nodes)||void 0===t?void 0:t.start)||this.getMediaStreamDestinationNode()}static setDefaultLatencyHint(e){w.defaultLatencyHint=e}static getAudioContext(){if(!w.audioContext){const e={};navigator.mediaDevices.getSupportedConstraints().sampleRate&&(e.sampleRate=w.defaultSampleRate),(new a.default).requiresPlaybackLatencyHintForAudioContext()&&(e.latencyHint="playback"),w.defaultLatencyHint&&(e.latencyHint=w.defaultLatencyHint),w.audioContext=new(window.AudioContext||window.webkitAudioContext)(e)}return w.audioContext}static closeAudioContext(){if(w.audioContext)try{w.audioContext.close()}catch(e){}w.audioContext=null}addMediaStreamBrokerObserver(e){this.mediaStreamBrokerObservers.add(e)}removeMediaStreamBrokerObserver(e){this.mediaStreamBrokerObservers.delete(e)}publishVideoInputDidChangeEvent(e){this.forEachMediaStreamBrokerObserver((t=>{t.videoInputDidChange&&t.videoInputDidChange(e)})),this.pushVideoMeetingStateForPermissions(e)}publishAudioInputDidChangeEvent(e){this.forEachMediaStreamBrokerObserver((t=>{t.audioInputDidChange&&t.audioInputDidChange(e)})),this.pushAudioMeetingStateForPermissions(e)}publishAudioOutputDidChangeEvent(e){this.forEachMediaStreamBrokerObserver((t=>{t.audioOutputDidChange&&t.audioOutputDidChange(e)}))}supportSampleRateConstraint(){return this.useWebAudio&&!!navigator.mediaDevices.getSupportedConstraints().sampleRate}supportSampleSizeConstraint(){return this.useWebAudio&&!!navigator.mediaDevices.getSupportedConstraints().sampleSize}supportChannelCountConstraint(){return this.useWebAudio&&!!navigator.mediaDevices.getSupportedConstraints().channelCount}trace(e,t,n){let i=`API/DefaultDeviceController/${e}`;void 0!==t&&(i+=` ${JSON.stringify(t)}`),void 0!==n&&(i+=` -> ${JSON.stringify(n)}`),this.logger.info(i)}}t.default=w,w.permissionDeniedOriginDetectionThresholdMs=500,w.defaultVideoWidth=960,w.defaultVideoHeight=540,w.defaultVideoFrameRate=15,w.defaultSampleRate=48e3,w.defaultSampleSize=16,w.defaultChannelCount=1,w.audioContext=null},8715:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.groupId=""}matchesConstraints(e){return JSON.stringify(this.constraints)===JSON.stringify(e)}}},7086:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n extends Error{constructor(e,t){super(t||"Error fetching device."),this.cause=e,this.name="GetUserMediaError"}}t.default=n},9605:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.NoOpDeviceControllerWithEventController=void 0;const a=r(n(8703)),o=r(n(7094));class s extends a.default{constructor(e){super(),this.destroyed=!1}destroy(){return i(this,void 0,void 0,(function*(){this.destroyed=!0}))}listAudioInputDevices(){return Promise.resolve([])}listVideoInputDevices(){return Promise.resolve([])}listAudioOutputDevices(){return Promise.resolve([])}startAudioInput(e){return Promise.reject()}stopAudioInput(){return Promise.resolve()}startVideoInput(e){return Promise.reject()}stopVideoInput(){return Promise.resolve()}chooseAudioOutput(e){return Promise.reject()}addDeviceChangeObserver(e){}removeDeviceChangeObserver(e){}createAnalyserNodeForAudioInput(){return null}startVideoPreviewForVideoInput(e){}stopVideoPreviewForVideoInput(e){}setDeviceLabelTrigger(e){}mixIntoAudioInput(e){return null}chooseVideoInputQuality(e,t,n){}getVideoInputQualitySettings(){return o.default.VideoDisabled}}t.default=s,t.NoOpDeviceControllerWithEventController=class extends s{constructor(e){super(),this.eventController=e}}},8736:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(7086));class a extends r.default{constructor(e){super(e),this.name="NotFoundError"}}t.default=a},478:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(7086));class a extends r.default{constructor(e){super(e),this.name="NotReadableError"}}t.default=a},903:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(7086));class a extends r.default{constructor(e,t){super(e),this.constraint=t,this.name="OverconstrainedError"}}t.default=a},8349:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(7086));class a extends r.default{constructor(e,t){super(e,t),this.name="PermissionDeniedError"}}t.default=a},7667:function(e,t){"use strict";var n=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e){this.inner=e}mute(e){return n(this,void 0,void 0,(function*(){}))}stop(){var e;return n(this,void 0,void 0,(function*(){null===(e=this.node)||void 0===e||e.disconnect()}))}intrinsicDevice(){return n(this,void 0,void 0,(function*(){return this.inner}))}createAudioNode(e){var t;return n(this,void 0,void 0,(function*(){return null===(t=this.node)||void 0===t||t.disconnect(),this.node=yield this.createSingleAudioNode(e),{start:this.node,end:this.node}}))}}},6801:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(7086));class a extends r.default{constructor(e){super(e),this.name="TypeError"}}t.default=a},7094:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n{constructor(e,t,n){this.videoWidth=e,this.videoHeight=t,this.videoFrameRate=n}equals(e){return this.videoWidth===e.videoWidth&&this.videoHeight===e.videoHeight&&this.videoFrameRate===e.videoFrameRate}}t.default=n,n.VideoDisabled=new n(0,0,0),n.VideoResolutionHD=new n(1280,720,30),n.VideoResolutionFHD=new n(1920,1080,30),n.VideoResolutionUHD=new n(3840,2160,30)},6880:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isVideoTransformDevice=void 0,t.isVideoTransformDevice=function(e){return!!e&&"object"==typeof e&&"transformStream"in e&&"stop"in e&&"intrinsicDevice"in e}},4926:function(e,t){"use strict";var n=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t){if(this.devicePixelRatioSource=e,this.observerQueue=new Set,this.mediaQueryListener=()=>{this.observerQueue.forEach((e=>{e.devicePixelRatioChanged(this.devicePixelRatioSource.devicePixelRatio())}))},"undefined"==typeof window)return;const n=matchMedia(`(resolution: ${this.devicePixelRatioSource.devicePixelRatio()}dppx)`);"function"==typeof n.addEventListener?(n.addEventListener("change",this.mediaQueryListener),this.mediaQueryList=n):"function"==typeof n.addListener?(n.addListener(this.mediaQueryListener),this.mediaQueryList=n):t.warn("ignoring DefaultDevicePixelRatioMonitor")}destroy(){return n(this,void 0,void 0,(function*(){this.mediaQueryList&&("function"==typeof this.mediaQueryList.addEventListener?this.mediaQueryList.removeEventListener("change",this.mediaQueryListener):this.mediaQueryList.removeListener(this.mediaQueryListener)),delete this.mediaQueryListener,this.observerQueue.clear()}))}registerObserver(e){this.observerQueue.add(e),e.devicePixelRatioChanged(this.devicePixelRatioSource.devicePixelRatio())}removeObserver(e){this.observerQueue.delete(e)}}},6009:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{devicePixelRatio(){return"undefined"!=typeof window&&window&&window.devicePixelRatio?window.devicePixelRatio:1}}},7393:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__rest||function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r({type:e.type,v:e.v,payloads:[...e.payloads]}),this.sendEvents=()=>i(this,void 0,void 0,(function*(){if(this.lock)return;const e=this.getItems(this.flushSize);if(0===e.length)return;this.lock=!0;const t=this.makeRequestBody(e);let n=!1;const i=Date.now();"firefox"===this.metadata.browserName.toLowerCase()&&this.cancellableEvents.set(i,e);try{this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - sendEvents - sending body ${t}`);const r=yield this.send(t);if(this.cancellableEvents.delete(i),r.ok)try{const e=yield r.json();this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - sendEvents - send successful events: ${t} message: ${JSON.stringify(e)}`)}catch(e){this.logger.warn(`Event Reporting - InMemoryJSONEventBuffer - sendEvents error reading OK response ${e} for events ${t}`)}else this.logger.error(`Event Reporting - InMemoryJSONEventBuffer - sendEvents - Failed to send events ${t} with response status ${r.status}`),n=!0}catch(e){n=!0,this.logger.warn(`Event Reporting - InMemoryJSONEventBuffer - sendEvents - Error in sending events ${t} to the ingestion endpoint ${e}`)}finally{this.lock=!1}n&&(this.cancellableEvents.delete(i),this.failedIngestionEvents.push(...e))}));const s=new c.default(o).getParserResult(),{browserMajorVersion:l}=s,d=r(s,["browserMajorVersion"]),u=t.toJSON(),{type:f,v:h}=u,m=r(u,["type","v"]);this.authenticationToken=t.getAuthenticationToken(),this.metadata=Object.assign(Object.assign({},d),m),Object.keys(this.metadata).forEach((e=>this.attributesToFilter.push(e))),this.type=f,this.v=h,this.ingestionURL=n,this.logger=o,this.importantEvents=new Set(a);const{maxBufferCapacityKb:p,totalBufferItems:g,flushSize:v,flushIntervalMs:b,retryCountLimit:y}=e;this.maxBufferCapacityBytes=1024*p,this.totalBufferItems=g,this.maxBufferItemCapacityBytes=Math.round(this.maxBufferCapacityBytes/g),this.flushIntervalMs=b,this.flushSize=v,this.retryCountLimit=y,this.currentIngestionEvent=this.initializeAndGetCurrentIngestionEvent(),this.beaconEventListener=e=>this.beaconEventHandler(e),this.addEventListeners()}addEventListeners(){this.beaconEventListener&&"window"in n.g&&window.addEventListener&&"document"in n.g&&document.addEventListener&&(this.logger.debug("Event Reporting - InMemoryJSONEventBuffer - addEventListeners - adding pagehide and visibility change event listeners"),window.addEventListener("pagehide",this.beaconEventListener),document.addEventListener("visibilitychange",this.beaconEventListener))}beaconEventHandler(e){("visibilitychange"===e.type&&"hidden"===document.visibilityState||"pagehide"===e.type)&&(this.logger.debug("Event Reporting - InMemoryJSONEventBuffer - beaconEventHandler is triggered calling sendBeacon"),this.sendBeacon())}removeEventListeners(){this.beaconEventListener&&"window"in n.g&&window.removeEventListener&&"document"in n.g&&document.removeEventListener&&(window.removeEventListener("pagehide",this.beaconEventListener),document.removeEventListener("visibilitychange",this.beaconEventListener),this.logger.debug("Event Reporting - InMemoryJSONEventBuffer - removeEventListeners - removing pagehide and visibility change event listeners"))}start(){var e;this.removeEventListeners(),this.addEventListeners(),null===(e=this.intervalScheduler)||void 0===e||e.stop(),this.intervalScheduler=new s.default(this.flushIntervalMs),this.intervalScheduler.start((()=>this.sendEvents()))}stop(){var e;null===(e=this.intervalScheduler)||void 0===e||e.stop(),this.intervalScheduler=void 0,this.sendBeacon(),this.removeEventListeners()}addItem(e){return i(this,void 0,void 0,(function*(){this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - addItem - received event ${JSON.stringify(e)}`);const{name:t,ts:n,attributes:i}=e,r=i&&this.filterAttributes(i,this.attributesToFilter),a=Object.assign({name:t,ts:n},r);this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - addItem - event after filtering attributes ${JSON.stringify(a)}`);const o=this.getSize(a);if(o>d.MAX_ITEM_SIZE_BYTES_ALLOWED)throw new Error(`Event Reporting - Item to be added has size ${o} bytes. Item cannot exceed max item size allowed of ${d.MAX_ITEM_SIZE_BYTES_ALLOWED} bytes.`);if(this.importantEvents.has(t))return this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - addItem - sending important event ${JSON.stringify(a)}`),void this.sendEventImmediately({name:t,ts:n,attributes:r});if(this.isFull())throw this.logger.warn("Event Reporting - Event buffer is full"),new Error("Buffer full");if(this.currentIngestionEvent.payloads.push(a),this.ingestionEventSize+=o,this.bufferItemThresholdReached(o)){const e=this.deepCopyCurrentIngestionEvent(this.currentIngestionEvent);this.buffer.push(e),this.bufferSize+=this.ingestionEventSize,this.currentIngestionEvent=this.initializeAndGetCurrentIngestionEvent(),this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - addItem - buffer item threshold reached updated buffer ${JSON.stringify(this.buffer)}`)}}))}filterAttributes(e,t){const n=new Set(t);return Object.keys(e).filter((e=>n.has(e))).forEach((t=>delete e[t])),e}initializeAndGetCurrentIngestionEvent(){const e={type:this.type,v:this.v,payloads:[]};return this.ingestionEventSize=this.getSize(e),e}bufferItemThresholdReached(e){return e+this.ingestionEventSize>=this.maxBufferItemCapacityBytes||this.currentIngestionEvent.payloads.length===d.MAX_PAYLOAD_ITEMS}getSize(e){let t=0;if("object"==typeof e)for(const[n,i]of Object.entries(e))t+=this.getPrimitiveSize(n),t+=this.getSize(i);else t+=this.getPrimitiveSize(e);return t}getPrimitiveSize(e){let t=0;return"string"==typeof e?t+=2*e.length:"number"==typeof e&&(t+=8),t}isFull(){return this.bufferSize===this.maxBufferCapacityBytes||this.buffer.length===this.totalBufferItems}isEmpty(){return 0===this.buffer.length||0===this.bufferSize}getItems(e,t=0){return this.isEmpty()?[]:(e=Math.min(this.buffer.length,e+1),this.buffer.splice(t,e))}makeBeaconRequestBody(e){const t={metadata:this.metadata,events:e,authorization:this.authenticationToken};return JSON.stringify(t)}makeRequestBody(e){const t={metadata:this.metadata,events:e};return JSON.stringify(t)}sendEventImmediately(e){return i(this,void 0,void 0,(function*(){this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - sendEventImmediately - important event received ${JSON.stringify(e)}`);const{name:t,ts:n,attributes:i}=e,r={type:this.type,v:this.v,payloads:[Object.assign({name:t,ts:n},i)]};let a=!1,o=null;const s=this.makeRequestBody([r]);try{if(o=yield this.send(s),o.ok){try{const e=yield o.json();this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - sendEventImmediately - send successful event: ${s}, message: ${JSON.stringify(e)}`)}catch(e){this.logger.warn(`Event Reporting - InMemoryJSONEventBuffer - sendEventImmediately - Error reading OK response ${e} for event ${s}`)}return}this.logger.error(`Event Reporting - InMemoryJSONEventBuffer - sendEventImmediately - Failed to send an important event ${s} with response status ${o.status}`),a=!0}catch(e){this.logger.warn(`Event Reporting - There may be a failure in sending an important event ${s} to the ingestion endpoint ${e}.`),a=!0;try{if("firefox"===this.metadata.browserName.toLowerCase()){const e=this.makeBeaconRequestBody([r]);this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - sendEventImmediately - beaconing data out ${e}`),a=!navigator.sendBeacon(`${this.ingestionURL}?beacon=1`,e)}}catch(e){this.logger.warn(`Event Reporting - Error sending beacon for an important event ${s}`),a=!0}}a&&(this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - sendEventImmediately - pushing to failed events ${s}`),this.failedIngestionEvents.push(r))}))}send(e){return i(this,void 0,void 0,(function*(){const t=new o.default(d.RETRY_FIXED_BACKOFF_WAIT_MS,d.RETRY_SHORT_BACKOFF_MS,d.RETRY_LONG_BACKOFF_MS);try{let n=0;for(;n0){const t=this.deepCopyCurrentIngestionEvent(this.currentIngestionEvent);e.push(t),this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - sendBeacon - clearing out current ingestion event ${JSON.stringify(t)}`),this.currentIngestionEvent=this.initializeAndGetCurrentIngestionEvent()}if(this.failedIngestionEvents.length>0){const t=this.failedIngestionEvents.map((e=>this.deepCopyCurrentIngestionEvent(e)));e.push(...t),this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - sendBeacon - clearing out any failed ingestion event ${JSON.stringify(t)}`),this.failedIngestionEvents=[]}if(this.cancellableEvents.size>0&&(this.cancellableEvents.forEach((t=>{e.push(...t),this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - sendBeacon - clearing out each cancellable event ${JSON.stringify(t)}`)})),this.cancellableEvents.clear()),0===e.length)return;const t=this.makeBeaconRequestBody(e);this.logger.debug(`Event Reporting - InMemoryJSONEventBuffer - sendBeacon - beacon data to send ${t}`);try{navigator.sendBeacon(`${this.ingestionURL}?beacon=1`,t)||this.logger.warn(`Event Reporting - Browser failed to queue beacon data ${t}`)}catch(e){this.logger.warn(`Event Reporting - Sending beacon data ${t} failed with error ${e}`)}}))}reset(){this.maxBufferCapacityBytes=0,this.totalBufferItems=0,this.buffer=[],this.bufferSize=0,this.maxBufferItemCapacityBytes=0,this.ingestionEventSize=0,this.flushIntervalMs=0,this.flushSize=0,this.failedIngestionEvents=[],this.lock=!1,this.beaconEventListener=void 0,this.cancellableEvents.clear()}destroy(){return i(this,void 0,void 0,(function*(){this.stop(),this.reset()}))}}t.default=d,d.SENDING_FAILURE_CODES=new Set([408,429,500,502,503,504]),d.RETRY_FIXED_BACKOFF_WAIT_MS=0,d.RETRY_SHORT_BACKOFF_MS=1e3,d.RETRY_LONG_BACKOFF_MS=15e3,d.MAX_PAYLOAD_ITEMS=2,d.MAX_ITEM_SIZE_BYTES_ALLOWED=3e3},85:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e=5e3,t=2,n=64,i=100,r=15){this.flushIntervalMs=e,this.flushSize=t,this.maxBufferCapacityKb=n,this.totalBufferItems=i,this.retryCountLimit=r}}},7292:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=n(7232),o=n(47),s=r(n(419)),c=r(n(7185)),l=r(n(4128)),d=r(n(4185)),u=r(n(6741)),f=r(n(3712));class h{constructor(e,t,n){var i,r,o,s,c,l,d;this.meetingHistoryStates=[],this.observerSet=new Set,this.destroyed=!1,this.logger=t,this.configuration=e,this.setupEventReporter(e,t,n);try{this.parserResult=navigator&&navigator.userAgent?new a.UAParser(navigator.userAgent).getResult():null}catch(e){this.logger.error(e.message)}this.browserMajorVersion=(null===(o=null===(r=null===(i=this.parserResult)||void 0===i?void 0:i.browser)||void 0===r?void 0:r.version)||void 0===o?void 0:o.split(".")[0])||h.UNAVAILABLE,this.browserName=(null===(s=this.parserResult)||void 0===s?void 0:s.browser.name)||h.UNAVAILABLE,this.browserVersion=(null===(c=this.parserResult)||void 0===c?void 0:c.browser.version)||h.UNAVAILABLE,this.deviceName=[(null===(l=this.parserResult)||void 0===l?void 0:l.device.vendor)||"",(null===(d=this.parserResult)||void 0===d?void 0:d.device.model)||""].join(" ").trim()||h.UNAVAILABLE}addObserver(e){this.observerSet.add(e)}removeObserver(e){this.observerSet.delete(e)}forEachObserver(e){for(const t of this.observerSet)d.default.nextTick((()=>{this.observerSet.has(t)&&e(t)}))}publishEvent(e,t){return i(this,void 0,void 0,(function*(){const n=Date.now();this.meetingHistoryStates.push({name:e,timestampMs:n});const i=Object.freeze(Object.assign(this.getAttributes(n),t));this.forEachObserver((t=>{t.eventDidReceive(e,i)})),this.reportEvent(e,n,t)}))}reportEvent(e,t,n){var r;return i(this,void 0,void 0,(function*(){let i;try{n&&(i=f.default(n)),yield null===(r=this.eventReporter)||void 0===r?void 0:r.reportEvent(t,e,i)}catch(e){this.logger.error(`Error reporting event ${e}`)}}))}setupEventReporter(e,t,n){if(n)this._eventReporter=n;else if(e.urls){const n=e.urls.eventIngestionURL;if(n){this.logger.info("Event ingestion URL is present in the configuration");const{meetingId:i,credentials:{attendeeId:r,joinToken:a}}=e,o=new l.default(i,r,a),d=new s.default(o,n);this._eventReporter=new c.default(d,t)}}}getAttributes(e){var t,n;return{attendeeId:this.configuration.credentials.attendeeId,browserMajorVersion:this.browserMajorVersion,browserName:this.browserName,browserVersion:this.browserVersion,deviceName:this.deviceName,externalMeetingId:"string"==typeof this.configuration.externalMeetingId?this.configuration.externalMeetingId:"",externalUserId:this.configuration.credentials.externalUserId,meetingHistory:this.meetingHistoryStates,meetingId:this.configuration.meetingId,osName:(null===(t=this.parserResult)||void 0===t?void 0:t.os.name)||h.UNAVAILABLE,osVersion:(null===(n=this.parserResult)||void 0===n?void 0:n.os.version)||h.UNAVAILABLE,sdkVersion:u.default.sdkVersion,sdkName:u.default.sdkName,timestampMs:e}}get eventReporter(){return this._eventReporter}destroy(){return i(this,void 0,void 0,(function*(){o.isDestroyable(this.eventReporter)&&(yield this.eventReporter.destroy()),this.logger=void 0,this.configuration=void 0,this._eventReporter=void 0,this.destroyed=!0}))}}t.default=h,h.UNAVAILABLE="Unavailable"},3712:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=e=>{const t={};for(const[n,i]of Object.entries(e))if(null!=i&&""!==i){if("number"!=typeof i&&"string"!=typeof i)throw new TypeError("Unhandled type received while flattening attributes.");t[n]=i}return t}},419:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(85));t.default=class{constructor(e,t,n=new r.default){this.eventsClientConfiguration=e,this.ingestionURL=t,this.eventBufferConfiguration=n}}},7185:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=n(47),o=r(n(7393));t.default=class{constructor(e,t){this.reportingEvents=!1,this.importantEvents=["meetingEnded","meetingFailed","meetingStartFailed","audioInputFailed","videoInputFailed","meetingStartSucceeded","deviceLabelTriggerFailed"],this.destroyed=!1;const{eventsClientConfiguration:n,ingestionURL:i,eventBufferConfiguration:r}=e,{eventsToIgnore:a}=n;this.eventBuffer=new o.default(r,n,i,this.importantEvents,t),this.logger=t,this.eventsToIgnore=a,this.start()}start(){if(!this.reportingEvents)try{this.eventBuffer.start(),this.logger.info("Event reporting started"),this.reportingEvents=!0}catch(e){this.logger.error(`Event Reporting - Error starting the event buffer ${e}`)}}stop(){if(this.reportingEvents)try{this.eventBuffer.stop(),this.logger.info("Event reporting stopped"),this.reportingEvents=!1}catch(e){this.logger.error(`Event Reporting - Error stopping the event buffer ${e}`)}}reportEvent(e,t,n){return i(this,void 0,void 0,(function*(){if(this.logger.debug(`Event Reporting - DefaultMeetingEventReporter - event received in reportEvent ${e}, ${t}, ${JSON.stringify(n)}`),this.eventsToIgnore.includes(t))this.logger.debug(`Event Reporting - DefaultMeetingEventReporter - ${t} event will be ignored as it is in events to ignore`);else try{this.logger.debug("Event Reporting - DefaultMeetingEventReporter - adding item to event buffer"),yield this.eventBuffer.addItem({ts:e,name:t,attributes:n})}catch(e){this.logger.error(`Event Reporting - Error adding event to buffer ${e}`)}}))}destroy(){return i(this,void 0,void 0,(function*(){this.destroyed=!0,this.stop(),a.isDestroyable(this.eventBuffer)&&this.eventBuffer.destroy(),this.eventBuffer=void 0}))}}},6795:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){}reportEvent(e,t,n){}start(){}stop(){}}},4128:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t,n,i=[]){this.type="Meet",this.v=1,this.meetingId=e,this.attendeeId=t,this.eventsToIgnore=i,this.authenticationToken=n}getAuthenticationToken(){return this.authenticationToken}toJSON(){const e={};return e.type=this.type,e.v=this.v,e.meetingId=this.meetingId,e.attendeeId=this.attendeeId,e}}},1016:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultEventController=t.DefaultDevicePixelRatioMonitor=t.DefaultDeviceController=t.DefaultContentShareController=t.DefaultBrowserBehavior=t.DefaultAudioVideoFacade=t.DefaultAudioVideoController=t.DefaultAudioMixController=t.DefaultActiveSpeakerPolicy=t.DefaultActiveSpeakerDetector=t.DataMessage=t.CreateSDPTask=t.CreatePeerConnectionTask=t.ContentShareMediaStreamBroker=t.ContentShareConstants=t.ConsoleLogger=t.ConnectionHealthPolicyConfiguration=t.ConnectionHealthData=t.ClientVideoStreamReceivingReport=t.ClientMetricReportMediaType=t.ClientMetricReportDirection=t.ClientMetricReport=t.CleanStoppedSessionTask=t.CleanRestartedSessionTask=t.CheckVideoInputFeedback=t.CheckVideoConnectivityFeedback=t.CheckNetworkUDPConnectivityFeedback=t.CheckNetworkTCPConnectivityFeedback=t.CheckContentShareConnectivityFeedback=t.CheckCameraResolutionFeedback=t.CheckAudioOutputFeedback=t.CheckAudioInputFeedback=t.CheckAudioConnectivityFeedback=t.CanvasVideoFrameBuffer=t.CSPMonitor=t.BitrateParameters=t.BaseTask=t.BaseConnectionHealthPolicy=t.BackgroundReplacementVideoFrameProcessor=t.BackgroundFilterVideoFrameProcessor=t.BackgroundBlurVideoFrameProcessor=t.BackgroundBlurStrength=t.AudioVideoControllerState=t.AudioProfile=t.AudioLogEvent=t.Attendee=t.AttachMediaInputTask=t.AsyncScheduler=t.ApplicationMetadata=t.AllHighestVideoBandwidthPolicy=void 0,t.MeetingReadinessCheckerConfiguration=t.MeetingFeatures=t.MeetingEventsClientConfiguration=t.MediaDeviceProxyHandler=t.Maybe=t.LogLevel=t.Log=t.ListenForVolumeIndicatorsTask=t.LeaveAndReceiveLeaveAckTask=t.JoinAndReceiveIndexTask=t.IntervalScheduler=t.InMemoryJSONEventBuffer=t.GlobalMetricReport=t.GetUserMediaError=t.FullJitterLimitedBackoff=t.FullJitterBackoffFactory=t.FullJitterBackoff=t.FinishGatheringICECandidatesTask=t.EventIngestionConfiguration=t.EventBufferConfiguration=t.DeviceSelection=t.DevicePixelRatioWindowSource=t.DefaultWebSocketAdapter=t.DefaultVolumeIndicatorAdapter=t.DefaultVideoTransformDevice=t.DefaultVideoTileFactory=t.DefaultVideoTileController=t.DefaultVideoTile=t.DefaultVideoStreamIndex=t.DefaultVideoStreamIdSet=t.DefaultVideoFrameProcessorTimer=t.DefaultVideoFrameProcessorPipeline=t.DefaultVideoCaptureAndEncodeParameter=t.DefaultUserAgentParser=t.DefaultTranscriptionController=t.DefaultTransceiverController=t.DefaultSimulcastUplinkPolicyForContentShare=t.DefaultSimulcastUplinkPolicy=t.DefaultSignalingClient=t.DefaultSigV4=t.DefaultSessionStateController=t.DefaultReconnectController=t.DefaultRealtimeController=t.DefaultPingPong=t.DefaultModality=t.DefaultMessagingSession=t.DefaultMeetingSession=t.DefaultMeetingReadinessChecker=t.DefaultMeetingEventReporter=t.DefaultMediaDeviceFactory=void 0,t.RedundantAudioEncoderWorkerCode=t.RedundantAudioEncoder=t.ReconnectionHealthPolicy=t.ReceiveVideoStreamIndexTask=t.ReceiveVideoInputTask=t.ReceiveRemoteVideoPauseResumeTask=t.ReceiveAudioInputTask=t.RealtimeVolumeIndicator=t.RealtimeState=t.RealtimeAttendeePositionInFrame=t.PromoteToPrimaryMeetingTask=t.PromiseQueue=t.PrefetchSortBy=t.PrefetchOn=t.PermissionDeniedError=t.ParallelGroupTask=t.POSTLogger=t.OverconstrainedError=t.OpenSignalingConnectionTask=t.OnceTask=t.NotReadableError=t.NotFoundError=t.None=t.NoVideoUplinkBandwidthPolicy=t.NoVideoDownlinkBandwidthPolicy=t.NoOpVideoFrameProcessor=t.NoOpVideoElementFactory=t.NoOpTask=t.NoOpMediaStreamBroker=t.NoOpLogger=t.NoOpEventReporter=t.NoOpDeviceController=t.NoOpDebugLogger=t.NoOpAudioVideoController=t.NScaleVideoUplinkBandwidthPolicy=t.MutableVideoPreferences=t.MultiLogger=t.MonitorTask=t.ModelSpecBuilder=t.MessagingSessionConfiguration=t.Message=t.MeetingSessionVideoAvailability=t.MeetingSessionURLs=t.MeetingSessionTURNCredentials=t.MeetingSessionStatusCode=t.MeetingSessionStatus=t.MeetingSessionLifecycleEventCondition=t.MeetingSessionLifecycleEvent=t.MeetingSessionCredentials=t.MeetingSessionConfiguration=void 0,t.VideoLogEvent=t.VideoFxProcessor=t.VideoCodecCapability=t.VideoAdaptiveProbePolicy=t.Versioning=t.UnusableAudioWarningConnectionHealthPolicy=t.TypeError=t.TranscriptionStatusType=t.TranscriptionStatus=t.TranscriptResult=t.TranscriptLanguageWithScore=t.TranscriptItemType=t.TranscriptItem=t.TranscriptEntity=t.TranscriptAlternative=t.Transcript=t.TimeoutTask=t.TimeoutScheduler=t.TaskStatus=t.TargetDisplaySize=t.SubscribeAndReceiveSubscribeAckTask=t.StreamMetricReport=t.Some=t.SingleNodeAudioTransformDevice=t.SimulcastVideoStreamIndex=t.SimulcastTransceiverController=t.SimulcastLayers=t.SimulcastContentShareTransceiverController=t.SignalingClientVideoSubscriptionConfiguration=t.SignalingClientSubscribe=t.SignalingClientJoin=t.SignalingClientEventType=t.SignalingClientEvent=t.SignalingClientConnectionRequest=t.SignalingAndMetricsConnectionMonitor=t.SetRemoteDescriptionTask=t.SetLocalDescriptionTask=t.SessionStateControllerTransitionResult=t.SessionStateControllerState=t.SessionStateControllerDeferPriority=t.SessionStateControllerAction=t.ServerSideNetworkAdaption=t.SerialGroupTask=t.SendingAudioFailureConnectionHealthPolicy=t.SendAndReceiveDataMessagesTask=t.SDPMediaSection=t.SDPCandidateType=t.SDP=t.RunnableTask=t.RedundantAudioRecoveryMetricReport=void 0,t.isVideoTransformDevice=t.isDestroyable=t.isAudioTransformDevice=t.ZLIBTextCompressor=t.WebSocketReadyState=t.WaitForAttendeePresenceTask=t.VoiceFocusTransformDevice=t.VoiceFocusDeviceTransformer=t.VideoTileState=t.VideoStreamDescription=t.VideoSource=t.VideoQualitySettings=t.VideoQualityAdaptationPreference=t.VideoPriorityBasedPolicyConfig=t.VideoPriorityBasedPolicy=t.VideoPreferences=t.VideoPreference=t.VideoOnlyTransceiverController=void 0;const r=i(n(1876));t.AllHighestVideoBandwidthPolicy=r.default;const a=i(n(5647));t.ApplicationMetadata=a.default;const o=i(n(4185));t.AsyncScheduler=o.default;const s=i(n(4014));t.AttachMediaInputTask=s.default;const c=i(n(6309));t.Attendee=c.default;const l=i(n(4651));t.AudioLogEvent=l.default;const d=i(n(1379));t.AudioProfile=d.default;const u=i(n(3894));t.AudioVideoControllerState=u.default;const f=i(n(390));t.BackgroundBlurStrength=f.default;const h=i(n(9799));t.BackgroundBlurVideoFrameProcessor=h.default;const m=i(n(6605));t.BackgroundFilterVideoFrameProcessor=m.default;const p=i(n(2557));t.BackgroundReplacementVideoFrameProcessor=p.default;const g=i(n(2852));t.BaseConnectionHealthPolicy=g.default;const v=i(n(698));t.BaseTask=v.default;const b=i(n(9473));t.BitrateParameters=b.default;const y=i(n(205));t.CSPMonitor=y.default;const S=i(n(2245));t.CanvasVideoFrameBuffer=S.default;const C=i(n(3439));t.CheckAudioConnectivityFeedback=C.default;const w=i(n(2524));t.CheckAudioInputFeedback=w.default;const M=i(n(3129));t.CheckAudioOutputFeedback=M.default;const z=i(n(3383));t.CheckCameraResolutionFeedback=z.default;const k=i(n(6857));t.CheckContentShareConnectivityFeedback=k.default;const x=i(n(7864));t.CheckNetworkTCPConnectivityFeedback=x.default;const V=i(n(4188));t.CheckNetworkUDPConnectivityFeedback=V.default;const H=i(n(2030));t.CheckVideoConnectivityFeedback=H.default;const E=i(n(2603));t.CheckVideoInputFeedback=E.default;const L=i(n(8214));t.CleanRestartedSessionTask=L.default;const T=i(n(7943));t.CleanStoppedSessionTask=T.default;const A=i(n(4671));t.ClientMetricReport=A.default;const _=i(n(1066));t.ClientMetricReportDirection=_.default;const N=i(n(3760));t.ClientMetricReportMediaType=N.default;const I=i(n(7824));t.ClientVideoStreamReceivingReport=I.default;const P=i(n(5799));t.ConnectionHealthData=P.default;const O=i(n(4127));t.ConnectionHealthPolicyConfiguration=O.default;const R=i(n(3804));t.ConsoleLogger=R.default;const D=i(n(5100));t.ContentShareConstants=D.default;const F=i(n(8896));t.ContentShareMediaStreamBroker=F.default;const B=i(n(7271));t.CreatePeerConnectionTask=B.default;const U=i(n(244));t.CreateSDPTask=U.default;const j=i(n(4783));t.DataMessage=j.default;const q=i(n(6762));t.DefaultActiveSpeakerDetector=q.default;const W=i(n(4498));t.DefaultActiveSpeakerPolicy=W.default;const $=i(n(6940));t.DefaultAudioMixController=$.default;const G=i(n(6460));t.DefaultAudioVideoController=G.default;const K=i(n(3644));t.DefaultAudioVideoFacade=K.default;const J=i(n(6244));t.DefaultBrowserBehavior=J.default;const Z=i(n(6960));t.DefaultContentShareController=Z.default;const Q=i(n(3236));t.DefaultDeviceController=Q.default;const Y=i(n(4926));t.DefaultDevicePixelRatioMonitor=Y.default;const X=i(n(7292));t.DefaultEventController=X.default;const ee=i(n(5032));t.DefaultMediaDeviceFactory=ee.default;const te=i(n(7185));t.DefaultMeetingEventReporter=te.default;const ne=i(n(8484));t.DefaultMeetingReadinessChecker=ne.default;const ie=i(n(4268));t.DefaultMeetingSession=ie.default;const re=i(n(5528));t.DefaultMessagingSession=re.default;const ae=i(n(832));t.DefaultModality=ae.default;const oe=i(n(4428));t.DefaultPingPong=oe.default;const se=i(n(7844));t.DefaultRealtimeController=se.default;const ce=i(n(822));t.DefaultReconnectController=ce.default;const le=i(n(3240));t.DefaultSessionStateController=le.default;const de=i(n(8854));t.DefaultSigV4=de.default;const ue=i(n(5826));t.DefaultSignalingClient=ue.default;const fe=i(n(6243));t.DefaultSimulcastUplinkPolicy=fe.default;const he=i(n(8172));t.DefaultSimulcastUplinkPolicyForContentShare=he.default;const me=i(n(8556));t.DefaultTransceiverController=me.default;const pe=i(n(1204));t.DefaultTranscriptionController=pe.default;const ge=i(n(3822));t.DefaultUserAgentParser=ge.default;const ve=i(n(8740));t.DefaultVideoCaptureAndEncodeParameter=ve.default;const be=i(n(6930));t.DefaultVideoFrameProcessorPipeline=be.default;const ye=i(n(6603));t.DefaultVideoFrameProcessorTimer=ye.default;const Se=i(n(4996));t.DefaultVideoStreamIdSet=Se.default;const Ce=i(n(9376));t.DefaultVideoStreamIndex=Ce.default;const we=i(n(8474));t.DefaultVideoTile=we.default;const Me=i(n(3038));t.DefaultVideoTileController=Me.default;const ze=i(n(5196));t.DefaultVideoTileFactory=ze.default;const ke=i(n(1729));t.DefaultVideoTransformDevice=ke.default;const xe=i(n(9164));t.DefaultVolumeIndicatorAdapter=xe.default;const Ve=i(n(388));t.DefaultWebSocketAdapter=Ve.default;const He=i(n(6009));t.DevicePixelRatioWindowSource=He.default;const Ee=i(n(8715));t.DeviceSelection=Ee.default;const Le=i(n(85));t.EventBufferConfiguration=Le.default;const Te=i(n(419));t.EventIngestionConfiguration=Te.default;const Ae=i(n(1218));t.FinishGatheringICECandidatesTask=Ae.default;const _e=i(n(3306));t.FullJitterBackoff=_e.default;const Ne=i(n(1042));t.FullJitterBackoffFactory=Ne.default;const Ie=i(n(6334));t.FullJitterLimitedBackoff=Ie.default;const Pe=i(n(7086));t.GetUserMediaError=Pe.default;const Oe=i(n(9215));t.GlobalMetricReport=Oe.default;const Re=i(n(7393));t.InMemoryJSONEventBuffer=Re.default;const De=i(n(8192));t.IntervalScheduler=De.default;const Fe=i(n(5591));t.JoinAndReceiveIndexTask=Fe.default;const Be=i(n(2352));t.LeaveAndReceiveLeaveAckTask=Be.default;const Ue=i(n(1919));t.ListenForVolumeIndicatorsTask=Ue.default;const je=i(n(5899));t.Log=je.default;const qe=i(n(3293));t.LogLevel=qe.default;const We=i(n(6479));t.MediaDeviceProxyHandler=We.default;const $e=i(n(4128));t.MeetingEventsClientConfiguration=$e.default;const Ge=i(n(4280));t.MeetingFeatures=Ge.default;const Ke=i(n(5025));t.MeetingReadinessCheckerConfiguration=Ke.default;const Je=i(n(1829));t.MeetingSessionConfiguration=Je.default;const Ze=i(n(7121));t.MeetingSessionCredentials=Ze.default;const Qe=i(n(6275));t.MeetingSessionLifecycleEvent=Qe.default;const Ye=i(n(8698));t.MeetingSessionLifecycleEventCondition=Ye.default;const Xe=i(n(565));t.MeetingSessionStatus=Xe.default;const et=i(n(484));t.MeetingSessionStatusCode=et.default;const tt=i(n(692));t.MeetingSessionTURNCredentials=tt.default;const nt=i(n(7385));t.MeetingSessionURLs=nt.default;const it=i(n(1835));t.MeetingSessionVideoAvailability=it.default;const rt=i(n(2636));t.Message=rt.default;const at=i(n(8035));t.MessagingSessionConfiguration=at.default;const ot=i(n(6387));t.ModelSpecBuilder=ot.default;const st=i(n(6835));t.MonitorTask=st.default;const ct=i(n(2132));t.MultiLogger=ct.default;const lt=i(n(7719));t.NScaleVideoUplinkBandwidthPolicy=lt.default;const dt=i(n(9263));t.NoOpAudioVideoController=dt.default;const ut=i(n(6782));t.NoOpDebugLogger=ut.default;const ft=i(n(9605));t.NoOpDeviceController=ft.default;const ht=i(n(6795));t.NoOpEventReporter=ht.default;const mt=i(n(5785));t.NoOpLogger=mt.default;const pt=i(n(8703));t.NoOpMediaStreamBroker=pt.default;const gt=i(n(1591));t.NoOpTask=gt.default;const vt=i(n(6751));t.NoOpVideoElementFactory=vt.default;const bt=i(n(255));t.NoOpVideoFrameProcessor=bt.default;const yt=i(n(1586));t.NoVideoDownlinkBandwidthPolicy=yt.default;const St=i(n(7880));t.NoVideoUplinkBandwidthPolicy=St.default;const Ct=i(n(8736));t.NotFoundError=Ct.default;const wt=i(n(478));t.NotReadableError=wt.default;const Mt=i(n(3750));t.OnceTask=Mt.default;const zt=i(n(5417));t.OpenSignalingConnectionTask=zt.default;const kt=i(n(903));t.OverconstrainedError=kt.default;const xt=i(n(7779));t.POSTLogger=xt.default;const Vt=i(n(1999));t.ParallelGroupTask=Vt.default;const Ht=i(n(8349));t.PermissionDeniedError=Ht.default;const Et=i(n(2335));t.PrefetchOn=Et.default;const Lt=i(n(2303));t.PrefetchSortBy=Lt.default;const Tt=i(n(8988));t.PromiseQueue=Tt.default;const At=i(n(5843));t.PromoteToPrimaryMeetingTask=At.default;const _t=i(n(9384));t.RealtimeAttendeePositionInFrame=_t.default;const Nt=i(n(990));t.RealtimeState=Nt.default;const It=i(n(8772));t.RealtimeVolumeIndicator=It.default;const Pt=i(n(3842));t.ReceiveAudioInputTask=Pt.default;const Ot=i(n(6522));t.ReceiveRemoteVideoPauseResumeTask=Ot.default;const Rt=i(n(3613));t.ReceiveVideoInputTask=Rt.default;const Dt=i(n(3381));t.ReceiveVideoStreamIndexTask=Dt.default;const Ft=i(n(2212));t.ReconnectionHealthPolicy=Ft.default;const Bt=i(n(5687));t.RedundantAudioEncoder=Bt.default;const Ut=i(n(551));t.RedundantAudioEncoderWorkerCode=Ut.default;const jt=i(n(7170));t.RedundantAudioRecoveryMetricReport=jt.default;const qt=i(n(8598));t.RunnableTask=qt.default;const Wt=i(n(5803));t.SDP=Wt.default;const $t=i(n(9762));t.SDPCandidateType=$t.default;const Gt=i(n(356));t.SDPMediaSection=Gt.default;const Kt=i(n(9103));t.SendAndReceiveDataMessagesTask=Kt.default;const Jt=i(n(6131));t.SendingAudioFailureConnectionHealthPolicy=Jt.default;const Zt=i(n(6706));t.SerialGroupTask=Zt.default;const Qt=i(n(980));t.ServerSideNetworkAdaption=Qt.default;const Yt=i(n(3797));t.SessionStateControllerAction=Yt.default;const Xt=i(n(3955));t.SessionStateControllerDeferPriority=Xt.default;const en=i(n(7670));t.SessionStateControllerState=en.default;const tn=i(n(2005));t.SessionStateControllerTransitionResult=tn.default;const nn=i(n(4518));t.SetLocalDescriptionTask=nn.default;const rn=i(n(4055));t.SetRemoteDescriptionTask=rn.default;const an=i(n(5437));t.SignalingAndMetricsConnectionMonitor=an.default;const on=i(n(2114));t.SignalingClientConnectionRequest=on.default;const sn=i(n(2887));t.SignalingClientEvent=sn.default;const cn=i(n(9183));t.SignalingClientEventType=cn.default;const ln=i(n(1903));t.SignalingClientJoin=ln.default;const dn=i(n(9295));t.SignalingClientSubscribe=dn.default;const un=i(n(9171));t.SignalingClientVideoSubscriptionConfiguration=un.default;const fn=i(n(2032));t.SimulcastContentShareTransceiverController=fn.default;const hn=i(n(1455));t.SimulcastLayers=hn.default;const mn=i(n(8020));t.SimulcastTransceiverController=mn.default;const pn=i(n(88));t.SimulcastVideoStreamIndex=pn.default;const gn=i(n(7667));t.SingleNodeAudioTransformDevice=gn.default;const vn=i(n(2260));t.StreamMetricReport=vn.default;const bn=i(n(4402));t.SubscribeAndReceiveSubscribeAckTask=bn.default;const yn=i(n(811));t.TargetDisplaySize=yn.default;const Sn=i(n(3533));t.TaskStatus=Sn.default;const Cn=i(n(1340));t.TimeoutScheduler=Cn.default;const wn=i(n(2058));t.TimeoutTask=wn.default;const Mn=i(n(9705));t.Transcript=Mn.default;const zn=i(n(7722));t.TranscriptAlternative=zn.default;const kn=i(n(5870));t.TranscriptEntity=kn.default;const xn=i(n(8742));t.TranscriptItem=xn.default;const Vn=i(n(9182));t.TranscriptItemType=Vn.default;const Hn=i(n(465));t.TranscriptLanguageWithScore=Hn.default;const En=i(n(6788));t.TranscriptResult=En.default;const Ln=i(n(7301));t.TranscriptionStatus=Ln.default;const Tn=i(n(4373));t.TranscriptionStatusType=Tn.default;const An=i(n(6801));t.TypeError=An.default;const _n=i(n(4880));t.UnusableAudioWarningConnectionHealthPolicy=_n.default;const Nn=i(n(6741));t.Versioning=Nn.default;const In=i(n(6804));t.VideoAdaptiveProbePolicy=In.default;const Pn=i(n(2049));t.VideoCodecCapability=Pn.default;const On=i(n(3239));t.VideoFxProcessor=On.default;const Rn=i(n(174));t.VideoLogEvent=Rn.default;const Dn=i(n(4664));t.VideoOnlyTransceiverController=Dn.default;const Fn=i(n(9501));t.VideoPreference=Fn.default;const Bn=i(n(9e3));t.VideoPreferences=Bn.default;const Un=i(n(5907));t.VideoPriorityBasedPolicy=Un.default;const jn=i(n(7405));t.VideoPriorityBasedPolicyConfig=jn.default;const qn=i(n(1583));t.VideoQualityAdaptationPreference=qn.default;const Wn=i(n(7094));t.VideoQualitySettings=Wn.default;const $n=i(n(8931));t.VideoSource=$n.default;const Gn=i(n(6409));t.VideoStreamDescription=Gn.default;const Kn=i(n(1510));t.VideoTileState=Kn.default;const Jn=i(n(4392));t.VoiceFocusDeviceTransformer=Jn.default;const Zn=i(n(2087));t.VoiceFocusTransformDevice=Zn.default;const Qn=i(n(8170));t.WaitForAttendeePresenceTask=Qn.default;const Yn=i(n(4696));t.WebSocketReadyState=Yn.default;const Xn=i(n(4095));t.ZLIBTextCompressor=Xn.default;const ei=n(9e3);Object.defineProperty(t,"MutableVideoPreferences",{enumerable:!0,get:function(){return ei.MutableVideoPreferences}});const ti=n(8807);Object.defineProperty(t,"Some",{enumerable:!0,get:function(){return ti.Some}}),Object.defineProperty(t,"None",{enumerable:!0,get:function(){return ti.None}}),Object.defineProperty(t,"Maybe",{enumerable:!0,get:function(){return ti.Maybe}});const ni=n(3099);Object.defineProperty(t,"isAudioTransformDevice",{enumerable:!0,get:function(){return ni.isAudioTransformDevice}});const ii=n(47);Object.defineProperty(t,"isDestroyable",{enumerable:!0,get:function(){return ii.isDestroyable}});const ri=n(6880);Object.defineProperty(t,"isVideoTransformDevice",{enumerable:!0,get:function(){return ri.isVideoTransformDevice}})},3804:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(3293));t.default=class{constructor(e,t=r.default.WARN){this.name=e,this.level=t}info(e){this.log(r.default.INFO,e)}warn(e){this.log(r.default.WARN,e)}error(e){this.log(r.default.ERROR,e)}debug(e){r.default.DEBUG{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t,n,i){this.sequenceNumber=e,this.message=t,this.timestampMs=n,this.logLevel=i}}},3293:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0,function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.OFF=4]="OFF"}(n=t.LogLevel||(t.LogLevel={})),t.default=n},2132:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(3293));t.default=class{constructor(...e){this._loggers=e}info(e){for(const t of this._loggers)t.info(e)}warn(e){for(const t of this._loggers)t.warn(e)}error(e){for(const t of this._loggers)t.error(e)}debug(e){let t,n;n="string"==typeof e?e:e?()=>(t||(t=e()),t):""+e;for(const e of this._loggers)e.debug(n)}setLogLevel(e){for(const t of this._loggers)t.setLogLevel(e)}getLogLevel(){for(const e of this._loggers)return e.getLogLevel();return r.default.OFF}}},6782:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(3293)),a=i(n(5785));class o extends a.default{constructor(){super(r.default.DEBUG)}}t.default=o},5785:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(3293));t.default=class{constructor(e=r.default.OFF){this.level=e}info(e){}warn(e){}error(e){}debug(e){r.default.DEBUG{this.stop()},this.addEventListener()}addEventListener(){this.eventListener&&"window"in n.g&&window.addEventListener&&window.addEventListener("unload",this.eventListener)}removeEventListener(){this.eventListener&&"window"in n.g&&window.removeEventListener&&window.removeEventListener("unload",this.eventListener)}debug(e){s.default.DEBUGi(this,void 0,void 0,(function*(){if(!0===this.lock||0===this.getLogCaptureSize())return;this.lock=!0;const e=this.logCapture.slice(0,this.batchSize),t=this.makeRequestBody(e);try{200===(yield fetch(this.url,Object.assign({method:"POST",body:t},this.headers?{headers:this.headers}:{}))).status&&(this.logCapture=this.logCapture.slice(e.length))}catch(e){console.warn("[POSTLogger] "+e.message)}finally{this.lock=!1}}))))}stop(){var e;null===(e=this.intervalScheduler)||void 0===e||e.stop(),this.intervalScheduler=void 0,this.removeEventListener();const t=this.makeRequestBody(this.logCapture);navigator.sendBeacon(this.url,t)}destroy(){return i(this,void 0,void 0,(function*(){this.stop(),this.metadata=void 0,this.headers=void 0,this.logCapture=[],this.sequenceNumber=0,this.lock=!1,this.batchSize=0,this.intervalMs=0,this.url=void 0}))}makeRequestBody(e){return JSON.stringify(Object.assign(Object.assign({},this.metadata),{logs:e}))}log(e,t){if(e{if(!Reflect.has(e,t))return;if(!("ondevicechange"in navigator.mediaDevices)){if("addEventListener"===t)return this.patchAddEventListener(e,t,n);if("removeEventListener"===t)return this.patchRemoveEventListener(e,t,n)}const i=Reflect.get(e,t,n);return"function"==typeof i?i.bind(e):i},this.patchAddEventListener=(e,t,n)=>{const i=Reflect.get(e,t,n);return(t,n,r)=>{if("devicechange"!==t)return Reflect.apply(i,e,[t,n,r]);this.deviceChangeListeners.add(n),this.scheduler||(this.scheduler=new o.default(s.INTERVAL_MS),this.scheduler.start(this.pollDeviceLists))}},this.patchRemoveEventListener=(e,t,n)=>{const i=Reflect.get(e,t,n);return(t,n,r)=>{if("devicechange"!==t)return Reflect.apply(i,e,[t,n,r]);this.deviceChangeListeners.delete(n),0===this.deviceChangeListeners.size&&this.scheduler&&(this.scheduler.stop(),this.scheduler=null)}},this.pollDeviceLists=()=>i(this,void 0,void 0,(function*(){const e=yield this.sortedDeviceList();this.devices&&(e.length!==this.devices.length||e.some(((e,t)=>e.deviceId!==this.devices[t].deviceId)))&&this.handleDeviceChangeEvent(),this.devices=e}))}sortedDeviceList(){return i(this,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).sort(((e,t)=>e.deviceIdt.deviceId?-1:0))}))}handleDeviceChangeEvent(){for(const e of this.deviceChangeListeners)a.default.nextTick((()=>{if(this.deviceChangeListeners.has(e)){const t=new Event("devicechange");"function"==typeof e?e(t):e.handleEvent(t)}}))}}t.default=s,s.INTERVAL_MS=1e3},8703:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{acquireAudioInputStream(){return Promise.reject()}acquireVideoInputStream(){return Promise.reject()}acquireDisplayInputStream(e){return Promise.reject()}muteLocalAudioInputStream(){}unmuteLocalAudioInputStream(){}addMediaStreamBrokerObserver(e){}removeMediaStreamBrokerObserver(e){}}},3439:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.CheckAudioConnectivityFeedback=void 0,function(e){e[e.Succeeded=0]="Succeeded",e[e.AudioInputRequestFailed=1]="AudioInputRequestFailed",e[e.AudioInputPermissionDenied=2]="AudioInputPermissionDenied",e[e.ConnectionFailed=3]="ConnectionFailed",e[e.AudioNotReceived=4]="AudioNotReceived"}(n=t.CheckAudioConnectivityFeedback||(t.CheckAudioConnectivityFeedback={})),t.default=n},2524:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.CheckAudioInputFeedback=void 0,function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed",e[e.PermissionDenied=2]="PermissionDenied"}(n=t.CheckAudioInputFeedback||(t.CheckAudioInputFeedback={})),t.default=n},3129:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.CheckAudioOutputFeedback=void 0,function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed"}(n=t.CheckAudioOutputFeedback||(t.CheckAudioOutputFeedback={})),t.default=n},3383:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.CheckCameraResolutionFeedback=void 0,function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed",e[e.ResolutionNotSupported=2]="ResolutionNotSupported",e[e.PermissionDenied=3]="PermissionDenied"}(n=t.CheckCameraResolutionFeedback||(t.CheckCameraResolutionFeedback={})),t.default=n},6857:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.CheckContentShareConnectivityFeedback=void 0,function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed",e[e.PermissionDenied=2]="PermissionDenied",e[e.TimedOut=3]="TimedOut",e[e.ConnectionFailed=4]="ConnectionFailed"}(n=t.CheckContentShareConnectivityFeedback||(t.CheckContentShareConnectivityFeedback={})),t.default=n},7864:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.CheckNetworkTCPConnectivityFeedback=void 0,function(e){e[e.Succeeded=0]="Succeeded",e[e.MeetingSessionURLsNotInitialized=1]="MeetingSessionURLsNotInitialized",e[e.ConnectionFailed=2]="ConnectionFailed",e[e.ICENegotiationFailed=3]="ICENegotiationFailed"}(n=t.CheckNetworkTCPConnectivityFeedback||(t.CheckNetworkTCPConnectivityFeedback={})),t.default=n},4188:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.CheckNetworkUDPConnectivityFeedback=void 0,function(e){e[e.Succeeded=0]="Succeeded",e[e.MeetingSessionURLsNotInitialized=1]="MeetingSessionURLsNotInitialized",e[e.ConnectionFailed=2]="ConnectionFailed",e[e.ICENegotiationFailed=3]="ICENegotiationFailed"}(n=t.CheckNetworkUDPConnectivityFeedback||(t.CheckNetworkUDPConnectivityFeedback={})),t.default=n},2030:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.CheckVideoConnectivityFeedback=void 0,function(e){e[e.Succeeded=0]="Succeeded",e[e.VideoInputRequestFailed=1]="VideoInputRequestFailed",e[e.VideoInputPermissionDenied=2]="VideoInputPermissionDenied",e[e.ConnectionFailed=3]="ConnectionFailed",e[e.VideoNotSent=4]="VideoNotSent"}(n=t.CheckVideoConnectivityFeedback||(t.CheckVideoConnectivityFeedback={})),t.default=n},2603:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.CheckVideoInputFeedback=void 0,function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed",e[e.PermissionDenied=2]="PermissionDenied"}(n=t.CheckVideoInputFeedback||(t.CheckVideoInputFeedback={})),t.default=n},8484:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(6940)),o=r(n(6244)),s=r(n(3236)),c=r(n(8349)),l=r(n(698)),d=r(n(2058)),u=r(n(3439)),f=r(n(2524)),h=r(n(3129)),m=r(n(3383)),p=r(n(6857)),g=r(n(7864)),v=r(n(4188)),b=r(n(2030)),y=r(n(2603)),S=r(n(5025));class C{constructor(e,t,n=new S.default){this.logger=e,this.meetingSession=t,this.configuration=n,this.browserBehavior=new o.default}static delay(e){return i(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}checkAudioInput(e){return i(this,void 0,void 0,(function*(){try{return yield this.meetingSession.audioVideo.startAudioInput(e),yield this.meetingSession.audioVideo.stopAudioInput(),f.default.Succeeded}catch(e){return this.logger.error(`MeetingReadinessChecker: Audio input check failed with error ${e}`),e instanceof c.default?f.default.PermissionDenied:f.default.Failed}}))}checkAudioOutput(e,t,n=null){return i(this,void 0,void 0,(function*(){try{const i=e?s.default.getIntrinsicDeviceId(e):"";return yield this.playTone(i,this.configuration.audioOutputFrequency,n),(yield t())?h.default.Succeeded:h.default.Failed}catch(e){return this.logger.error(`MeetingReadinessChecker: Audio output check failed with error: ${e}`),h.default.Failed}finally{this.stopTone()}}))}playTone(e,t,n){return i(this,void 0,void 0,(function*(){const i=this.configuration.audioOutputGain;this.oscillatorNode&&this.stopTone(),this.audioContext=s.default.getAudioContext(),this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=0,this.oscillatorNode=this.audioContext.createOscillator(),this.oscillatorNode.frequency.value=t,this.oscillatorNode.connect(this.gainNode),this.destinationStream=this.audioContext.createMediaStreamDestination(),this.gainNode.connect(this.destinationStream);const r=this.audioContext.currentTime+.1;this.gainNode.gain.linearRampToValueAtTime(0,r),this.gainNode.gain.linearRampToValueAtTime(i,r+.1),this.oscillatorNode.start();const o=new a.default(this.logger);try{this.browserBehavior.supportsSetSinkId()&&(yield o.bindAudioDevice({deviceId:e}))}catch(e){this.logger.error(`Failed to bind audio device: ${e}`)}try{yield o.bindAudioElement(n||new Audio)}catch(e){this.logger.error(`Failed to bind audio element: ${e}`)}yield o.bindAudioStream(this.destinationStream.stream)}))}stopTone(){if(!(this.audioContext&&this.gainNode&&this.oscillatorNode&&this.destinationStream))return;const e=this.configuration.audioOutputGain,t=this.audioContext.currentTime;this.gainNode.gain.linearRampToValueAtTime(e,t+.1+1),this.gainNode.gain.linearRampToValueAtTime(0,t+.2+1),this.oscillatorNode.stop(),this.oscillatorNode.disconnect(this.gainNode),this.gainNode.disconnect(this.destinationStream),this.oscillatorNode=null,this.gainNode=null,this.destinationStream=null}checkVideoInput(e){return i(this,void 0,void 0,(function*(){try{return yield this.meetingSession.audioVideo.startVideoInput(e),yield this.meetingSession.audioVideo.stopVideoInput(),y.default.Succeeded}catch(e){return this.logger.error(`MeetingReadinessChecker: Video check failed with error ${e}`),e instanceof c.default?y.default.PermissionDenied:y.default.Failed}}))}checkCameraResolution(e,t,n){return i(this,void 0,void 0,(function*(){let i;try{const r=s.default.getIntrinsicDeviceId(e),a={video:this.calculateVideoConstraint(r,t,n)};i=yield navigator.mediaDevices.getUserMedia(a)}catch(e){return this.logger.error(`MeetingReadinessChecker: Camera resolution check with width: ${t} height ${n} failed with error ${e}`),e&&"OverconstrainedError"===e.name?m.default.ResolutionNotSupported:e&&"NotAllowedError"===e.name?m.default.PermissionDenied:m.default.Failed}finally{i&&i.getTracks().forEach((function(e){e.stop()}))}return m.default.Succeeded}))}calculateVideoConstraint(e,t,n){const i=this.browserBehavior.requiresResolutionAlignment(t,n),r={};return this.browserBehavior.requiresNoExactMediaStreamConstraints()?(r.deviceId=e,r.width=t,r.height=n):(r.deviceId={exact:e},r.width={exact:i[0]},r.height={exact:i[1]}),r}checkContentShareConnectivity(e){return i(this,void 0,void 0,(function*(){let t=!1,n=!1;const r={contentShareDidStart:()=>{t=!0}},a={audioVideoDidStart:()=>{n=!0}};try{return this.meetingSession.audioVideo.addObserver(a),this.meetingSession.audioVideo.start(),this.meetingSession.audioVideo.addContentShareObserver(r),yield this.meetingSession.audioVideo.startContentShareFromScreenCapture(e),yield this.executeTimeoutTask((()=>i(this,void 0,void 0,(function*(){return n&&t})))),n?(yield this.stopMeeting(),t?p.default.Succeeded:p.default.TimedOut):p.default.ConnectionFailed}catch(e){return this.logger.error(`MeetingReadinessChecker: Content share check failed with error ${e}`),"NotAllowedError"===e.name?p.default.PermissionDenied:p.default.Failed}finally{this.meetingSession.audioVideo.removeObserver(a),this.meetingSession.audioVideo.stopContentShare(),this.meetingSession.audioVideo.removeContentShareObserver(r)}}))}checkAudioConnectivity(e){return i(this,void 0,void 0,(function*(){let t=!1;const n={packetsReceived:0},r=this.meetingSession.audioVideo,a={metricsDidReceive(e){e.getRTCStatsReport().forEach((e=>{"inbound-rtp"!==e.type||"audio"!==e.mediaType&&"audio"!==e.kind||(n.packetsReceived=e.packetsReceived)}))}},o=(e,n,i,r)=>{e===this.meetingSession.configuration.credentials.attendeeId&&n&&(t=!0)};try{yield r.startAudioInput(e)}catch(e){return this.logger.error(`MeetingReadinessChecker: Failed to get audio input device with error ${e}`),e instanceof c.default?u.default.AudioInputPermissionDenied:u.default.AudioInputRequestFailed}return r.realtimeSubscribeToAttendeeIdPresence(o),r.addObserver(a),(yield this.startMeeting())?(yield this.executeTimeoutTask((()=>i(this,void 0,void 0,(function*(){return this.isAudioConnectionSuccessful(t,n)})))),r.removeObserver(a),r.realtimeUnsubscribeToAttendeeIdPresence(o),yield this.stopMeeting(),yield this.meetingSession.audioVideo.stopAudioInput(),this.isAudioConnectionSuccessful(t,n)?u.default.Succeeded:u.default.AudioNotReceived):(r.removeObserver(a),r.realtimeUnsubscribeToAttendeeIdPresence(o),yield this.meetingSession.audioVideo.stopAudioInput(),u.default.ConnectionFailed)}))}checkVideoConnectivity(e){return i(this,void 0,void 0,(function*(){const t=this.meetingSession.audioVideo;let n=0;const r={metricsDidReceive(e){e.getRTCStatsReport().forEach((e=>{"outbound-rtp"!==e.type||"video"!==e.mediaType&&"video"!==e.kind||(n=e.packetsSent)}))}};try{yield t.startVideoInput(e)}catch(e){return this.logger.error(`MeetingReadinessChecker: Failed to get video input device with error ${e}`),e instanceof c.default?b.default.VideoInputPermissionDenied:b.default.VideoInputRequestFailed}return t.addObserver(r),(yield this.startMeeting())?(t.startLocalVideoTile(),yield this.executeTimeoutTask((()=>i(this,void 0,void 0,(function*(){return n>0})))),yield t.stopVideoInput(),yield this.stopMeeting(),t.removeObserver(r),n<=0?b.default.VideoNotSent:b.default.Succeeded):b.default.ConnectionFailed}))}checkNetworkUDPConnectivity(){return i(this,void 0,void 0,(function*(){let e=!1;const t={metricsDidReceive(t){t.getRTCStatsReport().forEach((t=>{"candidate-pair"===t.type&&"succeeded"===t.state&&(e=!0)}))}};try{this.originalURLRewriter=this.meetingSession.configuration.urls.urlRewriter}catch(e){return this.logger.error(`MeetingSessionConfiguration.urls doesn't exist. Error: ${e}`),v.default.MeetingSessionURLsNotInitialized}this.meetingSession.configuration.urls.urlRewriter=e=>{const t=this.originalURLRewriter(e);return t.includes("transport=tcp")?"":t};const n=this.meetingSession.audioVideo;return n.addObserver(t),(yield this.startMeeting())?(yield this.executeTimeoutTask((()=>i(this,void 0,void 0,(function*(){return e})))),this.meetingSession.configuration.urls.urlRewriter=this.originalURLRewriter,yield this.stopMeeting(),n.removeObserver(t),e?v.default.Succeeded:v.default.ICENegotiationFailed):(this.meetingSession.configuration.urls.urlRewriter=this.originalURLRewriter,v.default.ConnectionFailed)}))}checkNetworkTCPConnectivity(){return i(this,void 0,void 0,(function*(){let e=!1;const t={metricsDidReceive(t){t.getRTCStatsReport().forEach((t=>{"candidate-pair"===t.type&&"succeeded"===t.state&&(e=!0)}))}};try{this.originalURLRewriter=this.meetingSession.configuration.urls.urlRewriter}catch(e){return this.logger.error(`MeetingSessionConfiguration.urls doesn't exist. Error: ${e}`),g.default.MeetingSessionURLsNotInitialized}this.meetingSession.configuration.urls.urlRewriter=e=>{const t=this.originalURLRewriter(e);return t.includes("transport=udp")?"":t};const n=this.meetingSession.audioVideo;return n.addObserver(t),(yield this.startMeeting())?(yield this.executeTimeoutTask((()=>i(this,void 0,void 0,(function*(){return e})))),this.meetingSession.configuration.urls.urlRewriter=this.originalURLRewriter,yield this.stopMeeting(),n.removeObserver(t),e?g.default.Succeeded:g.default.ICENegotiationFailed):(this.meetingSession.configuration.urls.urlRewriter=this.originalURLRewriter,g.default.ConnectionFailed)}))}startMeeting(){return i(this,void 0,void 0,(function*(){let e=!1;const t={audioVideoDidStart:()=>{e=!0}};return this.meetingSession.audioVideo.addObserver(t),this.meetingSession.audioVideo.start(),yield this.executeTimeoutTask((()=>i(this,void 0,void 0,(function*(){return e})))),this.meetingSession.audioVideo.removeObserver(t),e}))}stopMeeting(){return i(this,void 0,void 0,(function*(){let e=!1;const t={audioVideoDidStop:t=>{e=!0}};return this.meetingSession.audioVideo.addObserver(t),this.meetingSession.audioVideo.stop(),yield this.executeTimeoutTask((()=>i(this,void 0,void 0,(function*(){return e})))),this.meetingSession.audioVideo.removeObserver(t),e}))}executeTimeoutTask(e){return i(this,void 0,void 0,(function*(){let t=!1;class n extends l.default{constructor(e,t){super(e),this.waitDurationMs=t,this.isCancelled=!1}cancel(){this.isCancelled=!0}run(){return i(this,void 0,void 0,(function*(){for(;!this.isCancelled;){if(yield e()){t=!0;break}yield C.delay(this.waitDurationMs)}}))}}const r=new d.default(this.logger,new n(this.logger,this.configuration.waitDurationMs),this.configuration.timeoutMs);return yield r.run(),t}))}isAudioConnectionSuccessful(e,t){return e&&t.packetsReceived>0}}t.default=C},5025:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.timeoutMs=1e4,this.waitDurationMs=3e3,this.audioOutputFrequency=440,this.audioOutputGain=.1}}},4268:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(6460)),o=r(n(3644)),s=r(n(3306)),c=r(n(6244)),l=r(n(8896)),d=r(n(6960)),u=r(n(205)),f=n(47),h=r(n(7292)),m=r(n(822)),p=r(n(388));t.default=class{constructor(e,t,n,i){this._eventController=i,this._configuration=e,this._logger=t,this.checkBrowserSupportAndFeatureConfiguration(),u.default.addLogger(this._logger),u.default.register(),this._eventController||(this._eventController=new h.default(e,t)),n.eventController||(n.eventController=this.eventController),this.audioVideoController=new a.default(this._configuration,this._logger,new p.default(this._logger),n,new m.default(this._configuration.reconnectTimeoutMs,new s.default(this._configuration.reconnectFixedWaitMs,this._configuration.reconnectShortBackOffMs,this._configuration.reconnectLongBackOffMs)),this.eventController),this._deviceController=n,this.logger.info(`MeetingFeatures: ${JSON.stringify(e.meetingFeatures)}`);const r=new l.default(this._logger);this.contentShareController=new d.default(r,new a.default(d.default.createContentShareMeetingSessionConfigure(this._configuration),this._logger,new p.default(this._logger),r,new m.default(this._configuration.reconnectTimeoutMs,new s.default(this._configuration.reconnectFixedWaitMs,this._configuration.reconnectShortBackOffMs,this._configuration.reconnectLongBackOffMs))),this.audioVideoController),this.audioVideoFacade=new o.default(this.audioVideoController,this.audioVideoController.videoTileController,this.audioVideoController.realtimeController,this.audioVideoController.audioMixController,this._deviceController,this.contentShareController)}get configuration(){return this._configuration}get logger(){return this._logger}get audioVideo(){return this.audioVideoFacade}get contentShare(){return this.contentShareController}get deviceController(){return this._deviceController}get eventController(){return this._eventController}destroy(){return i(this,void 0,void 0,(function*(){f.isDestroyable(this.contentShareController)&&(yield this.contentShareController.destroy()),f.isDestroyable(this.audioVideoController)&&(yield this.audioVideoController.destroy()),f.isDestroyable(this.eventController)&&(yield this.eventController.destroy()),u.default.removeLogger(this._logger),this._logger=void 0,this._configuration=void 0,this._deviceController=void 0,this.audioVideoFacade=void 0,this.audioVideoController=void 0,this.contentShareController=void 0,this._eventController=void 0}))}checkBrowserSupportAndFeatureConfiguration(){const e=new c.default,t=`${e.name()} ${e.majorVersion()} (${e.version()})`;if(this.logger.info(`browser is ${t}`),e.isSupported()||this.logger.warn(`this browser is not currently supported. Stability may suffer. Supported browsers are: ${e.supportString()}.`),this._configuration.videoUplinkBandwidthPolicy)if(this.isSimulcastUplinkPolicy(this._configuration.videoUplinkBandwidthPolicy)){if(!e.hasChromiumWebRTC())throw new Error("Simulcast is only supported on Chromium-based browsers");this._configuration.enableSimulcastForUnifiedPlanChromiumBasedBrowsers=!0}else this._configuration.enableSimulcastForUnifiedPlanChromiumBasedBrowsers=!1;this._configuration.enableSimulcastForUnifiedPlanChromiumBasedBrowsers&&(e.hasChromiumWebRTC()?this.logger.info(`Simulcast is enabled for ${e.name()}`):(this._configuration.enableSimulcastForUnifiedPlanChromiumBasedBrowsers=!1,this.logger.info("Simulcast is only supported on Chromium-based browsers")),this._configuration.enableSVC&&(this._configuration.enableSVC=!1,this.logger.info("SVC is not successfully enabled since simulcast is enabled"))),this._configuration.enableSVC&&!e.supportsScalableVideoCoding()&&(this._configuration.enableSVC=!1,this.logger.info("SVC is only supported on Chromium-based browsers with version 111 or above"))}isSimulcastUplinkPolicy(e){return!(!e||!e.addObserver)}}},4280:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(7094));class a{constructor(e=r.default.VideoResolutionHD,t=r.default.VideoResolutionFHD){this.videoMaxResolution=e,this.contentMaxResolution=t}clone(){return new a(this.videoMaxResolution,this.contentMaxResolution)}}t.default=a},1829:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(4127)),a=i(n(7094)),o=n(9979),s=i(n(4280)),c=i(n(7121)),l=i(n(7385));t.default=class{constructor(e,t){var n,i;if(this.meetingId=null,this.externalMeetingId=null,this.credentials=null,this.urls=null,this.connectionTimeoutMs=15e3,this.attendeePresenceTimeoutMs=0,this.connectionHealthPolicyConfiguration=new r.default,this.reconnectTimeoutMs=12e4,this.reconnectFixedWaitMs=0,this.reconnectShortBackOffMs=1e3,this.reconnectLongBackOffMs=5e3,this.enableSimulcastForUnifiedPlanChromiumBasedBrowsers=!1,this.enableSVC=!1,this.videoDownlinkBandwidthPolicy=null,this.videoUplinkBandwidthPolicy=null,this.keepLastFrameWhenPaused=!1,this.disablePeriodicKeyframeRequestOnContentSender=!1,this.meetingFeatures=new s.default,e){(e=o.toLowerCasePropertyNames(e)).meeting&&(e=e.meeting),this.meetingId=e.meetingid,this.externalMeetingId=e.externalmeetingid,this.urls=new l.default,this.urls.audioHostURL=e.mediaplacement.audiohosturl,this.urls.signalingURL=e.mediaplacement.signalingurl,this.urls.turnControlURL=e.mediaplacement.turncontrolurl,e.mediaplacement.eventingestionurl&&(this.urls.eventIngestionURL=e.mediaplacement.eventingestionurl);const t=(e,t)=>{switch(e){case"None":return a.default.VideoDisabled;case"HD":return a.default.VideoResolutionHD;case"FHD":return a.default.VideoResolutionFHD;case"UHD":return a.default.VideoResolutionUHD;default:return t}};if(void 0!==(null===(n=e.meetingfeatures)||void 0===n?void 0:n.video)||void 0!==(null===(i=e.meetingfeatures)||void 0===i?void 0:i.content)){const n=void 0===e.meetingfeatures.video?"HD":e.meetingfeatures.video.maxresolution,i=void 0===e.meetingfeatures.content?"FHD":e.meetingfeatures.content.maxresolution;this.meetingFeatures=new s.default(t(n,a.default.VideoResolutionHD),t(i,a.default.VideoResolutionFHD))}}t&&((t=o.toLowerCasePropertyNames(t)).attendee&&(t=t.attendee),this.credentials=new c.default,this.credentials.attendeeId=t.attendeeid,this.credentials.externalUserId=t.externaluserid,this.credentials.joinToken=t.jointoken)}}},7121:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.attendeeId=null,this.externalUserId=null,this.joinToken=null}toJSON(){return{attendeeId:this.attendeeId,joinToken:null===this.joinToken?null:""}}}},6275:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.MeetingSessionLifecycleEvent=void 0,function(e){e[e.Connecting=0]="Connecting",e[e.Started=1]="Started",e[e.Stopped=2]="Stopped"}(n=t.MeetingSessionLifecycleEvent||(t.MeetingSessionLifecycleEvent={})),t.default=n},8698:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.MeetingSessionLifecycleEventCondition=void 0,function(e){e[e.ConnectingNew=0]="ConnectingNew",e[e.ReconnectingExisting=1]="ReconnectingExisting",e[e.StartedNew=2]="StartedNew",e[e.StartedExisting=3]="StartedExisting",e[e.StartedAfterReconnect=4]="StartedAfterReconnect",e[e.StoppedCleanly=5]="StoppedCleanly",e[e.StoppedWithFailure=6]="StoppedWithFailure"}(n=t.MeetingSessionLifecycleEventCondition||(t.MeetingSessionLifecycleEventCondition={})),t.default=n},565:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=n(4955),a=i(n(484));class o{constructor(e){this._statusCode=e}statusCode(){return this._statusCode}isFailure(){switch(this._statusCode){case a.default.AudioAuthenticationRejected:case a.default.AudioCallAtCapacity:case a.default.AudioInternalServerError:case a.default.AudioServiceUnavailable:case a.default.AudioDisconnected:case a.default.VideoCallAtSourceCapacity:case a.default.SignalingBadRequest:case a.default.SignalingInternalServerError:case a.default.SignalingRequestFailed:case a.default.ICEGatheringTimeoutWorkaround:case a.default.ConnectionHealthReconnect:case a.default.RealtimeApiFailed:case a.default.TaskFailed:case a.default.NoAttendeePresent:return!0;default:return!1}}isTerminal(){switch(this._statusCode){case a.default.Left:case a.default.AudioJoinedFromAnotherDevice:case a.default.AudioAuthenticationRejected:case a.default.AudioCallAtCapacity:case a.default.MeetingEnded:case a.default.AudioDisconnected:case a.default.TURNCredentialsForbidden:case a.default.SignalingBadRequest:case a.default.SignalingRequestFailed:case a.default.VideoCallAtSourceCapacity:case a.default.RealtimeApiFailed:case a.default.AudioAttendeeRemoved:return!0;default:return!1}}isAudioConnectionFailure(){switch(this._statusCode){case a.default.AudioAuthenticationRejected:case a.default.AudioInternalServerError:case a.default.AudioServiceUnavailable:case a.default.ICEGatheringTimeoutWorkaround:case a.default.SignalingBadRequest:case a.default.SignalingInternalServerError:case a.default.SignalingRequestFailed:case a.default.RealtimeApiFailed:case a.default.NoAttendeePresent:return!0;default:return!1}}toString(){switch(this._statusCode){case a.default.OK:return"Everything is OK so far.";case a.default.Left:return"The attendee left the meeting.";case a.default.AudioJoinedFromAnotherDevice:return"The attendee joined from another device.";case a.default.AudioAuthenticationRejected:return"The meeting rejected the attendee.";case a.default.AudioCallAtCapacity:return"The attendee couldn't join because the meeting was at capacity.";case a.default.MeetingEnded:return"The meeting ended.";case a.default.AudioInternalServerError:case a.default.AudioServiceUnavailable:case a.default.AudioDisconnected:return"The audio connection failed.";case a.default.VideoCallSwitchToViewOnly:return"The attendee couldn't start the local video because the maximum video capacity was reached.";case a.default.VideoCallAtSourceCapacity:return"The connection failed due to an internal server error.";case a.default.SignalingBadRequest:case a.default.SignalingInternalServerError:case a.default.SignalingRequestFailed:return"The signaling connection failed.";case a.default.ICEGatheringTimeoutWorkaround:return"Gathering ICE candidates timed out. In Chrome, this might indicate that the browser is in a bad state after reconnecting to VPN.";case a.default.ConnectionHealthReconnect:return"The meeting was reconnected.";case a.default.RealtimeApiFailed:return"The real-time API failed. This status code might indicate that the callback you passed to the real-time API threw an exception.";case a.default.TaskFailed:return"The connection failed. See the error message for more details.";case a.default.IncompatibleSDP:return"The connection failed due to incompatible SDP.";case a.default.TURNCredentialsForbidden:return"The meeting ended, or the attendee was removed.";case a.default.NoAttendeePresent:return"The attendee was not present.";case a.default.AudioAttendeeRemoved:return"The meeting ended because attendee removed.";case a.default.AudioVideoWasRemovedFromPrimaryMeeting:return"The Primary meeting credentials provided are no longer valid. chime::DeleteAttendee may have been called on them.";case a.default.AudioDisconnectAudio:return"The audio connection failed.";default:{const e=this._statusCode;throw new Error(`Unhandled case: ${e}`)}}}static fromSignalFrame(e){return e.error&&e.error.status?this.fromSignalingStatus(e.error.status):e.type===r.SdkSignalFrame.Type.AUDIO_STATUS?e.audioStatus?this.fromAudioStatus(e.audioStatus.audioStatus):new o(a.default.SignalingRequestFailed):e.type===r.SdkSignalFrame.Type.PRIMARY_MEETING_LEAVE?new o(a.default.AudioVideoWasRemovedFromPrimaryMeeting):new o(a.default.OK)}static fromAudioStatus(e){switch(e){case 200:return new o(a.default.OK);case 301:return new o(a.default.AudioJoinedFromAnotherDevice);case 302:return new o(a.default.AudioDisconnectAudio);case 403:return new o(a.default.AudioAuthenticationRejected);case 409:return new o(a.default.AudioCallAtCapacity);case 410:return new o(a.default.MeetingEnded);case 411:return new o(a.default.AudioAttendeeRemoved);case 500:return new o(a.default.AudioInternalServerError);case 503:return new o(a.default.AudioServiceUnavailable);default:return 2===Math.floor(e/100)?new o(a.default.OK):new o(a.default.AudioDisconnected)}}static fromSignalingStatus(e){switch(e){case 206:return new o(a.default.VideoCallSwitchToViewOnly);case 509:return new o(a.default.VideoCallAtSourceCapacity);case 403:return new o(a.default.AudioAuthenticationRejected);case 409:return new o(a.default.AudioCallAtCapacity);default:switch(Math.floor(e/100)){case 2:return new o(a.default.OK);case 4:return new o(a.default.SignalingBadRequest);case 5:return new o(a.default.SignalingInternalServerError);default:return new o(a.default.SignalingRequestFailed)}}}}t.default=o},484:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.MeetingSessionStatusCode=void 0,function(e){e[e.OK=0]="OK",e[e.Left=1]="Left",e[e.AudioJoinedFromAnotherDevice=2]="AudioJoinedFromAnotherDevice",e[e.AudioAuthenticationRejected=3]="AudioAuthenticationRejected",e[e.AudioCallAtCapacity=4]="AudioCallAtCapacity",e[e.MeetingEnded=5]="MeetingEnded",e[e.AudioInternalServerError=6]="AudioInternalServerError",e[e.AudioServiceUnavailable=7]="AudioServiceUnavailable",e[e.AudioDisconnected=8]="AudioDisconnected",e[e.VideoCallSwitchToViewOnly=9]="VideoCallSwitchToViewOnly",e[e.VideoCallAtSourceCapacity=10]="VideoCallAtSourceCapacity",e[e.SignalingBadRequest=11]="SignalingBadRequest",e[e.SignalingInternalServerError=12]="SignalingInternalServerError",e[e.SignalingRequestFailed=13]="SignalingRequestFailed",e[e.ICEGatheringTimeoutWorkaround=14]="ICEGatheringTimeoutWorkaround",e[e.ConnectionHealthReconnect=15]="ConnectionHealthReconnect",e[e.RealtimeApiFailed=16]="RealtimeApiFailed",e[e.TaskFailed=17]="TaskFailed",e[e.IncompatibleSDP=18]="IncompatibleSDP",e[e.TURNCredentialsForbidden=19]="TURNCredentialsForbidden",e[e.NoAttendeePresent=20]="NoAttendeePresent",e[e.AudioAttendeeRemoved=21]="AudioAttendeeRemoved",e[e.AudioVideoWasRemovedFromPrimaryMeeting=22]="AudioVideoWasRemovedFromPrimaryMeeting",e[e.AudioDisconnectAudio=23]="AudioDisconnectAudio"}(n=t.MeetingSessionStatusCode||(t.MeetingSessionStatusCode={})),t.default=n},692:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.username=null,this.password=null,this.ttl=null,this.uris=null}}},7385:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this._audioHostURL=null,this._signalingURL=null,this._turnControlURL=null,this._eventIngestionURL=null,this.urlRewriter=e=>e}get audioHostURL(){return this.urlRewriter(this._audioHostURL)}set audioHostURL(e){this._audioHostURL=e}get signalingURL(){return this.urlRewriter(this._signalingURL)}set signalingURL(e){this._signalingURL=e}get turnControlURL(){return this.urlRewriter(this._turnControlURL)}set turnControlURL(e){this._turnControlURL=e}get eventIngestionURL(){return this.urlRewriter(this._eventIngestionURL)}set eventIngestionURL(e){this._eventIngestionURL=e}}},1835:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n{constructor(){this.remoteVideoAvailable=!1,this.canStartLocalVideo=!1}equal(e){return this.remoteVideoAvailable===e.remoteVideoAvailable&&this.canStartLocalVideo===e.canStartLocalVideo}clone(){const e=new n;return e.remoteVideoAvailable=this.remoteVideoAvailable,e.canStartLocalVideo=this.canStartLocalVideo,e}}t.default=n},2636:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t,n){this.type=e,this.headers=t,this.payload=n}}},5528:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=n(6901),o=r(n(3306)),s=r(n(205)),c=r(n(2636)),l=r(n(822)),d=r(n(4185)),u=r(n(8854)),f=r(n(388)),h=r(n(4696)),m=r(n(2335));t.default=class{constructor(e,t,n,i,r){this.configuration=e,this.logger=t,this.webSocket=n,this.reconnectController=i,this.sigV4=r,this.observerQueue=new Set,this.webSocket||(this.webSocket=new f.default(this.logger)),this.reconnectController||(this.reconnectController=new l.default(e.reconnectTimeoutMs,new o.default(e.reconnectFixedWaitMs,e.reconnectShortBackoffMs,e.reconnectLongBackoffMs))),this.sigV4||(this.sigV4=new u.default(this.configuration.chimeClient)),s.default.addLogger(this.logger),s.default.register(),this.preBootstrapMessages=[]}addObserver(e){this.logger.info("adding messaging observer"),this.observerQueue.add(e)}removeObserver(e){this.logger.info("removing messaging observer"),this.observerQueue.delete(e)}start(){return i(this,void 0,void 0,(function*(){this.isClosed()?yield this.startConnecting(!1):this.logger.info("messaging session already started")}))}stop(){this.isClosed()?this.logger.info("no existing messaging session needs closing"):(this.isClosing=!0,this.webSocket.close(),s.default.removeLogger(this.logger))}forEachObserver(e){for(const t of this.observerQueue)d.default.nextTick((()=>{this.observerQueue.has(t)&&e(t)}))}setUpEventListeners(){this.webSocket.addEventListener("open",(()=>{this.openEventHandler()})),this.webSocket.addEventListener("message",(e=>{this.receiveMessageHandler(e.data)})),this.webSocket.addEventListener("close",(e=>{this.closeEventHandler(e)})),this.webSocket.addEventListener("error",(()=>{this.logger.error("WebSocket error")}))}startConnecting(e){return i(this,void 0,void 0,(function*(){return yield this.startConnectingInternal(e),yield new Promise(((e,t)=>{this.bootstrapResolved=e,this.bootstrapRejected=t}))}))}startConnectingInternal(e){var t;return i(this,void 0,void 0,(function*(){let n=this.configuration.endpointUrl;if(e||this.reconnectController.reset(),this.reconnectController.hasStartedConnectionAttempt()?this.reconnectController.startedConnectionAttempt(!1):this.reconnectController.startedConnectionAttempt(!0),e||void 0===n)try{if(this.configuration.chimeClient.getMessagingSessionEndpoint instanceof Function){const e=yield this.configuration.chimeClient.getMessagingSessionEndpoint();n=(null===(t=e.Endpoint)||void 0===t?void 0:t.Url)?e.Endpoint.Url:(yield this.configuration.chimeClient.getMessagingSessionEndpoint().promise()).Endpoint.Url}else n=(yield this.configuration.chimeClient.send(new a.GetMessagingSessionEndpointCommand({}))).Endpoint.Url;this.logger.debug(`Messaging endpoint resolved to: ${n}`)}catch(e){this.logger.error(`Messaging Session failed to resolve endpoint: ${e}`);const t=new CloseEvent("close",{wasClean:!1,code:4999,reason:"Failed to get messaging session endpoint URL",bubbles:!1});return void this.closeEventHandler(t)}const i=yield this.prepareWebSocketUrl(n);this.logger.info(`opening connection to ${i}`),e||this.reconnectController.reset(),this.reconnectController.hasStartedConnectionAttempt()?this.reconnectController.startedConnectionAttempt(!1):this.reconnectController.startedConnectionAttempt(!0),this.webSocket.create(i,[],!0),this.forEachObserver((t=>{t.messagingSessionDidStartConnecting&&t.messagingSessionDidStartConnecting(e)})),this.setUpEventListeners()}))}prepareWebSocketUrl(e){return i(this,void 0,void 0,(function*(){const t=new Map;return t.set("userArn",[this.configuration.userArn]),t.set("sessionId",[this.configuration.messagingSessionId]),this.configuration.prefetchOn===m.default.Connect&&t.set("prefetch-on",[m.default.Connect]),this.configuration.prefetchSortBy&&t.set("prefetch-sort-by",[this.configuration.prefetchSortBy]),yield this.sigV4.signURL("GET","wss","chime",e,"/connect","",t)}))}isClosed(){return this.webSocket.readyState()===h.default.None||this.webSocket.readyState()===h.default.Closed}openEventHandler(){this.reconnectController.reset(),this.isSessionEstablished=!1}receiveMessageHandler(e){try{const t=JSON.parse(e),n=t.Headers["x-amz-chime-event-type"],i=new c.default(n,t.Headers,t.Payload||null);if(this.isSessionEstablished||"SESSION_ESTABLISHED"!==n){if(!this.isSessionEstablished)return void this.preBootstrapMessages.push(i)}else{this.forEachObserver((e=>{e.messagingSessionDidStart&&e.messagingSessionDidStart()})),this.bootstrapResolved(),this.isSessionEstablished=!0;const e=this.preBootstrapMessages.length;for(let t=0;t{this.sendMessageToObserver(t,e)}))}}this.forEachObserver((e=>{this.sendMessageToObserver(e,i)}))}catch(e){this.logger.error(`Messaging parsing failed: ${e}`)}}sendMessageToObserver(e,t){e.messagingSessionDidReceiveMessage&&e.messagingSessionDidReceiveMessage(t)}retryConnection(){return this.reconnectController.retryWithBackoff((()=>i(this,void 0,void 0,(function*(){yield this.startConnecting(!0)}))),null)}closeEventHandler(e){this.logger.info(`WebSocket close: ${e.code} ${e.reason}`),4999!==e.code&&this.webSocket.destroy(),!this.isClosing&&this.canReconnect(e.code)&&this.retryConnection()||(this.isClosing=!1,this.isSessionEstablished?this.forEachObserver((t=>{t.messagingSessionDidStop&&t.messagingSessionDidStop(e)})):this.bootstrapRejected(e))}canReconnect(e){return 1001===e||1006===e||e>=1011&&e<=1014||e>4e3&&4002!==e&&4003!==e&&4401!==e}}},8035:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9979);t.default=class{constructor(e,t,n,i){this.userArn=e,this.messagingSessionId=t,this.endpointUrl=n,this.chimeClient=i,this.reconnectTimeoutMs=1e4,this.reconnectFixedWaitMs=0,this.reconnectShortBackoffMs=1e3,this.reconnectLongBackoffMs=5e3,this.prefetchOn=void 0,this.prefetchSortBy=void 0,this.messagingSessionId||(this.messagingSessionId=this.generateSessionId())}generateSessionId(){const e=new Uint32Array(1);return i.getRandomValues(e),e[0].toString()}}},2335:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Connect="connect"}(n||(n={})),t.default=n},2303:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.Unread="unread",e.LastMessageTimestamp="last-message-timestamp"}(n||(n={})),t.default=n},832:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(5100));class a{constructor(e){this._id=e}id(){return this._id}base(){return this._id?this._id.split(a.MODALITY_SEPARATOR)[0]:""}modality(){if(!this._id)return"";const e=this._id.split(a.MODALITY_SEPARATOR);return 2===e.length?e[1]:""}hasModality(e){return""!==e&&this.modality()===e}withModality(e){const t=new a(this.base()+a.MODALITY_SEPARATOR+e);return""===e||""===this.base()||new a(t._id).modality()!==e?new a(this.base()):t}}t.default=a,a.MODALITY_SEPARATOR=r.default.Modality[0],a.MODALITY_CONTENT=r.default.Modality.substr(1)},4428:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(4185)),a=i(n(8192)),o=i(n(9183)),s=n(4955),c=n(8807);t.default=class{constructor(e,t,n){this.signalingClient=e,this.intervalMs=t,this.logger=n,this.observerQueue=new Set,this.consecutivePongsUnaccountedFor=0,this.intervalScheduler=new a.default(this.intervalMs),this.pingId=0}addObserver(e){this.logger.info("adding a ping-pong observer"),this.observerQueue.add(e)}removeObserver(e){this.logger.info("removing a ping-pong observer"),this.observerQueue.delete(e)}forEachObserver(e){for(const t of this.observerQueue)r.default.nextTick((()=>{this.observerQueue.has(t)&&e(t)}))}start(){this.stop(),this.signalingClient.registerObserver(this),this.signalingClient.ready()&&this.startPingInterval()}stop(){this.stopPingInterval(),this.signalingClient.removeObserver(this)}startPingInterval(){this.intervalScheduler.start((()=>{this.ping()})),this.ping()}stopPingInterval(){this.intervalScheduler.stop(),this.pingId=0,this.consecutivePongsUnaccountedFor=0}ping(){this.consecutivePongsUnaccountedFor>0&&(this.logger.warn(`missed pong ${this.consecutivePongsUnaccountedFor} time(s)`),this.forEachObserver((e=>{c.Maybe.of(e.didMissPongs).map((t=>t.bind(e)(this.consecutivePongsUnaccountedFor)))}))),this.consecutivePongsUnaccountedFor+=1,this.pingId=this.pingId+1&4294967295;const e=s.SdkPingPongFrame.create();e.pingId=this.pingId,e.type=s.SdkPingPongType.PING,this.pingTimestampLocalMs=this.signalingClient.pingPong(e),this.logger.debug((()=>`sent ping ${this.pingId}`))}pong(e){const t=s.SdkPingPongFrame.create();t.pingId=e,t.type=s.SdkPingPongType.PONG,this.signalingClient.pingPong(t)}handleSignalingClientEvent(e){switch(e.type){case o.default.WebSocketOpen:this.startPingInterval();break;case o.default.WebSocketFailed:case o.default.WebSocketError:this.logger.warn(`stopped pinging (${o.default[e.type]})`),this.stopPingInterval();break;case o.default.WebSocketClosing:case o.default.WebSocketClosed:this.logger.info(`stopped pinging (${o.default[e.type]})`),this.stopPingInterval();break;case o.default.ReceivedSignalFrame:if(e.message.type!==s.SdkSignalFrame.Type.PING_PONG)break;if(e.message.pingPong.type===s.SdkPingPongType.PONG){const t=e.message.pingPong.pingId;if(t!==this.pingId){this.logger.warn(`unexpected ping id ${t} (expected ${this.pingId})`);break}let n;if(this.consecutivePongsUnaccountedFor=0,"number"!=typeof e.message.timestampMs)break;n=e.message.timestampMs,this.logger.debug((()=>`received pong ${t} with timestamp ${n}`));const i=e.timestampMs-this.pingTimestampLocalMs,r=Math.round(n-i/2),a=this.pingTimestampLocalMs-r;this.logger.info(`local clock skew estimate=${a}ms from ping-pong time=${i}ms`),this.forEachObserver((e=>{c.Maybe.of(e.didReceivePong).map((n=>n.bind(e)(t,a,i)))}))}else this.pong(e.message.pingPong.pingId)}}}},7844:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(1204)),a=i(n(990)),o=i(n(8772));t.default=class{constructor(e,t){this.mediaStreamBroker=e,this.state=new a.default,this._transcriptionController=t||new r.default(this)}realtimeSetLocalAttendeeId(e,t){this.state.localAttendeeId=e,this.state.localExternalUserId=t}realtimeSetAttendeeIdPresence(e,t,n,i,r){try{t&&(this.state.attendeeIdToExternalUserId[e]=n);for(const a of this.state.attendeeIdChangesCallbacks)a(e,t,n,i,r)}catch(e){this.onError(e)}}realtimeSubscribeToAttendeeIdPresence(e){try{this.state.attendeeIdChangesCallbacks.push(e)}catch(e){this.onError(e)}}realtimeUnsubscribeToAttendeeIdPresence(e){try{const t=this.state.attendeeIdChangesCallbacks.indexOf(e);-1!==t&&this.state.attendeeIdChangesCallbacks.splice(t,1)}catch(e){this.onError(e)}}realtimeSetCanUnmuteLocalAudio(e){try{if(this.state.canUnmute===e)return;this.state.canUnmute=e;for(const t of this.state.setCanUnmuteLocalAudioCallbacks)t(e)}catch(e){this.onError(e)}}realtimeSubscribeToSetCanUnmuteLocalAudio(e){try{this.state.setCanUnmuteLocalAudioCallbacks.push(e)}catch(e){this.onError(e)}}realtimeUnsubscribeToSetCanUnmuteLocalAudio(e){try{const t=this.state.setCanUnmuteLocalAudioCallbacks.indexOf(e);-1!==t&&this.state.setCanUnmuteLocalAudioCallbacks.splice(t,1)}catch(e){this.onError(e)}}realtimeCanUnmuteLocalAudio(){return this.state.canUnmute}realtimeMuteLocalAudio(){if(!this.state.muted)try{this.setAudioInputEnabled(!1),this.state.muted=!0,this.realtimeUpdateVolumeIndicator(this.state.localAttendeeId,null,null,null,this.state.localExternalUserId);for(const e of this.state.muteAndUnmuteLocalAudioCallbacks)e(!0)}catch(e){this.onError(e)}}realtimeUnmuteLocalAudio(){if(!this.state.muted)return!0;if(!this.state.canUnmute)return!1;try{this.setAudioInputEnabled(!0),this.state.muted=!1,this.realtimeUpdateVolumeIndicator(this.state.localAttendeeId,null,null,null,this.state.localExternalUserId);for(const e of this.state.muteAndUnmuteLocalAudioCallbacks)e(!1);return!0}catch(e){return this.onError(e),!1}}realtimeSubscribeToMuteAndUnmuteLocalAudio(e){try{this.state.muteAndUnmuteLocalAudioCallbacks.push(e)}catch(e){this.onError(e)}}realtimeUnsubscribeToMuteAndUnmuteLocalAudio(e){try{const t=this.state.muteAndUnmuteLocalAudioCallbacks.indexOf(e);-1!==t&&this.state.muteAndUnmuteLocalAudioCallbacks.splice(t,1)}catch(e){this.onError(e)}}realtimeIsLocalAudioMuted(){return this.state.muted}realtimeSubscribeToVolumeIndicator(e,t){try{this.state.volumeIndicatorCallbacks.hasOwnProperty(e)||(this.state.volumeIndicatorCallbacks[e]=[]),this.state.volumeIndicatorCallbacks[e].push(t),this.sendVolumeIndicatorChange(e,!0,!0,!0,this.state.attendeeIdToExternalUserId[e])}catch(e){this.onError(e)}}realtimeUnsubscribeFromVolumeIndicator(e,t){if(this.state.volumeIndicatorCallbacks[e])if(t){const n=this.state.volumeIndicatorCallbacks[e].indexOf(t);n>=0&&this.state.volumeIndicatorCallbacks[e].splice(n,1)}else delete this.state.volumeIndicatorCallbacks[e]}realtimeUpdateVolumeIndicator(e,t,n,i,r){try{n=this.applyLocalMuteOverride(e,n);const a=this.getVolumeIndicatorState(e);let o=!1,s=!1,c=!1;null!==n&&a.muted!==n&&(a.muted=n,s=!0,a.muted&&0!==a.volume&&(a.volume=0,o=!0)),a.muted||null===t||(a.volume!==t&&(a.volume=t,o=!0),null===a.muted&&(a.muted=!1,s=!0)),null!==i&&a.signalStrength!==i&&(a.signalStrength=i,c=!0),this.sendVolumeIndicatorChange(e,o,s,c,r)}catch(e){this.onError(e)}}realtimeSubscribeToLocalSignalStrengthChange(e){try{if(this.state.localSignalStrengthChangeCallbacks.push(e),null===this.state.localAttendeeId)return;this.sendLocalSignalStrengthChange(this.state.localAttendeeId,!0)}catch(e){this.onError(e)}}realtimeUnsubscribeToLocalSignalStrengthChange(e){try{const t=this.state.localSignalStrengthChangeCallbacks.indexOf(e);-1!==t&&this.state.localSignalStrengthChangeCallbacks.splice(t,1)}catch(e){this.onError(e)}}realtimeSubscribeToSendDataMessage(e){try{this.state.sendDataMessageCallbacks.push(e)}catch(e){this.onError(e)}}realtimeUnsubscribeFromSendDataMessage(e){try{const t=this.state.sendDataMessageCallbacks.indexOf(e);-1!==t&&this.state.sendDataMessageCallbacks.splice(t,1)}catch(e){this.onError(e)}}realtimeSendDataMessage(e,t,n){try{for(const i of this.state.sendDataMessageCallbacks)i(e,t,n)}catch(e){this.onError(e)}}realtimeSubscribeToReceiveDataMessage(e,t){try{this.state.receiveDataMessageCallbacks.has(e)?this.state.receiveDataMessageCallbacks.get(e).push(t):this.state.receiveDataMessageCallbacks.set(e,[t])}catch(e){this.onError(e)}}realtimeUnsubscribeFromReceiveDataMessage(e){try{this.state.receiveDataMessageCallbacks.delete(e)}catch(e){this.onError(e)}}realtimeReceiveDataMessage(e){try{if(this.state.receiveDataMessageCallbacks.has(e.topic))for(const t of this.state.receiveDataMessageCallbacks.get(e.topic))t(e)}catch(e){this.onError(e)}}realtimeSubscribeToFatalError(e){try{this.state.fatalErrorCallbacks.push(e)}catch(e){this.onError(e)}}realtimeUnsubscribeToFatalError(e){try{const t=this.state.fatalErrorCallbacks.indexOf(e);-1!==t&&this.state.fatalErrorCallbacks.splice(t,1)}catch(e){this.onError(e)}}get transcriptionController(){return this._transcriptionController}setAudioInputEnabled(e){e?this.mediaStreamBroker.unmuteLocalAudioInputStream():this.mediaStreamBroker.muteLocalAudioInputStream()}applyLocalMuteOverride(e,t){const n=this.state.localAttendeeId,i=this.state.muted;return e!==n?t:"activeDevices"in this.mediaStreamBroker&&this.mediaStreamBroker.activeDevices.audio?i:t}sendVolumeIndicatorChange(e,t,n,i,r){if(this.sendLocalSignalStrengthChange(e,i),!this.state.volumeIndicatorCallbacks.hasOwnProperty(e))return;const a=this.getVolumeIndicatorState(e),s=new o.default;if(t&&(s.volume=a.volume),n&&(s.muted=a.muted),i&&(s.signalStrength=a.signalStrength),!this.stateIsEmpty(s))for(const t of this.state.volumeIndicatorCallbacks[e])t(e,s.volume,s.muted,s.signalStrength,r)}sendLocalSignalStrengthChange(e,t){if(!t)return;if(e!==this.state.localAttendeeId)return;const n=this.getVolumeIndicatorState(e).signalStrength;if(null!==n)for(const e of this.state.localSignalStrengthChangeCallbacks)e(n)}getVolumeIndicatorState(e){return this.state.volumeIndicatorState.hasOwnProperty(e)||(this.state.volumeIndicatorState[e]=new o.default),this.state.volumeIndicatorState[e]}stateIsEmpty(e){return null===e.volume&&null===e.muted&&null===e.signalStrength}onError(e){try{for(const t of this.state.fatalErrorCallbacks)t(e)}catch(t){try{console.error(e),console.error(t)}catch(e){}}}}},9384:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.attendeeIndex=null,this.attendeesInFrame=null}}},990:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.localAttendeeId=null,this.localExternalUserId=null,this.attendeeIdChangesCallbacks=[],this.canUnmute=!0,this.setCanUnmuteLocalAudioCallbacks=[],this.muted=!1,this.muteAndUnmuteLocalAudioCallbacks=[],this.volumeIndicatorState={},this.attendeeIdToExternalUserId={},this.volumeIndicatorCallbacks={},this.localSignalStrengthChangeCallbacks=[],this.fatalErrorCallbacks=[],this.sendDataMessageCallbacks=[],this.receiveDataMessageCallbacks=new Map}}},8772:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.volume=null,this.muted=null,this.signalStrength=null}}},822:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(1340));class a{constructor(e,t){this.reconnectTimeoutMs=e,this.backoffPolicy=t,this.shouldReconnect=!0,this.onlyRestartPeerConnection=!1,this.firstConnectionAttempted=!1,this.firstConnectionAttemptTimestampMs=0,this.lastActiveTimestampMs=1/0,this._isFirstConnection=!0,this.backoffTimer=null,this.backoffCancel=null,this.reset()}timeSpentReconnectingMs(){return this.firstConnectionAttempted?Date.now()-this.firstConnectionAttemptTimestampMs:0}hasPastReconnectDeadline(){return Date.now()-this.lastActiveTimestampMs>=this.reconnectTimeoutMs||this.timeSpentReconnectingMs()>=this.reconnectTimeoutMs}reset(){this.cancel(),this.shouldReconnect=!0,this.onlyRestartPeerConnection=!1,this.firstConnectionAttempted=!1,this.firstConnectionAttemptTimestampMs=0,this.lastActiveTimestampMs=1/0,this.backoffPolicy.reset()}startedConnectionAttempt(e){this._isFirstConnection=e,this.firstConnectionAttempted||(this.firstConnectionAttempted=!0,this.firstConnectionAttemptTimestampMs=Date.now())}hasStartedConnectionAttempt(){return this.firstConnectionAttempted}isFirstConnection(){return this._isFirstConnection}disableReconnect(){this.shouldReconnect=!1}enableRestartPeerConnection(){this.onlyRestartPeerConnection=!0}cancel(){this.disableReconnect(),this.backoffTimer&&(this.backoffTimer.stop(),this.backoffCancel&&(this.backoffCancel(),this.backoffCancel=null))}retryWithBackoff(e,t){const n=this.shouldReconnect&&!this.hasPastReconnectDeadline();return n&&(this.backoffCancel=t,this.backoffTimer=new r.default(this.backoffPolicy.nextBackoffAmountMs()),this.backoffTimer.start((()=>{this.backoffCancel=null,e()}))),n}shouldOnlyRestartPeerConnection(){return this.onlyRestartPeerConnection}clone(){return new a(this.reconnectTimeoutMs,this.backoffPolicy)}setLastActiveTimestampMs(e){this.lastActiveTimestampMs=e}}t.default=a},5687:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n{constructor(){this.maxRedPacketSizeBytes=1024,this.maxAudioPayloadSizeBytes=1e3,this.maxRedTimestampOffset=16384,this.redHeaderSizeBytes=4,this.redLastHeaderSizeBytes=1,this.redPacketizationTime=960,this.redPacketDistance=2,this.maxRedEncodings=2,this.redMaxRecoveryDistance=this.redPacketDistance*this.maxRedEncodings+1,this.maxEncodingHistorySize=10,this.numRedundantEncodings=0,this.redundancyEnabled=!0,this.lossReportInterval=24e4,this.maxOutOfOrderPacketDistance=16,this.OPUS_BAD_ARG=-1,this.OPUS_INVALID_PACKET=-4,this.OPUS_MAX_OPUS_FRAMES=48,this.OPUS_MAX_FRAME_SIZE_BYTES=1275,this.encodingHistory=new Array,this.opusPayloadType=0,this.redPayloadType=0,this.initializePacketLogs()}static initializeWorker(){n.log("Initializing RedundantAudioEncoder");const e=new n;self.RTCRtpScriptTransformer&&(self.onrtctransform=t=>{"SenderTransform"===t.transformer.options.type?e.setupSenderTransform(t.transformer.readable,t.transformer.writable):"ReceiverTransform"===t.transformer.options.type?e.setupReceiverTransform(t.transformer.readable,t.transformer.writable):"PassthroughTransform"===t.transformer.options.type&&e.setupPassthroughTransform(t.transformer.readable,t.transformer.writable)}),self.onmessage=t=>{"StartRedWorker"===t.data.msgType?(e.setupSenderTransform(t.data.send.readable,t.data.send.writable),e.setupReceiverTransform(t.data.receive.readable,t.data.receive.writable)):"PassthroughTransform"===t.data.msgType?(e.setupPassthroughTransform(t.data.send.readable,t.data.send.writable),e.setupPassthroughTransform(t.data.receive.readable,t.data.receive.writable)):"RedPayloadType"===t.data.msgType?e.setRedPayloadType(t.data.payloadType):"OpusPayloadType"===t.data.msgType?e.setOpusPayloadType(t.data.payloadType):"UpdateNumRedundantEncodings"===t.data.msgType?e.setNumRedundantEncodings(t.data.numRedundantEncodings):"Enable"===t.data.msgType?e.setRedundancyEnabled(!0):"Disable"===t.data.msgType&&e.setRedundancyEnabled(!1)}}static log(e){n.shouldLog&&self.postMessage({type:"REDWorkerLog",log:`[AudioRed] ${e}`})}static getNumRedundantEncodingsForPacketLoss(e){let t=0,n=!1;return e<=8?t=0:e<=18?t=1:e<=75?t=2:(t=0,n=!0),[t,n]}setupPassthroughTransform(e,t){n.log("Setting up passthrough transform"),e.pipeTo(t)}setupSenderTransform(e,t){n.log("Setting up sender RED transform");const i=new TransformStream({transform:this.senderTransform.bind(this)});e.pipeThrough(i).pipeTo(t)}setupReceiverTransform(e,t){n.log("Setting up receiver RED transform");const i=new TransformStream({transform:this.receivePacketLogTransform.bind(this)});e.pipeThrough(i).pipeTo(t)}setRedPayloadType(e){this.redPayloadType=e,n.log(`red payload type set to ${this.redPayloadType}`)}setOpusPayloadType(e){this.opusPayloadType=e,n.log(`opus payload type set to ${this.opusPayloadType}`)}setNumRedundantEncodings(e){this.numRedundantEncodings=e,this.numRedundantEncodings>this.maxRedEncodings&&(this.numRedundantEncodings=this.maxRedEncodings),n.log(`Updated numRedundantEncodings to ${this.numRedundantEncodings}`)}setRedundancyEnabled(e){this.redundancyEnabled=e,n.log("redundancy "+(this.redundancyEnabled?"enabled":"disabled"))}enqueueAudioFrameIfPayloadSizeIsValid(e,t){e.data.byteLength>this.maxAudioPayloadSizeBytes||t.enqueue(e)}senderTransform(e,t){if(e.getMetadata().payloadType!==this.redPayloadType)return void this.enqueueAudioFrameIfPayloadSizeIsValid(e,t);const n=this.getPrimaryPayload(e.timestamp,e.data);if(!n)return void this.enqueueAudioFrameIfPayloadSizeIsValid(e,t);const i=this.encode(e.timestamp,n);i?(e.data=i,this.enqueueAudioFrameIfPayloadSizeIsValid(e,t)):this.enqueueAudioFrameIfPayloadSizeIsValid(e,t)}getPrimaryPayload(e,t){const n=this.splitEncodings(e,t);return!n||n.length<1?null:n[n.length-1].payload}splitEncodings(e,t,n=!1,i=void 0){const r=new DataView(t);let a=r.byteLength,o=0,s=0,c=0,l=0,d=!1;const u=new Array,f=new Array,h=new Array;for(;a>0;){if(d=0==(128&r.getUint8(l)),d){if((127&r.getUint8(l))!==this.opusPayloadType)return null;if(o+=this.redLastHeaderSizeBytes,s+=this.redLastHeaderSizeBytes,o>=r.byteLength)return null;c=r.byteLength-o;break}{if(a>2);h.push(n),o+=t+this.redHeaderSizeBytes,s+=this.redHeaderSizeBytes,l+=this.redHeaderSizeBytes,a-=this.redHeaderSizeBytes}}if(!d)return null;let m=s;for(let e=0;e=this.maxRedPacketSizeBytes||n>=this.maxAudioPayloadSizeBytes)return null;const i=this.numRedundantEncodings;let r=this.redLastHeaderSizeBytes,a=n,o=this.maxAudioPayloadSizeBytes-n-r;const s=new Array,c=new Array;if(this.redundancyEnabled){let t=this.uint32WrapAround(e-this.redPacketizationTime*this.redPacketDistance);for(let n=0;n=this.maxRedTimestampOffset);n++){let e=t,n=this.encodingHistory.find((t=>t.timestamp===e));if(n||(e=this.uint32WrapAround(t-this.redPacketizationTime),n=this.encodingHistory.find((t=>t.timestamp===e))),n){const e=n.payload.byteLength;if(o>8),d.setUint8(u+3,255&c[t].byteLength),u+=this.redHeaderSizeBytes}d.setUint8(u,this.opusPayloadType),u+=this.redLastHeaderSizeBytes;const f=new Uint8Array(l);for(let e=0;e=n))break;this.encodingHistory.shift()}const n=new DataView(t);(this.opusPacketIsCeltOnly(n)||this.opusPacketHasVoiceActivity(n,n.byteLength)>0)&&(this.encodingHistory.length+1>this.maxEncodingHistorySize&&(this.encodingHistory.length=0),this.encodingHistory.push({timestamp:e,payload:t}))}initializePacketLogs(){const e=this.maxOutOfOrderPacketDistance+this.redMaxRecoveryDistance;this.primaryPacketLog={window:new Array(e),index:0,windowSize:e},this.redRecoveryLog={window:new Array(e),index:0,windowSize:e},this.fecRecoveryLog={window:new Array(e),index:0,windowSize:e},this.totalAudioPacketsExpected=0,this.totalAudioPacketsLost=0,this.totalAudioPacketsRecoveredRed=0,this.totalAudioPacketsRecoveredFec=0}receivePacketLogTransform(e,t){const n=e.getMetadata();if(n.payloadType!==this.redPayloadType)return void this.enqueueAudioFrameIfPayloadSizeIsValid(e,t);const i=this.splitEncodings(e.timestamp,e.data,!0,n.sequenceNumber);if(i){for(let e=i.length-1;e>=0;e--)this.updateLossStats(i[e])&&(this.updateRedStats(i[e]),this.updateFecStats(i[e]));this.maybeReportLossStats(i[i.length-1].timestamp,n.synchronizationSource),this.enqueueAudioFrameIfPayloadSizeIsValid(e,t)}else this.enqueueAudioFrameIfPayloadSizeIsValid(e,t)}updateLossStats(e){if(e.isRedundant)return!0;const t=e.timestamp,n=e.seq;if(0===this.totalAudioPacketsExpected)return this.totalAudioPacketsExpected=1,this.newestSequenceNumber=n,this.addTimestamp(this.primaryPacketLog,t),!0;const i=this.int16(n-this.newestSequenceNumber);return!(i<-this.maxOutOfOrderPacketDistance||(i<0?this.hasTimestamp(this.primaryPacketLog,t)||(this.totalAudioPacketsLost>0&&this.totalAudioPacketsLost--,this.addTimestamp(this.primaryPacketLog,t),this.removeFromRecoveryWindows(t)):i>1&&(this.totalAudioPacketsLost+=i-1),i>0&&(this.totalAudioPacketsExpected+=i,this.newestSequenceNumber=e.seq,this.addTimestamp(this.primaryPacketLog,t)),0))}updateRedStats(e){if(!e.isRedundant||0===this.totalAudioPacketsLost)return;const t=e.timestamp;this.hasTimestamp(this.primaryPacketLog,t)||(this.hasTimestamp(this.redRecoveryLog,t)||(this.totalAudioPacketsRecoveredRed++,this.addTimestamp(this.redRecoveryLog,t)),this.removeTimestamp(this.fecRecoveryLog,t)&&this.totalAudioPacketsRecoveredFec>0&&this.totalAudioPacketsRecoveredFec--)}updateFecStats(e){if(!e.hasFec||0===this.totalAudioPacketsLost)return;const t=e.timestamp-this.redPacketizationTime;this.hasTimestamp(this.primaryPacketLog,t)||this.hasTimestamp(this.redRecoveryLog,t)||this.hasTimestamp(this.fecRecoveryLog,t)||(this.totalAudioPacketsRecoveredFec++,this.addTimestamp(this.fecRecoveryLog,t))}maybeReportLossStats(e,t){e-this.lastLossReportTimestampe===t))}removeTimestamp(e,t){const n=e.window.indexOf(t);return n>=0&&(e.window[n]=void 0,!0)}removeFromRecoveryWindows(e){let t=this.removeTimestamp(this.redRecoveryLog,e);t&&this.totalAudioPacketsRecoveredRed>0&&this.totalAudioPacketsRecoveredRed--,t=this.removeTimestamp(this.fecRecoveryLog,e),t&&this.totalAudioPacketsRecoveredFec>0&&this.totalAudioPacketsRecoveredFec--}uint32WrapAround(e){const t=4294967296;let n=e;return e>=t?n=e-t:e<0&&(n=t+e),n}int16(e){return e<<16>>16}opusPacketIsCeltOnly(e){return!!(128&e.getUint8(0))}opusPacketGetSamplesPerFrame(e,t){let n,i;return t=Math.round(t),t=Math.min(Math.max(t,-Math.pow(2,32)),Math.pow(2,32)-1),this.opusPacketIsCeltOnly(e)?(i=e.getUint8(0)>>3&3,n=(t<>3&3,n=3===i?60*t/1e3:(t<h)return this.OPUS_INVALID_PACKET;m+=l,p=h-a[0][0];break;default:if(h<1)return this.OPUS_INVALID_PACKET;const t=e.getUint8(m++);if(--h,c=63&t,c<=0)return this.OPUS_INVALID_PACKET;if(this.opusPacketGetSamplesPerFrame(e,48e3)*c>5760)return this.OPUS_INVALID_PACKET;if(64&t){let t,n;do{if(h<=0)return this.OPUS_INVALID_PACKET;t=e.getUint8(m++),--h,n=255===t?254:t,h-=n,d+=n}while(255===t)}if(h<0)return this.OPUS_INVALID_PACKET;if(u=!(128&t),u){if(!n){if(p=Math.trunc(h/c),p*c!==h)return this.OPUS_INVALID_PACKET;for(let e=0;eh)return this.OPUS_INVALID_PACKET;m+=l,p-=l+a[t][0]}if(p<0)return this.OPUS_INVALID_PACKET}}if(n){if(l=this.opusParseSize(e,m,h,a[c-1]),h-=l,a[c-1][0]<0||a[c-1][0]>h)return this.OPUS_INVALID_PACKET;if(m+=l,u){if(a[c-1][0]*c>h)return this.OPUS_INVALID_PACKET;for(let e=0;ethis.OPUS_MAX_FRAME_SIZE_BYTES)return this.OPUS_INVALID_PACKET;a[c-1][0]=p}o&&(o[0]=m);for(let e=0;e>8-n)return 1;if(2===this.opusPacketGetNumChannels(e)&&e.getUint8(i[t][0])<>8-n)return 1}return 0}opusPacketHasFec(e,t){if(!e||t<=0)return!1;if(this.opusPacketIsCeltOnly(e))return!1;const n=new Array(this.OPUS_MAX_OPUS_FRAMES),i=new Array(this.OPUS_MAX_OPUS_FRAMES);for(let e=0;e>(t+1)*(r+1)-1)return!0;return!1}}t.default=n,n.shouldLog=!1,n.shouldReportStats=!1},551:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default="class RedundantAudioEncoder {\n constructor() {\n // Each payload must be less than 1024 bytes to fit the 10 bit block length\n this.maxRedPacketSizeBytes = 1 << 10;\n // Limit payload to 1000 bytes to handle small MTU. 1000 is chosen because in Chromium-based browsers, writing audio\n // payloads larger than 1000 bytes using the WebRTC Insertable Streams API (which is used to enable dynamic audio\n // redundancy) will cause an error to be thrown and cause audio flow to permanently stop. See\n // https://crbug.com/1248479.\n this.maxAudioPayloadSizeBytes = 1000;\n // Each payload can encode a timestamp delta of 14 bits\n this.maxRedTimestampOffset = 1 << 14;\n // 4 byte RED header\n this.redHeaderSizeBytes = 4;\n // reduced size for last RED header\n this.redLastHeaderSizeBytes = 1;\n // P-Time for Opus 20 msec packets\n // We do not support other p-times or clock rates\n this.redPacketizationTime = 960;\n // distance between redundant payloads, Opus FEC handles a distance of 1\n // TODO(https://issues.amazon.com/issues/ChimeSDKAudio-55):\n // Consider making this dynamic\n this.redPacketDistance = 2;\n // maximum number of redundant payloads per RTP packet\n this.maxRedEncodings = 2;\n // Maximum number of encodings that can be recovered with a single RED packet, assuming the primary and redundant\n // payloads have FEC.\n this.redMaxRecoveryDistance = this.redPacketDistance * this.maxRedEncodings + 1;\n // maximum history of prior payloads to keep\n // generally we will expire old entries based on timestamp\n // this limit is in place just to make sure the history does not\n // grow too large in the case of erroneous timestamp inputs\n this.maxEncodingHistorySize = 10;\n // Current number of encodings we want to send\n // to the remote end. This will be dynamically\n // updated through the setNumEncodingsFromPacketloss API\n this.numRedundantEncodings = 0;\n // Used to enable or disable redundancy\n // in response to very high packet loss events\n this.redundancyEnabled = true;\n // Loss stats are reported to the main thread every 5 seconds.\n // Since timestamp differences between 2 consecutive packets\n // give us the number of samples in each channel, 1 second\n // is equivalent to 48000 samples:\n // P-time * (1000ms/1s)\n // = (960 samples/20ms) * (1000ms/1s)\n // = 48000 samples/s\n this.lossReportInterval = 48000 * 5;\n // Maximum distance of a packet from the most recent packet timestamp\n // that we will consider for recovery.\n this.maxOutOfOrderPacketDistance = 16;\n /**\n * Below are Opus helper methods and constants.\n */\n this.OPUS_BAD_ARG = -1;\n this.OPUS_INVALID_PACKET = -4;\n // Max number of Opus frames in an Opus packet is 48 (https://www.rfc-editor.org/rfc/rfc6716#section-3.2.5).\n this.OPUS_MAX_OPUS_FRAMES = 48;\n // Max number of bytes that any individual Opus frame can have.\n this.OPUS_MAX_FRAME_SIZE_BYTES = 1275;\n this.encodingHistory = new Array();\n this.opusPayloadType = 0;\n this.redPayloadType = 0;\n this.initializePacketLogs();\n }\n /**\n * Creates an instance of RedundantAudioEncoder and sets up callbacks.\n */\n static initializeWorker() {\n RedundantAudioEncoder.log('Initializing RedundantAudioEncoder');\n const encoder = new RedundantAudioEncoder();\n // RED encoding is done using WebRTC Encoded Transform\n // https://github.com/w3c/webrtc-encoded-transform/blob/main/explainer.md\n // Check the DedicatedWorkerGlobalScope for existence of\n // RTCRtpScriptTransformer interface. If exists, then\n // RTCRtpScriptTransform is supported by this browser.\n // @ts-ignore\n if (self.RTCRtpScriptTransformer) {\n // @ts-ignore\n self.onrtctransform = (event) => {\n if (event.transformer.options.type === 'SenderTransform') {\n encoder.setupSenderTransform(event.transformer.readable, event.transformer.writable);\n }\n else if (event.transformer.options.type === 'ReceiverTransform') {\n encoder.setupReceiverTransform(event.transformer.readable, event.transformer.writable);\n }\n else if (event.transformer.options.type === 'PassthroughTransform') {\n encoder.setupPassthroughTransform(event.transformer.readable, event.transformer.writable);\n }\n };\n }\n self.onmessage = (event) => {\n if (event.data.msgType === 'StartRedWorker') {\n encoder.setupSenderTransform(event.data.send.readable, event.data.send.writable);\n encoder.setupReceiverTransform(event.data.receive.readable, event.data.receive.writable);\n }\n else if (event.data.msgType === 'PassthroughTransform') {\n encoder.setupPassthroughTransform(event.data.send.readable, event.data.send.writable);\n encoder.setupPassthroughTransform(event.data.receive.readable, event.data.receive.writable);\n }\n else if (event.data.msgType === 'RedPayloadType') {\n encoder.setRedPayloadType(event.data.payloadType);\n }\n else if (event.data.msgType === 'OpusPayloadType') {\n encoder.setOpusPayloadType(event.data.payloadType);\n }\n else if (event.data.msgType === 'UpdateNumRedundantEncodings') {\n encoder.setNumRedundantEncodings(event.data.numRedundantEncodings);\n }\n else if (event.data.msgType === 'Enable') {\n encoder.setRedundancyEnabled(true);\n }\n else if (event.data.msgType === 'Disable') {\n encoder.setRedundancyEnabled(false);\n }\n };\n }\n /**\n * Post logs to the main thread\n */\n static log(msg) {\n if (RedundantAudioEncoder.shouldLog) {\n // @ts-ignore\n self.postMessage({\n type: 'REDWorkerLog',\n log: `[AudioRed] ${msg}`,\n });\n }\n }\n /**\n * Returns the number of encodings based on packetLoss value. This is used by `DefaultTransceiverController` to\n * determine when to alert the encoder to update the number of encodings. It also determines if we need to\n * turn off red in cases of very high packet loss to avoid congestion collapse.\n */\n static getNumRedundantEncodingsForPacketLoss(packetLoss) {\n let recommendedRedundantEncodings = 0;\n let shouldTurnOffRed = false;\n if (packetLoss <= 8) {\n recommendedRedundantEncodings = 0;\n }\n else if (packetLoss <= 18) {\n recommendedRedundantEncodings = 1;\n }\n else if (packetLoss <= 75) {\n recommendedRedundantEncodings = 2;\n }\n else {\n recommendedRedundantEncodings = 0;\n shouldTurnOffRed = true;\n }\n return [recommendedRedundantEncodings, shouldTurnOffRed];\n }\n /**\n * Sets up a passthrough (no-op) transform for the given streams.\n */\n setupPassthroughTransform(readable, writable) {\n RedundantAudioEncoder.log('Setting up passthrough transform');\n readable.pipeTo(writable);\n }\n /**\n * Sets up the transform stream and pipes the outgoing encoded audio frames through the transform function.\n */\n setupSenderTransform(readable, writable) {\n RedundantAudioEncoder.log('Setting up sender RED transform');\n const transformStream = new TransformStream({\n transform: this.senderTransform.bind(this),\n });\n readable.pipeThrough(transformStream).pipeTo(writable);\n return;\n }\n /**\n * Sets up the transform stream and pipes the received encoded audio frames through the transform function.\n */\n setupReceiverTransform(readable, writable) {\n RedundantAudioEncoder.log('Setting up receiver RED transform');\n const transformStream = new TransformStream({\n transform: this.receivePacketLogTransform.bind(this),\n });\n readable.pipeThrough(transformStream).pipeTo(writable);\n return;\n }\n /**\n * Set the RED payload type ideally obtained from local offer.\n */\n setRedPayloadType(payloadType) {\n this.redPayloadType = payloadType;\n RedundantAudioEncoder.log(`red payload type set to ${this.redPayloadType}`);\n }\n /**\n * Set the opus payload type ideally obtained from local offer.\n */\n setOpusPayloadType(payloadType) {\n this.opusPayloadType = payloadType;\n RedundantAudioEncoder.log(`opus payload type set to ${this.opusPayloadType}`);\n }\n /**\n * Set the number of redundant encodings\n */\n setNumRedundantEncodings(numRedundantEncodings) {\n this.numRedundantEncodings = numRedundantEncodings;\n if (this.numRedundantEncodings > this.maxRedEncodings) {\n this.numRedundantEncodings = this.maxRedEncodings;\n }\n RedundantAudioEncoder.log(`Updated numRedundantEncodings to ${this.numRedundantEncodings}`);\n }\n /**\n * Enable or disable redundancy in response to\n * high packet loss event.\n */\n setRedundancyEnabled(enabled) {\n this.redundancyEnabled = enabled;\n RedundantAudioEncoder.log(`redundancy ${this.redundancyEnabled ? 'enabled' : 'disabled'}`);\n }\n /**\n * Helper function to only enqueue audio frames if they do not exceed the audio payload byte limit imposed by\n * Chromium-based browsers. Chromium will throw an error (https://crbug.com/1248479) if an audio payload larger than\n * 1000 bytes is enqueued. Any controller that attempts to enqueue an audio payload larger than 1000 bytes will\n * encounter this error and will permanently stop sending or receiving audio.\n */\n enqueueAudioFrameIfPayloadSizeIsValid(\n // @ts-ignore\n frame, controller) {\n if (frame.data.byteLength > this.maxAudioPayloadSizeBytes)\n return;\n controller.enqueue(frame);\n }\n /**\n * Receives encoded frames and modifies as needed before sending to transport.\n */\n senderTransform(\n // @ts-ignore\n frame, controller) {\n const frameMetadata = frame.getMetadata();\n // @ts-ignore\n if (frameMetadata.payloadType !== this.redPayloadType) {\n this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);\n return;\n }\n const primaryPayloadBuffer = this.getPrimaryPayload(frame.timestamp, frame.data);\n if (!primaryPayloadBuffer) {\n this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);\n return;\n }\n const encodedBuffer = this.encode(frame.timestamp, primaryPayloadBuffer);\n /* istanbul ignore next */\n if (!encodedBuffer) {\n this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);\n return;\n }\n frame.data = encodedBuffer;\n this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);\n return;\n }\n /**\n * Get the primary payload from encoding\n */\n getPrimaryPayload(primaryTimestamp, frame) {\n const encodings = this.splitEncodings(primaryTimestamp, frame);\n if (!encodings || encodings.length < 1)\n return null;\n return encodings[encodings.length - 1].payload;\n }\n /**\n * Split up the encoding received into primary and redundant encodings\n * These will be ordered oldest to newest which is the same ordering\n * in the RTP red payload.\n */\n splitEncodings(primaryTimestamp, frame, getFecInfo = false, primarySequenceNumber = undefined) {\n // process RED headers (according to RFC 2198)\n // 0 1 2 3\n // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n // |F| block PT | timestamp offset | block length |\n // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n //\n // last header\n // 0 1 2 3 4 5 6 7\n // +-+-+-+-+-+-+-+-+\n // |0| Block PT |\n // +-+-+-+-+-+-+-+-+\n const payload = new DataView(frame);\n let payloadSizeBytes = payload.byteLength;\n let totalPayloadSizeBytes = 0;\n let totalHeaderSizeBytes = 0;\n let primaryPayloadSizeBytes = 0;\n let payloadOffset = 0;\n let gotLastBlock = false;\n const encodings = new Array();\n const redundantEncodingBlockLengths = new Array();\n const redundantEncodingTimestamps = new Array();\n while (payloadSizeBytes > 0) {\n gotLastBlock = (payload.getUint8(payloadOffset) & 0x80) === 0;\n if (gotLastBlock) {\n // Bits 1 through 7 are payload type\n const payloadType = payload.getUint8(payloadOffset) & 0x7f;\n // Unexpected payload type. This is a bad packet.\n if (payloadType !== this.opusPayloadType) {\n return null;\n }\n totalPayloadSizeBytes += this.redLastHeaderSizeBytes;\n totalHeaderSizeBytes += this.redLastHeaderSizeBytes;\n // Accumulated block lengths are equal to or larger than the buffer, which means there is no primary block. This\n // is a bad packet.\n if (totalPayloadSizeBytes >= payload.byteLength) {\n return null;\n }\n primaryPayloadSizeBytes = payload.byteLength - totalPayloadSizeBytes;\n break;\n }\n else {\n if (payloadSizeBytes < this.redHeaderSizeBytes) {\n return null;\n }\n // Bits 22 through 31 are payload length\n const blockLength = ((payload.getUint8(payloadOffset + 2) & 0x03) << 8) + payload.getUint8(payloadOffset + 3);\n redundantEncodingBlockLengths.push(blockLength);\n const timestampOffset = payload.getUint16(payloadOffset + 1) >> 2;\n const timestamp = primaryTimestamp - timestampOffset;\n redundantEncodingTimestamps.push(timestamp);\n totalPayloadSizeBytes += blockLength + this.redHeaderSizeBytes;\n totalHeaderSizeBytes += this.redHeaderSizeBytes;\n payloadOffset += this.redHeaderSizeBytes;\n payloadSizeBytes -= this.redHeaderSizeBytes;\n }\n }\n // The last block was never found. This is a bad packet.\n if (!gotLastBlock) {\n return null;\n }\n let redundantPayloadOffset = totalHeaderSizeBytes;\n for (let i = 0; i < redundantEncodingTimestamps.length; i++) {\n const redundantPayloadBuffer = new ArrayBuffer(redundantEncodingBlockLengths[i]);\n const redundantPayloadArray = new Uint8Array(redundantPayloadBuffer);\n redundantPayloadArray.set(new Uint8Array(payload.buffer, redundantPayloadOffset, redundantEncodingBlockLengths[i]), 0);\n const encoding = {\n timestamp: redundantEncodingTimestamps[i],\n payload: redundantPayloadBuffer,\n isRedundant: true,\n };\n if (getFecInfo) {\n encoding.hasFec = this.opusPacketHasFec(new DataView(redundantPayloadBuffer), redundantPayloadBuffer.byteLength);\n }\n encodings.push(encoding);\n redundantPayloadOffset += redundantEncodingBlockLengths[i];\n }\n const primaryPayloadOffset = payload.byteLength - primaryPayloadSizeBytes;\n const primaryPayloadBuffer = new ArrayBuffer(primaryPayloadSizeBytes);\n const primaryArray = new Uint8Array(primaryPayloadBuffer);\n primaryArray.set(new Uint8Array(payload.buffer, primaryPayloadOffset, primaryPayloadSizeBytes), 0);\n const encoding = {\n timestamp: primaryTimestamp,\n payload: primaryPayloadBuffer,\n isRedundant: false,\n seq: primarySequenceNumber,\n };\n if (getFecInfo) {\n encoding.hasFec = this.opusPacketHasFec(new DataView(primaryPayloadBuffer), primaryPayloadBuffer.byteLength);\n }\n encodings.push(encoding);\n return encodings;\n }\n /**\n * Create a new encoding with current primary payload and the older payloads of choice.\n */\n encode(primaryTimestamp, primaryPayload) {\n const primaryPayloadSize = primaryPayload.byteLength;\n // Payload size needs to be valid.\n if (primaryPayloadSize === 0 ||\n primaryPayloadSize >= this.maxRedPacketSizeBytes ||\n primaryPayloadSize >= this.maxAudioPayloadSizeBytes) {\n return null;\n }\n const numRedundantEncodings = this.numRedundantEncodings;\n let headerSizeBytes = this.redLastHeaderSizeBytes;\n let payloadSizeBytes = primaryPayloadSize;\n let bytesAvailable = this.maxAudioPayloadSizeBytes - primaryPayloadSize - headerSizeBytes;\n const redundantEncodingTimestamps = new Array();\n const redundantEncodingPayloads = new Array();\n // If redundancy is disabled then only send the primary payload\n if (this.redundancyEnabled) {\n // Determine how much redundancy we can fit into our packet\n let redundantTimestamp = this.uint32WrapAround(primaryTimestamp - this.redPacketizationTime * this.redPacketDistance);\n for (let i = 0; i < numRedundantEncodings; i++) {\n // Do not add redundant encodings that are beyond the maximum timestamp offset.\n if (this.uint32WrapAround(primaryTimestamp - redundantTimestamp) >= this.maxRedTimestampOffset) {\n break;\n }\n let findTimestamp = redundantTimestamp;\n let encoding = this.encodingHistory.find(e => e.timestamp === findTimestamp);\n if (!encoding) {\n // If not found or not important then look for the previous packet.\n // The current packet may have included FEC for the previous, so just\n // use the previous packet instead provided that it has voice activity.\n findTimestamp = this.uint32WrapAround(redundantTimestamp - this.redPacketizationTime);\n encoding = this.encodingHistory.find(e => e.timestamp === findTimestamp);\n }\n if (encoding) {\n const redundantEncodingSizeBytes = encoding.payload.byteLength;\n // Only add redundancy if there are enough bytes available.\n if (bytesAvailable < this.redHeaderSizeBytes + redundantEncodingSizeBytes)\n break;\n bytesAvailable -= this.redHeaderSizeBytes + redundantEncodingSizeBytes;\n headerSizeBytes += this.redHeaderSizeBytes;\n payloadSizeBytes += redundantEncodingSizeBytes;\n redundantEncodingTimestamps.unshift(encoding.timestamp);\n redundantEncodingPayloads.unshift(encoding.payload);\n }\n redundantTimestamp -= this.redPacketizationTime * this.redPacketDistance;\n redundantTimestamp = this.uint32WrapAround(redundantTimestamp);\n }\n }\n const redPayloadBuffer = new ArrayBuffer(headerSizeBytes + payloadSizeBytes);\n const redPayloadView = new DataView(redPayloadBuffer);\n // Add redundant encoding header(s) to new buffer\n let redPayloadOffset = 0;\n for (let i = 0; i < redundantEncodingTimestamps.length; i++) {\n const timestampDelta = primaryTimestamp - redundantEncodingTimestamps[i];\n redPayloadView.setUint8(redPayloadOffset, this.opusPayloadType | 0x80);\n redPayloadView.setUint16(redPayloadOffset + 1, (timestampDelta << 2) | (redundantEncodingPayloads[i].byteLength >> 8));\n redPayloadView.setUint8(redPayloadOffset + 3, redundantEncodingPayloads[i].byteLength & 0xff);\n redPayloadOffset += this.redHeaderSizeBytes;\n }\n // Add primary encoding header to new buffer\n redPayloadView.setUint8(redPayloadOffset, this.opusPayloadType);\n redPayloadOffset += this.redLastHeaderSizeBytes;\n // Add redundant payload(s) to new buffer\n const redPayloadArray = new Uint8Array(redPayloadBuffer);\n for (let i = 0; i < redundantEncodingPayloads.length; i++) {\n redPayloadArray.set(new Uint8Array(redundantEncodingPayloads[i]), redPayloadOffset);\n redPayloadOffset += redundantEncodingPayloads[i].byteLength;\n }\n // Add primary payload to new buffer\n redPayloadArray.set(new Uint8Array(primaryPayload), redPayloadOffset);\n redPayloadOffset += primaryPayload.byteLength;\n /* istanbul ignore next */\n // Sanity check that we got the expected total payload size.\n if (redPayloadOffset !== headerSizeBytes + payloadSizeBytes)\n return null;\n this.updateEncodingHistory(primaryTimestamp, primaryPayload);\n return redPayloadBuffer;\n }\n /**\n * Update the encoding history with the latest primary encoding\n */\n updateEncodingHistory(primaryTimestamp, primaryPayload) {\n // Remove encodings from the history if they are too old.\n for (const encoding of this.encodingHistory) {\n const maxTimestampDelta = this.redPacketizationTime * this.redMaxRecoveryDistance;\n if (primaryTimestamp - encoding.timestamp >= maxTimestampDelta) {\n this.encodingHistory.shift();\n }\n else {\n break;\n }\n }\n // Only add an encoding to the history if the encoding is deemed to be important. An encoding is important if it is\n // a CELT-only packet or contains voice activity.\n const packet = new DataView(primaryPayload);\n if (this.opusPacketIsCeltOnly(packet) ||\n this.opusPacketHasVoiceActivity(packet, packet.byteLength) > 0) {\n // Check if adding an encoding will cause the length of the encoding history to exceed the maximum history size.\n // This is not expected to happen but could occur if we get incorrect timestamps. We want to make sure our memory\n // usage is bounded. In this case, just clear the history and start over from empty.\n if (this.encodingHistory.length + 1 > this.maxEncodingHistorySize)\n this.encodingHistory.length = 0;\n this.encodingHistory.push({ timestamp: primaryTimestamp, payload: primaryPayload });\n }\n }\n /**\n * Initialize packet logs and metric values.\n */\n initializePacketLogs() {\n // The extra space from the max RED recovery distance is to ensure that we do not incorrectly count recovery for\n // packets that have already been received but are outside of the max out-of-order distance.\n const packetLogSize = this.maxOutOfOrderPacketDistance + this.redMaxRecoveryDistance;\n this.primaryPacketLog = {\n window: new Array(packetLogSize),\n index: 0,\n windowSize: packetLogSize,\n };\n this.redRecoveryLog = {\n window: new Array(packetLogSize),\n index: 0,\n windowSize: packetLogSize,\n };\n this.fecRecoveryLog = {\n window: new Array(packetLogSize),\n index: 0,\n windowSize: packetLogSize,\n };\n this.totalAudioPacketsExpected = 0;\n this.totalAudioPacketsLost = 0;\n this.totalAudioPacketsRecoveredRed = 0;\n this.totalAudioPacketsRecoveredFec = 0;\n }\n /**\n * Receives encoded frames from the server\n * and adds the timestamps to a packet log\n * to calculate an approximate recovery metric.\n */\n receivePacketLogTransform(\n // @ts-ignore\n frame, controller) {\n const frameMetadata = frame.getMetadata();\n // @ts-ignore\n if (frameMetadata.payloadType !== this.redPayloadType) {\n this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);\n return;\n }\n // @ts-ignore\n const encodings = this.splitEncodings(frame.timestamp, frame.data, \n /*getFecInfo*/ true, frameMetadata.sequenceNumber);\n if (!encodings) {\n this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);\n return;\n }\n for (let i = encodings.length - 1; i >= 0; i--) {\n if (this.updateLossStats(encodings[i])) {\n this.updateRedStats(encodings[i]);\n this.updateFecStats(encodings[i]);\n }\n }\n this.maybeReportLossStats(encodings[encodings.length - 1].timestamp, frameMetadata.synchronizationSource);\n this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);\n }\n /**\n * Adds a timestamp to the primary packet log.\n * This also updates totalAudioPacketsLost and totalAudioPacketsExpected by looking\n * at the difference between timestamps.\n *\n * @param encoding : The encoding to be analyzed\n * @returns false if sequence number was greater than max out of order distance\n * true otherwise\n */\n updateLossStats(encoding) {\n if (encoding.isRedundant)\n return true;\n const timestamp = encoding.timestamp;\n const seq = encoding.seq;\n if (this.totalAudioPacketsExpected === 0) {\n this.totalAudioPacketsExpected = 1;\n this.newestSequenceNumber = seq;\n this.addTimestamp(this.primaryPacketLog, timestamp);\n return true;\n }\n const diff = this.int16(seq - this.newestSequenceNumber);\n if (diff < -this.maxOutOfOrderPacketDistance)\n return false;\n if (diff < 0) {\n if (!this.hasTimestamp(this.primaryPacketLog, timestamp)) {\n if (this.totalAudioPacketsLost > 0)\n this.totalAudioPacketsLost--;\n this.addTimestamp(this.primaryPacketLog, timestamp);\n this.removeFromRecoveryWindows(timestamp);\n }\n }\n else if (diff > 1) {\n this.totalAudioPacketsLost += diff - 1;\n }\n if (diff > 0) {\n this.totalAudioPacketsExpected += diff;\n this.newestSequenceNumber = encoding.seq;\n this.addTimestamp(this.primaryPacketLog, timestamp);\n }\n return true;\n }\n /**\n * Adds a timestamp to the red recovery log if it is not present in\n * the primary packet log and if it's not too old.\n *\n * @param encoding : The encoding to be analyzed\n */\n updateRedStats(encoding) {\n if (!encoding.isRedundant || this.totalAudioPacketsLost === 0)\n return;\n const timestamp = encoding.timestamp;\n if (!this.hasTimestamp(this.primaryPacketLog, timestamp)) {\n if (!this.hasTimestamp(this.redRecoveryLog, timestamp)) {\n this.totalAudioPacketsRecoveredRed++;\n this.addTimestamp(this.redRecoveryLog, timestamp);\n }\n if (this.removeTimestamp(this.fecRecoveryLog, timestamp)) {\n /* istanbul ignore else */\n if (this.totalAudioPacketsRecoveredFec > 0)\n this.totalAudioPacketsRecoveredFec--;\n }\n }\n }\n /**\n * Adds a timestamp to the fec recovery log if it is not present in\n * the primary packet log and red recovery log and if it is not too old.\n *\n * @param encoding : The encoding to be analyzed\n */\n updateFecStats(encoding) {\n if (!encoding.hasFec || this.totalAudioPacketsLost === 0)\n return;\n const fecTimestamp = encoding.timestamp - this.redPacketizationTime;\n if (this.hasTimestamp(this.primaryPacketLog, fecTimestamp) ||\n this.hasTimestamp(this.redRecoveryLog, fecTimestamp) ||\n this.hasTimestamp(this.fecRecoveryLog, fecTimestamp)) {\n return;\n }\n this.totalAudioPacketsRecoveredFec++;\n this.addTimestamp(this.fecRecoveryLog, fecTimestamp);\n }\n /**\n * Reports loss metrics to DefaultTransceiverController\n *\n * @param timestamp : Timestamp of most recent primary packet\n */\n maybeReportLossStats(timestamp, ssrc) {\n if (timestamp - this.lastLossReportTimestamp < this.lossReportInterval)\n return;\n /* istanbul ignore next */\n if (RedundantAudioEncoder.shouldReportStats) {\n // @ts-ignore\n self.postMessage({\n type: 'RedundantAudioEncoderStats',\n ssrc,\n totalAudioPacketsLost: this.totalAudioPacketsLost,\n totalAudioPacketsExpected: this.totalAudioPacketsExpected,\n totalAudioPacketsRecoveredRed: this.totalAudioPacketsRecoveredRed,\n totalAudioPacketsRecoveredFec: this.totalAudioPacketsRecoveredFec,\n });\n }\n this.lastLossReportTimestamp = timestamp;\n }\n /**\n * Adds a timestamp to a packet log\n *\n * @param packetLog : The packetlog to add the timestamp to\n * @param timestamp : The timestamp that should be added\n */\n addTimestamp(packetLog, timestamp) {\n packetLog.window[packetLog.index] = timestamp;\n packetLog.index = (packetLog.index + 1) % packetLog.windowSize;\n }\n /**\n * Checks if a timestamp is in a packetlog\n *\n * @param packetLog : The packetlog to search\n * @param timestamp : The timestamp to search for\n * @returns true if timestamp is present, false otherwise\n */\n hasTimestamp(packetLog, timestamp) {\n const element = packetLog.window.find(t => t === timestamp);\n return !!element;\n }\n /**\n * Removes a timestamp from a packet log\n *\n * @param packetLog : The packetlog from which the timestamp should be removed\n * @param timestamp : The timestamp to be removed\n * @returns true if timestamp was present in the log and removed, false otherwise\n */\n removeTimestamp(packetLog, timestamp) {\n const index = packetLog.window.indexOf(timestamp);\n if (index >= 0) {\n packetLog.window[index] = undefined;\n return true;\n }\n return false;\n }\n /**\n * Removes a timestamp from red and fec recovery windows.\n *\n * @param timestamp : The timestamp to be removed\n */\n removeFromRecoveryWindows(timestamp) {\n let removed = this.removeTimestamp(this.redRecoveryLog, timestamp);\n if (removed) {\n if (this.totalAudioPacketsRecoveredRed > 0)\n this.totalAudioPacketsRecoveredRed--;\n }\n removed = this.removeTimestamp(this.fecRecoveryLog, timestamp);\n if (removed) {\n if (this.totalAudioPacketsRecoveredFec > 0)\n this.totalAudioPacketsRecoveredFec--;\n }\n }\n /**\n * Converts the supplied argument to 32-bit unsigned integer\n */\n uint32WrapAround(num) {\n const mod = 4294967296; // 2^32\n let res = num;\n if (num >= mod) {\n res = num - mod;\n }\n else if (num < 0) {\n res = mod + num;\n }\n return res;\n }\n /**\n * Converts the supplied argument to 16-bit signed integer\n */\n int16(num) {\n return (num << 16) >> 16;\n }\n /**\n * Determines if an Opus packet is in CELT-only mode.\n *\n * @param packet Opus packet.\n * @returns `true` if the packet is in CELT-only mode.\n */\n opusPacketIsCeltOnly(packet) {\n // TOC byte format (https://www.rfc-editor.org/rfc/rfc6716#section-3.1):\n // 0\n // 0 1 2 3 4 5 6 7\n // +-+-+-+-+-+-+-+-+\n // | config |s| c |\n // +-+-+-+-+-+-+-+-+\n // Since CELT-only packets are represented using configurations 16 to 31, the highest 'config' bit will always be 1\n // for CELT-only packets.\n return !!(packet.getUint8(0) & 0x80);\n }\n /**\n * Gets the number of samples per frame from an Opus packet.\n *\n * @param packet Opus packet. This must contain at least one byte of data.\n * @param sampleRateHz 32-bit integer sampling rate in Hz. This must be a multiple of 400 or inaccurate results will\n * be returned.\n * @returns Number of samples per frame.\n */\n opusPacketGetSamplesPerFrame(packet, sampleRateHz) {\n // Sample rate must be a 32-bit integer.\n sampleRateHz = Math.round(sampleRateHz);\n sampleRateHz = Math.min(Math.max(sampleRateHz, -(Math.pow(2, 32))), Math.pow(2, 32) - 1);\n // TOC byte format (https://www.rfc-editor.org/rfc/rfc6716#section-3.1):\n // 0\n // 0 1 2 3 4 5 6 7\n // +-+-+-+-+-+-+-+-+\n // | config |s| c |\n // +-+-+-+-+-+-+-+-+\n let numSamples;\n let frameSizeOption;\n // Case for CELT-only packet.\n if (this.opusPacketIsCeltOnly(packet)) {\n // The lower 3 'config' bits indicate the frame size option.\n frameSizeOption = (packet.getUint8(0) >> 3) & 0x3;\n // The frame size options 0, 1, 2, 3 correspond to frame sizes of 2.5, 5, 10, 20 ms. Notice that the frame sizes\n // can be represented as (2.5 * 2^0), (2.5 * 2^1), (2.5 * 2^2), (2.5 * 2^3) ms. So, the number of samples can be\n // calculated as follows:\n // (sample/s) * (1s/1000ms) * (2.5ms) * 2^(frameSizeOption)\n // = (sample/s) * (1s/400) * 2^(frameSizeOption)\n // = (sample/s) * 2^(frameSizeOption) * (1s/400)\n numSamples = (sampleRateHz << frameSizeOption) / 400;\n }\n // Case for Hybrid packet. Since Hybrid packets are represented using configurations 12 to 15, bits 1 and 2 in the\n // above TOC byte diagram will both be 1.\n else if ((packet.getUint8(0) & 0x60) === 0x60) {\n // In the case of configuration 13 or 15, bit 4 in the above TOC byte diagram will be 1. Configurations 13 and 15\n // correspond to a 20ms frame size, so the number of samples is calculated as follows:\n // (sample/s) * (1s/1000ms) * (20ms)\n // = (sample/s) * (1s/50)\n //\n // In the case of configuration 12 or 14, bit 4 in the above TOC byte diagram will be 0. Configurations 12 and 14\n // correspond to a 10ms frame size, so the number of samples is calculated as follows:\n // (sample/s) * (1s/1000ms) * (10ms)\n // = (sample/s) * (1s/100)\n numSamples = packet.getUint8(0) & 0x08 ? sampleRateHz / 50 : sampleRateHz / 100;\n }\n // Case for SILK-only packet.\n else {\n // The lower 3 'config' bits indicate the frame size option for SILK-only packets.\n frameSizeOption = (packet.getUint8(0) >> 3) & 0x3;\n if (frameSizeOption === 3) {\n // Frame size option 3 corresponds to a frame size of 60ms, so the number of samples is calculated as follows:\n // (sample/s) * (1s/1000ms) * (60ms)\n // = (sample/s) * (60ms) * (1s/1000ms)\n numSamples = (sampleRateHz * 60) / 1000;\n }\n else {\n // The frame size options 0, 1, 2 correspond to frame sizes of 10, 20, 40 ms. Notice that the frame sizes can be\n // represented as (10 * 2^0), (10 * 2^1), (10 * 2^2) ms. So, the number of samples can be calculated as follows:\n // (sample/s) * (1s/1000ms) * (10ms) * 2^(frameSizeOption)\n // = (sample/s) * (1s/100) * 2^(frameSizeOption)\n // = (sample/s) * 2^(frameSizeOption) * (1s/100)\n numSamples = (sampleRateHz << frameSizeOption) / 100;\n }\n }\n return numSamples;\n }\n /**\n * Gets the number of SILK frames per Opus frame.\n *\n * @param packet Opus packet.\n * @returns Number of SILK frames per Opus frame.\n */\n opusNumSilkFrames(packet) {\n // For computing the frame length in ms, the sample rate is not important since it cancels out. We use 48 kHz, but\n // any valid sample rate would work.\n //\n // To calculate the length of a frame (with a 48kHz sample rate) in ms:\n // (samples/frame) * (1s/48000 samples) * (1000ms/s)\n // = (samples/frame) * (1000ms/48000 samples)\n // = (samples/frame) * (1ms/48 samples)\n let frameLengthMs = this.opusPacketGetSamplesPerFrame(packet, 48000) / 48;\n if (frameLengthMs < 10)\n frameLengthMs = 10;\n // The number of SILK frames per Opus frame is described in https://www.rfc-editor.org/rfc/rfc6716#section-4.2.2.\n switch (frameLengthMs) {\n case 10:\n case 20:\n return 1;\n case 40:\n return 2;\n case 60:\n return 3;\n // It is not possible to reach the default case since an Opus packet can only encode sizes of 2.5, 5, 10, 20, 40,\n // or 60 ms, so we ignore the default case for test coverage.\n /* istanbul ignore next */\n default:\n return 0;\n }\n }\n /**\n * Gets the number of channels from an Opus packet.\n *\n * @param packet Opus packet.\n * @returns Number of channels.\n */\n opusPacketGetNumChannels(packet) {\n // TOC byte format (https://www.rfc-editor.org/rfc/rfc6716#section-3.1):\n // 0\n // 0 1 2 3 4 5 6 7\n // +-+-+-+-+-+-+-+-+\n // | config |s| c |\n // +-+-+-+-+-+-+-+-+\n // The 's' bit indicates mono or stereo audio, with 0 indicating mono and 1 indicating stereo.\n return packet.getUint8(0) & 0x4 ? 2 : 1;\n }\n /**\n * Determine the size (in bytes) of an Opus frame.\n *\n * @param packet Opus packet.\n * @param byteOffset Offset (from the start of the packet) to the byte containing the size information.\n * @param remainingBytes Remaining number of bytes to parse from the Opus packet.\n * @param sizeBytes Variable to store the parsed frame size (in bytes).\n * @returns Number of bytes that were parsed to determine the frame size.\n */\n opusParseSize(packet, byteOffset, remainingBytes, sizeBytes) {\n // See https://www.rfc-editor.org/rfc/rfc6716#section-3.2.1 for an explanation of how frame size is represented.\n // If there are no remaining bytes to parse the size from, then the size cannot be determined.\n if (remainingBytes < 1) {\n sizeBytes[0] = -1;\n return -1;\n }\n // If the first byte is in the range 0...251, then this value is the size of the frame.\n else if (packet.getUint8(byteOffset) < 252) {\n sizeBytes[0] = packet.getUint8(byteOffset);\n return 1;\n }\n // If the first byte is in the range 252...255, a second byte is needed. If there is no second byte, then the size\n // cannot be determined.\n else if (remainingBytes < 2) {\n sizeBytes[0] = -1;\n return -1;\n }\n // The total size of the frame given two size bytes is:\n // (4 * secondSizeByte) + firstSizeByte\n else {\n sizeBytes[0] = 4 * packet.getUint8(byteOffset + 1) + packet.getUint8(byteOffset);\n return 2;\n }\n }\n /**\n * Parse binary data containing an Opus packet into one or more Opus frames.\n *\n * @param data Binary data containing an Opus packet to be parsed. The data should begin with the first byte (i.e the\n * TOC byte) of an Opus packet. Note that the size of the data does not have to equal the size of the\n * contained Opus packet.\n * @param lenBytes Size of the data (in bytes).\n * @param selfDelimited Indicates if the Opus packet is self-delimiting\n * (https://www.rfc-editor.org/rfc/rfc6716#appendix-B).\n * @param tocByte Optional variable to store the TOC (table of contents) byte.\n * @param frameOffsets Optional variable to store the offsets (from the start of the data) to the first bytes of each\n * Opus frame.\n * @param frameSizes Required variable to store the sizes (in bytes) of each Opus frame.\n * @param payloadOffset Optional variable to store the offset (from the start of the data) to the first byte of the\n * payload.\n * @param packetLenBytes Optional variable to store the length of the Opus packet (in bytes).\n * @returns Number of Opus frames.\n */\n opusPacketParseImpl(data, lenBytes, selfDelimited, tocByte, frameOffsets, frameSizes, payloadOffset, packetLenBytes) {\n if (!frameSizes || lenBytes < 0)\n return this.OPUS_BAD_ARG;\n if (lenBytes === 0)\n return this.OPUS_INVALID_PACKET;\n // The number of Opus frames in the packet.\n let numFrames;\n // Intermediate storage for the number of bytes parsed to determine the size of a frame.\n let numBytesParsed;\n // The number of the padding bytes (excluding the padding count bytes) in the packet.\n let paddingBytes = 0;\n // Indicates whether CBR (constant bitrate) framing is used.\n let cbr = false;\n // The TOC (table of contents) byte (https://www.rfc-editor.org/rfc/rfc6716#section-3.1).\n const toc = data.getUint8(0);\n // Store the TOC byte.\n if (tocByte)\n tocByte[0] = toc;\n // The remaining number of bytes to parse from the packet. Note that the TOC byte has already been parsed, hence the\n // minus 1.\n let remainingBytes = lenBytes - 1;\n // This keeps track of where we are in the packet. This starts at 1 since the TOC byte has already been read.\n let byteOffset = 1;\n // The size of the last Opus frame in bytes.\n let lastSizeBytes = remainingBytes;\n // Read the `c` bits (i.e. code bits) from the TOC byte.\n switch (toc & 0x3) {\n // A code 0 packet (https://www.rfc-editor.org/rfc/rfc6716#section-3.2.2) has one frame.\n case 0:\n numFrames = 1;\n break;\n // A code 1 packet (https://www.rfc-editor.org/rfc/rfc6716#section-3.2.3) has two CBR (constant bitrate) frames.\n case 1:\n numFrames = 2;\n cbr = true;\n if (!selfDelimited) {\n // Undelimited code 1 packets must be an even number of data bytes, otherwise the packet is invalid.\n if (remainingBytes & 0x1)\n return this.OPUS_INVALID_PACKET;\n // The sizes of both frames are equal (i.e. half of the number of data bytes).\n lastSizeBytes = remainingBytes / 2;\n // If `lastSizeBytes` is too large, we will catch it later.\n frameSizes[0][0] = lastSizeBytes;\n }\n break;\n // A code 2 packet (https://www.rfc-editor.org/rfc/rfc6716#section-3.2.4) has two VBR (variable bitrate) frames.\n case 2:\n numFrames = 2;\n numBytesParsed = this.opusParseSize(data, byteOffset, remainingBytes, frameSizes[0]);\n remainingBytes -= numBytesParsed;\n // The parsed size of the first frame cannot be larger than the number of remaining bytes in the packet.\n if (frameSizes[0][0] < 0 || frameSizes[0][0] > remainingBytes) {\n return this.OPUS_INVALID_PACKET;\n }\n byteOffset += numBytesParsed;\n // The size of the second frame is the remaining number of bytes after the first frame.\n lastSizeBytes = remainingBytes - frameSizes[0][0];\n break;\n // A code 3 packet (https://www.rfc-editor.org/rfc/rfc6716#section-3.2.5) has multiple CBR/VBR frames (from 0 to\n // 120 ms).\n default:\n // Code 3 packets must have at least 2 bytes (i.e. at least 1 byte after the TOC byte).\n if (remainingBytes < 1)\n return this.OPUS_INVALID_PACKET;\n // Frame count byte format:\n // 0\n // 0 1 2 3 4 5 6 7\n // +-+-+-+-+-+-+-+-+\n // |v|p| M |\n // +-+-+-+-+-+-+-+-+\n //\n // Read the frame count byte, which immediately follows the TOC byte.\n const frameCountByte = data.getUint8(byteOffset++);\n --remainingBytes;\n // Read the 'M' bits of the frame count byte, which encode the number of frames.\n numFrames = frameCountByte & 0x3f;\n // The number of frames in a code 3 packet must not be 0.\n if (numFrames <= 0)\n return this.OPUS_INVALID_PACKET;\n const samplesPerFrame = this.opusPacketGetSamplesPerFrame(data, 48000);\n // A single frame can have at most 2880 samples, which happens in the case where 60ms of 48kHz audio is encoded\n // per frame. A code 3 packet cannot contain more than 120ms of audio, so the total number of samples cannot\n // exceed 2880 * 2 = 5760.\n if (samplesPerFrame * numFrames > 5760)\n return this.OPUS_INVALID_PACKET;\n // Parse padding bytes if the 'p' bit is 1.\n if (frameCountByte & 0x40) {\n let paddingCountByte;\n let numPaddingBytes;\n // Remove padding bytes (including padding count bytes) from the remaining byte count.\n do {\n // Sanity check that there are enough bytes to parse and remove the padding.\n if (remainingBytes <= 0)\n return this.OPUS_INVALID_PACKET;\n // Get the next padding count byte.\n paddingCountByte = data.getUint8(byteOffset++);\n --remainingBytes;\n // If the padding count byte has a value in the range 0...254, then the total size of the padding is the\n // value in the padding count byte.\n //\n // If the padding count byte has value 255, then the total size of the padding is 254 plus the value in the\n // next padding count byte. Therefore, keep reading padding count bytes while the value is 255.\n numPaddingBytes = paddingCountByte === 255 ? 254 : paddingCountByte;\n remainingBytes -= numPaddingBytes;\n paddingBytes += numPaddingBytes;\n } while (paddingCountByte === 255);\n }\n // Sanity check that the remaining number of bytes is not negative after removing the padding.\n if (remainingBytes < 0)\n return this.OPUS_INVALID_PACKET;\n // Read the 'v' bit (i.e. VBR bit).\n cbr = !(frameCountByte & 0x80);\n // VBR case\n if (!cbr) {\n lastSizeBytes = remainingBytes;\n // Let M be the number of frames. There will be M - 1 frame length indicators (which can be 1 or 2 bytes)\n // corresponding to the lengths of frames 0 to M - 2. The size of the last frame (i.e. frame M - 1) is the\n // number of data bytes after the end of frame M - 2 and before the start of the padding bytes.\n for (let i = 0; i < numFrames - 1; ++i) {\n numBytesParsed = this.opusParseSize(data, byteOffset, remainingBytes, frameSizes[i]);\n remainingBytes -= numBytesParsed;\n // The remaining number of data bytes must be enough to contain each frame.\n if (frameSizes[i][0] < 0 || frameSizes[i][0] > remainingBytes) {\n return this.OPUS_INVALID_PACKET;\n }\n byteOffset += numBytesParsed;\n lastSizeBytes -= numBytesParsed + frameSizes[i][0];\n }\n // Sanity check that the size of the last frame is not negative.\n if (lastSizeBytes < 0)\n return this.OPUS_INVALID_PACKET;\n }\n // CBR case\n else if (!selfDelimited) {\n // The size of each frame is the number of data bytes divided by the number of frames.\n lastSizeBytes = Math.trunc(remainingBytes / numFrames);\n // The number of data bytes must be a non-negative integer multiple of the number of frames.\n if (lastSizeBytes * numFrames !== remainingBytes)\n return this.OPUS_INVALID_PACKET;\n // All frames have equal size in the undelimited CBR case.\n for (let i = 0; i < numFrames - 1; ++i) {\n frameSizes[i][0] = lastSizeBytes;\n }\n }\n }\n // Self-delimited framing uses an extra 1 or 2 bytes, immediately preceding the data bytes, to indicate either the\n // size of the last frame (for code 0, code 2, and VBR code 3 packets) or the size of all the frames (for code 1 and\n // CBR code 3 packets). See https://www.rfc-editor.org/rfc/rfc6716#appendix-B.\n if (selfDelimited) {\n // The extra frame size byte(s) will always indicate the size of the last frame.\n numBytesParsed = this.opusParseSize(data, byteOffset, remainingBytes, frameSizes[numFrames - 1]);\n remainingBytes -= numBytesParsed;\n // There must be enough data bytes for the last frame.\n if (frameSizes[numFrames - 1][0] < 0 || frameSizes[numFrames - 1][0] > remainingBytes) {\n return this.OPUS_INVALID_PACKET;\n }\n byteOffset += numBytesParsed;\n // For CBR packets, the sizes of all the frames are equal.\n if (cbr) {\n // There must be enough data bytes for all the frames.\n if (frameSizes[numFrames - 1][0] * numFrames > remainingBytes) {\n return this.OPUS_INVALID_PACKET;\n }\n for (let i = 0; i < numFrames - 1; ++i) {\n frameSizes[i][0] = frameSizes[numFrames - 1][0];\n }\n }\n // At this point, `lastSizeBytes` contains the size of the last frame plus the size of the extra frame size\n // byte(s), so sanity check that `lastSizeBytes` is the upper bound for the size of the last frame.\n else if (!(numBytesParsed + frameSizes[numFrames - 1][0] <= lastSizeBytes)) {\n return this.OPUS_INVALID_PACKET;\n }\n }\n // Undelimited case\n else {\n // Because the size of the last packet is not encoded explicitly, it is possible that the size of the last packet\n // (or of all the packets, for the CBR case) is larger than maximum frame size.\n if (lastSizeBytes > this.OPUS_MAX_FRAME_SIZE_BYTES)\n return this.OPUS_INVALID_PACKET;\n frameSizes[numFrames - 1][0] = lastSizeBytes;\n }\n // Store the offset to the start of the payload.\n if (payloadOffset)\n payloadOffset[0] = byteOffset;\n // Store the offsets to the start of each frame.\n for (let i = 0; i < numFrames; ++i) {\n if (frameOffsets)\n frameOffsets[i][0] = byteOffset;\n byteOffset += frameSizes[i][0];\n }\n // Store the length of the Opus packet.\n if (packetLenBytes)\n packetLenBytes[0] = byteOffset + paddingBytes;\n return numFrames;\n }\n /**\n * Parse a single undelimited Opus packet into one or more Opus frames.\n *\n * @param packet Opus packet to be parsed.\n * @param lenBytes Size of the packet (in bytes).\n * @param tocByte Optional variable to store the TOC (table of contents) byte.\n * @param frameOffsets Optional variable to store the offsets (from the start of the packet) to the first bytes of\n * each Opus frame.\n * @param frameSizes Required variable to store the sizes (in bytes) of each Opus frame.\n * @param payloadOffset Optional variable to store the offset (from the start of the packet) to the first byte of the\n * payload.\n * @returns Number of Opus frames.\n */\n opusPacketParse(packet, lenBytes, tocByte, frameOffsets, frameSizes, payloadOffset) {\n return this.opusPacketParseImpl(packet, lenBytes, \n /* selfDelimited */ false, tocByte, frameOffsets, frameSizes, payloadOffset, null);\n }\n /**\n * This function returns the SILK VAD (voice activity detection) information encoded in the Opus packet. For CELT-only\n * packets that do not have VAD information, it returns -1.\n *\n * @param packet Opus packet.\n * @param lenBytes Size of the packet (in bytes).\n * @returns 0: no frame had the VAD flag set.\n * 1: at least one frame had the VAD flag set.\n * -1: VAD status could not be determined.\n */\n opusPacketHasVoiceActivity(packet, lenBytes) {\n if (!packet || lenBytes <= 0)\n return 0;\n // In CELT-only mode, we can not determine whether there is VAD.\n if (this.opusPacketIsCeltOnly(packet))\n return -1;\n const numSilkFrames = this.opusNumSilkFrames(packet);\n // It is not possible for `opusNumSilkFrames()` to return 0, so we ignore the next sanity check for test coverage.\n /* istanbul ignore next */\n if (numSilkFrames === 0)\n return -1;\n const opusFrameOffsets = new Array(this.OPUS_MAX_OPUS_FRAMES);\n const opusFrameSizes = new Array(this.OPUS_MAX_OPUS_FRAMES);\n for (let i = 0; i < this.OPUS_MAX_OPUS_FRAMES; ++i) {\n opusFrameOffsets[i] = [undefined];\n opusFrameSizes[i] = [undefined];\n }\n // Parse packet to get the Opus frames.\n const numOpusFrames = this.opusPacketParse(packet, lenBytes, null, opusFrameOffsets, opusFrameSizes, null);\n // VAD status cannot be determined for invalid packets.\n if (numOpusFrames < 0)\n return -1;\n // Iterate over all Opus frames, which may contain multiple SILK frames, to determine the VAD status.\n for (let i = 0; i < numOpusFrames; ++i) {\n if (opusFrameSizes[i][0] < 1)\n continue;\n // LP layer header bits format (https://www.rfc-editor.org/rfc/rfc6716#section-4.2.3):\n //\n // Mono case:\n // +-----------------+----------+\n // | 1 to 3 VAD bits | LBRR bit |\n // +-----------------+----------+\n //\n // Stereo case:\n // +---------------------+--------------+----------------------+---------------+\n // | 1 to 3 mid VAD bits | mid LBRR bit | 1 to 3 side VAD bits | side LBRR bit |\n // +---------------------+--------------+----------------------+---------------+\n // The upper 1 to 3 bits (dependent on the number of SILK frames) of the LP layer contain VAD bits. If any of\n // these VAD bits are 1, then voice activity is present.\n if (packet.getUint8(opusFrameOffsets[i][0]) >> (8 - numSilkFrames))\n return 1;\n // In the stereo case, there is a second set of 1 to 3 VAD bits, so also check these VAD bits.\n const channels = this.opusPacketGetNumChannels(packet);\n if (channels === 2 &&\n (packet.getUint8(opusFrameOffsets[i][0]) << (numSilkFrames + 1)) >> (8 - numSilkFrames)) {\n return 1;\n }\n }\n // No voice activity was detected.\n return 0;\n }\n /**\n * This method is based on Definition of the Opus Audio Codec\n * (https://tools.ietf.org/html/rfc6716). Basically, this method is based on\n * parsing the LP layer of an Opus packet, particularly the LBRR flag.\n *\n * @param packet Opus packet.\n * @param lenBytes Size of the packet (in bytes).\n * @returns true: packet has fec encoding about previous packet.\n * false: no fec encoding present.\n */\n opusPacketHasFec(packet, lenBytes) {\n if (!packet || lenBytes <= 0)\n return false;\n // In CELT-only mode, packets should not have FEC.\n if (this.opusPacketIsCeltOnly(packet))\n return false;\n const opusFrameOffsets = new Array(this.OPUS_MAX_OPUS_FRAMES);\n const opusFrameSizes = new Array(this.OPUS_MAX_OPUS_FRAMES);\n for (let i = 0; i < this.OPUS_MAX_OPUS_FRAMES; ++i) {\n opusFrameOffsets[i] = [undefined];\n opusFrameSizes[i] = [undefined];\n }\n // Parse packet to get the Opus frames.\n const numOpusFrames = this.opusPacketParse(packet, lenBytes, null, opusFrameOffsets, opusFrameSizes, null);\n if (numOpusFrames < 0)\n return false;\n /* istanbul ignore next */\n if (opusFrameSizes[0][0] <= 1)\n return false;\n const numSilkFrames = this.opusNumSilkFrames(packet);\n /* istanbul ignore next */\n if (numSilkFrames === 0)\n return false;\n const channels = this.opusPacketGetNumChannels(packet);\n /* istanbul ignore next */\n if (channels !== 1 && channels !== 2)\n return false;\n // A frame starts with the LP layer. The LP layer begins with two to eight\n // header bits.These consist of one VAD bit per SILK frame (up to 3),\n // followed by a single flag indicating the presence of LBRR frames.\n // For a stereo packet, these first flags correspond to the mid channel, and\n // a second set of flags is included for the side channel. Because these are\n // the first symbols decoded by the range coder and because they are coded\n // as binary values with uniform probability, they can be extracted directly\n // from the most significant bits of the first byte of compressed data.\n for (let i = 0; i < channels; i++) {\n if (packet.getUint8(opusFrameOffsets[0][0]) & (0x80 >> ((i + 1) * (numSilkFrames + 1) - 1)))\n return true;\n }\n return false;\n }\n}\nRedundantAudioEncoder.shouldLog = true;\nRedundantAudioEncoder.shouldReportStats = true;\nRedundantAudioEncoder.initializeWorker();\n"},4185:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(1340));class a extends r.default{constructor(){super(0)}static nextTick(e){setTimeout(e,0)}}t.default=a},8192:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e){this.intervalMs=e}start(e){this.stop(),this.timer=setInterval(e,this.intervalMs)}stop(){void 0!==this.timer&&(clearInterval(this.timer),this.timer=void 0)}running(){return void 0!==this.timer}}},1340:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e){this.timeoutMs=e,this.timer=null}start(e){this.stop(),this.timer=setTimeout((()=>{clearTimeout(this.timer),e()}),this.timeoutMs)}stop(){null!==this.timer&&(clearTimeout(this.timer),this.timer=null)}}},5803:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(9762)),a=i(n(356)),o=i(n(2049));class s{constructor(e){this.sdp=e}clone(){return new s(this.sdp)}static isRTPCandidate(e){const t=/candidate[:](\S+) (\d+)/g.exec(e);return null!==t&&"1"===t[2]}static linesToSDP(e){return new s(e.join(s.CRLF))}static candidateTypeFromString(e){switch(e){case r.default.Host:return r.default.Host;case r.default.ServerReflexive:return r.default.ServerReflexive;case r.default.PeerReflexive:return r.default.PeerReflexive;case r.default.Relay:return r.default.Relay}return null}static candidateType(e){const t=/a[=]candidate[:].* typ ([a-z]+) /g.exec(e);return null===t?null:s.candidateTypeFromString(t[1])}static mediaType(e){const t=/m=(audio|video)/g.exec(e);if(null!==t)return t[1]}static mid(e){if(e.includes("a=mid:"))return e.replace(/^(a=mid:)/,"")}static direction(e){const t=/a=(sendrecv|sendonly|recvonly|inactive)/g.exec(e);if(null!==t)return t[1]}static splitLines(e){return e.trim().split("\n").map((e=>e.trim()))}static splitSections(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+s.CRLF))}static findActiveCameraSection(e){let t=0,n=!1;for(const i of e){if(/^m=video/.test(i)&&(i.indexOf("sendrecv")>-1||-1===i.indexOf("sendonly")&&-1===i.indexOf("recvonly")&&-1===i.indexOf("inactive"))){n=!0;break}t++}return!1===n&&(t=-1),t}static extractSSRCsFromFIDGroupLine(e){return/^a=ssrc-group:FID\s(.+)/.exec(e)[1]}static matchPrefix(e,t){return s.splitLines(e).filter((e=>0===e.indexOf(t)))}lines(){return this.sdp.split(s.CRLF)}hasVideo(){return null!==/^m=video/gm.exec(this.sdp)}hasCandidates(){return null!==/a[=]candidate[:]/g.exec(this.sdp)}hasCandidatesForAllMLines(){return!(this.sdp.indexOf("c=IN IP4 0.0.0.0")>-1)}withoutCandidateType(e){return s.linesToSDP(this.lines().filter((t=>s.candidateType(t)!==e)))}withoutServerReflexiveCandidates(){return this.withoutCandidateType(r.default.ServerReflexive)}withAudioMaxAverageBitrate(e){if(!e)return this.clone();e=Math.trunc(Math.min(Math.max(e,s.rfc7587LowestBitrate),s.rfc7587HighestBitrate));const t=this.lines(),n=s.findOpusFmtpAttributes(t),i=s.updateOpusFmtpAttributes(t,n,[`maxaveragebitrate=${e}`]);return s.linesToSDP(i)}withStereoAudio(){const e=this.lines(),t=s.findOpusFmtpAttributes(e),n=s.updateOpusFmtpAttributes(e,t,["stereo=1","sprop-stereo=1"]);return s.linesToSDP(n)}static findOpusFmtpAttributes(e){const t=/^a=rtpmap:\s*(\d+)\s+opus\/48000/;let n=!1;const i=[];for(const r of e)if(r.startsWith("m=audio")&&(i.push(null),n=!0),r.startsWith("m=video")&&(n=!1),n){const e=t.exec(r);null!==e&&(i[i.length-1]=`a=fmtp:${e[1]} `)}return i}static updateOpusFmtpAttributes(e,t,n){const i=[];let r=0,a=null;for(const o of e)if(o.startsWith("m=audio")&&(a=t[r],r++),o.startsWith("m=video")&&(a=null),a&&o.startsWith(a)){const e=o.slice(a.length).split(";"),t=[];for(const i of e)n.findIndex((e=>e.startsWith(i.split("=")[0])))<0&&t.push(i);for(const e of n)t.push(e);i.push(a+t.join(";"))}else i.push(o);return i}withUnifiedPlanFormat(){let e=this.sdp;return e.includes("mozilla")?this.clone():(e=e.replace("o=-","o=mozilla-chrome"),new s(e))}getUniqueRtpHeaderExtensionId(e){const t=[];for(const n of e)if(/^a=extmap:/.test(n.trim())){const e=+n.split("a=extmap:")[1].split(" ")[0];t.includes(e)||t.push(e)}t.sort(((e,t)=>e-t));let n=0;for(const e of t){if(e-n>1)return n+1;n=e}return 14===n?-1:n+1}withVideoLayersAllocationRtpHeaderExtension(e){return this.withRtpHeaderExtension(e,s.videoLayersAllocationRtpHeaderExtensionUrl)}withDependencyDescriptorRtpHeaderExtension(e){return this.withRtpHeaderExtension(e,s.dependencyDescriptorRtpHeaderExtensionUrl)}withoutDependencyDescriptorRtpHeaderExtension(){const e=s.splitLines(this.sdp).filter((e=>!e.includes(s.dependencyDescriptorRtpHeaderExtensionUrl)));return new s(e.join(s.CRLF)+s.CRLF)}withRtpHeaderExtension(e,t){const n=e?e.getRtpHeaderExtensionId(t):-1,i=-1===n?this.getUniqueRtpHeaderExtensionId(s.splitLines(this.sdp)):n,r=s.splitSections(this.sdp),a=[];for(let e of r){if(/^m=video/.test(e)&&-1===s.getRtpHeaderExtensionIdInSection(e,t)){const n=s.splitLines(e),r=[];if(-1===i||this.hasRtpHeaderExtensionId(i)){a.push(e);continue}for(const e of n)if(r.push(e),/^a=sendrecv/.test(e.trim())){const e="a=extmap:"+i+" "+t;r.push(e)}e=r.join(s.CRLF)+s.CRLF}else if(-1!==n&&/^m=video/.test(e)&&s.getRtpHeaderExtensionIdInSection(e,t)!==n){const i=s.splitLines(e),r=[];for(const e of i)if(/^a=extmap:/.test(e.trim())&&e.split("a=extmap:")[1].split(" ")[1]===t){if(!this.hasRtpHeaderExtensionId(n)){const e="a=extmap:"+n+" "+t;r.push(e)}}else r.push(e);e=r.join(s.CRLF)+s.CRLF}a.push(e)}const o=a.join("");return new s(o)}ssrcForVideoSendingSection(){const e=this.sdp,t=s.splitSections(e);if(t.length<2)return"";const n=s.findActiveCameraSection(t);if(-1===n)return"";const i=s.matchPrefix(t[n],"a=ssrc-group:FID ");if(i.length<1)return"";const r=s.extractSSRCsFromFIDGroupLine(i[0]),[a]=r.split(" ").map((e=>parseInt(e,10)));return a.toString()}videoSendSectionHasDifferentSSRC(e){const t=this.ssrcForVideoSendingSection(),n=e.ssrcForVideoSendingSection();return""!==t&&""!==n&&parseInt(t,10)!==parseInt(n,10)}removeH264SupportFromSendSection(){const e=this.sdp,t=s.splitSections(e),n=s.findActiveCameraSection(t);if(-1===n)return new s(this.sdp);const i=t[n],r=s.splitLines(i),a=[],o=new Map;r.forEach((e=>{if(/^a=rtpmap:/.test(e)){const t=/^a=rtpmap:([0-9]+)\s/.exec(e);t&&e.toLowerCase().includes("h264")&&a.push(parseInt(t[1],10))}if(/^a=fmtp:/.test(e)){const t=/^a=fmtp:([0-9]+) apt=([0-9]+)/.exec(e);if(t&&3===t.length){const e=parseInt(t[1],10),n=parseInt(t[2],10);o.has(n)?o.get(n).push(e):o.set(n,[e])}}}));const c=new Set;for(const e of a){c.add(e);const t=o.get(e);if(t)for(const e of t)c.add(e)}if(a.length>0){const e=r[0].split(" ");r[0]=e.filter((e=>!c.has(parseInt(e)))).join(" ")}const l=r.filter((e=>{if(!e.includes("rtpmap")&&!e.includes("rtcp-fb")&&!e.includes("fmtp"))return!0;for(const t of c)if(e.includes(t.toString()))return!1;return!0}));t[n]=l.join(s.CRLF)+s.CRLF;const d=t.join("");return new s(d)}mediaSections(){const e=s.splitSections(this.sdp);if(e.length<2)return[];const t=[];for(let n=1;n{if(!e.startsWith("a=rtpmap:"))return;const r=/^a=rtpmap:(\d+)\s/.exec(e);if(!r)return;const a=r[1];for(const r of t){if(!e.includes(`${r.codecName}/${r.codecCapability.clockRate}`))continue;let t=!1;if(void 0!==r.codecCapability.sdpFmtpLine){let e=!1;for(const n of i){if(r.fmtpLineMatches(n,parseInt(a))){t=!0;break}e||(e=n.startsWith(`a=fmtp:${a} profile-id=`))}r.equals(o.default.vp9Profile0())&&!e&&(t=!0)}else t=!0;if(t){n.set(a,r);break}}}));const r=new Set(n.keys()),a=i[0].split(" ").filter((e=>!r.has(e))),c=Array.from(n.entries()).sort((([e,n],[i,r])=>t.indexOf(n)-t.indexOf(r))).map((([e,t])=>e));return a.splice(3,0,...c),i[0]=a.join(" "),i.join(s.CRLF)+s.CRLF}highestPriorityVideoSendCodec(){const e=this.prioritizedSendVideoCodecCapabilities();return e.length>0?e[0]:void 0}prioritizedSendVideoCodecCapabilities(){const e=this.sdp,t=s.splitSections(e),n=s.findActiveCameraSection(t);if(-1===n)return[];const i=s.splitLines(t[n]),r=i[0].split(" ");return r.length<4?[]:r.slice(3).map((e=>this.videoCodecCapabilityForPayloadType(i,e))).filter((e=>void 0!==e&&["VP8","H264","VP9","AV1"].includes(e.codecName)))}videoCodecCapabilityForPayloadType(e,t){let n,i,r;for(const a of e){const e=/^a=rtpmap:([0-9]+)\s/.exec(a);if(e&&e[1]===t){const e=a.split(" ")[1].split("/");e.length>=2&&(n=e[0],i=e[1])}a.startsWith(`a=fmtp:${t} `)&&(r=a.split(" ")[1])}if(void 0!==n)return new o.default(n,{clockRate:parseInt(i),mimeType:`video/${n}`,sdpFmtpLine:r})}getAudioPayloadTypes(){const e=new Map,t=this.sdp,n=s.splitSections(t);return e.set("opus",s.findAudioPayloadType("opus",n)),e.set("red",s.findAudioPayloadType("red",n)),e}static findAudioPayloadType(e,t){const n=new RegExp(`a=rtpmap:\\s*(\\d+)\\s+${e}\\/48000`);for(const e of t)if(/^m=audio/.test(e)){const t=n.exec(e);if(null!==t)return Number(t[1])}return 0}withStartingVideoSendBitrate(e){const t=s.splitSections(this.sdp),n=s.findActiveCameraSection(t);if(-1===n)return this;const i=s.splitLines(t[n]),r=[];for(const t of i)if(/^a=fmtp:\d*/.test(t)){const n=t+";x-google-start-bitrate="+1e3*e;r.push(n)}else r.push(t);t[n]=r.join(s.CRLF)+s.CRLF;const a=t.join("");return new s(a)}}t.default=s,s.CRLF="\r\n",s.rfc7587LowestBitrate=6e3,s.rfc7587HighestBitrate=51e4,s.dependencyDescriptorRtpHeaderExtensionUrl="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension",s.videoLayersAllocationRtpHeaderExtensionUrl="http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00"},9762:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SDPCandidateType=void 0,function(e){e.Host="host",e.ServerReflexive="srflx",e.PeerReflexive="prflx",e.Relay="relay"}(n=t.SDPCandidateType||(t.SDPCandidateType={})),t.default=n},356:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{}},2049:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(4955);class r{constructor(e,t){this.codecName=e,this.codecCapability=t}equals(e){return void 0!==e&&this.codecName===e.codecName&&this.codecCapability.mimeType===e.codecCapability.mimeType&&this.codecCapability.clockRate===e.codecCapability.clockRate&&this.codecCapability.sdpFmtpLine===e.codecCapability.sdpFmtpLine}fmtpLineMatches(e,t){const n=this.codecCapability.sdpFmtpLine;if(!n)return!1;if("H264"===this.codecName){const i=/profile-level-id=([0-9a-f]{4})[0-9a-f]{2}/i,r=n.replace(i,"profile-level-id=$1");return e.replace(i,"profile-level-id=$1").startsWith(`a=fmtp:${t} ${r}`)}return e.startsWith(`a=fmtp:${t} ${n}`)}static vp8(){return new r("VP8",{clockRate:9e4,mimeType:"video/VP8"})}static h264BaselineProfile(){return new r("H264",{clockRate:9e4,mimeType:"video/H264",sdpFmtpLine:"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f"})}static h264ConstrainedBaselineProfile(){return new r("H264",{clockRate:9e4,mimeType:"video/H264",sdpFmtpLine:"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"})}static h264MainProfile(){return new r("H264",{clockRate:9e4,mimeType:"video/H264",sdpFmtpLine:"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f"})}static h264HighProfile(){return new r("H264",{clockRate:9e4,mimeType:"video/H264",sdpFmtpLine:"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=64001f"})}static h264ConstrainedHighProfile(){return new r("H264",{clockRate:9e4,mimeType:"video/H264",sdpFmtpLine:"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640c1f"})}static h264(){return r.h264ConstrainedBaselineProfile()}static vp9Profile0(){return new r("VP9",{clockRate:9e4,mimeType:"video/VP9",sdpFmtpLine:"profile-id=0"})}static vp9(){return r.vp9Profile0()}static av1Main(){return new r("AV1",{clockRate:9e4,mimeType:"video/AV1"})}static av1(){return r.av1Main()}static fromSignaled(e){switch(e){case i.SdkVideoCodecCapability.VP8:return r.vp8();case i.SdkVideoCodecCapability.H264_BASELINE_PROFILE:return r.h264BaselineProfile();case i.SdkVideoCodecCapability.H264_CONSTRAINED_BASELINE_PROFILE:return r.h264ConstrainedBaselineProfile();case i.SdkVideoCodecCapability.H264_MAIN_PROFILE:return r.h264MainProfile();case i.SdkVideoCodecCapability.H264_HIGH_PROFILE:return r.h264HighProfile();case i.SdkVideoCodecCapability.H264_CONSTRAINED_HIGH_PROFILE:return r.h264ConstrainedHighProfile();case i.SdkVideoCodecCapability.VP9_PROFILE_0:return r.vp9Profile0();case i.SdkVideoCodecCapability.AV1_MAIN_PROFILE:return r.av1Main();default:return}}}t.default=r},4095:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(1668);class r{constructor(e){this.logger=e}compress(e,t){if(t.length>0){const e=Math.min(t.length,r.MAX_DICTIONARY_SIZE);t=t.slice(0,e)}const n={memLevel:r.Z_MEM_LEVEL,dictionary:t};return i.deflateRaw(e,n)}decompress(e,t){if(t.length>0){const e=Math.min(t.length,r.MAX_DICTIONARY_SIZE);t=t.slice(0,e)}const n={to:"string",dictionary:t,chunkSize:4096};let a="";try{a=i.inflateRaw(e,n)}catch(e){this.logger.error(`failed to decompress the string with error: [${e}]`)}return a}}t.default=r,r.Z_MEM_LEVEL=9,r.MAX_DICTIONARY_SIZE=31744},3240:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3797),r=n(3955),a=n(7670),o=n(2005);t.default=class{constructor(e){this.logger=e,this.currentState=a.SessionStateControllerState.NotConnected,this.deferredAction=null,this.deferredWork=null}perform(e,t){const n=this.currentState;if(n===a.SessionStateControllerState.NotConnected&&e===i.SessionStateControllerAction.Connect)this.transition(a.SessionStateControllerState.Connecting,e);else if(n===a.SessionStateControllerState.Connecting&&e===i.SessionStateControllerAction.Fail)this.transition(a.SessionStateControllerState.Disconnecting,e);else if(n===a.SessionStateControllerState.Connecting&&e===i.SessionStateControllerAction.FinishConnecting)this.transition(a.SessionStateControllerState.Connected,e);else if(n===a.SessionStateControllerState.Connected&&e===i.SessionStateControllerAction.Disconnect)this.transition(a.SessionStateControllerState.Disconnecting,e);else if(n===a.SessionStateControllerState.Connected&&e===i.SessionStateControllerAction.Reconnect)this.transition(a.SessionStateControllerState.Connecting,e);else if(n===a.SessionStateControllerState.Connected&&e===i.SessionStateControllerAction.Fail)this.transition(a.SessionStateControllerState.Disconnecting,e);else if(n===a.SessionStateControllerState.Connected&&e===i.SessionStateControllerAction.Update)this.transition(a.SessionStateControllerState.Updating,e);else if(n===a.SessionStateControllerState.Updating&&e===i.SessionStateControllerAction.Fail)this.transition(a.SessionStateControllerState.Disconnecting,e);else if(n===a.SessionStateControllerState.Updating&&e===i.SessionStateControllerAction.FinishUpdating)this.transition(a.SessionStateControllerState.Connected,e);else{if(n!==a.SessionStateControllerState.Disconnecting||e!==i.SessionStateControllerAction.FinishDisconnecting)return this.canDefer(e)?(this.logger.info(`deferring transition from ${a.SessionStateControllerState[this.currentState]} with ${i.SessionStateControllerAction[e]}`),this.deferAction(e,t),o.SessionStateControllerTransitionResult.DeferredTransition):(this.logger.warn(`no transition found from ${a.SessionStateControllerState[this.currentState]} with ${i.SessionStateControllerAction[e]}`),o.SessionStateControllerTransitionResult.NoTransitionAvailable);this.transition(a.SessionStateControllerState.NotConnected,e)}try{t()}catch(t){return this.logger.error(`error during state ${a.SessionStateControllerState[this.currentState]} with action ${i.SessionStateControllerAction[e]}: ${t}`),this.logger.info(`rolling back transition to ${a.SessionStateControllerState[n]}`),this.currentState=n,o.SessionStateControllerTransitionResult.TransitionFailed}return this.performDeferredAction(),o.SessionStateControllerTransitionResult.Transitioned}state(){return this.currentState}transition(e,t){this.logger.info(`transitioning from ${a.SessionStateControllerState[this.currentState]} to ${a.SessionStateControllerState[e]} with ${i.SessionStateControllerAction[t]}`),this.currentState=e}deferPriority(e){switch(e){case i.SessionStateControllerAction.Disconnect:return r.SessionStateControllerDeferPriority.VeryHigh;case i.SessionStateControllerAction.Fail:return r.SessionStateControllerDeferPriority.High;case i.SessionStateControllerAction.Reconnect:return r.SessionStateControllerDeferPriority.Medium;case i.SessionStateControllerAction.Update:return r.SessionStateControllerDeferPriority.Low;default:return r.SessionStateControllerDeferPriority.DoNotDefer}}deferAction(e,t){null!==this.deferredAction&&this.deferPriority(this.deferredAction)>this.deferPriority(e)||(this.deferredAction=e,this.deferredWork=t)}canDefer(e){return this.deferPriority(e)!==r.SessionStateControllerDeferPriority.DoNotDefer&&(this.currentState===a.SessionStateControllerState.Connecting||this.currentState===a.SessionStateControllerState.Updating)}performDeferredAction(){if(!this.deferredAction)return;const e=this.deferredAction,t=this.deferredWork;this.deferredAction=null,this.deferredWork=null,this.logger.info(`performing deferred action ${i.SessionStateControllerAction[e]}`),this.perform(e,t)!==o.SessionStateControllerTransitionResult.Transitioned&&this.logger.info(`unable to perform deferred action ${i.SessionStateControllerAction[e]} in state ${a.SessionStateControllerState[this.currentState]}`)}}},3797:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SessionStateControllerAction=void 0,function(e){e[e.Connect=0]="Connect",e[e.FinishConnecting=1]="FinishConnecting",e[e.Update=2]="Update",e[e.FinishUpdating=3]="FinishUpdating",e[e.Reconnect=4]="Reconnect",e[e.Disconnect=5]="Disconnect",e[e.Fail=6]="Fail",e[e.FinishDisconnecting=7]="FinishDisconnecting"}(n=t.SessionStateControllerAction||(t.SessionStateControllerAction={})),t.default=n},3955:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SessionStateControllerDeferPriority=void 0,function(e){e[e.DoNotDefer=0]="DoNotDefer",e[e.Low=1]="Low",e[e.Medium=2]="Medium",e[e.High=3]="High",e[e.VeryHigh=4]="VeryHigh"}(n=t.SessionStateControllerDeferPriority||(t.SessionStateControllerDeferPriority={})),t.default=n},7670:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SessionStateControllerState=void 0,function(e){e[e.NotConnected=0]="NotConnected",e[e.Connecting=1]="Connecting",e[e.Connected=2]="Connected",e[e.Updating=3]="Updating",e[e.Disconnecting=4]="Disconnecting"}(n=t.SessionStateControllerState||(t.SessionStateControllerState={})),t.default=n},2005:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SessionStateControllerTransitionResult=void 0,function(e){e[e.Transitioned=0]="Transitioned",e[e.NoTransitionAvailable=1]="NoTransitionAvailable",e[e.DeferredTransition=2]="DeferredTransition",e[e.TransitionFailed=3]="TransitionFailed"}(n=t.SessionStateControllerTransitionResult||(t.SessionStateControllerTransitionResult={})),t.default=n},5826:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(6244)),a=i(n(1340)),o=n(4955),s=n(9979),c=i(n(6741)),l=i(n(1583)),d=i(n(4696)),u=n(980),f=i(n(2887)),h=i(n(9183));class m{constructor(e,t){this.webSocket=e,this.logger=t,this.unloadHandler=null,this.closeEventHandler=e=>{this.deactivatePageUnloadHandler(),this.resetConnection(),this.sendEvent(new f.default(this,h.default.WebSocketClosed,null,e.code,e.reason)),this.serviceConnectionRequestQueue()},this.observerQueue=new Set,this.connectionRequestQueue=[],this.resetConnection(),this.logger.debug((()=>"signaling client init")),this.audioSessionId=this.generateNewAudioSessionId()}registerObserver(e){this.logger.debug((()=>"registering signaling client observer")),this.observerQueue.add(e)}removeObserver(e){this.logger.debug((()=>"removing signaling client observer")),this.observerQueue.delete(e)}openConnection(e){this.logger.info("adding connection request to queue: "+e.url()),this.connectionRequestQueue.push(e),this.closeConnection()}pingPong(e){this.logger.debug((()=>"sending ping"));const t=o.SdkSignalFrame.create();return t.type=o.SdkSignalFrame.Type.PING_PONG,t.pingPong=e,this.sendMessage(t),t.timestampMs}join(e){this.logger.info("sending join");const t=o.SdkJoinFrame.create();t.protocolVersion=2,t.flags=o.SdkJoinFlags.HAS_STREAM_UPDATE;const n=new r.default,i={platformName:n.name(),platformVersion:n.version(),clientSource:c.default.sdkName,chimeSdkVersion:c.default.sdkVersion,clientUtcOffset:s.getFormattedOffset((new Date).getTimezoneOffset())};if(e.applicationMetadata){const{appName:t,appVersion:n}=e.applicationMetadata;i.appName=t,i.appVersion=n}t.clientDetails=o.SdkClientDetails.create(i),t.audioSessionId=this.audioSessionId,t.wantsCompressedSdp=m.CLIENT_SUPPORTS_COMPRESSION,t.disablePeriodicKeyframeRequestOnContentSender=e.disablePeriodicKeyframeRequestOnContentSender,t.serverSideNetworkAdaption=u.convertServerSideNetworkAdaptionEnumToSignaled(e.serverSideNetworkAdaption),t.supportedServerSideNetworkAdaptions=e.supportedServerSideNetworkAdaptions.map(u.convertServerSideNetworkAdaptionEnumToSignaled),t.wantsAllTemporalLayersInIndex=e.wantsAllTemporalLayersInIndex;const a=o.SdkSignalFrame.create();a.type=o.SdkSignalFrame.Type.JOIN,a.join=t,this.sendMessage(a)}subscribe(e){const t=o.SdkSubscribeFrame.create();if(t.sendStreams=[],t.sdpOffer=e.sdpOffer,e.connectionTypeHasVideo&&(t.receiveStreamIds=e.receiveStreamIds),e.audioHost&&(t.audioCheckin=e.audioCheckin,t.audioHost=e.audioHost,t.audioMuted=e.audioMuted,!e.audioCheckin)){const n=o.SdkStreamDescriptor.create();n.mediaType=o.SdkStreamMediaType.AUDIO,n.trackLabel="AmazonChimeExpressAudio",n.attendeeId=e.attendeeId,n.streamId=1,n.groupId=1,n.framerate=15,n.maxBitrateKbps=600,n.avgBitrateBps=4e5,t.sendStreams.push(n)}if(t.compressedSdpOffer=e.compressedSdpOffer,t.duplex=o.SdkStreamServiceType.RX,e.localVideoEnabled){t.duplex=o.SdkStreamServiceType.DUPLEX;for(let n=0;n0&&(t.videoSubscriptionConfiguration=e.videoSubscriptionConfiguration.map(this.convertSignalingClientVideoSubscriptionConfiguration));const n=o.SdkSignalFrame.create();n.type=o.SdkSignalFrame.Type.SUBSCRIBE,n.sub=t,this.sendMessage(n)}remoteVideoUpdate(e,t){const n=o.SdkRemoteVideoUpdateFrame.create();n.addedOrUpdatedVideoSubscriptions=e.map(this.convertSignalingClientVideoSubscriptionConfiguration),n.removedVideoSubscriptionMids=t;const i=o.SdkSignalFrame.create();i.type=o.SdkSignalFrame.Type.REMOTE_VIDEO_UPDATE,i.remoteVideoUpdate=n,this.sendMessage(i)}convertSignalingClientVideoSubscriptionConfiguration(e){const t=new o.SdkVideoSubscriptionConfiguration;switch(t.mid=e.mid,t.attendeeId=e.attendeeId,t.streamId=e.streamId,t.groupId=e.groupId,t.priority=e.priority,t.targetBitrateKbps=e.targetBitrateKbps,e.qualityAdaptationPreference){case l.default.Balanced:t.qualityAdaptationPreference=o.SdkVideoQualityAdaptationPreference.BALANCED;break;case l.default.MaintainFramerate:t.qualityAdaptationPreference=o.SdkVideoQualityAdaptationPreference.MAINTAIN_FRAMERATE;break;case l.default.MaintainResolution:t.qualityAdaptationPreference=o.SdkVideoQualityAdaptationPreference.MAINTAIN_RESOLUTION;break;default:t.qualityAdaptationPreference=o.SdkVideoQualityAdaptationPreference.BALANCED}return t}leave(){const e=o.SdkSignalFrame.create();e.type=o.SdkSignalFrame.Type.LEAVE,e.leave=o.SdkLeaveFrame.create(),this.sendMessage(e),this.logger.debug((()=>"sent leave"))}sendClientMetrics(e){const t=o.SdkSignalFrame.create();t.type=o.SdkSignalFrame.Type.CLIENT_METRIC,t.clientMetric=e,this.sendMessage(t)}sendDataMessage(e){const t=o.SdkSignalFrame.create();t.type=o.SdkSignalFrame.Type.DATA_MESSAGE,t.dataMessage=e,this.sendMessage(t)}closeConnection(){var e,t;if(this.webSocket.readyState()!==d.default.None&&this.webSocket.readyState()!==d.default.Closed){this.isClosing=!0,this.sendEvent(new f.default(this,h.default.WebSocketClosing,null));const n=new a.default(m.CLOSE_EVENT_TIMEOUT_MS),i=e=>{var t,r;null===(r=(t=this.webSocket).removeEventListener)||void 0===r||r.call(t,"close",i),n.stop(),this.closeEventHandler(e)};null===(t=(e=this.webSocket).removeEventListener)||void 0===t||t.call(e,"close",this.closeEventHandler),this.webSocket.addEventListener("close",i),n.start((()=>{i(new CloseEvent("close",{wasClean:!1,code:1006,reason:"",bubbles:!1}))})),this.webSocket.close(),this.deactivatePageUnloadHandler()}else this.logger.info("no existing signaling client connection needs closing"),this.serviceConnectionRequestQueue()}ready(){return this.webSocket.readyState()===d.default.Open&&!this.isClosing&&this.wasOpened}mute(e){const t=o.SdkSignalFrame.create();t.type=o.SdkSignalFrame.Type.AUDIO_CONTROL;const n=o.SdkAudioControlFrame.create();n.muted=e,t.audioControl=n,this.sendMessage(t)}pause(e){const t=o.SdkSignalFrame.create();t.type=o.SdkSignalFrame.Type.PAUSE,t.pause=o.SdkPauseResumeFrame.create(),t.pause.streamIds=e,this.sendMessage(t)}resume(e){const t=o.SdkSignalFrame.create();t.type=o.SdkSignalFrame.Type.RESUME,t.pause=o.SdkPauseResumeFrame.create(),t.pause.streamIds=e,this.sendMessage(t)}resetConnection(){this.webSocket.destroy(),this.wasOpened=!1}sendMessage(e){e.timestampMs=Date.now(),this.logger.debug((()=>`sending: ${JSON.stringify(e)}`));const t=this.prependWithFrameTypeRTC(o.SdkSignalFrame.encode(e).finish());if(this.ready()){if(!this.webSocket.send(t))return void this.sendEvent(new f.default(this,h.default.WebSocketSendMessageFailure,null));this.sendEvent(new f.default(this,h.default.WebSocketSentMessage,null))}else this.sendEvent(new f.default(this,h.default.WebSocketSkippedMessage,null))}receiveMessage(e){let t;try{t=o.SdkSignalFrame.decode(e)}catch(t){return this.logger.info(`failed to decode: ${e}`),void this.sendEvent(new f.default(this,h.default.ProtocolDecodeFailure,null))}this.logger.debug((()=>`received: ${JSON.stringify(t)}`)),this.webSocket.readyState()===d.default.Open?this.sendEvent(new f.default(this,h.default.ReceivedSignalFrame,t)):this.logger.info(`skipping notification of message since WebSocket is not open: ${JSON.stringify(t)}`)}stripFrameTypeRTC(e){const t=e[0];return t!==m.FRAME_TYPE_RTC&&2!==t&&this.logger.warn(`expected FrameTypeRTC for message but got ${t}`),e.slice(1)}prependWithFrameTypeRTC(e){const t=new Uint8Array(e.length+1);return t[0]=m.FRAME_TYPE_RTC,t.set(e,1),t}serviceConnectionRequestQueue(){if(0===this.connectionRequestQueue.length)return void this.logger.info("no connection requests to service");const e=this.connectionRequestQueue.shift();this.logger.info(`opening connection to ${e.url()}`),this.isClosing=!1,this.webSocket.create(e.url(),e.protocols()),this.setUpEventListeners(),this.sendEvent(new f.default(this,h.default.WebSocketConnecting,null))}sendEvent(e){switch(e.type){case h.default.WebSocketMessage:case h.default.ReceivedSignalFrame:case h.default.WebSocketSentMessage:this.logger.debug((()=>`notifying event: ${h.default[e.type]}`));break;case h.default.WebSocketSkippedMessage:this.logger.debug((()=>`notifying event: ${h.default[e.type]}, websocket state=${d.default[this.webSocket.readyState()]}`));break;default:this.logger.info(`notifying event: ${h.default[e.type]}`)}for(const t of this.observerQueue)t.handleSignalingClientEvent(e)}setUpEventListeners(){this.webSocket.addEventListener("open",(()=>{this.activatePageUnloadHandler(),this.wasOpened=!0,this.sendEvent(new f.default(this,h.default.WebSocketOpen,null))})),this.webSocket.addEventListener("message",(e=>{this.sendEvent(new f.default(this,h.default.WebSocketMessage,null)),this.receiveMessage(this.stripFrameTypeRTC(new Uint8Array(e.data)))})),this.webSocket.addEventListener("close",this.closeEventHandler),this.webSocket.addEventListener("error",(()=>{!this.isClosing||this.wasOpened?this.wasOpened?(this.logger.error("received error while connected"),this.sendEvent(new f.default(this,h.default.WebSocketError,null))):(this.logger.error("failed to connect"),this.sendEvent(new f.default(this,h.default.WebSocketFailed,null))):this.logger.info("ignoring error closing signaling while connecting")}))}activatePageUnloadHandler(){this.unloadHandler=()=>{this.leave()};const e=n.g;e.window&&e.window.addEventListener&&window.addEventListener("unload",this.unloadHandler)}deactivatePageUnloadHandler(){const e=n.g;e.window&&e.window.removeEventListener&&window.removeEventListener("unload",this.unloadHandler),this.unloadHandler=null}generateNewAudioSessionId(){const e=new Uint32Array(1);return s.getRandomValues(e),e[0]}promoteToPrimaryMeeting(e){const t=o.SdkMeetingSessionCredentials.create();t.attendeeId=e.attendeeId,t.externalUserId=e.externalUserId,t.joinToken=e.joinToken;const n=o.SdkPrimaryMeetingJoinFrame.create();n.credentials=t;const i=o.SdkSignalFrame.create();i.type=o.SdkSignalFrame.Type.PRIMARY_MEETING_JOIN,i.primaryMeetingJoin=n,this.sendMessage(i)}demoteFromPrimaryMeeting(){const e=o.SdkPrimaryMeetingLeaveFrame.create(),t=o.SdkSignalFrame.create();t.type=o.SdkSignalFrame.Type.PRIMARY_MEETING_LEAVE,t.primaryMeetingLeave=e,this.sendMessage(t)}}t.default=m,m.FRAME_TYPE_RTC=5,m.CLOSE_EVENT_TIMEOUT_MS=2e3,m.CLIENT_SUPPORTS_COMPRESSION=!0},980:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.convertServerSideNetworkAdaptionEnumToSignaled=t.convertServerSideNetworkAdaptionEnumFromSignaled=t.serverSideNetworkAdaptionIsNoneOrDefault=t.ServerSideNetworkAdaption=void 0;const i=n(4955);var r;!function(e){e[e.Default=0]="Default",e[e.None=1]="None",e[e.BandwidthProbing=2]="BandwidthProbing",e[e.BandwidthProbingAndRemoteVideoQualityAdaption=3]="BandwidthProbingAndRemoteVideoQualityAdaption"}(r=t.ServerSideNetworkAdaption||(t.ServerSideNetworkAdaption={})),t.default=r,t.serverSideNetworkAdaptionIsNoneOrDefault=function(e){return e===r.None||e===r.Default},t.convertServerSideNetworkAdaptionEnumFromSignaled=function(e){switch(e){case i.SdkServerSideNetworkAdaption.DEFAULT:return r.Default;case i.SdkServerSideNetworkAdaption.NONE:return r.None;case i.SdkServerSideNetworkAdaption.BANDWIDTH_PROBING:return r.BandwidthProbing;case i.SdkServerSideNetworkAdaption.BANDWIDTH_PROBING_AND_VIDEO_QUALITY_ADAPTION:return r.BandwidthProbingAndRemoteVideoQualityAdaption}},t.convertServerSideNetworkAdaptionEnumToSignaled=function(e){switch(e){case r.Default:return i.SdkServerSideNetworkAdaption.DEFAULT;case r.None:return i.SdkServerSideNetworkAdaption.NONE;case r.BandwidthProbing:return i.SdkServerSideNetworkAdaption.BANDWIDTH_PROBING;case r.BandwidthProbingAndRemoteVideoQualityAdaption:return i.SdkServerSideNetworkAdaption.BANDWIDTH_PROBING_AND_VIDEO_QUALITY_ADAPTION}}},2114:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t){this.signalingURL=e,this.joinToken=t}url(){return this.signalingURL+"?X-Chime-Control-Protocol-Version=3&X-Amzn-Chime-Send-Close-On-Error=1"}protocols(){return["_aws_wt_session",this.joinToken]}}},2887:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(9183));t.default=class{constructor(e,t,n,i,r){this.client=e,this.type=t,this.message=n,this.closeCode=i,this.closeReason=r,this.timestampMs=Date.now()}isConnectionTerminated(){switch(this.type){case r.default.WebSocketFailed:case r.default.WebSocketError:case r.default.WebSocketClosing:case r.default.WebSocketClosed:return!0;default:return!1}}}},9183:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SignalingClientEventType=void 0,function(e){e[e.WebSocketConnecting=0]="WebSocketConnecting",e[e.WebSocketOpen=1]="WebSocketOpen",e[e.WebSocketError=2]="WebSocketError",e[e.WebSocketClosing=3]="WebSocketClosing",e[e.WebSocketClosed=4]="WebSocketClosed",e[e.WebSocketFailed=5]="WebSocketFailed",e[e.WebSocketMessage=6]="WebSocketMessage",e[e.WebSocketSendMessageFailure=7]="WebSocketSendMessageFailure",e[e.WebSocketSentMessage=8]="WebSocketSentMessage",e[e.ProtocolDecodeFailure=9]="ProtocolDecodeFailure",e[e.ReceivedSignalFrame=10]="ReceivedSignalFrame",e[e.WebSocketSkippedMessage=11]="WebSocketSkippedMessage"}(n=t.SignalingClientEventType||(t.SignalingClientEventType={})),t.default=n},1903:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(980));t.default=class{constructor(e){this.applicationMetadata=e,this.serverSideNetworkAdaption=r.default.Default,this.supportedServerSideNetworkAdaptions=[],this.wantsAllTemporalLayersInIndex=!1,this.disablePeriodicKeyframeRequestOnContentSender=!1}}},9295:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t,n,i,r,a,o,s,c,l){this.attendeeId=e,this.sdpOffer=t,this.audioHost=n,this.audioMuted=i,this.audioCheckin=r,this.receiveStreamIds=a,this.localVideoEnabled=o,this.videoStreamDescriptions=s,this.connectionTypeHasVideo=c,this.compressedSdpOffer=l,this.videoSubscriptionConfiguration=[]}}},9171:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{equals(e){return void 0!==e&&this.mid===e.mid&&this.attendeeId===e.attendeeId&&this.streamId===e.streamId&&this.groupId===e.groupId&&this.priority===e.priority&&this.targetBitrateKbps===e.targetBitrateKbps&&this.qualityAdaptationPreference===e.qualityAdaptationPreference}}},4955:(e,t,n)=>{"use strict";var i,r,a=n(6946),o=a.Reader,s=a.Writer,c=a.util,l=a.roots.default||(a.roots.default={});l.SdkSignalFrame=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.timestampMs=e.uint64();break;case 2:i.type=e.int32();break;case 3:i.error=l.SdkErrorFrame.decode(e,e.uint32());break;case 4:i.join=l.SdkJoinFrame.decode(e,e.uint32());break;case 5:i.joinack=l.SdkJoinAckFrame.decode(e,e.uint32());break;case 6:i.sub=l.SdkSubscribeFrame.decode(e,e.uint32());break;case 7:i.suback=l.SdkSubscribeAckFrame.decode(e,e.uint32());break;case 8:i.index=l.SdkIndexFrame.decode(e,e.uint32());break;case 10:i.pause=l.SdkPauseResumeFrame.decode(e,e.uint32());break;case 11:i.leave=l.SdkLeaveFrame.decode(e,e.uint32());break;case 12:i.leaveAck=l.SdkLeaveAckFrame.decode(e,e.uint32());break;case 14:i.bitrates=l.SdkBitrateFrame.decode(e,e.uint32());break;case 17:i.audioControl=l.SdkAudioControlFrame.decode(e,e.uint32());break;case 18:i.audioMetadata=l.SdkAudioMetadataFrame.decode(e,e.uint32());break;case 19:i.audioStreamIdInfo=l.SdkAudioStreamIdInfoFrame.decode(e,e.uint32());break;case 20:i.pingPong=l.SdkPingPongFrame.decode(e,e.uint32());break;case 21:i.audioStatus=l.SdkAudioStatusFrame.decode(e,e.uint32());break;case 22:i.clientMetric=l.SdkClientMetricFrame.decode(e,e.uint32());break;case 23:i.dataMessage=l.SdkDataMessageFrame.decode(e,e.uint32());break;case 25:i.remoteVideoUpdate=l.SdkRemoteVideoUpdateFrame.decode(e,e.uint32());break;case 26:i.primaryMeetingJoin=l.SdkPrimaryMeetingJoinFrame.decode(e,e.uint32());break;case 27:i.primaryMeetingJoinAck=l.SdkPrimaryMeetingJoinAckFrame.decode(e,e.uint32());break;case 28:i.primaryMeetingLeave=l.SdkPrimaryMeetingLeaveFrame.decode(e,e.uint32());break;case 35:i.notification=l.SdkNotificationFrame.decode(e,e.uint32());break;default:e.skipType(7&r)}}if(!i.hasOwnProperty("timestampMs"))throw c.ProtocolError("missing required 'timestampMs'",{instance:i});if(!i.hasOwnProperty("type"))throw c.ProtocolError("missing required 'type'",{instance:i});return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(!(c.isInteger(e.timestampMs)||e.timestampMs&&c.isInteger(e.timestampMs.low)&&c.isInteger(e.timestampMs.high)))return"timestampMs: integer|Long expected";switch(e.type){default:return"type: enum value expected";case 1:case 2:case 3:case 4:case 5:case 7:case 8:case 9:case 10:case 13:case 16:case 17:case 18:case 19:case 20:case 21:case 22:case 24:case 25:case 26:case 27:case 34:}var t;return null!=e.error&&e.hasOwnProperty("error")&&(t=l.SdkErrorFrame.verify(e.error))?"error."+t:null!=e.join&&e.hasOwnProperty("join")&&(t=l.SdkJoinFrame.verify(e.join))?"join."+t:null!=e.joinack&&e.hasOwnProperty("joinack")&&(t=l.SdkJoinAckFrame.verify(e.joinack))?"joinack."+t:null!=e.sub&&e.hasOwnProperty("sub")&&(t=l.SdkSubscribeFrame.verify(e.sub))?"sub."+t:null!=e.suback&&e.hasOwnProperty("suback")&&(t=l.SdkSubscribeAckFrame.verify(e.suback))?"suback."+t:null!=e.index&&e.hasOwnProperty("index")&&(t=l.SdkIndexFrame.verify(e.index))?"index."+t:null!=e.pause&&e.hasOwnProperty("pause")&&(t=l.SdkPauseResumeFrame.verify(e.pause))?"pause."+t:null!=e.leave&&e.hasOwnProperty("leave")&&(t=l.SdkLeaveFrame.verify(e.leave))?"leave."+t:null!=e.leaveAck&&e.hasOwnProperty("leaveAck")&&(t=l.SdkLeaveAckFrame.verify(e.leaveAck))?"leaveAck."+t:null!=e.bitrates&&e.hasOwnProperty("bitrates")&&(t=l.SdkBitrateFrame.verify(e.bitrates))?"bitrates."+t:null!=e.audioControl&&e.hasOwnProperty("audioControl")&&(t=l.SdkAudioControlFrame.verify(e.audioControl))?"audioControl."+t:null!=e.audioMetadata&&e.hasOwnProperty("audioMetadata")&&(t=l.SdkAudioMetadataFrame.verify(e.audioMetadata))?"audioMetadata."+t:null!=e.audioStreamIdInfo&&e.hasOwnProperty("audioStreamIdInfo")&&(t=l.SdkAudioStreamIdInfoFrame.verify(e.audioStreamIdInfo))?"audioStreamIdInfo."+t:null!=e.pingPong&&e.hasOwnProperty("pingPong")&&(t=l.SdkPingPongFrame.verify(e.pingPong))?"pingPong."+t:null!=e.audioStatus&&e.hasOwnProperty("audioStatus")&&(t=l.SdkAudioStatusFrame.verify(e.audioStatus))?"audioStatus."+t:null!=e.clientMetric&&e.hasOwnProperty("clientMetric")&&(t=l.SdkClientMetricFrame.verify(e.clientMetric))?"clientMetric."+t:null!=e.dataMessage&&e.hasOwnProperty("dataMessage")&&(t=l.SdkDataMessageFrame.verify(e.dataMessage))?"dataMessage."+t:null!=e.remoteVideoUpdate&&e.hasOwnProperty("remoteVideoUpdate")&&(t=l.SdkRemoteVideoUpdateFrame.verify(e.remoteVideoUpdate))?"remoteVideoUpdate."+t:null!=e.primaryMeetingJoin&&e.hasOwnProperty("primaryMeetingJoin")&&(t=l.SdkPrimaryMeetingJoinFrame.verify(e.primaryMeetingJoin))?"primaryMeetingJoin."+t:null!=e.primaryMeetingJoinAck&&e.hasOwnProperty("primaryMeetingJoinAck")&&(t=l.SdkPrimaryMeetingJoinAckFrame.verify(e.primaryMeetingJoinAck))?"primaryMeetingJoinAck."+t:null!=e.primaryMeetingLeave&&e.hasOwnProperty("primaryMeetingLeave")&&(t=l.SdkPrimaryMeetingLeaveFrame.verify(e.primaryMeetingLeave))?"primaryMeetingLeave."+t:null!=e.notification&&e.hasOwnProperty("notification")&&(t=l.SdkNotificationFrame.verify(e.notification))?"notification."+t:null},e.fromObject=function(e){if(e instanceof l.SdkSignalFrame)return e;var t=new l.SdkSignalFrame;switch(null!=e.timestampMs&&(c.Long?(t.timestampMs=c.Long.fromValue(e.timestampMs)).unsigned=!0:"string"==typeof e.timestampMs?t.timestampMs=parseInt(e.timestampMs,10):"number"==typeof e.timestampMs?t.timestampMs=e.timestampMs:"object"==typeof e.timestampMs&&(t.timestampMs=new c.LongBits(e.timestampMs.low>>>0,e.timestampMs.high>>>0).toNumber(!0))),e.type){default:if("number"==typeof e.type){t.type=e.type;break}break;case"JOIN":case 1:t.type=1;break;case"JOIN_ACK":case 2:t.type=2;break;case"SUBSCRIBE":case 3:t.type=3;break;case"SUBSCRIBE_ACK":case 4:t.type=4;break;case"INDEX":case 5:t.type=5;break;case"PAUSE":case 7:t.type=7;break;case"RESUME":case 8:t.type=8;break;case"LEAVE":case 9:t.type=9;break;case"LEAVE_ACK":case 10:t.type=10;break;case"BITRATES":case 13:t.type=13;break;case"AUDIO_CONTROL":case 16:t.type=16;break;case"AUDIO_METADATA":case 17:t.type=17;break;case"AUDIO_STREAM_ID_INFO":case 18:t.type=18;break;case"PING_PONG":case 19:t.type=19;break;case"AUDIO_STATUS":case 20:t.type=20;break;case"CLIENT_METRIC":case 21:t.type=21;break;case"DATA_MESSAGE":case 22:t.type=22;break;case"REMOTE_VIDEO_UPDATE":case 24:t.type=24;break;case"PRIMARY_MEETING_JOIN":case 25:t.type=25;break;case"PRIMARY_MEETING_JOIN_ACK":case 26:t.type=26;break;case"PRIMARY_MEETING_LEAVE":case 27:t.type=27;break;case"NOTIFICATION":case 34:t.type=34}if(null!=e.error){if("object"!=typeof e.error)throw TypeError(".SdkSignalFrame.error: object expected");t.error=l.SdkErrorFrame.fromObject(e.error)}if(null!=e.join){if("object"!=typeof e.join)throw TypeError(".SdkSignalFrame.join: object expected");t.join=l.SdkJoinFrame.fromObject(e.join)}if(null!=e.joinack){if("object"!=typeof e.joinack)throw TypeError(".SdkSignalFrame.joinack: object expected");t.joinack=l.SdkJoinAckFrame.fromObject(e.joinack)}if(null!=e.sub){if("object"!=typeof e.sub)throw TypeError(".SdkSignalFrame.sub: object expected");t.sub=l.SdkSubscribeFrame.fromObject(e.sub)}if(null!=e.suback){if("object"!=typeof e.suback)throw TypeError(".SdkSignalFrame.suback: object expected");t.suback=l.SdkSubscribeAckFrame.fromObject(e.suback)}if(null!=e.index){if("object"!=typeof e.index)throw TypeError(".SdkSignalFrame.index: object expected");t.index=l.SdkIndexFrame.fromObject(e.index)}if(null!=e.pause){if("object"!=typeof e.pause)throw TypeError(".SdkSignalFrame.pause: object expected");t.pause=l.SdkPauseResumeFrame.fromObject(e.pause)}if(null!=e.leave){if("object"!=typeof e.leave)throw TypeError(".SdkSignalFrame.leave: object expected");t.leave=l.SdkLeaveFrame.fromObject(e.leave)}if(null!=e.leaveAck){if("object"!=typeof e.leaveAck)throw TypeError(".SdkSignalFrame.leaveAck: object expected");t.leaveAck=l.SdkLeaveAckFrame.fromObject(e.leaveAck)}if(null!=e.bitrates){if("object"!=typeof e.bitrates)throw TypeError(".SdkSignalFrame.bitrates: object expected");t.bitrates=l.SdkBitrateFrame.fromObject(e.bitrates)}if(null!=e.audioControl){if("object"!=typeof e.audioControl)throw TypeError(".SdkSignalFrame.audioControl: object expected");t.audioControl=l.SdkAudioControlFrame.fromObject(e.audioControl)}if(null!=e.audioMetadata){if("object"!=typeof e.audioMetadata)throw TypeError(".SdkSignalFrame.audioMetadata: object expected");t.audioMetadata=l.SdkAudioMetadataFrame.fromObject(e.audioMetadata)}if(null!=e.audioStreamIdInfo){if("object"!=typeof e.audioStreamIdInfo)throw TypeError(".SdkSignalFrame.audioStreamIdInfo: object expected");t.audioStreamIdInfo=l.SdkAudioStreamIdInfoFrame.fromObject(e.audioStreamIdInfo)}if(null!=e.pingPong){if("object"!=typeof e.pingPong)throw TypeError(".SdkSignalFrame.pingPong: object expected");t.pingPong=l.SdkPingPongFrame.fromObject(e.pingPong)}if(null!=e.audioStatus){if("object"!=typeof e.audioStatus)throw TypeError(".SdkSignalFrame.audioStatus: object expected");t.audioStatus=l.SdkAudioStatusFrame.fromObject(e.audioStatus)}if(null!=e.clientMetric){if("object"!=typeof e.clientMetric)throw TypeError(".SdkSignalFrame.clientMetric: object expected");t.clientMetric=l.SdkClientMetricFrame.fromObject(e.clientMetric)}if(null!=e.dataMessage){if("object"!=typeof e.dataMessage)throw TypeError(".SdkSignalFrame.dataMessage: object expected");t.dataMessage=l.SdkDataMessageFrame.fromObject(e.dataMessage)}if(null!=e.remoteVideoUpdate){if("object"!=typeof e.remoteVideoUpdate)throw TypeError(".SdkSignalFrame.remoteVideoUpdate: object expected");t.remoteVideoUpdate=l.SdkRemoteVideoUpdateFrame.fromObject(e.remoteVideoUpdate)}if(null!=e.primaryMeetingJoin){if("object"!=typeof e.primaryMeetingJoin)throw TypeError(".SdkSignalFrame.primaryMeetingJoin: object expected");t.primaryMeetingJoin=l.SdkPrimaryMeetingJoinFrame.fromObject(e.primaryMeetingJoin)}if(null!=e.primaryMeetingJoinAck){if("object"!=typeof e.primaryMeetingJoinAck)throw TypeError(".SdkSignalFrame.primaryMeetingJoinAck: object expected");t.primaryMeetingJoinAck=l.SdkPrimaryMeetingJoinAckFrame.fromObject(e.primaryMeetingJoinAck)}if(null!=e.primaryMeetingLeave){if("object"!=typeof e.primaryMeetingLeave)throw TypeError(".SdkSignalFrame.primaryMeetingLeave: object expected");t.primaryMeetingLeave=l.SdkPrimaryMeetingLeaveFrame.fromObject(e.primaryMeetingLeave)}if(null!=e.notification){if("object"!=typeof e.notification)throw TypeError(".SdkSignalFrame.notification: object expected");t.notification=l.SdkNotificationFrame.fromObject(e.notification)}return t},e.toObject=function(e,t){t||(t={});var n={};if(t.defaults){if(c.Long){var i=new c.Long(0,0,!0);n.timestampMs=t.longs===String?i.toString():t.longs===Number?i.toNumber():i}else n.timestampMs=t.longs===String?"0":0;n.type=t.enums===String?"JOIN":1,n.error=null,n.join=null,n.joinack=null,n.sub=null,n.suback=null,n.index=null,n.pause=null,n.leave=null,n.leaveAck=null,n.bitrates=null,n.audioControl=null,n.audioMetadata=null,n.audioStreamIdInfo=null,n.pingPong=null,n.audioStatus=null,n.clientMetric=null,n.dataMessage=null,n.remoteVideoUpdate=null,n.primaryMeetingJoin=null,n.primaryMeetingJoinAck=null,n.primaryMeetingLeave=null,n.notification=null}return null!=e.timestampMs&&e.hasOwnProperty("timestampMs")&&("number"==typeof e.timestampMs?n.timestampMs=t.longs===String?String(e.timestampMs):e.timestampMs:n.timestampMs=t.longs===String?c.Long.prototype.toString.call(e.timestampMs):t.longs===Number?new c.LongBits(e.timestampMs.low>>>0,e.timestampMs.high>>>0).toNumber(!0):e.timestampMs),null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?void 0===l.SdkSignalFrame.Type[e.type]?e.type:l.SdkSignalFrame.Type[e.type]:e.type),null!=e.error&&e.hasOwnProperty("error")&&(n.error=l.SdkErrorFrame.toObject(e.error,t)),null!=e.join&&e.hasOwnProperty("join")&&(n.join=l.SdkJoinFrame.toObject(e.join,t)),null!=e.joinack&&e.hasOwnProperty("joinack")&&(n.joinack=l.SdkJoinAckFrame.toObject(e.joinack,t)),null!=e.sub&&e.hasOwnProperty("sub")&&(n.sub=l.SdkSubscribeFrame.toObject(e.sub,t)),null!=e.suback&&e.hasOwnProperty("suback")&&(n.suback=l.SdkSubscribeAckFrame.toObject(e.suback,t)),null!=e.index&&e.hasOwnProperty("index")&&(n.index=l.SdkIndexFrame.toObject(e.index,t)),null!=e.pause&&e.hasOwnProperty("pause")&&(n.pause=l.SdkPauseResumeFrame.toObject(e.pause,t)),null!=e.leave&&e.hasOwnProperty("leave")&&(n.leave=l.SdkLeaveFrame.toObject(e.leave,t)),null!=e.leaveAck&&e.hasOwnProperty("leaveAck")&&(n.leaveAck=l.SdkLeaveAckFrame.toObject(e.leaveAck,t)),null!=e.bitrates&&e.hasOwnProperty("bitrates")&&(n.bitrates=l.SdkBitrateFrame.toObject(e.bitrates,t)),null!=e.audioControl&&e.hasOwnProperty("audioControl")&&(n.audioControl=l.SdkAudioControlFrame.toObject(e.audioControl,t)),null!=e.audioMetadata&&e.hasOwnProperty("audioMetadata")&&(n.audioMetadata=l.SdkAudioMetadataFrame.toObject(e.audioMetadata,t)),null!=e.audioStreamIdInfo&&e.hasOwnProperty("audioStreamIdInfo")&&(n.audioStreamIdInfo=l.SdkAudioStreamIdInfoFrame.toObject(e.audioStreamIdInfo,t)),null!=e.pingPong&&e.hasOwnProperty("pingPong")&&(n.pingPong=l.SdkPingPongFrame.toObject(e.pingPong,t)),null!=e.audioStatus&&e.hasOwnProperty("audioStatus")&&(n.audioStatus=l.SdkAudioStatusFrame.toObject(e.audioStatus,t)),null!=e.clientMetric&&e.hasOwnProperty("clientMetric")&&(n.clientMetric=l.SdkClientMetricFrame.toObject(e.clientMetric,t)),null!=e.dataMessage&&e.hasOwnProperty("dataMessage")&&(n.dataMessage=l.SdkDataMessageFrame.toObject(e.dataMessage,t)),null!=e.remoteVideoUpdate&&e.hasOwnProperty("remoteVideoUpdate")&&(n.remoteVideoUpdate=l.SdkRemoteVideoUpdateFrame.toObject(e.remoteVideoUpdate,t)),null!=e.primaryMeetingJoin&&e.hasOwnProperty("primaryMeetingJoin")&&(n.primaryMeetingJoin=l.SdkPrimaryMeetingJoinFrame.toObject(e.primaryMeetingJoin,t)),null!=e.primaryMeetingJoinAck&&e.hasOwnProperty("primaryMeetingJoinAck")&&(n.primaryMeetingJoinAck=l.SdkPrimaryMeetingJoinAckFrame.toObject(e.primaryMeetingJoinAck,t)),null!=e.primaryMeetingLeave&&e.hasOwnProperty("primaryMeetingLeave")&&(n.primaryMeetingLeave=l.SdkPrimaryMeetingLeaveFrame.toObject(e.primaryMeetingLeave,t)),null!=e.notification&&e.hasOwnProperty("notification")&&(n.notification=l.SdkNotificationFrame.toObject(e.notification,t)),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkSignalFrame"},e.Type=(t={},(n=Object.create(t))[t[1]="JOIN"]=1,n[t[2]="JOIN_ACK"]=2,n[t[3]="SUBSCRIBE"]=3,n[t[4]="SUBSCRIBE_ACK"]=4,n[t[5]="INDEX"]=5,n[t[7]="PAUSE"]=7,n[t[8]="RESUME"]=8,n[t[9]="LEAVE"]=9,n[t[10]="LEAVE_ACK"]=10,n[t[13]="BITRATES"]=13,n[t[16]="AUDIO_CONTROL"]=16,n[t[17]="AUDIO_METADATA"]=17,n[t[18]="AUDIO_STREAM_ID_INFO"]=18,n[t[19]="PING_PONG"]=19,n[t[20]="AUDIO_STATUS"]=20,n[t[21]="CLIENT_METRIC"]=21,n[t[22]="DATA_MESSAGE"]=22,n[t[24]="REMOTE_VIDEO_UPDATE"]=24,n[t[25]="PRIMARY_MEETING_JOIN"]=25,n[t[26]="PRIMARY_MEETING_JOIN_ACK"]=26,n[t[27]="PRIMARY_MEETING_LEAVE"]=27,n[t[34]="NOTIFICATION"]=34,n),e}(),l.SdkErrorFrame=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.status=e.uint32();break;case 2:i.description=e.string();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.status&&e.hasOwnProperty("status")&&!c.isInteger(e.status)?"status: integer expected":null!=e.description&&e.hasOwnProperty("description")&&!c.isString(e.description)?"description: string expected":null},e.fromObject=function(e){if(e instanceof l.SdkErrorFrame)return e;var t=new l.SdkErrorFrame;return null!=e.status&&(t.status=e.status>>>0),null!=e.description&&(t.description=String(e.description)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.status=0,n.description=""),null!=e.status&&e.hasOwnProperty("status")&&(n.status=e.status),null!=e.description&&e.hasOwnProperty("description")&&(n.description=e.description),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkErrorFrame"},e}(),l.SdkJoinFlags=(i={},(r=Object.create(i))[i[2]="HAS_STREAM_UPDATE"]=2,r[i[16]="COMPLETE_VIDEO_SOURCES_LIST"]=16,r[i[32]="EXCLUDE_SELF_CONTENT_IN_INDEX"]=32,r),l.SdkClientDetails=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.appName=e.string();break;case 2:i.appVersion=e.string();break;case 3:i.deviceModel=e.string();break;case 4:i.deviceMake=e.string();break;case 5:i.platformName=e.string();break;case 6:i.platformVersion=e.string();break;case 7:i.clientSource=e.string();break;case 8:i.chimeSdkVersion=e.string();break;case 9:i.clientUtcOffset=e.string();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.appName&&e.hasOwnProperty("appName")&&!c.isString(e.appName)?"appName: string expected":null!=e.appVersion&&e.hasOwnProperty("appVersion")&&!c.isString(e.appVersion)?"appVersion: string expected":null!=e.deviceModel&&e.hasOwnProperty("deviceModel")&&!c.isString(e.deviceModel)?"deviceModel: string expected":null!=e.deviceMake&&e.hasOwnProperty("deviceMake")&&!c.isString(e.deviceMake)?"deviceMake: string expected":null!=e.platformName&&e.hasOwnProperty("platformName")&&!c.isString(e.platformName)?"platformName: string expected":null!=e.platformVersion&&e.hasOwnProperty("platformVersion")&&!c.isString(e.platformVersion)?"platformVersion: string expected":null!=e.clientSource&&e.hasOwnProperty("clientSource")&&!c.isString(e.clientSource)?"clientSource: string expected":null!=e.chimeSdkVersion&&e.hasOwnProperty("chimeSdkVersion")&&!c.isString(e.chimeSdkVersion)?"chimeSdkVersion: string expected":null!=e.clientUtcOffset&&e.hasOwnProperty("clientUtcOffset")&&!c.isString(e.clientUtcOffset)?"clientUtcOffset: string expected":null},e.fromObject=function(e){if(e instanceof l.SdkClientDetails)return e;var t=new l.SdkClientDetails;return null!=e.appName&&(t.appName=String(e.appName)),null!=e.appVersion&&(t.appVersion=String(e.appVersion)),null!=e.deviceModel&&(t.deviceModel=String(e.deviceModel)),null!=e.deviceMake&&(t.deviceMake=String(e.deviceMake)),null!=e.platformName&&(t.platformName=String(e.platformName)),null!=e.platformVersion&&(t.platformVersion=String(e.platformVersion)),null!=e.clientSource&&(t.clientSource=String(e.clientSource)),null!=e.chimeSdkVersion&&(t.chimeSdkVersion=String(e.chimeSdkVersion)),null!=e.clientUtcOffset&&(t.clientUtcOffset=String(e.clientUtcOffset)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.appName="",n.appVersion="",n.deviceModel="",n.deviceMake="",n.platformName="",n.platformVersion="",n.clientSource="",n.chimeSdkVersion="",n.clientUtcOffset=""),null!=e.appName&&e.hasOwnProperty("appName")&&(n.appName=e.appName),null!=e.appVersion&&e.hasOwnProperty("appVersion")&&(n.appVersion=e.appVersion),null!=e.deviceModel&&e.hasOwnProperty("deviceModel")&&(n.deviceModel=e.deviceModel),null!=e.deviceMake&&e.hasOwnProperty("deviceMake")&&(n.deviceMake=e.deviceMake),null!=e.platformName&&e.hasOwnProperty("platformName")&&(n.platformName=e.platformName),null!=e.platformVersion&&e.hasOwnProperty("platformVersion")&&(n.platformVersion=e.platformVersion),null!=e.clientSource&&e.hasOwnProperty("clientSource")&&(n.clientSource=e.clientSource),null!=e.chimeSdkVersion&&e.hasOwnProperty("chimeSdkVersion")&&(n.chimeSdkVersion=e.chimeSdkVersion),null!=e.clientUtcOffset&&e.hasOwnProperty("clientUtcOffset")&&(n.clientUtcOffset=e.clientUtcOffset),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkClientDetails"},e}(),l.SdkServerSideNetworkAdaption=function(){var e={},t=Object.create(e);return t[e[1]="DEFAULT"]=1,t[e[2]="NONE"]=2,t[e[3]="BANDWIDTH_PROBING"]=3,t[e[4]="BANDWIDTH_PROBING_AND_VIDEO_QUALITY_ADAPTION"]=4,t}(),l.SdkJoinFrame=function(){function e(e){if(this.supportedServerSideNetworkAdaptions=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.protocolVersion=e.uint32();break;case 2:i.maxNumOfVideos=e.uint32();break;case 3:i.flags=e.uint32();break;case 4:i.clientDetails=l.SdkClientDetails.decode(e,e.uint32());break;case 6:i.audioSessionId=e.uint64();break;case 7:i.wantsCompressedSdp=e.bool();break;case 10:i.serverSideNetworkAdaption=e.int32();break;case 11:if(i.supportedServerSideNetworkAdaptions&&i.supportedServerSideNetworkAdaptions.length||(i.supportedServerSideNetworkAdaptions=[]),2==(7&r))for(var a=e.uint32()+e.pos;e.pos>>0),null!=e.maxNumOfVideos&&(t.maxNumOfVideos=e.maxNumOfVideos>>>0),null!=e.flags&&(t.flags=e.flags>>>0),null!=e.clientDetails){if("object"!=typeof e.clientDetails)throw TypeError(".SdkJoinFrame.clientDetails: object expected");t.clientDetails=l.SdkClientDetails.fromObject(e.clientDetails)}switch(null!=e.audioSessionId&&(c.Long?(t.audioSessionId=c.Long.fromValue(e.audioSessionId)).unsigned=!0:"string"==typeof e.audioSessionId?t.audioSessionId=parseInt(e.audioSessionId,10):"number"==typeof e.audioSessionId?t.audioSessionId=e.audioSessionId:"object"==typeof e.audioSessionId&&(t.audioSessionId=new c.LongBits(e.audioSessionId.low>>>0,e.audioSessionId.high>>>0).toNumber(!0))),null!=e.wantsCompressedSdp&&(t.wantsCompressedSdp=Boolean(e.wantsCompressedSdp)),e.serverSideNetworkAdaption){default:if("number"==typeof e.serverSideNetworkAdaption){t.serverSideNetworkAdaption=e.serverSideNetworkAdaption;break}break;case"DEFAULT":case 1:t.serverSideNetworkAdaption=1;break;case"NONE":case 2:t.serverSideNetworkAdaption=2;break;case"BANDWIDTH_PROBING":case 3:t.serverSideNetworkAdaption=3;break;case"BANDWIDTH_PROBING_AND_VIDEO_QUALITY_ADAPTION":case 4:t.serverSideNetworkAdaption=4}if(e.supportedServerSideNetworkAdaptions){if(!Array.isArray(e.supportedServerSideNetworkAdaptions))throw TypeError(".SdkJoinFrame.supportedServerSideNetworkAdaptions: array expected");t.supportedServerSideNetworkAdaptions=[];for(var n=0;n>>0,e.audioSessionId.high>>>0).toNumber(!0):e.audioSessionId),null!=e.wantsCompressedSdp&&e.hasOwnProperty("wantsCompressedSdp")&&(n.wantsCompressedSdp=e.wantsCompressedSdp),null!=e.serverSideNetworkAdaption&&e.hasOwnProperty("serverSideNetworkAdaption")&&(n.serverSideNetworkAdaption=t.enums===String?void 0===l.SdkServerSideNetworkAdaption[e.serverSideNetworkAdaption]?e.serverSideNetworkAdaption:l.SdkServerSideNetworkAdaption[e.serverSideNetworkAdaption]:e.serverSideNetworkAdaption),e.supportedServerSideNetworkAdaptions&&e.supportedServerSideNetworkAdaptions.length){n.supportedServerSideNetworkAdaptions=[];for(var r=0;r>>3){case 1:i.turnCredentials=l.SdkTurnCredentials.decode(e,e.uint32());break;case 2:i.videoSubscriptionLimit=e.uint32();break;case 3:i.wantsCompressedSdp=e.bool();break;case 4:i.defaultServerSideNetworkAdaption=e.int32();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.turnCredentials&&e.hasOwnProperty("turnCredentials")){var t=l.SdkTurnCredentials.verify(e.turnCredentials);if(t)return"turnCredentials."+t}if(null!=e.videoSubscriptionLimit&&e.hasOwnProperty("videoSubscriptionLimit")&&!c.isInteger(e.videoSubscriptionLimit))return"videoSubscriptionLimit: integer expected";if(null!=e.wantsCompressedSdp&&e.hasOwnProperty("wantsCompressedSdp")&&"boolean"!=typeof e.wantsCompressedSdp)return"wantsCompressedSdp: boolean expected";if(null!=e.defaultServerSideNetworkAdaption&&e.hasOwnProperty("defaultServerSideNetworkAdaption"))switch(e.defaultServerSideNetworkAdaption){default:return"defaultServerSideNetworkAdaption: enum value expected";case 1:case 2:case 3:case 4:}return null},e.fromObject=function(e){if(e instanceof l.SdkJoinAckFrame)return e;var t=new l.SdkJoinAckFrame;if(null!=e.turnCredentials){if("object"!=typeof e.turnCredentials)throw TypeError(".SdkJoinAckFrame.turnCredentials: object expected");t.turnCredentials=l.SdkTurnCredentials.fromObject(e.turnCredentials)}switch(null!=e.videoSubscriptionLimit&&(t.videoSubscriptionLimit=e.videoSubscriptionLimit>>>0),null!=e.wantsCompressedSdp&&(t.wantsCompressedSdp=Boolean(e.wantsCompressedSdp)),e.defaultServerSideNetworkAdaption){default:if("number"==typeof e.defaultServerSideNetworkAdaption){t.defaultServerSideNetworkAdaption=e.defaultServerSideNetworkAdaption;break}break;case"DEFAULT":case 1:t.defaultServerSideNetworkAdaption=1;break;case"NONE":case 2:t.defaultServerSideNetworkAdaption=2;break;case"BANDWIDTH_PROBING":case 3:t.defaultServerSideNetworkAdaption=3;break;case"BANDWIDTH_PROBING_AND_VIDEO_QUALITY_ADAPTION":case 4:t.defaultServerSideNetworkAdaption=4}return t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.turnCredentials=null,n.videoSubscriptionLimit=0,n.wantsCompressedSdp=!1,n.defaultServerSideNetworkAdaption=t.enums===String?"DEFAULT":1),null!=e.turnCredentials&&e.hasOwnProperty("turnCredentials")&&(n.turnCredentials=l.SdkTurnCredentials.toObject(e.turnCredentials,t)),null!=e.videoSubscriptionLimit&&e.hasOwnProperty("videoSubscriptionLimit")&&(n.videoSubscriptionLimit=e.videoSubscriptionLimit),null!=e.wantsCompressedSdp&&e.hasOwnProperty("wantsCompressedSdp")&&(n.wantsCompressedSdp=e.wantsCompressedSdp),null!=e.defaultServerSideNetworkAdaption&&e.hasOwnProperty("defaultServerSideNetworkAdaption")&&(n.defaultServerSideNetworkAdaption=t.enums===String?void 0===l.SdkServerSideNetworkAdaption[e.defaultServerSideNetworkAdaption]?e.defaultServerSideNetworkAdaption:l.SdkServerSideNetworkAdaption[e.defaultServerSideNetworkAdaption]:e.defaultServerSideNetworkAdaption),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkJoinAckFrame"},e}(),l.SdkLeaveFrame=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.duplex=e.int32();break;case 2:i.sendStreams&&i.sendStreams.length||(i.sendStreams=[]),i.sendStreams.push(l.SdkStreamDescriptor.decode(e,e.uint32()));break;case 3:if(i.receiveStreamIds&&i.receiveStreamIds.length||(i.receiveStreamIds=[]),2==(7&r))for(var a=e.uint32()+e.pos;e.pos>>0}if(null!=e.sdpOffer&&(t.sdpOffer=String(e.sdpOffer)),null!=e.audioHost&&(t.audioHost=String(e.audioHost)),null!=e.audioCheckin&&(t.audioCheckin=Boolean(e.audioCheckin)),null!=e.audioMuted&&(t.audioMuted=Boolean(e.audioMuted)),null!=e.compressedSdpOffer&&("string"==typeof e.compressedSdpOffer?c.base64.decode(e.compressedSdpOffer,t.compressedSdpOffer=c.newBuffer(c.base64.length(e.compressedSdpOffer)),0):e.compressedSdpOffer.length>=0&&(t.compressedSdpOffer=e.compressedSdpOffer)),e.videoSubscriptionConfiguration){if(!Array.isArray(e.videoSubscriptionConfiguration))throw TypeError(".SdkSubscribeFrame.videoSubscriptionConfiguration: array expected");for(t.videoSubscriptionConfiguration=[],n=0;n>>3){case 1:i.duplex=e.int32();break;case 2:i.allocations&&i.allocations.length||(i.allocations=[]),i.allocations.push(l.SdkStreamAllocation.decode(e,e.uint32()));break;case 3:i.sdpAnswer=e.string();break;case 4:i.tracks&&i.tracks.length||(i.tracks=[]),i.tracks.push(l.SdkTrackMapping.decode(e,e.uint32()));break;case 5:i.compressedSdpAnswer=e.bytes();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.duplex&&e.hasOwnProperty("duplex"))switch(e.duplex){default:return"duplex: enum value expected";case 1:case 2:case 3:}if(null!=e.allocations&&e.hasOwnProperty("allocations")){if(!Array.isArray(e.allocations))return"allocations: array expected";for(var t=0;t=0&&(t.compressedSdpAnswer=e.compressedSdpAnswer)),t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.allocations=[],n.tracks=[]),t.defaults&&(n.duplex=t.enums===String?"RX":1,n.sdpAnswer="",t.bytes===String?n.compressedSdpAnswer="":(n.compressedSdpAnswer=[],t.bytes!==Array&&(n.compressedSdpAnswer=c.newBuffer(n.compressedSdpAnswer)))),null!=e.duplex&&e.hasOwnProperty("duplex")&&(n.duplex=t.enums===String?void 0===l.SdkStreamServiceType[e.duplex]?e.duplex:l.SdkStreamServiceType[e.duplex]:e.duplex),e.allocations&&e.allocations.length){n.allocations=[];for(var i=0;i>>3){case 1:i.atCapacity=e.bool();break;case 2:i.sources&&i.sources.length||(i.sources=[]),i.sources.push(l.SdkStreamDescriptor.decode(e,e.uint32()));break;case 3:if(i.pausedAtSourceIds&&i.pausedAtSourceIds.length||(i.pausedAtSourceIds=[]),2==(7&r))for(var a=e.uint32()+e.pos;e.pos>>0}if(null!=e.numParticipants&&(t.numParticipants=e.numParticipants>>>0),e.supportedReceiveCodecIntersection){if(!Array.isArray(e.supportedReceiveCodecIntersection))throw TypeError(".SdkIndexFrame.supportedReceiveCodecIntersection: array expected");for(t.supportedReceiveCodecIntersection=[],n=0;n>>3){case 1:if(i.streamIds&&i.streamIds.length||(i.streamIds=[]),2==(7&r))for(var a=e.uint32()+e.pos;e.pos>>0}if(e.groupIds){if(!Array.isArray(e.groupIds))throw TypeError(".SdkPauseResumeFrame.groupIds: array expected");for(t.groupIds=[],n=0;n>>0}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.streamIds=[],n.groupIds=[]),e.streamIds&&e.streamIds.length){n.streamIds=[];for(var i=0;i>>3){case 1:i.bitrates&&i.bitrates.length||(i.bitrates=[]),i.bitrates.push(l.SdkBitrate.decode(e,e.uint32()));break;case 2:i.serverAvailableOutgoingBitrate=e.uint32();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.bitrates&&e.hasOwnProperty("bitrates")){if(!Array.isArray(e.bitrates))return"bitrates: array expected";for(var t=0;t>>0),t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.bitrates=[]),t.defaults&&(n.serverAvailableOutgoingBitrate=0),e.bitrates&&e.bitrates.length){n.bitrates=[];for(var i=0;i>>3){case 1:i.streamId=e.uint32();break;case 2:i.framerate=e.uint32();break;case 3:i.maxBitrateKbps=e.uint32();break;case 4:i.trackLabel=e.string();break;case 6:i.groupId=e.uint32();break;case 7:i.avgBitrateBps=e.uint32();break;case 8:i.attendeeId=e.string();break;case 9:i.mediaType=e.int32();break;case 10:i.externalUserId=e.string();break;case 11:i.width=e.uint32();break;case 12:i.height=e.uint32();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.streamId&&e.hasOwnProperty("streamId")&&!c.isInteger(e.streamId))return"streamId: integer expected";if(null!=e.framerate&&e.hasOwnProperty("framerate")&&!c.isInteger(e.framerate))return"framerate: integer expected";if(null!=e.maxBitrateKbps&&e.hasOwnProperty("maxBitrateKbps")&&!c.isInteger(e.maxBitrateKbps))return"maxBitrateKbps: integer expected";if(null!=e.trackLabel&&e.hasOwnProperty("trackLabel")&&!c.isString(e.trackLabel))return"trackLabel: string expected";if(null!=e.groupId&&e.hasOwnProperty("groupId")&&!c.isInteger(e.groupId))return"groupId: integer expected";if(null!=e.avgBitrateBps&&e.hasOwnProperty("avgBitrateBps")&&!c.isInteger(e.avgBitrateBps))return"avgBitrateBps: integer expected";if(null!=e.attendeeId&&e.hasOwnProperty("attendeeId")&&!c.isString(e.attendeeId))return"attendeeId: string expected";if(null!=e.mediaType&&e.hasOwnProperty("mediaType"))switch(e.mediaType){default:return"mediaType: enum value expected";case 1:case 2:}return null!=e.externalUserId&&e.hasOwnProperty("externalUserId")&&!c.isString(e.externalUserId)?"externalUserId: string expected":null!=e.width&&e.hasOwnProperty("width")&&!c.isInteger(e.width)?"width: integer expected":null!=e.height&&e.hasOwnProperty("height")&&!c.isInteger(e.height)?"height: integer expected":null},e.fromObject=function(e){if(e instanceof l.SdkStreamDescriptor)return e;var t=new l.SdkStreamDescriptor;switch(null!=e.streamId&&(t.streamId=e.streamId>>>0),null!=e.framerate&&(t.framerate=e.framerate>>>0),null!=e.maxBitrateKbps&&(t.maxBitrateKbps=e.maxBitrateKbps>>>0),null!=e.trackLabel&&(t.trackLabel=String(e.trackLabel)),null!=e.groupId&&(t.groupId=e.groupId>>>0),null!=e.avgBitrateBps&&(t.avgBitrateBps=e.avgBitrateBps>>>0),null!=e.attendeeId&&(t.attendeeId=String(e.attendeeId)),e.mediaType){default:if("number"==typeof e.mediaType){t.mediaType=e.mediaType;break}break;case"AUDIO":case 1:t.mediaType=1;break;case"VIDEO":case 2:t.mediaType=2}return null!=e.externalUserId&&(t.externalUserId=String(e.externalUserId)),null!=e.width&&(t.width=e.width>>>0),null!=e.height&&(t.height=e.height>>>0),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.streamId=0,n.framerate=0,n.maxBitrateKbps=0,n.trackLabel="",n.groupId=0,n.avgBitrateBps=0,n.attendeeId="",n.mediaType=t.enums===String?"AUDIO":1,n.externalUserId="",n.width=0,n.height=0),null!=e.streamId&&e.hasOwnProperty("streamId")&&(n.streamId=e.streamId),null!=e.framerate&&e.hasOwnProperty("framerate")&&(n.framerate=e.framerate),null!=e.maxBitrateKbps&&e.hasOwnProperty("maxBitrateKbps")&&(n.maxBitrateKbps=e.maxBitrateKbps),null!=e.trackLabel&&e.hasOwnProperty("trackLabel")&&(n.trackLabel=e.trackLabel),null!=e.groupId&&e.hasOwnProperty("groupId")&&(n.groupId=e.groupId),null!=e.avgBitrateBps&&e.hasOwnProperty("avgBitrateBps")&&(n.avgBitrateBps=e.avgBitrateBps),null!=e.attendeeId&&e.hasOwnProperty("attendeeId")&&(n.attendeeId=e.attendeeId),null!=e.mediaType&&e.hasOwnProperty("mediaType")&&(n.mediaType=t.enums===String?void 0===l.SdkStreamMediaType[e.mediaType]?e.mediaType:l.SdkStreamMediaType[e.mediaType]:e.mediaType),null!=e.externalUserId&&e.hasOwnProperty("externalUserId")&&(n.externalUserId=e.externalUserId),null!=e.width&&e.hasOwnProperty("width")&&(n.width=e.width),null!=e.height&&e.hasOwnProperty("height")&&(n.height=e.height),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkStreamDescriptor"},e}(),l.SdkStreamAllocation=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.trackLabel=e.string();break;case 2:i.streamId=e.uint32();break;case 3:i.groupId=e.uint32();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.trackLabel&&e.hasOwnProperty("trackLabel")&&!c.isString(e.trackLabel)?"trackLabel: string expected":null!=e.streamId&&e.hasOwnProperty("streamId")&&!c.isInteger(e.streamId)?"streamId: integer expected":null!=e.groupId&&e.hasOwnProperty("groupId")&&!c.isInteger(e.groupId)?"groupId: integer expected":null},e.fromObject=function(e){if(e instanceof l.SdkStreamAllocation)return e;var t=new l.SdkStreamAllocation;return null!=e.trackLabel&&(t.trackLabel=String(e.trackLabel)),null!=e.streamId&&(t.streamId=e.streamId>>>0),null!=e.groupId&&(t.groupId=e.groupId>>>0),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.trackLabel="",n.streamId=0,n.groupId=0),null!=e.trackLabel&&e.hasOwnProperty("trackLabel")&&(n.trackLabel=e.trackLabel),null!=e.streamId&&e.hasOwnProperty("streamId")&&(n.streamId=e.streamId),null!=e.groupId&&e.hasOwnProperty("groupId")&&(n.groupId=e.groupId),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkStreamAllocation"},e}(),l.SdkTrackMapping=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.streamId=e.uint32();break;case 2:i.ssrc=e.uint32();break;case 3:i.trackLabel=e.string();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.streamId&&e.hasOwnProperty("streamId")&&!c.isInteger(e.streamId)?"streamId: integer expected":null!=e.ssrc&&e.hasOwnProperty("ssrc")&&!c.isInteger(e.ssrc)?"ssrc: integer expected":null!=e.trackLabel&&e.hasOwnProperty("trackLabel")&&!c.isString(e.trackLabel)?"trackLabel: string expected":null},e.fromObject=function(e){if(e instanceof l.SdkTrackMapping)return e;var t=new l.SdkTrackMapping;return null!=e.streamId&&(t.streamId=e.streamId>>>0),null!=e.ssrc&&(t.ssrc=e.ssrc>>>0),null!=e.trackLabel&&(t.trackLabel=String(e.trackLabel)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.streamId=0,n.ssrc=0,n.trackLabel=""),null!=e.streamId&&e.hasOwnProperty("streamId")&&(n.streamId=e.streamId),null!=e.ssrc&&e.hasOwnProperty("ssrc")&&(n.ssrc=e.ssrc),null!=e.trackLabel&&e.hasOwnProperty("trackLabel")&&(n.trackLabel=e.trackLabel),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkTrackMapping"},e}(),l.SdkBitrate=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.sourceStreamId=e.uint32();break;case 2:i.avgBitrateBps=e.uint32();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.sourceStreamId&&e.hasOwnProperty("sourceStreamId")&&!c.isInteger(e.sourceStreamId)?"sourceStreamId: integer expected":null!=e.avgBitrateBps&&e.hasOwnProperty("avgBitrateBps")&&!c.isInteger(e.avgBitrateBps)?"avgBitrateBps: integer expected":null},e.fromObject=function(e){if(e instanceof l.SdkBitrate)return e;var t=new l.SdkBitrate;return null!=e.sourceStreamId&&(t.sourceStreamId=e.sourceStreamId>>>0),null!=e.avgBitrateBps&&(t.avgBitrateBps=e.avgBitrateBps>>>0),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.sourceStreamId=0,n.avgBitrateBps=0),null!=e.sourceStreamId&&e.hasOwnProperty("sourceStreamId")&&(n.sourceStreamId=e.sourceStreamId),null!=e.avgBitrateBps&&e.hasOwnProperty("avgBitrateBps")&&(n.avgBitrateBps=e.avgBitrateBps),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkBitrate"},e}(),l.SdkAudioControlFrame=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3==1?i.muted=e.bool():e.skipType(7&r)}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.muted&&e.hasOwnProperty("muted")&&"boolean"!=typeof e.muted?"muted: boolean expected":null},e.fromObject=function(e){if(e instanceof l.SdkAudioControlFrame)return e;var t=new l.SdkAudioControlFrame;return null!=e.muted&&(t.muted=Boolean(e.muted)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.muted=!1),null!=e.muted&&e.hasOwnProperty("muted")&&(n.muted=e.muted),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkAudioControlFrame"},e}(),l.SdkAudioMetadataFrame=function(){function e(e){if(this.attendeeStates=[],e)for(var t=Object.keys(e),n=0;n>>3==1?(i.attendeeStates&&i.attendeeStates.length||(i.attendeeStates=[]),i.attendeeStates.push(l.SdkAudioAttendeeState.decode(e,e.uint32()))):e.skipType(7&r)}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.attendeeStates&&e.hasOwnProperty("attendeeStates")){if(!Array.isArray(e.attendeeStates))return"attendeeStates: array expected";for(var t=0;t>>3){case 1:i.audioStreamId=e.uint32();break;case 2:i.volume=e.uint32();break;case 3:i.muted=e.bool();break;case 4:i.signalStrength=e.uint32();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.audioStreamId&&e.hasOwnProperty("audioStreamId")&&!c.isInteger(e.audioStreamId)?"audioStreamId: integer expected":null!=e.volume&&e.hasOwnProperty("volume")&&!c.isInteger(e.volume)?"volume: integer expected":null!=e.muted&&e.hasOwnProperty("muted")&&"boolean"!=typeof e.muted?"muted: boolean expected":null!=e.signalStrength&&e.hasOwnProperty("signalStrength")&&!c.isInteger(e.signalStrength)?"signalStrength: integer expected":null},e.fromObject=function(e){if(e instanceof l.SdkAudioAttendeeState)return e;var t=new l.SdkAudioAttendeeState;return null!=e.audioStreamId&&(t.audioStreamId=e.audioStreamId>>>0),null!=e.volume&&(t.volume=e.volume>>>0),null!=e.muted&&(t.muted=Boolean(e.muted)),null!=e.signalStrength&&(t.signalStrength=e.signalStrength>>>0),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.audioStreamId=0,n.volume=0,n.muted=!1,n.signalStrength=0),null!=e.audioStreamId&&e.hasOwnProperty("audioStreamId")&&(n.audioStreamId=e.audioStreamId),null!=e.volume&&e.hasOwnProperty("volume")&&(n.volume=e.volume),null!=e.muted&&e.hasOwnProperty("muted")&&(n.muted=e.muted),null!=e.signalStrength&&e.hasOwnProperty("signalStrength")&&(n.signalStrength=e.signalStrength),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkAudioAttendeeState"},e}(),l.SdkAudioStreamIdInfoFrame=function(){function e(e){if(this.streams=[],e)for(var t=Object.keys(e),n=0;n>>3==1?(i.streams&&i.streams.length||(i.streams=[]),i.streams.push(l.SdkAudioStreamIdInfo.decode(e,e.uint32()))):e.skipType(7&r)}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.streams&&e.hasOwnProperty("streams")){if(!Array.isArray(e.streams))return"streams: array expected";for(var t=0;t>>3){case 1:i.audioStreamId=e.uint32();break;case 2:i.attendeeId=e.string();break;case 3:i.muted=e.bool();break;case 4:i.externalUserId=e.string();break;case 5:i.dropped=e.bool();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.audioStreamId&&e.hasOwnProperty("audioStreamId")&&!c.isInteger(e.audioStreamId)?"audioStreamId: integer expected":null!=e.attendeeId&&e.hasOwnProperty("attendeeId")&&!c.isString(e.attendeeId)?"attendeeId: string expected":null!=e.muted&&e.hasOwnProperty("muted")&&"boolean"!=typeof e.muted?"muted: boolean expected":null!=e.externalUserId&&e.hasOwnProperty("externalUserId")&&!c.isString(e.externalUserId)?"externalUserId: string expected":null!=e.dropped&&e.hasOwnProperty("dropped")&&"boolean"!=typeof e.dropped?"dropped: boolean expected":null},e.fromObject=function(e){if(e instanceof l.SdkAudioStreamIdInfo)return e;var t=new l.SdkAudioStreamIdInfo;return null!=e.audioStreamId&&(t.audioStreamId=e.audioStreamId>>>0),null!=e.attendeeId&&(t.attendeeId=String(e.attendeeId)),null!=e.muted&&(t.muted=Boolean(e.muted)),null!=e.externalUserId&&(t.externalUserId=String(e.externalUserId)),null!=e.dropped&&(t.dropped=Boolean(e.dropped)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.audioStreamId=0,n.attendeeId="",n.muted=!1,n.externalUserId="",n.dropped=!1),null!=e.audioStreamId&&e.hasOwnProperty("audioStreamId")&&(n.audioStreamId=e.audioStreamId),null!=e.attendeeId&&e.hasOwnProperty("attendeeId")&&(n.attendeeId=e.attendeeId),null!=e.muted&&e.hasOwnProperty("muted")&&(n.muted=e.muted),null!=e.externalUserId&&e.hasOwnProperty("externalUserId")&&(n.externalUserId=e.externalUserId),null!=e.dropped&&e.hasOwnProperty("dropped")&&(n.dropped=e.dropped),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkAudioStreamIdInfo"},e}(),l.SdkPingPongType=function(){var e={},t=Object.create(e);return t[e[1]="PING"]=1,t[e[2]="PONG"]=2,t}(),l.SdkPingPongFrame=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.type=e.int32();break;case 2:i.pingId=e.uint32();break;default:e.skipType(7&r)}}if(!i.hasOwnProperty("type"))throw c.ProtocolError("missing required 'type'",{instance:i});if(!i.hasOwnProperty("pingId"))throw c.ProtocolError("missing required 'pingId'",{instance:i});return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";switch(e.type){default:return"type: enum value expected";case 1:case 2:}return c.isInteger(e.pingId)?null:"pingId: integer expected"},e.fromObject=function(e){if(e instanceof l.SdkPingPongFrame)return e;var t=new l.SdkPingPongFrame;switch(e.type){default:if("number"==typeof e.type){t.type=e.type;break}break;case"PING":case 1:t.type=1;break;case"PONG":case 2:t.type=2}return null!=e.pingId&&(t.pingId=e.pingId>>>0),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.type=t.enums===String?"PING":1,n.pingId=0),null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?void 0===l.SdkPingPongType[e.type]?e.type:l.SdkPingPongType[e.type]:e.type),null!=e.pingId&&e.hasOwnProperty("pingId")&&(n.pingId=e.pingId),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkPingPongFrame"},e}(),l.SdkAudioStatusFrame=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3==1?i.audioStatus=e.uint32():e.skipType(7&r)}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.audioStatus&&e.hasOwnProperty("audioStatus")&&!c.isInteger(e.audioStatus)?"audioStatus: integer expected":null},e.fromObject=function(e){if(e instanceof l.SdkAudioStatusFrame)return e;var t=new l.SdkAudioStatusFrame;return null!=e.audioStatus&&(t.audioStatus=e.audioStatus>>>0),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.audioStatus=0),null!=e.audioStatus&&e.hasOwnProperty("audioStatus")&&(n.audioStatus=e.audioStatus),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkAudioStatusFrame"},e}(),l.SdkMetric=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.type=e.int32();break;case 2:i.value=e.double();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.type&&e.hasOwnProperty("type"))switch(e.type){default:return"type: enum value expected";case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:case 16:case 17:case 18:case 19:case 20:case 21:case 22:case 23:case 24:case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:case 48:case 49:case 64:case 66:case 69:case 72:case 86:case 87:case 88:case 89:case 90:case 91:case 92:case 93:case 94:case 95:case 96:case 97:case 98:case 99:case 100:case 101:case 102:}return null!=e.value&&e.hasOwnProperty("value")&&"number"!=typeof e.value?"value: number expected":null},e.fromObject=function(e){if(e instanceof l.SdkMetric)return e;var t=new l.SdkMetric;switch(e.type){default:if("number"==typeof e.type){t.type=e.type;break}break;case"VIDEO_ACTUAL_ENCODER_BITRATE":case 1:t.type=1;break;case"VIDEO_AVAILABLE_SEND_BANDWIDTH":case 2:t.type=2;break;case"VIDEO_RETRANSMIT_BITRATE":case 3:t.type=3;break;case"VIDEO_AVAILABLE_RECEIVE_BANDWIDTH":case 4:t.type=4;break;case"VIDEO_TARGET_ENCODER_BITRATE":case 5:t.type=5;break;case"VIDEO_BUCKET_DELAY_MS":case 6:t.type=6;break;case"STUN_RTT_MS":case 7:t.type=7;break;case"SOCKET_DISCARDED_PPS":case 8:t.type=8;break;case"RTC_MIC_JITTER_MS":case 9:t.type=9;break;case"RTC_MIC_PPS":case 10:t.type=10;break;case"RTC_MIC_FRACTION_PACKET_LOST_PERCENT":case 11:t.type=11;break;case"RTC_MIC_BITRATE":case 12:t.type=12;break;case"RTC_MIC_RTT_MS":case 13:t.type=13;break;case"RTC_SPK_PPS":case 14:t.type=14;break;case"RTC_SPK_FRACTION_PACKET_LOST_PERCENT":case 15:t.type=15;break;case"RTC_SPK_JITTER_MS":case 16:t.type=16;break;case"RTC_SPK_FRACTION_DECODER_LOSS_PERCENT":case 17:t.type=17;break;case"RTC_SPK_BITRATE":case 18:t.type=18;break;case"RTC_SPK_CURRENT_DELAY_MS":case 19:t.type=19;break;case"RTC_SPK_JITTER_BUFFER_MS":case 20:t.type=20;break;case"VIDEO_SENT_RTT_MS":case 21:t.type=21;break;case"VIDEO_ENCODE_USAGE_PERCENT":case 22:t.type=22;break;case"VIDEO_NACKS_RECEIVED":case 23:t.type=23;break;case"VIDEO_PLIS_RECEIVED":case 24:t.type=24;break;case"VIDEO_ENCODE_MS":case 25:t.type=25;break;case"VIDEO_INPUT_FPS":case 26:t.type=26;break;case"VIDEO_ENCODE_FPS":case 27:t.type=27;break;case"VIDEO_SENT_FPS":case 28:t.type=28;break;case"VIDEO_FIRS_RECEIVED":case 29:t.type=29;break;case"VIDEO_SENT_PPS":case 30:t.type=30;break;case"VIDEO_SENT_FRACTION_PACKET_LOST_PERCENT":case 31:t.type=31;break;case"VIDEO_SENT_BITRATE":case 32:t.type=32;break;case"VIDEO_DROPPED_FPS":case 33:t.type=33;break;case"VIDEO_TARGET_DELAY_MS":case 34:t.type=34;break;case"VIDEO_DECODE_MS":case 35:t.type=35;break;case"VIDEO_OUTPUT_FPS":case 36:t.type=36;break;case"VIDEO_RECEIVED_PPS":case 37:t.type=37;break;case"VIDEO_RECEIVED_FRACTION_PACKET_LOST_PERCENT":case 38:t.type=38;break;case"VIDEO_RENDER_DELAY_MS":case 39:t.type=39;break;case"VIDEO_RECEIVED_FPS":case 40:t.type=40;break;case"VIDEO_DECODE_FPS":case 41:t.type=41;break;case"VIDEO_NACKS_SENT":case 42:t.type=42;break;case"VIDEO_FIRS_SENT":case 43:t.type=43;break;case"VIDEO_RECEIVED_BITRATE":case 44:t.type=44;break;case"VIDEO_CURRENT_DELAY_MS":case 45:t.type=45;break;case"VIDEO_JITTER_BUFFER_MS":case 46:t.type=46;break;case"VIDEO_DISCARDED_PPS":case 47:t.type=47;break;case"VIDEO_PLIS_SENT":case 48:t.type=48;break;case"VIDEO_RECEIVED_JITTER_MS":case 49:t.type=49;break;case"VIDEO_ENCODE_HEIGHT":case 64:t.type=64;break;case"VIDEO_SENT_QP_SUM":case 66:t.type=66;break;case"VIDEO_DECODE_HEIGHT":case 69:t.type=69;break;case"VIDEO_RECEIVED_QP_SUM":case 72:t.type=72;break;case"VIDEO_ENCODE_WIDTH":case 86:t.type=86;break;case"VIDEO_DECODE_WIDTH":case 87:t.type=87;break;case"VIDEO_ENCODER_IS_HARDWARE":case 88:t.type=88;break;case"VIDEO_DECODER_IS_HARDWARE":case 89:t.type=89;break;case"VIDEO_FREEZE_COUNT":case 90:t.type=90;break;case"VIDEO_FREEZE_DURATION":case 91:t.type=91;break;case"VIDEO_PAUSE_COUNT":case 92:t.type=92;break;case"VIDEO_PAUSE_DURATION":case 93:t.type=93;break;case"VIDEO_QUALITY_REASON":case 94:t.type=94;break;case"VIDEO_PROCESSING_TIME":case 95:t.type=95;break;case"RTC_SPK_AUDIO_LEVEL":case 96:t.type=96;break;case"RTC_MIC_AUDIO_LEVEL":case 97:t.type=97;break;case"RTC_SPK_TOTAL_LOST":case 98:t.type=98;break;case"RTC_SPK_TOTAL_EXPECTED":case 99:t.type=99;break;case"RTC_SPK_TOTAL_RECOVERED_RED":case 100:t.type=100;break;case"RTC_SPK_TOTAL_RECOVERED_FEC":case 101:t.type=101;break;case"VIDEO_QUALITY_LIMITATION_DURATION_CPU":case 102:t.type=102}return null!=e.value&&(t.value=Number(e.value)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.type=t.enums===String?"VIDEO_ACTUAL_ENCODER_BITRATE":1,n.value=0),null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?void 0===l.SdkMetric.Type[e.type]?e.type:l.SdkMetric.Type[e.type]:e.type),null!=e.value&&e.hasOwnProperty("value")&&(n.value=t.json&&!isFinite(e.value)?String(e.value):e.value),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkMetric"},e.Type=function(){var e={},t=Object.create(e);return t[e[1]="VIDEO_ACTUAL_ENCODER_BITRATE"]=1,t[e[2]="VIDEO_AVAILABLE_SEND_BANDWIDTH"]=2,t[e[3]="VIDEO_RETRANSMIT_BITRATE"]=3,t[e[4]="VIDEO_AVAILABLE_RECEIVE_BANDWIDTH"]=4,t[e[5]="VIDEO_TARGET_ENCODER_BITRATE"]=5,t[e[6]="VIDEO_BUCKET_DELAY_MS"]=6,t[e[7]="STUN_RTT_MS"]=7,t[e[8]="SOCKET_DISCARDED_PPS"]=8,t[e[9]="RTC_MIC_JITTER_MS"]=9,t[e[10]="RTC_MIC_PPS"]=10,t[e[11]="RTC_MIC_FRACTION_PACKET_LOST_PERCENT"]=11,t[e[12]="RTC_MIC_BITRATE"]=12,t[e[13]="RTC_MIC_RTT_MS"]=13,t[e[14]="RTC_SPK_PPS"]=14,t[e[15]="RTC_SPK_FRACTION_PACKET_LOST_PERCENT"]=15,t[e[16]="RTC_SPK_JITTER_MS"]=16,t[e[17]="RTC_SPK_FRACTION_DECODER_LOSS_PERCENT"]=17,t[e[18]="RTC_SPK_BITRATE"]=18,t[e[19]="RTC_SPK_CURRENT_DELAY_MS"]=19,t[e[20]="RTC_SPK_JITTER_BUFFER_MS"]=20,t[e[21]="VIDEO_SENT_RTT_MS"]=21,t[e[22]="VIDEO_ENCODE_USAGE_PERCENT"]=22,t[e[23]="VIDEO_NACKS_RECEIVED"]=23,t[e[24]="VIDEO_PLIS_RECEIVED"]=24,t[e[25]="VIDEO_ENCODE_MS"]=25,t[e[26]="VIDEO_INPUT_FPS"]=26,t[e[27]="VIDEO_ENCODE_FPS"]=27,t[e[28]="VIDEO_SENT_FPS"]=28,t[e[29]="VIDEO_FIRS_RECEIVED"]=29,t[e[30]="VIDEO_SENT_PPS"]=30,t[e[31]="VIDEO_SENT_FRACTION_PACKET_LOST_PERCENT"]=31,t[e[32]="VIDEO_SENT_BITRATE"]=32,t[e[33]="VIDEO_DROPPED_FPS"]=33,t[e[34]="VIDEO_TARGET_DELAY_MS"]=34,t[e[35]="VIDEO_DECODE_MS"]=35,t[e[36]="VIDEO_OUTPUT_FPS"]=36,t[e[37]="VIDEO_RECEIVED_PPS"]=37,t[e[38]="VIDEO_RECEIVED_FRACTION_PACKET_LOST_PERCENT"]=38,t[e[39]="VIDEO_RENDER_DELAY_MS"]=39,t[e[40]="VIDEO_RECEIVED_FPS"]=40,t[e[41]="VIDEO_DECODE_FPS"]=41,t[e[42]="VIDEO_NACKS_SENT"]=42,t[e[43]="VIDEO_FIRS_SENT"]=43,t[e[44]="VIDEO_RECEIVED_BITRATE"]=44,t[e[45]="VIDEO_CURRENT_DELAY_MS"]=45,t[e[46]="VIDEO_JITTER_BUFFER_MS"]=46,t[e[47]="VIDEO_DISCARDED_PPS"]=47,t[e[48]="VIDEO_PLIS_SENT"]=48,t[e[49]="VIDEO_RECEIVED_JITTER_MS"]=49,t[e[64]="VIDEO_ENCODE_HEIGHT"]=64,t[e[66]="VIDEO_SENT_QP_SUM"]=66,t[e[69]="VIDEO_DECODE_HEIGHT"]=69,t[e[72]="VIDEO_RECEIVED_QP_SUM"]=72,t[e[86]="VIDEO_ENCODE_WIDTH"]=86,t[e[87]="VIDEO_DECODE_WIDTH"]=87,t[e[88]="VIDEO_ENCODER_IS_HARDWARE"]=88,t[e[89]="VIDEO_DECODER_IS_HARDWARE"]=89,t[e[90]="VIDEO_FREEZE_COUNT"]=90,t[e[91]="VIDEO_FREEZE_DURATION"]=91,t[e[92]="VIDEO_PAUSE_COUNT"]=92,t[e[93]="VIDEO_PAUSE_DURATION"]=93,t[e[94]="VIDEO_QUALITY_REASON"]=94,t[e[95]="VIDEO_PROCESSING_TIME"]=95,t[e[96]="RTC_SPK_AUDIO_LEVEL"]=96,t[e[97]="RTC_MIC_AUDIO_LEVEL"]=97,t[e[98]="RTC_SPK_TOTAL_LOST"]=98,t[e[99]="RTC_SPK_TOTAL_EXPECTED"]=99,t[e[100]="RTC_SPK_TOTAL_RECOVERED_RED"]=100,t[e[101]="RTC_SPK_TOTAL_RECOVERED_FEC"]=101,t[e[102]="VIDEO_QUALITY_LIMITATION_DURATION_CPU"]=102,t}(),e}(),l.SdkStreamMetricFrame=function(){function e(e){if(this.metrics=[],this.dimensions=[],e)for(var t=Object.keys(e),n=0;n>>3){case 3:i.streamId=e.uint32();break;case 4:i.groupId=e.uint32();break;case 5:i.metrics&&i.metrics.length||(i.metrics=[]),i.metrics.push(l.SdkMetric.decode(e,e.uint32()));break;case 6:i.dimensions&&i.dimensions.length||(i.dimensions=[]),i.dimensions.push(l.SdkStreamDimension.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.streamId&&e.hasOwnProperty("streamId")&&!c.isInteger(e.streamId))return"streamId: integer expected";if(null!=e.groupId&&e.hasOwnProperty("groupId")&&!c.isInteger(e.groupId))return"groupId: integer expected";if(null!=e.metrics&&e.hasOwnProperty("metrics")){if(!Array.isArray(e.metrics))return"metrics: array expected";for(var t=0;t>>0),null!=e.groupId&&(t.groupId=e.groupId>>>0),e.metrics){if(!Array.isArray(e.metrics))throw TypeError(".SdkStreamMetricFrame.metrics: array expected");t.metrics=[];for(var n=0;n>>3){case 1:i.globalMetrics&&i.globalMetrics.length||(i.globalMetrics=[]),i.globalMetrics.push(l.SdkMetric.decode(e,e.uint32()));break;case 2:i.streamMetricFrames&&i.streamMetricFrames.length||(i.streamMetricFrames=[]),i.streamMetricFrames.push(l.SdkStreamMetricFrame.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.globalMetrics&&e.hasOwnProperty("globalMetrics")){if(!Array.isArray(e.globalMetrics))return"globalMetrics: array expected";for(var t=0;t>>3){case 1:i.type=e.int32();break;case 2:i.value=l.SdkDimensionValue.decode(e,e.uint32());break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.type&&e.hasOwnProperty("type"))switch(e.type){default:return"type: enum value expected";case 1:case 2:}if(null!=e.value&&e.hasOwnProperty("value")){var t=l.SdkDimensionValue.verify(e.value);if(t)return"value."+t}return null},e.fromObject=function(e){if(e instanceof l.SdkStreamDimension)return e;var t=new l.SdkStreamDimension;switch(e.type){default:if("number"==typeof e.type){t.type=e.type;break}break;case"VIDEO_ENCODER_NAME":case 1:t.type=1;break;case"VIDEO_DECODER_NAME":case 2:t.type=2}if(null!=e.value){if("object"!=typeof e.value)throw TypeError(".SdkStreamDimension.value: object expected");t.value=l.SdkDimensionValue.fromObject(e.value)}return t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.type=t.enums===String?"VIDEO_ENCODER_NAME":1,n.value=null),null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?void 0===l.SdkStreamDimension.Type[e.type]?e.type:l.SdkStreamDimension.Type[e.type]:e.type),null!=e.value&&e.hasOwnProperty("value")&&(n.value=l.SdkDimensionValue.toObject(e.value,t)),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkStreamDimension"},e.Type=function(){var e={},t=Object.create(e);return t[e[1]="VIDEO_ENCODER_NAME"]=1,t[e[2]="VIDEO_DECODER_NAME"]=2,t}(),e}(),l.SdkDimensionValue=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.stringValue=e.string();break;case 2:i.boolValue=e.bool();break;case 3:i.uintValue=e.uint64();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.stringValue&&e.hasOwnProperty("stringValue")&&!c.isString(e.stringValue)?"stringValue: string expected":null!=e.boolValue&&e.hasOwnProperty("boolValue")&&"boolean"!=typeof e.boolValue?"boolValue: boolean expected":null!=e.uintValue&&e.hasOwnProperty("uintValue")&&!(c.isInteger(e.uintValue)||e.uintValue&&c.isInteger(e.uintValue.low)&&c.isInteger(e.uintValue.high))?"uintValue: integer|Long expected":null},e.fromObject=function(e){if(e instanceof l.SdkDimensionValue)return e;var t=new l.SdkDimensionValue;return null!=e.stringValue&&(t.stringValue=String(e.stringValue)),null!=e.boolValue&&(t.boolValue=Boolean(e.boolValue)),null!=e.uintValue&&(c.Long?(t.uintValue=c.Long.fromValue(e.uintValue)).unsigned=!0:"string"==typeof e.uintValue?t.uintValue=parseInt(e.uintValue,10):"number"==typeof e.uintValue?t.uintValue=e.uintValue:"object"==typeof e.uintValue&&(t.uintValue=new c.LongBits(e.uintValue.low>>>0,e.uintValue.high>>>0).toNumber(!0))),t},e.toObject=function(e,t){t||(t={});var n={};if(t.defaults)if(n.stringValue="",n.boolValue=!1,c.Long){var i=new c.Long(0,0,!0);n.uintValue=t.longs===String?i.toString():t.longs===Number?i.toNumber():i}else n.uintValue=t.longs===String?"0":0;return null!=e.stringValue&&e.hasOwnProperty("stringValue")&&(n.stringValue=e.stringValue),null!=e.boolValue&&e.hasOwnProperty("boolValue")&&(n.boolValue=e.boolValue),null!=e.uintValue&&e.hasOwnProperty("uintValue")&&("number"==typeof e.uintValue?n.uintValue=t.longs===String?String(e.uintValue):e.uintValue:n.uintValue=t.longs===String?c.Long.prototype.toString.call(e.uintValue):t.longs===Number?new c.LongBits(e.uintValue.low>>>0,e.uintValue.high>>>0).toNumber(!0):e.uintValue),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkDimensionValue"},e}(),l.SdkDataMessageFrame=function(){function e(e){if(this.messages=[],e)for(var t=Object.keys(e),n=0;n>>3==1?(i.messages&&i.messages.length||(i.messages=[]),i.messages.push(l.SdkDataMessagePayload.decode(e,e.uint32()))):e.skipType(7&r)}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.messages&&e.hasOwnProperty("messages")){if(!Array.isArray(e.messages))return"messages: array expected";for(var t=0;t>>3){case 1:i.topic=e.string();break;case 2:i.data=e.bytes();break;case 3:i.lifetimeMs=e.uint32();break;case 4:i.senderAttendeeId=e.string();break;case 5:i.ingestTimeNs=e.int64();break;case 6:i.senderExternalUserId=e.string();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.topic&&e.hasOwnProperty("topic")&&!c.isString(e.topic)?"topic: string expected":null!=e.data&&e.hasOwnProperty("data")&&!(e.data&&"number"==typeof e.data.length||c.isString(e.data))?"data: buffer expected":null!=e.lifetimeMs&&e.hasOwnProperty("lifetimeMs")&&!c.isInteger(e.lifetimeMs)?"lifetimeMs: integer expected":null!=e.senderAttendeeId&&e.hasOwnProperty("senderAttendeeId")&&!c.isString(e.senderAttendeeId)?"senderAttendeeId: string expected":null!=e.ingestTimeNs&&e.hasOwnProperty("ingestTimeNs")&&!(c.isInteger(e.ingestTimeNs)||e.ingestTimeNs&&c.isInteger(e.ingestTimeNs.low)&&c.isInteger(e.ingestTimeNs.high))?"ingestTimeNs: integer|Long expected":null!=e.senderExternalUserId&&e.hasOwnProperty("senderExternalUserId")&&!c.isString(e.senderExternalUserId)?"senderExternalUserId: string expected":null},e.fromObject=function(e){if(e instanceof l.SdkDataMessagePayload)return e;var t=new l.SdkDataMessagePayload;return null!=e.topic&&(t.topic=String(e.topic)),null!=e.data&&("string"==typeof e.data?c.base64.decode(e.data,t.data=c.newBuffer(c.base64.length(e.data)),0):e.data.length>=0&&(t.data=e.data)),null!=e.lifetimeMs&&(t.lifetimeMs=e.lifetimeMs>>>0),null!=e.senderAttendeeId&&(t.senderAttendeeId=String(e.senderAttendeeId)),null!=e.ingestTimeNs&&(c.Long?(t.ingestTimeNs=c.Long.fromValue(e.ingestTimeNs)).unsigned=!1:"string"==typeof e.ingestTimeNs?t.ingestTimeNs=parseInt(e.ingestTimeNs,10):"number"==typeof e.ingestTimeNs?t.ingestTimeNs=e.ingestTimeNs:"object"==typeof e.ingestTimeNs&&(t.ingestTimeNs=new c.LongBits(e.ingestTimeNs.low>>>0,e.ingestTimeNs.high>>>0).toNumber())),null!=e.senderExternalUserId&&(t.senderExternalUserId=String(e.senderExternalUserId)),t},e.toObject=function(e,t){t||(t={});var n={};if(t.defaults){if(n.topic="",t.bytes===String?n.data="":(n.data=[],t.bytes!==Array&&(n.data=c.newBuffer(n.data))),n.lifetimeMs=0,n.senderAttendeeId="",c.Long){var i=new c.Long(0,0,!1);n.ingestTimeNs=t.longs===String?i.toString():t.longs===Number?i.toNumber():i}else n.ingestTimeNs=t.longs===String?"0":0;n.senderExternalUserId=""}return null!=e.topic&&e.hasOwnProperty("topic")&&(n.topic=e.topic),null!=e.data&&e.hasOwnProperty("data")&&(n.data=t.bytes===String?c.base64.encode(e.data,0,e.data.length):t.bytes===Array?Array.prototype.slice.call(e.data):e.data),null!=e.lifetimeMs&&e.hasOwnProperty("lifetimeMs")&&(n.lifetimeMs=e.lifetimeMs),null!=e.senderAttendeeId&&e.hasOwnProperty("senderAttendeeId")&&(n.senderAttendeeId=e.senderAttendeeId),null!=e.ingestTimeNs&&e.hasOwnProperty("ingestTimeNs")&&("number"==typeof e.ingestTimeNs?n.ingestTimeNs=t.longs===String?String(e.ingestTimeNs):e.ingestTimeNs:n.ingestTimeNs=t.longs===String?c.Long.prototype.toString.call(e.ingestTimeNs):t.longs===Number?new c.LongBits(e.ingestTimeNs.low>>>0,e.ingestTimeNs.high>>>0).toNumber():e.ingestTimeNs),null!=e.senderExternalUserId&&e.hasOwnProperty("senderExternalUserId")&&(n.senderExternalUserId=e.senderExternalUserId),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkDataMessagePayload"},e}(),l.SdkTurnCredentials=function(){function e(e){if(this.uris=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.username=e.string();break;case 2:i.password=e.string();break;case 3:i.ttl=e.uint32();break;case 4:i.uris&&i.uris.length||(i.uris=[]),i.uris.push(e.string());break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.username&&e.hasOwnProperty("username")&&!c.isString(e.username))return"username: string expected";if(null!=e.password&&e.hasOwnProperty("password")&&!c.isString(e.password))return"password: string expected";if(null!=e.ttl&&e.hasOwnProperty("ttl")&&!c.isInteger(e.ttl))return"ttl: integer expected";if(null!=e.uris&&e.hasOwnProperty("uris")){if(!Array.isArray(e.uris))return"uris: array expected";for(var t=0;t>>0),e.uris){if(!Array.isArray(e.uris))throw TypeError(".SdkTurnCredentials.uris: array expected");t.uris=[];for(var n=0;n>>3){case 1:i.content=e.string();break;case 2:i.endTime=e.int64();break;case 3:i.speakerAttendeeId=e.string();break;case 4:i.speakerExternalUserId=e.string();break;case 5:i.startTime=e.int64();break;case 6:i.type=e.int32();break;case 7:i.vocabularyFilterMatch=e.bool();break;case 8:i.confidence=e.double();break;case 9:i.stable=e.bool();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.content&&e.hasOwnProperty("content")&&!c.isString(e.content))return"content: string expected";if(null!=e.endTime&&e.hasOwnProperty("endTime")&&!(c.isInteger(e.endTime)||e.endTime&&c.isInteger(e.endTime.low)&&c.isInteger(e.endTime.high)))return"endTime: integer|Long expected";if(null!=e.speakerAttendeeId&&e.hasOwnProperty("speakerAttendeeId")&&!c.isString(e.speakerAttendeeId))return"speakerAttendeeId: string expected";if(null!=e.speakerExternalUserId&&e.hasOwnProperty("speakerExternalUserId")&&!c.isString(e.speakerExternalUserId))return"speakerExternalUserId: string expected";if(null!=e.startTime&&e.hasOwnProperty("startTime")&&!(c.isInteger(e.startTime)||e.startTime&&c.isInteger(e.startTime.low)&&c.isInteger(e.startTime.high)))return"startTime: integer|Long expected";if(null!=e.type&&e.hasOwnProperty("type"))switch(e.type){default:return"type: enum value expected";case 1:case 2:}return null!=e.vocabularyFilterMatch&&e.hasOwnProperty("vocabularyFilterMatch")&&"boolean"!=typeof e.vocabularyFilterMatch?"vocabularyFilterMatch: boolean expected":null!=e.confidence&&e.hasOwnProperty("confidence")&&"number"!=typeof e.confidence?"confidence: number expected":null!=e.stable&&e.hasOwnProperty("stable")&&"boolean"!=typeof e.stable?"stable: boolean expected":null},e.fromObject=function(e){if(e instanceof l.SdkTranscriptItem)return e;var t=new l.SdkTranscriptItem;switch(null!=e.content&&(t.content=String(e.content)),null!=e.endTime&&(c.Long?(t.endTime=c.Long.fromValue(e.endTime)).unsigned=!1:"string"==typeof e.endTime?t.endTime=parseInt(e.endTime,10):"number"==typeof e.endTime?t.endTime=e.endTime:"object"==typeof e.endTime&&(t.endTime=new c.LongBits(e.endTime.low>>>0,e.endTime.high>>>0).toNumber())),null!=e.speakerAttendeeId&&(t.speakerAttendeeId=String(e.speakerAttendeeId)),null!=e.speakerExternalUserId&&(t.speakerExternalUserId=String(e.speakerExternalUserId)),null!=e.startTime&&(c.Long?(t.startTime=c.Long.fromValue(e.startTime)).unsigned=!1:"string"==typeof e.startTime?t.startTime=parseInt(e.startTime,10):"number"==typeof e.startTime?t.startTime=e.startTime:"object"==typeof e.startTime&&(t.startTime=new c.LongBits(e.startTime.low>>>0,e.startTime.high>>>0).toNumber())),e.type){default:if("number"==typeof e.type){t.type=e.type;break}break;case"PRONUNCIATION":case 1:t.type=1;break;case"PUNCTUATION":case 2:t.type=2}return null!=e.vocabularyFilterMatch&&(t.vocabularyFilterMatch=Boolean(e.vocabularyFilterMatch)),null!=e.confidence&&(t.confidence=Number(e.confidence)),null!=e.stable&&(t.stable=Boolean(e.stable)),t},e.toObject=function(e,t){t||(t={});var n={};if(t.defaults){if(n.content="",c.Long){var i=new c.Long(0,0,!1);n.endTime=t.longs===String?i.toString():t.longs===Number?i.toNumber():i}else n.endTime=t.longs===String?"0":0;n.speakerAttendeeId="",n.speakerExternalUserId="",c.Long?(i=new c.Long(0,0,!1),n.startTime=t.longs===String?i.toString():t.longs===Number?i.toNumber():i):n.startTime=t.longs===String?"0":0,n.type=t.enums===String?"PRONUNCIATION":1,n.vocabularyFilterMatch=!1,n.confidence=0,n.stable=!1}return null!=e.content&&e.hasOwnProperty("content")&&(n.content=e.content),null!=e.endTime&&e.hasOwnProperty("endTime")&&("number"==typeof e.endTime?n.endTime=t.longs===String?String(e.endTime):e.endTime:n.endTime=t.longs===String?c.Long.prototype.toString.call(e.endTime):t.longs===Number?new c.LongBits(e.endTime.low>>>0,e.endTime.high>>>0).toNumber():e.endTime),null!=e.speakerAttendeeId&&e.hasOwnProperty("speakerAttendeeId")&&(n.speakerAttendeeId=e.speakerAttendeeId),null!=e.speakerExternalUserId&&e.hasOwnProperty("speakerExternalUserId")&&(n.speakerExternalUserId=e.speakerExternalUserId),null!=e.startTime&&e.hasOwnProperty("startTime")&&("number"==typeof e.startTime?n.startTime=t.longs===String?String(e.startTime):e.startTime:n.startTime=t.longs===String?c.Long.prototype.toString.call(e.startTime):t.longs===Number?new c.LongBits(e.startTime.low>>>0,e.startTime.high>>>0).toNumber():e.startTime),null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?void 0===l.SdkTranscriptItem.Type[e.type]?e.type:l.SdkTranscriptItem.Type[e.type]:e.type),null!=e.vocabularyFilterMatch&&e.hasOwnProperty("vocabularyFilterMatch")&&(n.vocabularyFilterMatch=e.vocabularyFilterMatch),null!=e.confidence&&e.hasOwnProperty("confidence")&&(n.confidence=t.json&&!isFinite(e.confidence)?String(e.confidence):e.confidence),null!=e.stable&&e.hasOwnProperty("stable")&&(n.stable=e.stable),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkTranscriptItem"},e.Type=function(){var e={},t=Object.create(e);return t[e[1]="PRONUNCIATION"]=1,t[e[2]="PUNCTUATION"]=2,t}(),e}(),l.SdkTranscriptEntity=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.category=e.string();break;case 2:i.confidence=e.double();break;case 3:i.content=e.string();break;case 4:i.endTime=e.int64();break;case 5:i.startTime=e.int64();break;case 6:i.type=e.string();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.category&&e.hasOwnProperty("category")&&!c.isString(e.category)?"category: string expected":null!=e.confidence&&e.hasOwnProperty("confidence")&&"number"!=typeof e.confidence?"confidence: number expected":null!=e.content&&e.hasOwnProperty("content")&&!c.isString(e.content)?"content: string expected":null!=e.endTime&&e.hasOwnProperty("endTime")&&!(c.isInteger(e.endTime)||e.endTime&&c.isInteger(e.endTime.low)&&c.isInteger(e.endTime.high))?"endTime: integer|Long expected":null!=e.startTime&&e.hasOwnProperty("startTime")&&!(c.isInteger(e.startTime)||e.startTime&&c.isInteger(e.startTime.low)&&c.isInteger(e.startTime.high))?"startTime: integer|Long expected":null!=e.type&&e.hasOwnProperty("type")&&!c.isString(e.type)?"type: string expected":null},e.fromObject=function(e){if(e instanceof l.SdkTranscriptEntity)return e;var t=new l.SdkTranscriptEntity;return null!=e.category&&(t.category=String(e.category)),null!=e.confidence&&(t.confidence=Number(e.confidence)),null!=e.content&&(t.content=String(e.content)),null!=e.endTime&&(c.Long?(t.endTime=c.Long.fromValue(e.endTime)).unsigned=!1:"string"==typeof e.endTime?t.endTime=parseInt(e.endTime,10):"number"==typeof e.endTime?t.endTime=e.endTime:"object"==typeof e.endTime&&(t.endTime=new c.LongBits(e.endTime.low>>>0,e.endTime.high>>>0).toNumber())),null!=e.startTime&&(c.Long?(t.startTime=c.Long.fromValue(e.startTime)).unsigned=!1:"string"==typeof e.startTime?t.startTime=parseInt(e.startTime,10):"number"==typeof e.startTime?t.startTime=e.startTime:"object"==typeof e.startTime&&(t.startTime=new c.LongBits(e.startTime.low>>>0,e.startTime.high>>>0).toNumber())),null!=e.type&&(t.type=String(e.type)),t},e.toObject=function(e,t){t||(t={});var n={};if(t.defaults){if(n.category="",n.confidence=0,n.content="",c.Long){var i=new c.Long(0,0,!1);n.endTime=t.longs===String?i.toString():t.longs===Number?i.toNumber():i}else n.endTime=t.longs===String?"0":0;c.Long?(i=new c.Long(0,0,!1),n.startTime=t.longs===String?i.toString():t.longs===Number?i.toNumber():i):n.startTime=t.longs===String?"0":0,n.type=""}return null!=e.category&&e.hasOwnProperty("category")&&(n.category=e.category),null!=e.confidence&&e.hasOwnProperty("confidence")&&(n.confidence=t.json&&!isFinite(e.confidence)?String(e.confidence):e.confidence),null!=e.content&&e.hasOwnProperty("content")&&(n.content=e.content),null!=e.endTime&&e.hasOwnProperty("endTime")&&("number"==typeof e.endTime?n.endTime=t.longs===String?String(e.endTime):e.endTime:n.endTime=t.longs===String?c.Long.prototype.toString.call(e.endTime):t.longs===Number?new c.LongBits(e.endTime.low>>>0,e.endTime.high>>>0).toNumber():e.endTime),null!=e.startTime&&e.hasOwnProperty("startTime")&&("number"==typeof e.startTime?n.startTime=t.longs===String?String(e.startTime):e.startTime:n.startTime=t.longs===String?c.Long.prototype.toString.call(e.startTime):t.longs===Number?new c.LongBits(e.startTime.low>>>0,e.startTime.high>>>0).toNumber():e.startTime),null!=e.type&&e.hasOwnProperty("type")&&(n.type=e.type),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkTranscriptEntity"},e}(),l.SdkTranscriptAlternative=function(){function e(e){if(this.items=[],this.entities=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.items&&i.items.length||(i.items=[]),i.items.push(l.SdkTranscriptItem.decode(e,e.uint32()));break;case 2:i.transcript=e.string();break;case 3:i.entities&&i.entities.length||(i.entities=[]),i.entities.push(l.SdkTranscriptEntity.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.items&&e.hasOwnProperty("items")){if(!Array.isArray(e.items))return"items: array expected";for(var t=0;t>>3){case 1:i.languageCode=e.string();break;case 2:i.score=e.double();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.languageCode&&e.hasOwnProperty("languageCode")&&!c.isString(e.languageCode)?"languageCode: string expected":null!=e.score&&e.hasOwnProperty("score")&&"number"!=typeof e.score?"score: number expected":null},e.fromObject=function(e){if(e instanceof l.SdkTranscriptLanguageWithScore)return e;var t=new l.SdkTranscriptLanguageWithScore;return null!=e.languageCode&&(t.languageCode=String(e.languageCode)),null!=e.score&&(t.score=Number(e.score)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.languageCode="",n.score=0),null!=e.languageCode&&e.hasOwnProperty("languageCode")&&(n.languageCode=e.languageCode),null!=e.score&&e.hasOwnProperty("score")&&(n.score=t.json&&!isFinite(e.score)?String(e.score):e.score),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkTranscriptLanguageWithScore"},e}(),l.SdkTranscriptResult=function(){function e(e){if(this.alternatives=[],this.languageIdentification=[],e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.alternatives&&i.alternatives.length||(i.alternatives=[]),i.alternatives.push(l.SdkTranscriptAlternative.decode(e,e.uint32()));break;case 2:i.channelId=e.string();break;case 3:i.endTime=e.int64();break;case 4:i.isPartial=e.bool();break;case 5:i.resultId=e.string();break;case 6:i.startTime=e.int64();break;case 7:i.languageCode=e.string();break;case 8:i.languageIdentification&&i.languageIdentification.length||(i.languageIdentification=[]),i.languageIdentification.push(l.SdkTranscriptLanguageWithScore.decode(e,e.uint32()));break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.alternatives&&e.hasOwnProperty("alternatives")){if(!Array.isArray(e.alternatives))return"alternatives: array expected";for(var t=0;t>>0,e.endTime.high>>>0).toNumber())),null!=e.isPartial&&(t.isPartial=Boolean(e.isPartial)),null!=e.resultId&&(t.resultId=String(e.resultId)),null!=e.startTime&&(c.Long?(t.startTime=c.Long.fromValue(e.startTime)).unsigned=!1:"string"==typeof e.startTime?t.startTime=parseInt(e.startTime,10):"number"==typeof e.startTime?t.startTime=e.startTime:"object"==typeof e.startTime&&(t.startTime=new c.LongBits(e.startTime.low>>>0,e.startTime.high>>>0).toNumber())),null!=e.languageCode&&(t.languageCode=String(e.languageCode)),e.languageIdentification){if(!Array.isArray(e.languageIdentification))throw TypeError(".SdkTranscriptResult.languageIdentification: array expected");for(t.languageIdentification=[],n=0;n>>0,e.endTime.high>>>0).toNumber():e.endTime),null!=e.isPartial&&e.hasOwnProperty("isPartial")&&(n.isPartial=e.isPartial),null!=e.resultId&&e.hasOwnProperty("resultId")&&(n.resultId=e.resultId),null!=e.startTime&&e.hasOwnProperty("startTime")&&("number"==typeof e.startTime?n.startTime=t.longs===String?String(e.startTime):e.startTime:n.startTime=t.longs===String?c.Long.prototype.toString.call(e.startTime):t.longs===Number?new c.LongBits(e.startTime.low>>>0,e.startTime.high>>>0).toNumber():e.startTime),null!=e.languageCode&&e.hasOwnProperty("languageCode")&&(n.languageCode=e.languageCode),e.languageIdentification&&e.languageIdentification.length)for(n.languageIdentification=[],r=0;r>>3==1?(i.results&&i.results.length||(i.results=[]),i.results.push(l.SdkTranscriptResult.decode(e,e.uint32()))):e.skipType(7&r)}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.results&&e.hasOwnProperty("results")){if(!Array.isArray(e.results))return"results: array expected";for(var t=0;t>>3){case 1:i.type=e.int32();break;case 2:i.eventTime=e.int64();break;case 3:i.transcriptionRegion=e.string();break;case 4:i.transcriptionConfiguration=e.string();break;case 5:i.message=e.string();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.type&&e.hasOwnProperty("type"))switch(e.type){default:return"type: enum value expected";case 1:case 2:case 3:case 4:case 5:}return null!=e.eventTime&&e.hasOwnProperty("eventTime")&&!(c.isInteger(e.eventTime)||e.eventTime&&c.isInteger(e.eventTime.low)&&c.isInteger(e.eventTime.high))?"eventTime: integer|Long expected":null!=e.transcriptionRegion&&e.hasOwnProperty("transcriptionRegion")&&!c.isString(e.transcriptionRegion)?"transcriptionRegion: string expected":null!=e.transcriptionConfiguration&&e.hasOwnProperty("transcriptionConfiguration")&&!c.isString(e.transcriptionConfiguration)?"transcriptionConfiguration: string expected":null!=e.message&&e.hasOwnProperty("message")&&!c.isString(e.message)?"message: string expected":null},e.fromObject=function(e){if(e instanceof l.SdkTranscriptionStatus)return e;var t=new l.SdkTranscriptionStatus;switch(e.type){default:if("number"==typeof e.type){t.type=e.type;break}break;case"STARTED":case 1:t.type=1;break;case"INTERRUPTED":case 2:t.type=2;break;case"RESUMED":case 3:t.type=3;break;case"STOPPED":case 4:t.type=4;break;case"FAILED":case 5:t.type=5}return null!=e.eventTime&&(c.Long?(t.eventTime=c.Long.fromValue(e.eventTime)).unsigned=!1:"string"==typeof e.eventTime?t.eventTime=parseInt(e.eventTime,10):"number"==typeof e.eventTime?t.eventTime=e.eventTime:"object"==typeof e.eventTime&&(t.eventTime=new c.LongBits(e.eventTime.low>>>0,e.eventTime.high>>>0).toNumber())),null!=e.transcriptionRegion&&(t.transcriptionRegion=String(e.transcriptionRegion)),null!=e.transcriptionConfiguration&&(t.transcriptionConfiguration=String(e.transcriptionConfiguration)),null!=e.message&&(t.message=String(e.message)),t},e.toObject=function(e,t){t||(t={});var n={};if(t.defaults){if(n.type=t.enums===String?"STARTED":1,c.Long){var i=new c.Long(0,0,!1);n.eventTime=t.longs===String?i.toString():t.longs===Number?i.toNumber():i}else n.eventTime=t.longs===String?"0":0;n.transcriptionRegion="",n.transcriptionConfiguration="",n.message=""}return null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?void 0===l.SdkTranscriptionStatus.Type[e.type]?e.type:l.SdkTranscriptionStatus.Type[e.type]:e.type),null!=e.eventTime&&e.hasOwnProperty("eventTime")&&("number"==typeof e.eventTime?n.eventTime=t.longs===String?String(e.eventTime):e.eventTime:n.eventTime=t.longs===String?c.Long.prototype.toString.call(e.eventTime):t.longs===Number?new c.LongBits(e.eventTime.low>>>0,e.eventTime.high>>>0).toNumber():e.eventTime),null!=e.transcriptionRegion&&e.hasOwnProperty("transcriptionRegion")&&(n.transcriptionRegion=e.transcriptionRegion),null!=e.transcriptionConfiguration&&e.hasOwnProperty("transcriptionConfiguration")&&(n.transcriptionConfiguration=e.transcriptionConfiguration),null!=e.message&&e.hasOwnProperty("message")&&(n.message=e.message),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkTranscriptionStatus"},e.Type=function(){var e={},t=Object.create(e);return t[e[1]="STARTED"]=1,t[e[2]="INTERRUPTED"]=2,t[e[3]="RESUMED"]=3,t[e[4]="STOPPED"]=4,t[e[5]="FAILED"]=5,t}(),e}(),l.SdkTranscriptEvent=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.status=l.SdkTranscriptionStatus.decode(e,e.uint32());break;case 2:i.transcript=l.SdkTranscript.decode(e,e.uint32());break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";var t={};if(null!=e.status&&e.hasOwnProperty("status")&&(t.Event=1,n=l.SdkTranscriptionStatus.verify(e.status)))return"status."+n;if(null!=e.transcript&&e.hasOwnProperty("transcript")){if(1===t.Event)return"Event: multiple values";var n;if(t.Event=1,n=l.SdkTranscript.verify(e.transcript))return"transcript."+n}return null},e.fromObject=function(e){if(e instanceof l.SdkTranscriptEvent)return e;var t=new l.SdkTranscriptEvent;if(null!=e.status){if("object"!=typeof e.status)throw TypeError(".SdkTranscriptEvent.status: object expected");t.status=l.SdkTranscriptionStatus.fromObject(e.status)}if(null!=e.transcript){if("object"!=typeof e.transcript)throw TypeError(".SdkTranscriptEvent.transcript: object expected");t.transcript=l.SdkTranscript.fromObject(e.transcript)}return t},e.toObject=function(e,t){t||(t={});var n={};return null!=e.status&&e.hasOwnProperty("status")&&(n.status=l.SdkTranscriptionStatus.toObject(e.status,t),t.oneofs&&(n.Event="status")),null!=e.transcript&&e.hasOwnProperty("transcript")&&(n.transcript=l.SdkTranscript.toObject(e.transcript,t),t.oneofs&&(n.Event="transcript")),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkTranscriptEvent"},e}(),l.SdkTranscriptFrame=function(){function e(e){if(this.events=[],e)for(var t=Object.keys(e),n=0;n>>3==1?(i.events&&i.events.length||(i.events=[]),i.events.push(l.SdkTranscriptEvent.decode(e,e.uint32()))):e.skipType(7&r)}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.events&&e.hasOwnProperty("events")){if(!Array.isArray(e.events))return"events: array expected";for(var t=0;t>>3){case 1:i.addedOrUpdatedVideoSubscriptions&&i.addedOrUpdatedVideoSubscriptions.length||(i.addedOrUpdatedVideoSubscriptions=[]),i.addedOrUpdatedVideoSubscriptions.push(l.SdkVideoSubscriptionConfiguration.decode(e,e.uint32()));break;case 2:i.removedVideoSubscriptionMids&&i.removedVideoSubscriptionMids.length||(i.removedVideoSubscriptionMids=[]),i.removedVideoSubscriptionMids.push(e.string());break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.addedOrUpdatedVideoSubscriptions&&e.hasOwnProperty("addedOrUpdatedVideoSubscriptions")){if(!Array.isArray(e.addedOrUpdatedVideoSubscriptions))return"addedOrUpdatedVideoSubscriptions: array expected";for(var t=0;t>>3){case 1:i.mid=e.string();break;case 2:i.attendeeId=e.string();break;case 3:i.streamId=e.uint32();break;case 4:i.priority=e.uint32();break;case 5:i.targetBitrateKbps=e.uint32();break;case 6:i.groupId=e.uint32();break;case 7:i.qualityAdaptationPreference=e.int32();break;default:e.skipType(7&r)}}if(!i.hasOwnProperty("mid"))throw c.ProtocolError("missing required 'mid'",{instance:i});return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(!c.isString(e.mid))return"mid: string expected";if(null!=e.attendeeId&&e.hasOwnProperty("attendeeId")&&!c.isString(e.attendeeId))return"attendeeId: string expected";if(null!=e.streamId&&e.hasOwnProperty("streamId")&&!c.isInteger(e.streamId))return"streamId: integer expected";if(null!=e.priority&&e.hasOwnProperty("priority")&&!c.isInteger(e.priority))return"priority: integer expected";if(null!=e.targetBitrateKbps&&e.hasOwnProperty("targetBitrateKbps")&&!c.isInteger(e.targetBitrateKbps))return"targetBitrateKbps: integer expected";if(null!=e.groupId&&e.hasOwnProperty("groupId")&&!c.isInteger(e.groupId))return"groupId: integer expected";if(null!=e.qualityAdaptationPreference&&e.hasOwnProperty("qualityAdaptationPreference"))switch(e.qualityAdaptationPreference){default:return"qualityAdaptationPreference: enum value expected";case 1:case 2:case 3:}return null},e.fromObject=function(e){if(e instanceof l.SdkVideoSubscriptionConfiguration)return e;var t=new l.SdkVideoSubscriptionConfiguration;switch(null!=e.mid&&(t.mid=String(e.mid)),null!=e.attendeeId&&(t.attendeeId=String(e.attendeeId)),null!=e.streamId&&(t.streamId=e.streamId>>>0),null!=e.priority&&(t.priority=e.priority>>>0),null!=e.targetBitrateKbps&&(t.targetBitrateKbps=e.targetBitrateKbps>>>0),null!=e.groupId&&(t.groupId=e.groupId>>>0),e.qualityAdaptationPreference){default:if("number"==typeof e.qualityAdaptationPreference){t.qualityAdaptationPreference=e.qualityAdaptationPreference;break}break;case"BALANCED":case 1:t.qualityAdaptationPreference=1;break;case"MAINTAIN_FRAMERATE":case 2:t.qualityAdaptationPreference=2;break;case"MAINTAIN_RESOLUTION":case 3:t.qualityAdaptationPreference=3}return t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.mid="",n.attendeeId="",n.streamId=0,n.priority=0,n.targetBitrateKbps=0,n.groupId=0,n.qualityAdaptationPreference=t.enums===String?"BALANCED":1),null!=e.mid&&e.hasOwnProperty("mid")&&(n.mid=e.mid),null!=e.attendeeId&&e.hasOwnProperty("attendeeId")&&(n.attendeeId=e.attendeeId),null!=e.streamId&&e.hasOwnProperty("streamId")&&(n.streamId=e.streamId),null!=e.priority&&e.hasOwnProperty("priority")&&(n.priority=e.priority),null!=e.targetBitrateKbps&&e.hasOwnProperty("targetBitrateKbps")&&(n.targetBitrateKbps=e.targetBitrateKbps),null!=e.groupId&&e.hasOwnProperty("groupId")&&(n.groupId=e.groupId),null!=e.qualityAdaptationPreference&&e.hasOwnProperty("qualityAdaptationPreference")&&(n.qualityAdaptationPreference=t.enums===String?void 0===l.SdkVideoQualityAdaptationPreference[e.qualityAdaptationPreference]?e.qualityAdaptationPreference:l.SdkVideoQualityAdaptationPreference[e.qualityAdaptationPreference]:e.qualityAdaptationPreference),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkVideoSubscriptionConfiguration"},e}(),l.SdkNotificationFrame=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.level=e.int32();break;case 2:i.message=e.string();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.level&&e.hasOwnProperty("level"))switch(e.level){default:return"level: enum value expected";case 1:case 2:case 3:}return null!=e.message&&e.hasOwnProperty("message")&&!c.isString(e.message)?"message: string expected":null},e.fromObject=function(e){if(e instanceof l.SdkNotificationFrame)return e;var t=new l.SdkNotificationFrame;switch(e.level){case"INFO":case 1:t.level=1;break;case"WARNING":case 2:t.level=2;break;default:if("number"==typeof e.level){t.level=e.level;break}break;case"ERROR":case 3:t.level=3}return null!=e.message&&(t.message=String(e.message)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.level=t.enums===String?"ERROR":3,n.message=""),null!=e.level&&e.hasOwnProperty("level")&&(n.level=t.enums===String?void 0===l.SdkNotificationFrame.NotificationLevel[e.level]?e.level:l.SdkNotificationFrame.NotificationLevel[e.level]:e.level),null!=e.message&&e.hasOwnProperty("message")&&(n.message=e.message),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkNotificationFrame"},e.NotificationLevel=function(){var e={},t=Object.create(e);return t[e[1]="INFO"]=1,t[e[2]="WARNING"]=2,t[e[3]="ERROR"]=3,t}(),e}(),l.SdkPrimaryMeetingJoinFrame=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3==1?i.credentials=l.SdkMeetingSessionCredentials.decode(e,e.uint32()):e.skipType(7&r)}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.credentials&&e.hasOwnProperty("credentials")){var t=l.SdkMeetingSessionCredentials.verify(e.credentials);if(t)return"credentials."+t}return null},e.fromObject=function(e){if(e instanceof l.SdkPrimaryMeetingJoinFrame)return e;var t=new l.SdkPrimaryMeetingJoinFrame;if(null!=e.credentials){if("object"!=typeof e.credentials)throw TypeError(".SdkPrimaryMeetingJoinFrame.credentials: object expected");t.credentials=l.SdkMeetingSessionCredentials.fromObject(e.credentials)}return t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.credentials=null),null!=e.credentials&&e.hasOwnProperty("credentials")&&(n.credentials=l.SdkMeetingSessionCredentials.toObject(e.credentials,t)),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkPrimaryMeetingJoinFrame"},e}(),l.SdkPrimaryMeetingJoinAckFrame=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n>>3){case 1:i.attendeeId=e.string();break;case 2:i.externalUserId=e.string();break;case 3:i.joinToken=e.string();break;default:e.skipType(7&r)}}return i},e.decodeDelimited=function(e){return e instanceof o||(e=new o(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.attendeeId&&e.hasOwnProperty("attendeeId")&&!c.isString(e.attendeeId)?"attendeeId: string expected":null!=e.externalUserId&&e.hasOwnProperty("externalUserId")&&!c.isString(e.externalUserId)?"externalUserId: string expected":null!=e.joinToken&&e.hasOwnProperty("joinToken")&&!c.isString(e.joinToken)?"joinToken: string expected":null},e.fromObject=function(e){if(e instanceof l.SdkMeetingSessionCredentials)return e;var t=new l.SdkMeetingSessionCredentials;return null!=e.attendeeId&&(t.attendeeId=String(e.attendeeId)),null!=e.externalUserId&&(t.externalUserId=String(e.externalUserId)),null!=e.joinToken&&(t.joinToken=String(e.joinToken)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.attendeeId="",n.externalUserId="",n.joinToken=""),null!=e.attendeeId&&e.hasOwnProperty("attendeeId")&&(n.attendeeId=e.attendeeId),null!=e.externalUserId&&e.hasOwnProperty("externalUserId")&&(n.externalUserId=e.externalUserId),null!=e.joinToken&&e.hasOwnProperty("joinToken")&&(n.joinToken=e.joinToken),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e.getTypeUrl=function(e){return void 0===e&&(e="type.googleapis.com"),e+"/SdkMeetingSessionCredentials"},e}(),l.SdkVideoCodecCapability=function(){var e={},t=Object.create(e);return t[e[1]="VP8"]=1,t[e[2]="H264_BASELINE_PROFILE"]=2,t[e[3]="H264_CONSTRAINED_BASELINE_PROFILE"]=3,t[e[4]="H264_MAIN_PROFILE"]=4,t[e[5]="H264_HIGH_PROFILE"]=5,t[e[6]="H264_CONSTRAINED_HIGH_PROFILE"]=6,t[e[8]="VP9_PROFILE_0"]=8,t[e[11]="AV1_MAIN_PROFILE"]=11,t}(),e.exports=l,c.Long=void 0,a.configure()},8854:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=n(3523),o=n(9649),s=r(n(6741));t.default=class{constructor(e){this.chimeClient=e}makeTwoDigits(e){return e>9?e.toString():"0"+e.toString()}hmac(e,t){const n=new a.Sha256(t);return n.update(e),n.digest()}getDateTimeString(){const e=new Date;return e.getUTCFullYear()+this.makeTwoDigits(e.getUTCMonth()+1)+this.makeTwoDigits(e.getUTCDate())+"T"+this.makeTwoDigits(e.getUTCHours())+this.makeTwoDigits(e.getUTCMinutes())+this.makeTwoDigits(e.getUTCSeconds())+"Z"}getDateString(e){return e.substring(0,e.indexOf("T"))}getSignatureKey(e,t,n,r){return i(this,void 0,void 0,(function*(){const i=yield this.hmac(t,"AWS4"+e),a=yield this.hmac(n,i),o=yield this.hmac(r,a);return yield this.hmac("aws4_request",o)}))}signURL(e,t,n,r,a,c,l){return i(this,void 0,void 0,(function*(){const i=this.getDateTimeString(),d=this.getDateString(i);let u="";u=this.chimeClient.config.region instanceof Function?yield this.chimeClient.config.region():this.chimeClient.config.region;const f="host:"+r.toLowerCase()+"\n",h=d+"/"+u+"/"+n+"/aws4_request";let m;m=this.chimeClient.config.credentials instanceof Function?yield this.chimeClient.config.credentials():this.chimeClient.config.credentials;let p=new Map;p.set("X-Amz-Algorithm",["AWS4-HMAC-SHA256"]),p.set("X-Amz-Credential",[encodeURIComponent(m.accessKeyId+"/"+h)]),p.set("X-Amz-Date",[i]),p.set("X-Amz-Expires",["10"]),p.set("X-Amz-SignedHeaders",["host"]),m.sessionToken&&p.set("X-Amz-Security-Token",[encodeURIComponent(m.sessionToken)]),p.set(s.default.X_AMZN_VERSION,[encodeURIComponent(s.default.sdkVersion)]),p.set(s.default.X_AMZN_USER_AGENT,[encodeURIComponent(s.default.sdkUserAgentLowResolution)]),null==l||l.forEach(((e,t)=>{const n=encodeURIComponent(t);e.sort().forEach((e=>{p.has(n)||p.set(n,[]),p.get(n).push(encodeURIComponent(e))}))}));let g="";p=new Map([...p.entries()].sort()),p.forEach(((e,t)=>{e.forEach((e=>{g.length&&(g+="&"),g+=t+"="+e}))}));const v=e+"\n"+a+"\n"+g+"\n"+f+"\nhost\n"+o.toHex(yield this.hmac(c)),b=o.toHex(yield this.hmac(v)),y="AWS4-HMAC-SHA256\n"+i+"\n"+d+"/"+u+"/"+n+"/aws4_request\n"+b,S=yield this.getSignatureKey(m.secretAccessKey,d,u,n),C=o.toHex(yield this.hmac(y,S));return t+"://"+r+a+"?"+g+"&X-Amz-Signature="+C}))}}},1455:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SimulcastLayers=void 0,function(e){e[e.Low=0]="Low",e[e.LowAndMedium=1]="LowAndMedium",e[e.LowAndHigh=2]="LowAndHigh",e[e.Medium=3]="Medium",e[e.MediumAndHigh=4]="MediumAndHigh",e[e.High=5]="High"}(n=t.SimulcastLayers||(t.SimulcastLayers={})),t.default=n},4651:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.AudioLogEvent=void 0,function(e){e[e.DeviceChanged=0]="DeviceChanged",e[e.MutedLocal=1]="MutedLocal",e[e.UnmutedLocal=2]="UnmutedLocal",e[e.Connected=3]="Connected",e[e.ConnectFailed=4]="ConnectFailed",e[e.RedmicStartLoss=5]="RedmicStartLoss",e[e.RedmicEndLoss=6]="RedmicEndLoss"}(n=t.AudioLogEvent||(t.AudioLogEvent={})),t.default=n},1333:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(4671)),o=r(n(1066)),s=r(n(3760)),c=r(n(7170)),l=r(n(2260)),d=r(n(6275)),u=r(n(8698)),f=r(n(8192)),h=n(4955),m=n(8807),p=r(n(4651)),g=r(n(174));class v{constructor(e,t,n=v.INTERVAL_MS){this.audioVideoController=e,this.logger=t,this.interval=n,this.intervalScheduler=null,this.redRecoveryMetricReport=new c.default,this.lastRedRecoveryMetricReportConsumedTimestampMs=0,this.metricsAddTime=(e,t,n)=>{},this.metricsLogEvent=(e,t)=>{}}toAttribute(e){return this.toSuffix(e).substring(1)}toSuffix(e){return e.toLowerCase()===e?`_${e}`:e.toUpperCase()===e?`_${e.toLowerCase()}`:e.replace(/([A-Z][a-z]+)/g,(function(e){return`_${e}`})).replace(/([A-Z][A-Z]+)/g,(function(e){return`_${e}`})).toLowerCase()}logLatency(e,t,n){const i=this.toSuffix(e);this.logEventTime("meeting"+i,t,n)}logStateTimeout(e,t){const n=this.toSuffix(e);this.logEvent("meeting_session_state_timeout",Object.assign(Object.assign({},t),{state:`state${n}`}))}logAudioEvent(e,t){const n="audio"+this.toSuffix(p.default[e]);this.logEvent(n,t)}logVideoEvent(e,t){const n="video"+this.toSuffix(g.default[e]);this.logEvent(n,t)}logEventTime(e,t,n={}){const i=Object.assign(Object.assign({},n),{call_id:this.audioVideoController.configuration.meetingId,client_type:v.CLIENT_TYPE,metric_type:"latency"});this.logger.debug((()=>`[StatsCollector] ${e}: ${JSON.stringify(i)}`)),this.metricsAddTime(e,t,i)}logMeetingSessionStatus(e){const t=`${e.statusCode()}`;this.logEvent(t);const n={status:t,status_code:`${e.statusCode()}`};this.logEvent("meeting_session_status",n),e.isTerminal()&&this.logEvent("meeting_session_stopped",n),e.isAudioConnectionFailure()&&this.logEvent("meeting_session_audio_failed",n),e.isFailure()&&this.logEvent("meeting_session_failed",n)}logLifecycleEvent(e,t){const n={lifecycle_event:`lifecycle${this.toSuffix(d.default[e])}`,lifecycle_event_code:`${e}`,lifecycle_event_condition:`condition${this.toSuffix(u.default[t])}`,lifecycle_event_condition_code:`${t}`};this.logEvent("meeting_session_lifecycle",n)}logEvent(e,t={}){const n=Object.assign(Object.assign({},t),{call_id:this.audioVideoController.configuration.meetingId,client_type:v.CLIENT_TYPE});this.logger.debug((()=>`[StatsCollector] ${e}: ${JSON.stringify(n)}`)),this.metricsLogEvent(e,n)}start(e,t){return!this.intervalScheduler&&(this.logger.info("Starting StatsCollector"),this.signalingClient=e,this.videoStreamIndex=t,this.clientMetricReport=new a.default(this.logger,this.videoStreamIndex,this.audioVideoController.configuration.credentials.attendeeId),this.intervalScheduler=new f.default(this.interval),this.intervalScheduler.start((()=>i(this,void 0,void 0,(function*(){yield this.getStatsWrapper()})))),!0)}stop(){this.logger.info("Stopping StatsCollector"),this.intervalScheduler&&this.intervalScheduler.stop(),this.intervalScheduler=null}updateMetricValues(e,t){const n=t?this.clientMetricReport.streamMetricReports[Number(e.ssrc)]:this.clientMetricReport.globalMetricReport;let i;i=t?this.clientMetricReport.getMetricMap(n.mediaType,n.direction):this.clientMetricReport.getMetricMap();for(const t in e)t in i&&("number"==typeof e[t]?(n.previousMetrics[t]=n.currentMetrics[t],n.currentMetrics[t]=e[t]):"string"==typeof e[t]?n.currentStringMetrics[t]=e[t]:"object"==typeof e[t]?(n.previousObjectMetrics[t]=void 0===n.currentObjectMetrics[t]?e[t]:n.currentObjectMetrics[t],n.currentObjectMetrics[t]=e[t]):this.logger.error(`Unknown metric value type ${typeof e[t]} for metric ${t}`))}processRawMetricReports(e){this.clientMetricReport.currentSsrcs={};const t=Date.now();for(const t of e){const e=this.isStreamRawMetricReport(t.type);if(e){const e=this.clientMetricReport.streamMetricReports[Number(t.ssrc)];if(e)e.mediaType===s.default.VIDEO&&e.direction===o.default.UPSTREAM?e.streamId=this.videoStreamIndex.sendVideoStreamIdFromRid(t.rid):e.streamId=this.videoStreamIndex.streamIdForSSRC(Number(t.ssrc));else{const e=new l.default;e.mediaType=this.getMediaType(t),e.direction=this.getDirectionType(t),e.mediaType===s.default.VIDEO&&e.direction===o.default.UPSTREAM?e.streamId=this.videoStreamIndex.sendVideoStreamIdFromRid(t.rid):this.videoStreamIndex.allStreams().empty()||(e.streamId=this.videoStreamIndex.streamIdForSSRC(Number(t.ssrc)),void 0!==this.videoStreamIndex.groupIdForSSRC&&(e.groupId=this.videoStreamIndex.groupIdForSSRC(Number(t.ssrc)))),this.clientMetricReport.streamMetricReports[Number(t.ssrc)]=e}this.clientMetricReport.currentSsrcs[Number(t.ssrc)]=1}this.updateMetricValues(t,e)}this.clientMetricReport.removeDestroyedSsrcs(),this.clientMetricReport.previousTimestampMs=this.clientMetricReport.currentTimestampMs,this.clientMetricReport.currentTimestampMs=t,this.clientMetricReport.print()}addStreamMetricDimensionFrames(e,t){const n=this.clientMetricReport.getStreamDimensionMap();for(const i in t.currentStringMetrics)if(i in n){const r=h.SdkStreamDimension.create();r.type=n[i];const a=h.SdkDimensionValue.create();a.stringValue=t.currentStringMetrics[i],r.value=a,e.dimensions.push(r)}}addMetricFrame(e,t,n,i){const r=n.type,a=n.transform,o=n.source,s=t.streamMetricFrames.length,c=t.streamMetricFrames[s-1];if(r){const n=h.SdkMetric.create();n.type=r,n.value=a(o||e,i),i?c.metrics.push(n):t.globalMetrics.push(n)}}addGlobalMetricsToProtobuf(e){const t=this.clientMetricReport.getMetricMap();for(const n in this.clientMetricReport.globalMetricReport.currentMetrics)this.addMetricFrame(n,e,t[n])}addStreamMetricsToProtobuf(e){for(const t in this.clientMetricReport.streamMetricReports){const n=this.clientMetricReport.streamMetricReports[t],i=h.SdkStreamMetricFrame.create();i.streamId=n.streamId,i.metrics=[],this.addStreamMetricDimensionFrames(i,n),e.streamMetricFrames.push(i);const r=this.clientMetricReport.getMetricMap(n.mediaType,n.direction);for(const i in n.currentMetrics)this.addMetricFrame(i,e,r[i],Number(t));for(const i in n.currentStringMetrics)this.addMetricFrame(i,e,r[i],Number(t));for(const i in n.currentObjectMetrics)this.addMetricFrame(i,e,r[i],Number(t))}}makeClientMetricProtobuf(){const e=h.SdkClientMetricFrame.create();return e.globalMetrics=[],e.streamMetricFrames=[],this.addGlobalMetricsToProtobuf(e),this.addStreamMetricsToProtobuf(e),e}sendClientMetricProtobuf(e){this.signalingClient.sendClientMetrics(e)}isStreamRawMetricReport(e){return["inbound-rtp","inbound-rtp-red","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp"].includes(e)}getMediaType(e){return"audio"===e.kind?s.default.AUDIO:s.default.VIDEO}getDirectionType(e){const{type:t}=e;return"inbound-rtp"===t||"remote-outbound-rtp"===t||"inbound-rtp-red"===t?o.default.DOWNSTREAM:o.default.UPSTREAM}isValidStandardRawMetric(e){return"inbound-rtp"===e.type||"inbound-rtp-red"===e.type||"outbound-rtp"===e.type||"remote-inbound-rtp"===e.type||"remote-outbound-rtp"===e.type||"candidate-pair"===e.type&&"succeeded"===e.state||"media-source"===e.type&&"audio"===e.kind}isValidSsrc(e){let t=!0;return this.isStreamRawMetricReport(e.type)&&this.getDirectionType(e)===o.default.DOWNSTREAM&&this.getMediaType(e)===s.default.VIDEO&&(t=this.videoStreamIndex.streamIdForSSRC(Number(e.ssrc))>0),t}isValidRawMetricReport(e){return this.isValidStandardRawMetric(e)&&this.isValidSsrc(e)}filterRawMetricReports(e){const t=[];for(const n of e)this.isValidRawMetricReport(n)&&t.push(n);return t}handleRawMetricReports(e){const t=this.filterRawMetricReports(e);this.logger.debug((()=>`Filtered raw metrics : ${JSON.stringify(t)}`));const n=[];this.maybeAddRedRecoveryMetrics(n),this.clientMetricReport.customStatsReports=n,t.push(...n),this.processRawMetricReports(t);const i=this.makeClientMetricProtobuf();this.sendClientMetricProtobuf(i),this.audioVideoController.forEachObserver((e=>{m.Maybe.of(e.metricsDidReceive).map((t=>t.bind(e)(this.clientMetricReport.clone())))}))}getStatsWrapper(){return i(this,void 0,void 0,(function*(){if(!this.audioVideoController.rtcPeerConnection)return;const e=[];try{const t=yield this.audioVideoController.rtcPeerConnection.getStats();this.clientMetricReport.rtcStatsReport=t,t.forEach((t=>{e.push(t)})),this.handleRawMetricReports(e)}catch(e){this.logger.error(e.message)}}))}overrideObservableMetric(e,t){this.clientMetricReport.overrideObservableMetric(e,t)}recoveryMetricsDidReceive(e){this.redRecoveryMetricReport=e}maybeAddRedRecoveryMetrics(e){this.redRecoveryMetricReport.currentTimestampMs!==this.lastRedRecoveryMetricReportConsumedTimestampMs&&(e.push({kind:"audio",type:"inbound-rtp-red",ssrc:this.redRecoveryMetricReport.ssrc,timestamp:this.redRecoveryMetricReport.currentTimestampMs,totalAudioPacketsLost:this.redRecoveryMetricReport.totalAudioPacketsLost,totalAudioPacketsExpected:this.redRecoveryMetricReport.totalAudioPacketsExpected,totalAudioPacketsRecoveredRed:this.redRecoveryMetricReport.totalAudioPacketsRecoveredRed,totalAudioPacketsRecoveredFec:this.redRecoveryMetricReport.totalAudioPacketsRecoveredFec}),this.lastRedRecoveryMetricReportConsumedTimestampMs=this.redRecoveryMetricReport.currentTimestampMs)}}t.default=v,v.INTERVAL_MS=1e3,v.CLIENT_TYPE="amazon-chime-sdk-js"},174:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.VideoLogEvent=void 0,function(e){e[e.InputAttached=0]="InputAttached",e[e.SendingFailed=1]="SendingFailed",e[e.SendingSuccess=2]="SendingSuccess"}(n=t.VideoLogEvent||(t.VideoLogEvent={})),t.default=n},4014:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(174)),o=r(n(698));class s extends o.default{constructor(e){super(e.logger),this.context=e,this.taskName="AttachMediaInputTask"}run(){return i(this,void 0,void 0,(function*(){const e=this.context.transceiverController;e.setPeer(this.context.peer),e.setupLocalTransceivers();const t=this.context.activeAudioInput;if(t){const n=t.getAudioTracks();this.context.logger.info("attaching audio track to peer connection"),yield e.setAudioInput(n.length?n[0]:null)}else yield e.setAudioInput(null),this.context.logger.info("no audio track");this.setAudioCodecPreferences();const n=this.context.activeVideoInput;if(n){const t=n.getVideoTracks(),i=t.length?t[0]:null;if(this.context.logger.info("attaching video track to peer connection"),yield e.setVideoInput(i),this.context.enableSimulcast&&this.context.videoUplinkBandwidthPolicy){const t=this.context.videoUplinkBandwidthPolicy.chooseEncodingParameters();e.setEncodingParameters(t)}i&&this.context.statsCollector.logVideoEvent(a.default.InputAttached,this.context.videoDeviceInformation)}else yield e.setVideoInput(null),this.context.logger.info("no video track");this.context.videoSubscriptions=e.updateVideoTransceivers(this.context.videoStreamIndex,this.context.videosToReceive)}))}setAudioCodecPreferences(){const e=window.RTCRtpTransceiver&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype,t=this.context.audioProfile.hasRedundancyEnabled();if(!e)return void this.context.logger.warn("Setting codec preferences not supported");const n=this.context.transceiverController.localAudioTransceiver(),{codecs:i}=RTCRtpSender.getCapabilities("audio");this.context.logger.debug(`Available audio codecs ${JSON.stringify(i,null,4)}`);const r=i.findIndex((e=>"audio/red"===e.mimeType));if(n){if(r>=0){const e=i[r];return i.splice(r,1),t?(i.unshift(e),this.context.logger.info("audio/red set as preferred codec")):this.context.logger.info("audio/red removed from preferred codec"),void n.setCodecPreferences(i)}this.context.logger.info("audio/red codec not supported")}else this.context.logger.error("audio transceiver is null")}}t.default=s},698:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(3750)),o=r(n(3533));t.default=class{constructor(e){this.logger=e,this.taskName="BaseTask",this.parentTask=null,this.status=o.default.IDLE,this.run=this.baseRun.bind(this,this.run),this.cancel=this.baseCancel.bind(this,this.cancel)}once(...e){return new a.default(this.logger,this,e)}cancel(){}name(){return this.parentTask?`${this.parentTask.name()}/${this.taskName}`:this.taskName}setParent(e){this.parentTask=e}getStatus(){return this.status}logAndThrow(e){throw this.logger.info(e),new Error(e)}baseRun(e){return i(this,void 0,void 0,(function*(){try{const t=Date.now();switch(this.logger.info(`running task ${this.name()}`),this.status){case o.default.RUNNING:this.logAndThrow(`${this.name()} is already running`);case o.default.CANCELED:this.logAndThrow(`${this.name()} was canceled before running`);case o.default.FINISHED:this.logAndThrow(`${this.name()} was already finished`)}this.status=o.default.RUNNING,yield e.call(this),this.logger.info(`${this.name()} took ${Math.round(Date.now()-t)} ms`)}catch(e){throw e}finally{this.status!==o.default.CANCELED&&(this.status=o.default.FINISHED)}}))}baseCancel(e){this.status!==o.default.CANCELED&&this.status!==o.default.FINISHED?(this.logger.info(`canceling task ${this.name()}`),this.status=o.default.CANCELED,e.call(this)):this.logger.info(`Not canceling ${this.name()}: state is ${this.status}`)}}},8214:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(698));class o extends a.default{constructor(e){super(e.logger),this.context=e,this.taskName="CleanRestartedSessionTask"}run(){return i(this,void 0,void 0,(function*(){this.context.resetConnectionSpecificState()}))}}t.default=o},7943:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(9183)),o=r(n(698));class s extends o.default{constructor(e){super(e.logger),this.context=e,this.taskName="CleanStoppedSessionTask",this.taskCanceler=null}cancel(){this.taskCanceler&&(this.taskCanceler.cancel(),this.taskCanceler=null)}run(){return i(this,void 0,void 0,(function*(){try{this.context.signalingClient.ready()&&(this.context.signalingClient.closeConnection(),yield this.receiveWebSocketClosedEvent())}catch(e){throw e}finally{for(const e of this.context.removableObservers)e.removeObserver();this.context.resetConnectionSpecificState(),this.context.statsCollector.stop(),this.context.statsCollector=null,this.context.connectionMonitor.stop(),this.context.connectionMonitor=null,this.context.videoUplinkBandwidthPolicy.setTransceiverController&&this.context.videoUplinkBandwidthPolicy.setTransceiverController(void 0),this.context.videoDownlinkBandwidthPolicy.bindToTileController&&this.context.videoDownlinkBandwidthPolicy.bindToTileController(void 0);const e=this.context.videoTileController.getLocalVideoTile();e&&e.bindVideoStream("",!0,null,null,null,null),this.context.videoTileController.removeAllVideoTiles()}}))}receiveWebSocketClosedEvent(){return new Promise(((e,t)=>{const n=new class{constructor(e){this.signalingClient=e}cancel(){this.signalingClient.removeObserver(this),t(new Error("CleanStoppedSessionTask got canceled while waiting for the WebSocket closed event"))}handleSignalingClientEvent(t){t.type===a.default.WebSocketClosed&&(this.signalingClient.removeObserver(this),e())}}(this.context.signalingClient);this.taskCanceler=n,this.context.signalingClient.registerObserver(n)}))}}t.default=s},7271:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(698));class o extends a.default{constructor(e){super(e.logger),this.context=e,this.taskName="CreatePeerConnectionTask",this.removeTrackAddedEventListener=null,this.removeTrackRemovedEventListeners={},this.trackEvents=["ended","mute","unmute","isolationchange","overconstrained"],this.removeVideoTrackEventListeners={},this.trackAddedHandler=e=>{const t=e.track;if(this.context.logger.info(`received track event: kind=${t.kind} id=${t.id} label=${t.label}`),e.transceiver&&"inactive"===e.transceiver.currentDirection)return;if(0===e.streams.length)return void this.context.logger.warn("Track event but no stream");const n=e.streams[0];"audio"===t.kind?this.context.audioMixController.bindAudioStream(n):"video"!==t.kind||this.trackIsVideoInput(t)||this.addRemoteVideoTrack(t,n)}}removeObserver(){this.removeTrackAddedEventListener&&this.removeTrackAddedEventListener();for(const e in this.removeTrackRemovedEventListeners)this.removeTrackRemovedEventListeners[e]()}addPeerConnectionEventLogger(){const e=this.context.peer;e.addEventListener("connectionstatechange",(()=>{this.context.logger.info(`peer connection state changed: ${e.connectionState}`)})),e.addEventListener("negotiationneeded",(()=>{this.context.logger.info("peer connection negotiation is needed")})),e.addEventListener("icegatheringstatechange",(()=>{this.context.logger.info(`peer connection ice gathering state changed: ${e.iceGatheringState}`)})),e.addEventListener("icecandidate",(e=>{this.context.logger.info(`peer connection ice candidate: ${e.candidate?e.candidate.candidate:"(null)"}`)})),e.addEventListener("iceconnectionstatechange",(()=>{this.context.logger.info(`peer connection ice connection state changed: ${e.iceConnectionState}`)}))}run(){return i(this,void 0,void 0,(function*(){this.context.removableObservers.push(this);const e=this.context.turnCredentials&&this.context.turnCredentials.uris.length>0?{iceServers:[{urls:this.context.turnCredentials.uris,username:this.context.turnCredentials.username,credential:this.context.turnCredentials.password,credentialType:"password"}],iceTransportPolicy:"relay"}:{};e.bundlePolicy=this.context.browserBehavior.requiresBundlePolicy(),e.sdpSemantics="unified-plan",e.encodedInsertableStreams=this.context.audioProfile.hasRedundancyEnabled(),this.context.peer?this.context.logger.info("reusing peer connection"):(this.context.logger.info("creating new peer connection"),this.context.peer=new RTCPeerConnection(e),this.addPeerConnectionEventLogger()),this.removeTrackAddedEventListener=()=>{this.context.peer&&this.context.peer.removeEventListener("track",this.trackAddedHandler),this.removeTrackAddedEventListener=null},this.context.peer.addEventListener("track",this.trackAddedHandler)}))}trackIsVideoInput(e){return!!this.context.transceiverController.useTransceivers()&&(this.logger.debug((()=>"getting video track type")),this.context.transceiverController.trackIsVideoInput(e))}addRemoteVideoTrack(e,t){var n;const i=t.id,r=this.context.videoStreamIndex.attendeeIdForTrack(i);let a,o;if(this.context.videoTileController.getVideoTileForAttendeeId?(o=this.context.videoTileController.getVideoTileForAttendeeId(r),a=!!(null===(n=null==o?void 0:o.state())||void 0===n?void 0:n.boundVideoStream)):a=this.context.videoTileController.haveVideoTileForAttendeeId(r),a)return void this.context.logger.info(`Not adding remote track. Already have tile for attendeeId: ${r}`);o||(o=this.context.videoTileController.addVideoTile(),this.logger.info(`Created video tile ${o.id()}`));let s,c,l=this.context.videoStreamIndex.streamIdForTrack(i);void 0===l&&(this.logger.warn(`stream not found for tile=${o.id()} track=${i}`),l=null);for(let n=0;n{this.context.logger.info(`received the ${i} event for tile=${o.id()} id=${e.id} streamId=${l}`),"ended"===i&&this.removeRemoteVideoTrack(e,o.state())};t.addEventListener(i,n),this.removeVideoTrackEventListeners[e.id]||(this.removeVideoTrackEventListeners[e.id]=[]),this.removeVideoTrackEventListeners[e.id].push((()=>{t.removeEventListener(i,n)}))}}if(e.getSettings){const t=e.getSettings();s=t.width,c=t.height}else{const t=e.getCapabilities();s=t.width,c=t.height}const d=this.context.videoStreamIndex.externalUserIdForTrack(i);o.bindVideoStream(r,!1,t,s,c,l,d),this.logger.info(`video track added, use tile=${o.id()} track=${i} streamId=${l}`);const u="removetrack",f=t,h=()=>this.removeRemoteVideoTrack(e,o.state());this.removeTrackRemovedEventListeners[e.id]=()=>{f.removeEventListener(u,h),delete this.removeTrackRemovedEventListeners[e.id]},f.addEventListener(u,h)}removeRemoteVideoTrack(e,t){if(this.removeTrackRemovedEventListeners.hasOwnProperty(e.id)){this.removeTrackRemovedEventListeners[e.id]();for(const t of this.removeVideoTrackEventListeners[e.id])t();delete this.removeVideoTrackEventListeners[e.id]}this.logger.info(`video track ended, removing tile=${t.tileId} id=${e.id} stream=${t.streamId}`),t.streamId?this.context.videosPaused.remove(t.streamId):this.logger.warn(`no stream found for tile=${t.tileId}`),this.context.videoTileController.removeVideoTile(t.tileId)}}t.default=o,o.REMOVE_HANDLER_INTERVAL_MS=1e4},244:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(484)),o=r(n(5803)),s=r(n(698));class c extends s.default{constructor(e){super(e.logger),this.context=e,this.taskName="CreateSDPTask"}cancel(){if(this.cancelPromise){const e=new Error(`canceling ${this.name()}`);this.cancelPromise(e),delete this.cancelPromise}}sessionUsesAudio(){var e,t;return!!(null===(t=null===(e=this.context.meetingSessionConfiguration)||void 0===e?void 0:e.urls)||void 0===t?void 0:t.audioHostURL)}sessionUsesVideo(){let e;e=this.context.transceiverController.useTransceivers()?this.context.transceiverController.hasVideoInput():this.context.videoTileController.hasStartedLocalVideoTile();const t=!!this.context.videosToReceive&&!this.context.videosToReceive.empty(),n=e||t;return this.context.logger.info(`uses video: ${n} (enabled: true, sending: ${e}, receiving: ${t})`),n}run(){return i(this,void 0,void 0,(function*(){const e={offerToReceiveAudio:this.sessionUsesAudio(),offerToReceiveVideo:this.sessionUsesVideo()};this.logger.info(`peer connection offerOptions: ${JSON.stringify(e)}`),yield new Promise(((t,n)=>i(this,void 0,void 0,(function*(){this.cancelPromise=e=>{n(e)};try{if(this.context.sdpOfferInit=yield this.context.peer.createOffer(e),this.context.logger.info("peer connection created offer"),this.context.previousSdpOffer&&new o.default(this.context.sdpOfferInit.sdp).videoSendSectionHasDifferentSSRC(this.context.previousSdpOffer)){const e=new Error(`canceling ${this.name()} due to the meeting status code: ${a.default.IncompatibleSDP}`);return this.context.previousSdpOffer=null,void n(e)}t()}catch(e){n(e)}finally{delete this.cancelPromise}}))))}))}}t.default=c},1218:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(484)),o=r(n(5803)),s=r(n(698));class c extends s.default{constructor(e,t=c.CHROME_VPN_TIMEOUT_MS){super(e.logger),this.context=e,this.chromeVpnTimeoutMs=t,this.taskName="FinishGatheringICECandidatesTask"}removeEventListener(){this.context.peer&&(this.context.peer.removeEventListener("icecandidate",this.context.iceCandidateHandler),this.context.turnCredentials||this.context.peer.removeEventListener("icegatheringstatechange",this.context.iceGatheringStateEventHandler))}cancel(){let e;this.context.browserBehavior.requiresIceCandidateGatheringTimeoutWorkaround()&&this.chromeVpnTimeoutMsthis.chromeVpnTimeoutMs&&(e=new Error(`canceling ${this.name()} due to the meeting status code: ${a.default.ICEGatheringTimeoutWorkaround}`)),this.cancelPromise&&(e=e||new Error(`canceling ${this.name()}`),this.cancelPromise(e),delete this.cancelPromise)}run(){return i(this,void 0,void 0,(function*(){if(this.context.peer||this.logAndThrow("session does not have peer connection; bypass ice gathering"),this.context.browserBehavior.requiresCheckForSdpConnectionAttributes()){if(new o.default(this.context.peer.localDescription.sdp).hasCandidatesForAllMLines())return void this.context.logger.info(`ice gathering already complete; bypass gathering, current local description ${this.context.peer.localDescription.sdp}`)}else this.context.logger.info(`iOS device does not require checking for connection attributes in SDP, current local description ${this.context.peer.localDescription.sdp}`);if(!this.context.browserBehavior.hasFirefoxWebRTC()&&"complete"!==this.context.peer.iceGatheringState||!new o.default(this.context.peer.localDescription.sdp).hasCandidates())try{yield new Promise(((e,t)=>{this.cancelPromise=e=>{this.removeEventListener(),t(e)},this.context.turnCredentials||(this.context.iceGatheringStateEventHandler=()=>{if("complete"===this.context.peer.iceGatheringState)return this.removeEventListener(),e(),void delete this.cancelPromise},this.context.peer.addEventListener("icegatheringstatechange",this.context.iceGatheringStateEventHandler)),this.context.iceCandidateHandler=n=>{if(this.context.logger.info(`ice candidate: ${n.candidate?n.candidate.candidate:"(null)"} state: ${this.context.peer.iceGatheringState}`),n.candidate&&(o.default.isRTPCandidate(n.candidate.candidate)&&this.context.iceCandidates.push(n.candidate),this.context.turnCredentials&&this.context.iceCandidates.length>=1))return this.context.logger.info("gathered at least one relay candidate"),this.removeEventListener(),e(),void delete this.cancelPromise;"complete"===this.context.peer.iceGatheringState&&(this.context.logger.info("done gathering ice candidates"),this.removeEventListener(),new o.default(this.context.peer.localDescription.sdp).hasCandidates()&&0!==this.context.iceCandidates.length?(e(),delete this.cancelPromise):(t(new Error("no ice candidates were gathered")),delete this.cancelPromise))},this.context.peer.addEventListener("icecandidate",this.context.iceCandidateHandler),this.startTimestampMs=Date.now()}))}catch(e){throw e}finally{this.startTimestampMs&&(this.context.iceGatheringDurationMs=Math.round(Date.now()-this.startTimestampMs))}else this.context.logger.info("ice gathering state is complete and candidates are in SDP; bypass gathering")}))}}t.default=c,c.CHROME_VPN_TIMEOUT_MS=5e3},5591:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const c=s(n(565)),l=s(n(484)),d=s(n(692)),u=a(n(980)),f=s(n(9183)),h=s(n(1903)),m=n(4955),p=s(n(698));class g extends p.default{constructor(e){super(e.logger),this.context=e,this.taskName="JoinAndReceiveIndexTask",this.taskCanceler=null}cancel(){this.taskCanceler&&(this.taskCanceler.cancel(),this.taskCanceler=null)}run(){return o(this,void 0,void 0,(function*(){const e=yield new Promise(((e,t)=>{const n=this.context;n.turnCredentials=null;const i=new class{constructor(e){this.signalingClient=e}cancel(){this.signalingClient.removeObserver(this),t(new Error("JoinAndReceiveIndexTask got canceled while waiting for SdkIndexFrame"))}handleSignalingClientEvent(t){if(t.type===f.default.WebSocketClosed){let e=`The signaling connection was closed with code ${t.closeCode} and reason: ${t.closeReason}`;n.logger.warn(e);let i=l.default.SignalingBadRequest;return 4410===t.closeCode?(e="The meeting already ended.",n.logger.warn(e),i=l.default.MeetingEnded):t.closeCode>=4500&&t.closeCode<4600&&(i=l.default.SignalingInternalServerError),void n.audioVideoController.handleMeetingSessionStatus(new c.default(i),new Error(e))}if(t.type!==f.default.ReceivedSignalFrame)return;if(t.message.type===m.SdkSignalFrame.Type.JOIN_ACK){const e=t.message.joinack;if(!e)return void n.audioVideoController.handleMeetingSessionStatus(new c.default(l.default.SignalingRequestFailed),new Error("Join ACK message did not include expected frame"));if(e.videoSubscriptionLimit&&(n.videoSubscriptionLimit=e.videoSubscriptionLimit),n.serverSupportsCompression=e.wantsCompressedSdp,void 0!==e.defaultServerSideNetworkAdaption&&e.defaultServerSideNetworkAdaption!==u.default.Default&&void 0!==n.videoDownlinkBandwidthPolicy.setServerSideNetworkAdaption){const t=e.defaultServerSideNetworkAdaption;n.logger.info(`Overriding server side network adaption value to ${t}`),n.videoDownlinkBandwidthPolicy.setServerSideNetworkAdaption(u.convertServerSideNetworkAdaptionEnumFromSignaled(t))}return void(e&&e.turnCredentials?(n.turnCredentials=new d.default,n.turnCredentials.username=e.turnCredentials.username,n.turnCredentials.password=e.turnCredentials.password,n.turnCredentials.ttl=e.turnCredentials.ttl,n.turnCredentials.uris=e.turnCredentials.uris.map((e=>n.meetingSessionConfiguration.urls.urlRewriter(e))).filter((e=>!!e))):n.logger.error("missing TURN credentials in JoinAckFrame"))}if(t.message.type!==m.SdkSignalFrame.Type.INDEX)return;this.signalingClient.removeObserver(this);const i=t.message.index;e(i)}}(this.context.signalingClient);this.context.signalingClient.registerObserver(i),this.taskCanceler=i,this.context.previousSdpAnswerAsString="",this.context.previousSdpOffer=null,this.context.serverSupportsCompression=!1;const r=new h.default(this.context.meetingSessionConfiguration.applicationMetadata);void 0!==this.context.videoDownlinkBandwidthPolicy.getServerSideNetworkAdaption&&void 0!==this.context.videoDownlinkBandwidthPolicy.supportedServerSideNetworkAdaptions&&(r.serverSideNetworkAdaption=this.context.videoDownlinkBandwidthPolicy.getServerSideNetworkAdaption(),r.supportedServerSideNetworkAdaptions=this.context.videoDownlinkBandwidthPolicy.supportedServerSideNetworkAdaptions()),void 0!==this.context.videoDownlinkBandwidthPolicy.wantsAllTemporalLayersInIndex&&(r.wantsAllTemporalLayersInIndex=this.context.videoDownlinkBandwidthPolicy.wantsAllTemporalLayersInIndex()),r.disablePeriodicKeyframeRequestOnContentSender=this.context.meetingSessionConfiguration.disablePeriodicKeyframeRequestOnContentSender,this.context.signalingClient.join(r)}));this.context.logger.info(`received first index ${JSON.stringify(e)}`),this.context.indexFrame=e}))}}t.default=g},2352:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(9183)),o=n(4955),s=r(n(698));class c extends s.default{constructor(e){super(e.logger),this.context=e,this.taskName="LeaveAndReceiveLeaveAckTask",this.taskCanceler=null}cancel(){this.taskCanceler&&(this.taskCanceler.cancel(),this.taskCanceler=null)}run(){return i(this,void 0,void 0,(function*(){this.context.signalingClient.ready()&&(this.context.signalingClient.leave(),this.context.logger.info("sent leave"),yield this.receiveLeaveAck())}))}receiveLeaveAck(){return new Promise(((e,t)=>{const n=new class{constructor(e,t){this.signalingClient=e,this.logger=t}cancel(){this.signalingClient.removeObserver(this),t(new Error("LeaveAndReceiveLeaveAckTask got canceled while waiting for IndexFrame"))}handleSignalingClientEvent(t){if(t.isConnectionTerminated())return this.signalingClient.removeObserver(this),this.logger.info("LeaveAndReceiveLeaveAckTask connection terminated"),void e();t.type===a.default.ReceivedSignalFrame&&t.message.type===o.SdkSignalFrame.Type.LEAVE_ACK&&(this.signalingClient.removeObserver(this),this.logger.info("got leave ack"),e())}}(this.context.signalingClient,this.context.logger);this.taskCanceler=n,this.context.signalingClient.registerObserver(n)}))}}t.default=c},1919:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(9183)),o=n(4955),s=r(n(698));class c extends s.default{constructor(e){super(e.logger),this.context=e,this.taskName="ListenForVolumeIndicatorsTask",this.realtimeMuteAndUnmuteHandler=e=>{this.context.signalingClient.mute(e)}}run(){return i(this,void 0,void 0,(function*(){this.context.removableObservers.push(this),this.context.signalingClient.registerObserver(this),this.context.realtimeController.realtimeSubscribeToMuteAndUnmuteLocalAudio(this.realtimeMuteAndUnmuteHandler)}))}removeObserver(){this.context.realtimeController.realtimeUnsubscribeToMuteAndUnmuteLocalAudio(this.realtimeMuteAndUnmuteHandler),this.context.signalingClient.removeObserver(this)}handleSignalingClientEvent(e){if(e.type===a.default.ReceivedSignalFrame)if(e.message.type===o.SdkSignalFrame.Type.AUDIO_STREAM_ID_INFO){const t=e.message.audioStreamIdInfo;this.context.volumeIndicatorAdapter.sendRealtimeUpdatesForAudioStreamIdInfo(t)}else if(e.message.type===o.SdkSignalFrame.Type.AUDIO_METADATA){const t=e.message.audioMetadata;this.context.volumeIndicatorAdapter.sendRealtimeUpdatesForAudioMetadata(t)}}}t.default=c},6835:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(1066)),o=r(n(3760)),s=r(n(2212)),c=r(n(6131)),l=r(n(4880)),d=r(n(565)),u=r(n(484)),f=r(n(9183)),h=n(4955),m=r(n(4651)),p=n(8807),g=r(n(698));class v extends g.default{constructor(e,t,n){super(e.logger),this.context=e,this.initialConnectionHealthData=n,this.taskName="MonitorTask",this.prevSignalStrength=1,this.currentAvailableStreamAvgBitrates=null,this.hasSignalingError=!1,this.presenceHandlerCalled=!1,this.isResubscribeCheckPaused=!1,this.pendingMetricsReport=void 0,this.isMeetingConnected=!1,this.checkAndSendWeakSignalEvent=e=>{const t=e<1,n=this.prevSignalStrength<1,i=t?n?null:m.default.RedmicStartLoss:n?m.default.RedmicEndLoss:null;i&&this.context.statsCollector.logAudioEvent(i),this.prevSignalStrength=e},this.realtimeFatalErrorCallback=e=>{this.logger.error(`realtime error: ${e}: ${e.stack}`),this.context.audioVideoController.handleMeetingSessionStatus(new d.default(u.default.RealtimeApiFailed),e)},this.realtimeAttendeeIdPresenceHandler=(e,t)=>{var n;const i=this.context.meetingSessionConfiguration.credentials.attendeeId;this.logger.info(`attendeePresenceReceived: ${i}`),i===e&&t&&!this.presenceHandlerCalled&&(this.presenceHandlerCalled=!0,this.context.attendeePresenceDurationMs=Date.now()-this.context.startAudioVideoTimestamp,null===(n=this.context.eventController)||void 0===n||n.publishEvent("attendeePresenceReceived",{attendeePresenceDurationMs:this.context.attendeePresenceDurationMs}))},this.generateBaseAudioVideoEventAttributes=()=>{const{signalingOpenDurationMs:e,startTimeMs:t,iceGatheringDurationMs:n,attendeePresenceDurationMs:i,meetingStartDurationMs:r}=this.context;return{meetingDurationMs:null===t?0:Math.round(Date.now()-t),signalingOpenDurationMs:e,iceGatheringDurationMs:n,attendeePresenceDurationMs:i,meetingStartDurationMs:r}},this.generateAudioVideoEventAttributesForReceivingAudioDropped=()=>{const e=this.generateBaseAudioVideoEventAttributes();return Object.assign(Object.assign({},e),{maxVideoTileCount:this.context.maxVideoTileCount,poorConnectionCount:this.context.poorConnectionCount})},this.reconnectionHealthPolicy=new s.default(e.logger,Object.assign({},t),this.initialConnectionHealthData.clone()),this.unusableAudioWarningHealthPolicy=new l.default(Object.assign({},t),this.initialConnectionHealthData.clone()),this.sendingAudioFailureHealthPolicy=new c.default(e.logger,Object.assign({},t),this.initialConnectionHealthData.clone())}removeObserver(){this.context.audioVideoController.removeObserver(this),this.context.realtimeController.realtimeUnsubscribeToFatalError(this.realtimeFatalErrorCallback),this.context.realtimeController.realtimeUnsubscribeToLocalSignalStrengthChange(this.checkAndSendWeakSignalEvent),this.context.realtimeController.realtimeUnsubscribeToAttendeeIdPresence(this.realtimeAttendeeIdPresenceHandler),this.context.signalingClient.removeObserver(this)}run(){return i(this,void 0,void 0,(function*(){this.context.removableObservers.push(this),this.context.audioVideoController.addObserver(this),this.context.realtimeController.realtimeSubscribeToFatalError(this.realtimeFatalErrorCallback),this.context.realtimeController.realtimeSubscribeToLocalSignalStrengthChange(this.checkAndSendWeakSignalEvent),this.context.realtimeController.realtimeSubscribeToAttendeeIdPresence(this.realtimeAttendeeIdPresenceHandler),this.context.connectionMonitor.start(),this.context.statsCollector.start(this.context.signalingClient,this.context.videoStreamIndex),this.context.signalingClient.registerObserver(this)}))}pauseResubscribeCheck(){this.isResubscribeCheckPaused=!0}resumeResubscribeCheck(){this.isResubscribeCheckPaused&&(this.isResubscribeCheckPaused=!1,this.pendingMetricsReport&&(this.context.logger.info("Resuming resubscribe check with pending metrics report"),this.checkResubscribe(this.pendingMetricsReport)&&this.context.audioVideoController.update({needsRenegotiation:!1})))}videoTileDidUpdate(e){this.context.maxVideoTileCount=Math.max(this.context.maxVideoTileCount,this.context.videoTileController.getAllVideoTiles().length)}checkResubscribe(e){if(this.isResubscribeCheckPaused)return this.context.logger.info("Resubscribe check is paused, setting incoming client metric report as pending"),void(this.pendingMetricsReport=e);this.pendingMetricsReport=void 0;const t=e.getObservableMetrics(),n=t.availableOutgoingBitrate,i=t.nackCountReceivedPerSecond;let r=!1;this.context.videoDownlinkBandwidthPolicy.updateMetrics(e);const a=this.context.videoDownlinkBandwidthPolicy.wantsResubscribe();if(r=r||a,a){const e=this.context.videoDownlinkBandwidthPolicy.chooseSubscriptions();this.context.videosToReceive=e.truncate(this.context.videoSubscriptionLimit),e.size()>this.context.videosToReceive.size()&&this.logger.warn(`Video receive limit exceeded. Limiting the videos to ${this.context.videosToReceive.size()}. Please consider using AllHighestVideoBandwidthPolicy or VideoPriorityBasedPolicy along with chooseRemoteVideoSources api to select the video sources to be displayed.`),this.logger.info(`trigger resubscribe for down=${a}; videosToReceive=[${this.context.videosToReceive.array()}]`)}if(this.context.videoTileController.hasStartedLocalVideoTile()){this.context.videoUplinkBandwidthPolicy.updateConnectionMetric({uplinkKbps:n/1e3,nackCountPerSecond:i});const e=this.context.videoUplinkBandwidthPolicy.wantsResubscribe();r=r||e,e&&(this.logger.info(`trigger resubscribe for up=${e}; videosToReceive=[${this.context.videosToReceive.array()}]`),this.context.videoUplinkBandwidthPolicy.chooseEncodingParameters(),this.context.videoUplinkBandwidthPolicy.chooseMediaTrackConstraints())}return r}metricsDidReceive(e){if(this.checkResubscribe(e)&&this.context.audioVideoController.update({needsRenegotiation:!1}),!this.currentAvailableStreamAvgBitrates)return;const t=e.streamMetricReports,n=new Map;for(const e in t)t[e].mediaType===o.default.VIDEO&&t[e].direction===a.default.DOWNSTREAM&&n.set(t[e].streamId,t[e])}connectionHealthDidChange(e){0===e.consecutiveMissedPongs&&this.context.reconnectController&&this.context.reconnectController.setLastActiveTimestampMs(Date.now()),this.applyHealthPolicy(this.reconnectionHealthPolicy,e,(()=>{this.context.audioVideoController.handleMeetingSessionStatus(new d.default(u.default.ConnectionHealthReconnect),null)})),this.applyHealthPolicy(this.unusableAudioWarningHealthPolicy,e,(()=>{var e;this.context.poorConnectionCount+=1;const t=this.generateAudioVideoEventAttributesForReceivingAudioDropped();null===(e=this.context.eventController)||void 0===e||e.publishEvent("receivingAudioDropped",t),this.context.videoTileController.haveVideoTilesWithStreams()?this.context.audioVideoController.forEachObserver((e=>{p.Maybe.of(e.connectionDidSuggestStopVideo).map((t=>t.bind(e)()))})):this.context.audioVideoController.forEachObserver((e=>{p.Maybe.of(e.connectionDidBecomePoor).map((t=>t.bind(e)()))}))}),(()=>{this.context.audioVideoController.forEachObserver((e=>{p.Maybe.of(e.connectionDidBecomeGood).map((t=>t.bind(e)()))}))})),this.isMeetingConnected&&this.applyHealthPolicy(this.sendingAudioFailureHealthPolicy,e,(()=>{var e;const t=this.generateBaseAudioVideoEventAttributes();null===(e=this.context.eventController)||void 0===e||e.publishEvent("sendingAudioFailed",t)}),(()=>{var e;const t=this.generateBaseAudioVideoEventAttributes();null===(e=this.context.eventController)||void 0===e||e.publishEvent("sendingAudioRecovered",t)}))}audioVideoDidStart(){this.isMeetingConnected=!0}audioVideoDidStartConnecting(e){this.isMeetingConnected=!1}audioVideoDidStop(e){this.isMeetingConnected=!1}applyHealthPolicy(e,t,n,i){e.update(t);const r=e.healthIfChanged();null!==r&&(this.logger.info(`${e.name} value is now ${r}`),r<=e.minimumHealth()?p.Maybe.of(n).map((e=>e.bind(this)())):p.Maybe.of(i).map((e=>e.bind(this)())))}handleBitrateFrame(e){this.currentAvailableStreamAvgBitrates=e,e.serverAvailableOutgoingBitrate>0&&(this.logger.info(`Received server side estimation of available incoming bitrate ${e.serverAvailableOutgoingBitrate}kbps`),this.context.statsCollector.overrideObservableMetric("availableIncomingBitrate",1e3*e.serverAvailableOutgoingBitrate))}handleSignalingClientEvent(e){var t;if(e.type===f.default.WebSocketClosed&&(4410===e.closeCode||e.closeCode>=4500&&e.closeCode<4600)||e.type===f.default.WebSocketError||e.type===f.default.WebSocketFailed){if(!this.hasSignalingError){const e=this.generateAudioVideoEventAttributesForReceivingAudioDropped();null===(t=this.context.eventController)||void 0===t||t.publishEvent("signalingDropped",e),this.hasSignalingError=!0}}else e.type===f.default.WebSocketOpen&&(this.hasSignalingError=!1);if(e.type===f.default.ReceivedSignalFrame){if(e.message.type===h.SdkSignalFrame.Type.NOTIFICATION){switch(e.message.notification.level){case h.SdkNotificationFrame.NotificationLevel.INFO:this.logger.info(`Received notification from server: ${e.message.notification.message}`);break;case h.SdkNotificationFrame.NotificationLevel.WARNING:this.logger.warn(`Received warning from server: ${e.message.notification.message}`);break;case h.SdkNotificationFrame.NotificationLevel.ERROR:this.logger.error(`Received error from server: ${e.message.notification.message}`);break;default:this.logger.error(`Received notification from server with unknown level ${e.message.notification.level}: ${e.message.notification.message}`)}return}if(e.message.bitrates){const t=e.message.bitrates;this.context.videoStreamIndex.integrateBitratesFrame(t),this.context.videoDownlinkBandwidthPolicy.updateIndex(this.context.videoStreamIndex),this.handleBitrateFrame(e.message.bitrates)}const t=d.default.fromSignalFrame(e.message);e.message.type!==h.SdkSignalFrame.Type.PRIMARY_MEETING_JOIN_ACK&&t.statusCode()!==u.default.OK&&this.context.audioVideoController.handleMeetingSessionStatus(t,null)}}}t.default=v},1591:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{cancel(){}name(){return"NoOpTask"}run(){return Promise.resolve()}setParent(e){}}},3750:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(3293)),a=i(n(4185));t.default=class{constructor(e,t,n){this.logger=e,this.task=t,this.dependencies=n,this.canceled=!1}name(){return`${this.task.name()} (once)`}cancel(){if(!this.canceled){if(this.dependencies)for(const e of this.dependencies)e.cancel();this.logger.info(`Canceling ${this.name()}`),a.default.nextTick((()=>this.task.cancel())),this.canceled=!0,this.cancelPromise&&a.default.nextTick((()=>this.cancelPromise(new Error(`canceling ${this.name()}`))))}}logDependencies(){if(this.logger.getLogLevel()>r.default.INFO)return;if(!this.dependencies)return;const e=this.dependencies.filter((e=>e)).map((e=>e.name())).join(", ");this.logger.info(`${this.task.name()} waiting for dependencies: ${e}`)}run(){if(this.promise)return this.promise;const e=this.dependencies?Promise.all(this.dependencies.map((e=>null==e?void 0:e.run()))):Promise.resolve();return this.logDependencies(),this.ongoing=e.then((()=>this.task.run())),this.promise=new Promise(((e,t)=>{this.cancelPromise=t,this.ongoing.then(e).catch(t)}))}setParent(e){this.task.setParent(e)}}},5417:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(2114)),o=r(n(9183)),s=r(n(698));class c extends s.default{constructor(e){super(e.logger),this.context=e,this.taskName="OpenSignalingConnectionTask",this.taskCanceler=null}cancel(){this.taskCanceler&&(this.taskCanceler.cancel(),this.taskCanceler=null)}run(){return i(this,void 0,void 0,(function*(){const e=this.context.meetingSessionConfiguration;this.context.signalingClient.openConnection(new a.default(e.urls.signalingURL,e.credentials.joinToken));const t=Date.now();try{yield new Promise(((e,t)=>{const n=new class{constructor(e){this.signalingClient=e}cancel(){this.signalingClient.removeObserver(this),t(new Error("OpenSignalingConnectionTask got canceled while waiting to open signaling connection"))}handleSignalingClientEvent(n){switch(n.type){case o.default.WebSocketOpen:this.signalingClient.removeObserver(this),e();break;case o.default.WebSocketFailed:this.signalingClient.removeObserver(this),t(new Error("WebSocket connection failed"))}}}(this.context.signalingClient);this.context.signalingClient.registerObserver(n),this.taskCanceler=n}))}catch(e){throw e}finally{this.context.signalingOpenDurationMs=Math.round(Date.now()-t),this.logger.info(`Opening signaling connection took ${this.context.signalingOpenDurationMs} ms`)}}))}}t.default=c},1999:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(698));class o extends a.default{constructor(e,t,n){super(e),this.taskName=t,this.tasksToRunParallel=n;for(const e of n)e.setParent(this)}cancel(){for(const e of this.tasksToRunParallel)this.logger.info(`canceling parallel group task ${this.name()} subtask ${e.name()}`),e.cancel()}run(){return i(this,void 0,void 0,(function*(){const e=[];for(const t of this.tasksToRunParallel)this.logger.info(`parallel group task ${this.name()} running subtask ${t.name()}`),e.push(t.run());const t=[];for(let n=0;n0){const e=t.join(", ");this.logAndThrow(`parallel group task ${this.name()} failed for tasks: ${e}`)}this.logger.info(`parallel group task ${this.name()} completed`)}))}}t.default=o},5843:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=n(1016),o=r(n(9183)),s=n(4955),c=r(n(698));class l extends c.default{constructor(e,t,n){super(e.logger),this.context=e,this.credentials=t,this.completionCallback=n,this.taskName="PromoteToPrimaryMeetingTask",this.taskCanceler=null}cancel(){this.taskCanceler&&(this.taskCanceler.cancel(),this.taskCanceler=null)}run(){return i(this,void 0,void 0,(function*(){this.context.signalingClient.ready()?(this.context.signalingClient.promoteToPrimaryMeeting(this.credentials),this.context.logger.info("Sent request to join primary meeting"),yield this.receivePrimaryMeetingJoinAck()):this.completionCallback(new a.MeetingSessionStatus(a.MeetingSessionStatusCode.SignalingRequestFailed))}))}receivePrimaryMeetingJoinAck(){return new Promise(((e,t)=>{const n=new class{constructor(e,t,n){this.signalingClient=e,this.completionCallback=t,this.logger=n}cancel(){this.signalingClient.removeObserver(this),this.completionCallback(new a.MeetingSessionStatus(a.MeetingSessionStatusCode.SignalingRequestFailed)),e()}handleSignalingClientEvent(t){t.isConnectionTerminated()&&(this.signalingClient.removeObserver(this),this.logger.info("PromoteToPrimaryMeetingTask connection terminated"),this.completionCallback(new a.MeetingSessionStatus(a.MeetingSessionStatusCode.SignalingRequestFailed)),e()),t.type===o.default.ReceivedSignalFrame&&t.message.type===s.SdkSignalFrame.Type.PRIMARY_MEETING_JOIN_ACK&&(this.signalingClient.removeObserver(this),this.logger.info("Got a primary meeting join ACK"),this.completionCallback(a.MeetingSessionStatus.fromSignalFrame(t.message)),e())}}(this.context.signalingClient,this.completionCallback,this.context.logger);this.taskCanceler=n,this.context.signalingClient.registerObserver(n)}))}}t.default=l},3842:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(698));class o extends a.default{constructor(e){super(e.logger),this.context=e,this.taskName="ReceiveAudioInputTask"}run(){var e,t;return i(this,void 0,void 0,(function*(){if(!(null===(t=null===(e=this.context.meetingSessionConfiguration)||void 0===e?void 0:e.urls)||void 0===t?void 0:t.audioHostURL))return void this.context.logger.info("No audio connection: not acquiring audio input");if(this.context.activeAudioInput)return void this.context.logger.info("an active audio input exists");let n;try{n=yield this.context.mediaStreamBroker.acquireAudioInputStream()}catch(e){this.context.logger.warn("could not acquire audio input from current device")}n?this.context.activeAudioInput=n:this.context.logger.warn("an audio input is not available")}))}}t.default=o},6522:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(9183)),o=n(4955),s=r(n(698));class c extends s.default{constructor(e){super(e.logger),this.context=e,this.taskName="ReceiveRemoteVideoPauseResume",this.serverPausedVideoTileIds=new Set}removeObserver(){this.context.signalingClient.removeObserver(this)}run(){return i(this,void 0,void 0,(function*(){this.context.signalingClient.registerObserver(this),this.context.removableObservers.push(this)}))}handleSignalingClientEvent(e){if(e.type!==a.default.ReceivedSignalFrame||e.message.type!==o.SdkSignalFrame.Type.PAUSE&&e.message.type!==o.SdkSignalFrame.Type.RESUME)return;const t=e.message.pause,n=e.message.type;if(this.context.logger.info(`received new ${n===o.SdkSignalFrame.Type.PAUSE?"pause":"resume"} frame: ${JSON.stringify(t)}`),!t||void 0===this.context.videoTileController.getVideoTileForAttendeeId||void 0===this.context.videoDownlinkBandwidthPolicy.forEachObserver||void 0===this.context.videoStreamIndex.attendeeIdForGroupId)return;const i=t.groupIds.map((e=>{const t=this.context.videoStreamIndex.attendeeIdForGroupId(e);return this.context.videoTileController.getVideoTileForAttendeeId(t)}));for(const e of i)void 0!==e&&(n===o.SdkSignalFrame.Type.PAUSE?e.state().paused||(this.serverPausedVideoTileIds.add(e.id()),this.context.videoDownlinkBandwidthPolicy.forEachObserver((t=>{t.tileWillBePausedByDownlinkPolicy(e.id())})),e.pause()):e.state().paused&&this.serverPausedVideoTileIds.has(e.id())&&(this.serverPausedVideoTileIds.delete(e.id()),this.context.videoDownlinkBandwidthPolicy.forEachObserver((t=>{t.tileWillBeUnpausedByDownlinkPolicy(e.id())})),e.unpause()))}}t.default=c},3613:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(832)),o=n(4955),s=r(n(698));class c extends s.default{constructor(e){super(e.logger),this.context=e,this.taskName="ReceiveVideoInputTask"}checkAndApplyVideoConstraint(e,t,n,r,a){return i(this,void 0,void 0,(function*(){const i=t.getSettings();let o;if(o=e?this.context.meetingSessionConfiguration.meetingFeatures.contentMaxResolution:this.context.meetingSessionConfiguration.meetingFeatures.videoMaxResolution,n>o.videoWidth||r>o.videoHeight||a>o.videoFrameRate){const n={width:{ideal:o.videoWidth},height:{ideal:o.videoHeight},frameRate:{ideal:o.videoFrameRate}};this.context.logger.warn(`Video track (content = ${e}) will be constrained to: ${JSON.stringify(n)} to remain below configured video quality settings, trackSettings: ${JSON.stringify(i)}`);try{yield t.applyConstraints(n)}catch(t){this.context.logger.info(`Could not apply constraint for video track (content = ${e})`)}}}))}run(){return i(this,void 0,void 0,(function*(){const e=this.context.videoDuplexMode===o.SdkStreamServiceType.RX||this.context.videoDuplexMode===o.SdkStreamServiceType.DUPLEX;if(this.context.videoTileController.hasStartedLocalVideoTile()?this.context.videoDuplexMode=e?o.SdkStreamServiceType.DUPLEX:o.SdkStreamServiceType.TX:this.context.videoDuplexMode=e?o.SdkStreamServiceType.RX:0,this.context.videoCaptureAndEncodeParameter=this.context.videoUplinkBandwidthPolicy.chooseCaptureAndEncodeParameters(),!this.context.videoTileController.hasStartedLocalVideoTile())return this.context.logger.info("has not started local video tile"),void(this.context.activeVideoInput&&(this.context.activeVideoInput=void 0,this.context.videoStreamIndex.integrateUplinkPolicyDecision([])));const t=this.context.videoTileController.getLocalVideoTile();let n;try{n=yield this.context.mediaStreamBroker.acquireVideoInputStream()}catch(e){this.context.logger.warn("could not acquire video input from current device"),this.context.videoTileController.stopLocalVideoTile()}if(this.context.enableSimulcast){const e=this.context.videoUplinkBandwidthPolicy.chooseEncodingParameters();this.context.videoStreamIndex.integrateUplinkPolicyDecision(Array.from(e.values()))}if(this.context.activeVideoInput=n,n){const i=n.getVideoTracks();if(!i||0===i.length)return;const r=this.context.meetingSessionConfiguration.credentials.attendeeId,o=new a.default(r).hasModality(a.default.MODALITY_CONTENT),s=i[0].getSettings();if(this.context.enableSimulcast){const t=this.context.videoUplinkBandwidthPolicy.chooseMediaTrackConstraints();this.context.logger.info(`simulcast: choose constraint ${JSON.stringify(t)}`);try{yield i[0].applyConstraints(t)}catch(e){this.context.logger.info("simulcast: pass video without more constraint")}}else this.checkAndApplyVideoConstraint(o,i[0],s.width,s.height,s.frameRate);const c=this.context.audioVideoController.configuration.credentials.externalUserId;t.bindVideoStream(r,!0,n,s.width,s.height,null,c);for(let e=0;e{const n=new o.default(e.attendeeId);return!(n.base()===t&&n.hasModality(o.default.MODALITY_CONTENT))}));const{videoStreamIndex:n,videoDownlinkBandwidthPolicy:i,videoUplinkBandwidthPolicy:r}=this.context,a=n.allVideoSendingSourcesExcludingSelf(t);n.integrateIndexFrame(e),i.updateIndex(n),r.updateIndex(n),this.resubscribe(i,r),this.updateVideoAvailability(e),this.handleIndexVideosPausedAtSource(),e.supportedReceiveCodecIntersection.length>0&&this.handleSupportedVideoReceiveCodecIntersection(e);const s=n.allVideoSendingSourcesExcludingSelf(t);this.areVideoSourcesEqual(a,s)||this.context.audioVideoController.forEachObserver((e=>{d.Maybe.of(e.remoteVideoSourcesDidChange).map((t=>t.bind(e)(s)))}))}areVideoSourcesEqual(e,t){if(e.length!==t.length)return!1;const n=(e,t)=>e.attendee.attendeeId.localeCompare(t.attendee.attendeeId),i=[...e].sort(n),r=[...t].sort(n);for(let e=0;ethis.context.videosToReceive.size()&&this.logger.warn(`Video receive limit exceeded. Limiting the videos to ${this.context.videosToReceive.size()}. Please consider using AllHighestVideoBandwidthPolicy or VideoPriorityBasedPolicy along with chooseRemoteVideoSources api to select the video sources to be displayed.`),this.context.videoCaptureAndEncodeParameter=t.chooseCaptureAndEncodeParameters(),this.logger.info(`trigger resubscribe for up=${i} down=${n}; videosToReceive=[${this.context.videosToReceive.array()}] captureParams=${JSON.stringify(this.context.videoCaptureAndEncodeParameter)}`),this.context.audioVideoController.update({needsRenegotiation:!1})}updateVideoAvailability(e){if(!this.context.videosToReceive)return void this.logger.error("videosToReceive must be set in the meeting context.");const t=new a.default;t.remoteVideoAvailable=!this.context.videosToReceive.empty(),t.canStartLocalVideo=!e.atCapacity,this.context.lastKnownVideoAvailability&&this.context.lastKnownVideoAvailability.equal(t)||(this.context.lastKnownVideoAvailability=t.clone(),this.context.audioVideoController.forEachObserver((e=>{d.Maybe.of(e.videoAvailabilityDidChange).map((n=>n.bind(e)(t.clone())))})))}handleSupportedVideoReceiveCodecIntersection(e){if(void 0===this.context.videoSendCodecPreferences)return;const t=[];let n=!1;for(const n of this.context.videoSendCodecPreferences)for(const i of e.supportedReceiveCodecIntersection)if(n.equals(s.default.fromSignaled(i))){t.push(n);break}if(t.length>0){const e=t.find((e=>this.context.prioritizedSendVideoCodecCapabilities.some((t=>e.equals(t)))));void 0===this.context.currentVideoSendCodec||void 0!==e&&this.context.currentVideoSendCodec.equals(e)||(n=!0),this.context.meetingSupportedVideoSendCodecPreferences=t}else this.logger.warn("Interesection of meeting receive codec support and send codec preferences has no overlap, falling back to just values provided in `setVideoCodecSendPreferences`"),this.context.meetingSupportedVideoSendCodecPreferences=void 0;this.context.videoUplinkBandwidthPolicy.setMeetingSupportedVideoSendCodecs&&this.context.videoUplinkBandwidthPolicy.setMeetingSupportedVideoSendCodecs(this.context.meetingSupportedVideoSendCodecPreferences,this.context.videoSendCodecPreferences),n&&this.context.audioVideoController.update({needsRenegotiation:!0})}handleIndexVideosPausedAtSource(){const e=this.context.videoStreamIndex.streamsPausedAtSource();for(const t of this.context.videoTileController.getAllVideoTiles()){const n=t.state();e.contain(n.streamId)?t.markPoorConnection()&&this.logger.info(`marks the tile ${n.tileId} as having a poor connection`):t.unmarkPoorConnection()&&this.logger.info(`unmarks the tile ${n.tileId} as having a poor connection`)}}}t.default=f},8598:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(698));class a extends r.default{constructor(e,t,n="RunnableTask"){super(e),this.fn=t,this.taskName=n}run(){return this.fn().then((()=>{}))}}t.default=a},9103:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(4783)),o=r(n(9183)),s=n(4955),c=r(n(698));class l extends c.default{constructor(e){super(e.logger),this.context=e,this.taskName="SendAndReceiveDataMessagesTask",this.sendDataMessageHandler=(e,t,n)=>{if(this.context.signalingClient.ready()){let i;i=t instanceof Uint8Array?t:"string"==typeof t?(new TextEncoder).encode(t):(new TextEncoder).encode(JSON.stringify(t)),this.validateDataMessage(e,i,n);const r=s.SdkDataMessagePayload.create();r.topic=e,r.lifetimeMs=n,r.data=i;const a=s.SdkDataMessageFrame.create();a.messages=[r],this.context.signalingClient.sendDataMessage(a)}else this.context.logger.error("Signaling client is not ready")}}run(){return i(this,void 0,void 0,(function*(){this.context.removableObservers.push(this),this.context.signalingClient.registerObserver(this),this.context.realtimeController.realtimeSubscribeToSendDataMessage(this.sendDataMessageHandler)}))}removeObserver(){this.context.realtimeController.realtimeUnsubscribeFromSendDataMessage(this.sendDataMessageHandler),this.context.signalingClient.removeObserver(this)}handleSignalingClientEvent(e){if(e.type===o.default.ReceivedSignalFrame&&e.message.type===s.SdkSignalFrame.Type.DATA_MESSAGE)for(const t of e.message.dataMessage.messages){const e=new a.default(t.ingestTimeNs/1e6,t.topic,t.data,t.senderAttendeeId,t.senderExternalUserId,0===t.ingestTimeNs);this.context.realtimeController.realtimeReceiveDataMessage(e)}}validateDataMessage(e,t,n){if(!l.TOPIC_REGEX.test(e))throw new Error("Invalid topic");if(t.length>l.DATA_SIZE)throw new Error("Data size has to be less than 2048 bytes");if(n&&n<0)throw new Error("The life time of the message has to be non negative")}}t.default=l,l.TOPIC_REGEX=new RegExp(/^[a-zA-Z0-9_-]{1,36}$/),l.DATA_SIZE=2048},6706:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(698)),o=r(n(3533));class s extends a.default{constructor(e,t,n){super(e),this.taskName=t,this.tasksToRunSerially=n,this.currentTask=null;for(const e of n)e.setParent(this)}cancel(){this.currentTask&&(this.logger.info(`canceling serial group task ${this.name()} subtask ${this.currentTask.name()}`),this.currentTask.cancel())}run(){return i(this,void 0,void 0,(function*(){for(const e of this.tasksToRunSerially){this.getStatus()===o.default.CANCELED&&this.logAndThrow(`serial group task ${this.name()} was canceled`);try{this.logger.info(`serial group task ${this.name()} running subtask ${e.name()}`),this.currentTask=e,yield e.run(),this.logger.info(`serial group task ${this.name()} completed subtask ${e.name()}`)}catch(e){this.logAndThrow(`serial group task ${this.name()} was canceled due to subtask ${this.currentTask.name()} error: ${e.message}`)}finally{this.currentTask=null}}this.logger.info(`serial group task ${this.name()} completed`)}))}}t.default=s},4518:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(6244)),o=r(n(832)),s=r(n(5803)),c=r(n(698));class l extends c.default{constructor(e){super(e.logger),this.context=e,this.taskName="SetLocalDescriptionTask"}cancel(){if(this.cancelPromise){const e=new Error(`canceling ${this.name()}`);this.cancelPromise(e),delete this.cancelPromise}}run(){return i(this,void 0,void 0,(function*(){const e=this.context.peer;let t=this.context.sdpOfferInit.sdp;this.context.browserBehavior.supportsVideoLayersAllocationRtpHeaderExtension()&&(t=new s.default(t).withVideoLayersAllocationRtpHeaderExtension(this.context.previousSdpOffer).sdp),this.context.browserBehavior.supportsDependencyDescriptorRtpHeaderExtension()&&void 0!==this.context.videoUplinkBandwidthPolicy.wantsVideoDependencyDescriptorRtpHeaderExtension&&this.context.videoUplinkBandwidthPolicy.wantsVideoDependencyDescriptorRtpHeaderExtension()&&(t=new s.default(t).withDependencyDescriptorRtpHeaderExtension(this.context.previousSdpOffer).sdp),(new a.default).requiresDisablingH264Encoding()&&(t=new s.default(t).removeH264SupportFromSendSection().sdp);const n=this.context.audioVideoController.configuration.credentials.attendeeId;if(new o.default(n).hasModality(o.default.MODALITY_CONTENT)&&this.context.audioVideoController.configuration.enableSVC&&(t=new s.default(t).withStartingVideoSendBitrate(100).sdp),void 0!==this.context.videoSendCodecPreferences&&this.context.videoSendCodecPreferences.length>0&&(t=new s.default(t).withVideoSendCodecPreferences(void 0!==this.context.meetingSupportedVideoSendCodecPreferences?this.context.meetingSupportedVideoSendCodecPreferences:this.context.videoSendCodecPreferences).sdp),this.context.audioProfile&&(t=new s.default(t).withAudioMaxAverageBitrate(this.context.audioProfile.audioBitrateBps).sdp,this.context.audioProfile.isStereo()&&(t=new s.default(t).withStereoAudio().sdp),this.context.audioProfile.hasRedundancyEnabled())){const e=new s.default(t).getAudioPayloadTypes();this.context.transceiverController&&this.context.transceiverController.setAudioPayloadTypes&&this.context.transceiverController.setAudioPayloadTypes(e)}this.logger.debug((()=>`local description is >>>${t}<<<`));const r={type:"offer",sdp:t,toJSON:null};yield new Promise(((t,n)=>i(this,void 0,void 0,(function*(){this.cancelPromise=e=>{n(e)};try{yield e.setLocalDescription(r),t()}catch(e){n(e)}finally{delete this.cancelPromise}})))),this.context.logger.info("set local description")}))}}t.default=l},4055:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(832)),o=r(n(5803)),s=r(n(2049)),c=r(n(698));class l extends c.default{constructor(e){super(e.logger),this.context=e,this.taskName="SetRemoteDescriptionTask"}cancel(){this.cancelICEPromise&&this.cancelICEPromise()}run(){var e;return i(this,void 0,void 0,(function*(){this.context.peer||this.logAndThrow("session does not have peer connection; bypass set remote description");let t=this.context.sdpAnswer;t=new o.default(t).withoutServerReflexiveCandidates().sdp,this.context.audioProfile&&(t=new o.default(t).withAudioMaxAverageBitrate(this.context.audioProfile.audioBitrateBps).sdp,this.context.audioProfile.isStereo()&&(t=new o.default(t).withStereoAudio().sdp)),void 0!==this.context.videoSendCodecPreferences&&this.context.videoSendCodecPreferences.length>0&&(t=new o.default(t).withVideoSendCodecPreferences(void 0!==this.context.meetingSupportedVideoSendCodecPreferences?this.context.meetingSupportedVideoSendCodecPreferences:this.context.videoSendCodecPreferences).sdp),this.context.prioritizedSendVideoCodecCapabilities=new o.default(t).prioritizedSendVideoCodecCapabilities(),this.context.currentVideoSendCodec=this.context.prioritizedSendVideoCodecCapabilities.length>0?this.context.prioritizedSendVideoCodecCapabilities[0]:void 0;const n=this.context.activeVideoInput;if(void 0!==n){const t=this.context.audioVideoController.configuration.credentials.attendeeId,i=new a.default(t).hasModality(a.default.MODALITY_CONTENT),r=n.getVideoTracks()[0];i&&((null===(e=this.context.currentVideoSendCodec)||void 0===e?void 0:e.codecName)===s.default.av1Main().codecName?(r.contentHint="text",this.logger.info(`Setting content hint to text for AV1, attendee: ${t}`)):this.context.audioVideoController.configuration.enableSVC&&(r.contentHint="motion",this.logger.info(`Setting content hint to motion to enable SVC, attendee: ${t}`)))}this.logger.info(`processed remote description is >>>${t}<<<`);const i={type:"answer",sdp:t,toJSON:null};try{yield this.createICEConnectionCompletedPromise(i)}catch(e){throw e}}))}createICEConnectionCompletedPromise(e){return new Promise(((t,n)=>i(this,void 0,void 0,(function*(){const i=()=>{"connected"!==this.context.peer.iceConnectionState&&"completed"!==this.context.peer.iceConnectionState||(this.context.peer.removeEventListener("iceconnectionstatechange",i),t())};this.cancelICEPromise=()=>{this.context.peer&&this.context.peer.removeEventListener("iceconnectionstatechange",i),n(new Error(`${this.name()} got canceled while waiting for the ICE connection state`))},this.context.peer.addEventListener("iceconnectionstatechange",i);try{yield this.context.peer.setRemoteDescription(e),this.logger.info("set remote description, waiting for ICE connection"),i()}catch(e){n(e)}}))))}}t.default=l},4402:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(565)),o=r(n(484)),s=r(n(5803)),c=r(n(4095)),l=n(980),d=r(n(9183)),u=r(n(9295)),f=n(4955),h=n(9e3),m=r(n(698));class p extends m.default{constructor(e){super(e.logger),this.context=e,this.taskName="SubscribeAndReceiveSubscribeAckTask",this.taskCanceler=null,this.textCompressor=new c.default(e.logger)}cancel(){this.taskCanceler&&(this.taskCanceler.cancel(),this.taskCanceler=null)}run(){return i(this,void 0,void 0,(function*(){let e="";if(this.context.peer&&this.context.peer.localDescription&&(e=new s.default(this.context.peer.localDescription.sdp).withUnifiedPlanFormat().sdp),!this.context.enableSimulcast){let e=0,t=0;this.context.videoCaptureAndEncodeParameter&&(e=this.context.videoCaptureAndEncodeParameter.captureFrameRate(),t=this.context.videoCaptureAndEncodeParameter.encodeBitrates()[0]);const n={rid:"hi",maxBitrate:1e3*t,maxFramerate:e,active:!0};this.context.videoStreamIndex.integrateUplinkPolicyDecision([n])}this.context.videoStreamIndex.subscribeFrameSent();const t=this.fixUpSubscriptionOrder(e,this.context.videoSubscriptions),n=this.context.videoDuplexMode===f.SdkStreamServiceType.TX||this.context.videoDuplexMode===f.SdkStreamServiceType.DUPLEX;let i,r=e;if(void 0!==this.context.videoUplinkBandwidthPolicy.wantsVideoDependencyDescriptorRtpHeaderExtension&&this.context.videoUplinkBandwidthPolicy.wantsVideoDependencyDescriptorRtpHeaderExtension()||(r=new s.default(r).withoutDependencyDescriptorRtpHeaderExtension().sdp),this.context.serverSupportsCompression){const t=this.context.previousSdpOffer?this.context.previousSdpOffer.sdp:"";i=this.textCompressor.compress(r,t),this.context.logger.info(`Compressed the SDP message from ${r.length} to ${i.length} bytes.`),e=""}this.context.previousSdpOffer=new s.default(e);const a=new u.default(this.context.meetingSessionConfiguration.credentials.attendeeId,e,this.context.meetingSessionConfiguration.urls.audioHostURL,this.context.realtimeController.realtimeIsLocalAudioMuted(),!1,t,n,this.context.videoStreamIndex.localStreamDescriptions(),!0,i);void 0===this.context.videoDownlinkBandwidthPolicy.getServerSideNetworkAdaption||l.serverSideNetworkAdaptionIsNoneOrDefault(this.context.videoDownlinkBandwidthPolicy.getServerSideNetworkAdaption())||void 0===this.context.videoDownlinkBandwidthPolicy.getVideoPreferences||(a.videoSubscriptionConfiguration=h.convertVideoPreferencesToSignalingClientVideoSubscriptionConfiguration(this.context,t.map((e=>0===e?0:this.context.videoStreamIndex.groupIdForStreamId(e))),this.context.videoDownlinkBandwidthPolicy.getVideoPreferences())),this.context.logger.info(`sending subscribe: ${JSON.stringify(a)}`),this.context.signalingClient.subscribe(a);const o=yield this.receiveSubscribeAck();this.context.logger.info(`got subscribe ack: ${JSON.stringify(o)}`);let c="";o.compressedSdpAnswer&&o.compressedSdpAnswer.length?(c=this.textCompressor.decompress(o.compressedSdpAnswer,this.context.previousSdpAnswerAsString),0===c.length&&(this.context.sdpAnswer="",this.context.previousSdpAnswerAsString="",this.logAndThrow("Error occurred while trying to decompress the SDP answer.")),this.context.logger.info(`Decompressed the SDP message from ${o.compressedSdpAnswer.length} to ${c.length} bytes.`),this.context.sdpAnswer=c):this.context.sdpAnswer=o.sdpAnswer,this.context.previousSdpAnswerAsString=this.context.sdpAnswer,this.context.videoStreamIndex.integrateSubscribeAckFrame(o)}))}fixUpSubscriptionOrder(e,t){if(void 0===this.context.transceiverController.getMidForStreamId)return t;const n=new Map;for(const e of t){const t=this.context.transceiverController.getMidForStreamId(e);void 0!==t?n.set(t,e):0!==e&&this.logger.warn(`Could not find MID for stream ID: ${e}`)}const i=new s.default(e).mediaSections(),r=[];for(const e of i)if("video"===e.mediaType)if("recvonly"===e.direction){const t=n.get(e.mid);if(void 0===t){this.logger.warn(`Could not find stream ID for MID: ${e.mid}`);continue}r.push(t)}else r.push(0);return this.logger.info(`Fixed up ${JSON.stringify(t)} to ${JSON.stringify(r)} (may be same))}`),r}receiveSubscribeAck(){return new Promise(((e,t)=>{const n=this.context,i=new class{constructor(e){this.signalingClient=e}cancel(){this.signalingClient.removeObserver(this),t(new Error("SubscribeAndReceiveSubscribeAckTask got canceled while waiting for SdkSubscribeAckFrame"))}handleSignalingClientEvent(t){if(t.isConnectionTerminated()){const e=`SubscribeAndReceiveSubscribeAckTask connection was terminated with code ${t.closeCode} and reason: ${t.closeReason}`;n.logger.warn(e);let i=o.default.TaskFailed;return t.closeCode>=4500&&t.closeCode<4600&&(i=o.default.SignalingInternalServerError),void n.audioVideoController.handleMeetingSessionStatus(new a.default(i),new Error(e))}if(t.type!==d.default.ReceivedSignalFrame||t.message.type!==f.SdkSignalFrame.Type.SUBSCRIBE_ACK)return;this.signalingClient.removeObserver(this);const i=t.message.suback;e(i)}}(this.context.signalingClient);this.context.signalingClient.registerObserver(i),this.taskCanceler=i}))}}t.default=p},3533:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.IDLE="IDLE",e.RUNNING="RUNNING",e.CANCELED="CANCELED",e.FINISHED="FINISHED"}(n||(n={})),t.default=n},2058:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(1340)),o=r(n(698));class s extends o.default{constructor(e,t,n){super(e),this.taskToRunBeforeTimeout=t,this.timeoutMs=n,this.taskName=`Timeout${this.timeoutMs}ms`,t.setParent(this)}cancel(){this.logger.info(`canceling timeout task ${this.name()} subtask ${this.taskToRunBeforeTimeout}`),this.taskToRunBeforeTimeout.cancel()}run(){return i(this,void 0,void 0,(function*(){const e=new a.default(this.timeoutMs);e.start((()=>{this.logger.info(`timeout reached for task ${this.name()}`),this.taskToRunBeforeTimeout.cancel()}));try{yield this.taskToRunBeforeTimeout.run()}finally{e.stop()}this.logger.info(`timeout task ${this.name()} completed`)}))}}t.default=s},8170:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(484)),o=r(n(698));class s extends o.default{constructor(e){super(e.logger),this.context=e,this.taskName="WaitForAttendeePresenceTask"}cancel(){if(this.cancelPromise){const e=new Error(`canceling ${this.name()} due to the meeting status code: ${a.default.NoAttendeePresent}`);this.cancelPromise(e),delete this.cancelPromise}}run(){return i(this,void 0,void 0,(function*(){const e=this.context.meetingSessionConfiguration.credentials.attendeeId;return new Promise(((t,n)=>{const i=(n,r,a,o,s)=>{e===n&&r&&(this.context.realtimeController.realtimeUnsubscribeToAttendeeIdPresence(i),t(),delete this.cancelPromise)};this.cancelPromise=e=>{this.context.realtimeController.realtimeUnsubscribeToAttendeeIdPresence(i),n(e)},this.context.realtimeController.realtimeSubscribeToAttendeeIdPresence(i)}))}))}}t.default=s},8556:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(1379)),o=r(n(7170)),s=r(n(5687)),c=r(n(551)),l=r(n(4185));t.default=class{constructor(e,t,n){this.logger=e,this.browserBehavior=t,this.meetingSessionContext=n,this._localCameraTransceiver=null,this._localAudioTransceiver=null,this.videoSubscriptions=[],this.defaultMediaStream=null,this.peer=null,this.streamIdToTransceiver=new Map,this.groupIdToTransceiver=new Map,this.audioRedWorker=null,this.audioRedWorkerURL=null,this.audioMetricsHistory=new Array,this.redMetricsObservers=new Set,this.currentNumRedundantEncodings=0,this.lastRedHolddownTimerStartTimestampMs=0,this.lastHighPacketLossEventTimestampMs=0,this.lastAudioRedTurnOffTimestampMs=0,this.maxAudioMetricsHistory=20,this.audioRedPacketLossShortEvalPeriodMs=5e3,this.audioRedPacketLossLongEvalPeriodMs=15e3,this.audioRedHoldDownTimeMs=3e5,this.redRecoveryTimeMs=6e4}setEncodingParameters(e){return i(this,void 0,void 0,(function*(){if(!this._localCameraTransceiver||"sendrecv"!==this._localCameraTransceiver.direction)return;const t=this._localCameraTransceiver.sender;if(!e||0===e.size)return;const n=Array.from(e.values()),i=t.getParameters();if(i.encodings&&0!==i.encodings.length)for(const e of i.encodings)for(const t of n){if((e.rid||t.rid)&&e.rid!==t.rid)continue;let n;for(n in t)"rid"!==n&&"codecPayloadType"!==n&&t.hasOwnProperty(n)&&(e[n]=t[n])}else i.encodings=n;yield t.setParameters(i)}))}localAudioTransceiver(){return this._localAudioTransceiver}localVideoTransceiver(){return this._localCameraTransceiver}setVideoSendingBitrateKbps(e){return i(this,void 0,void 0,(function*(){if(!this._localCameraTransceiver||"sendrecv"!==this._localCameraTransceiver.direction)return;const t=this._localCameraTransceiver.sender;if(!t||e<=0)return;const n=t.getParameters();n.encodings||(n.encodings=[{}]);for(const t of n.encodings)t.maxBitrate=1e3*e;yield t.setParameters(n)}))}setPeer(e){this.peer=e}reset(){this.destroyAudioRedWorkerAndStates(),this._localCameraTransceiver=null,this._localAudioTransceiver=null,this.videoSubscriptions=[],this.defaultMediaStream=null,this.peer=null}useTransceivers(){return!!this.peer&&void 0!==this.peer.getTransceivers}hasVideoInput(){return!(!this._localCameraTransceiver||"sendrecv"!==this._localCameraTransceiver.direction)}trackIsVideoInput(e){return!!this._localCameraTransceiver&&(e===this._localCameraTransceiver.sender.track||e===this._localCameraTransceiver.receiver.track)}setupLocalTransceivers(){var e,t;this.useTransceivers()&&(this.defaultMediaStream||"undefined"==typeof MediaStream||(this.defaultMediaStream=new MediaStream),this._localAudioTransceiver||(this._localAudioTransceiver=this.peer.addTransceiver("audio",{direction:"inactive",streams:[this.defaultMediaStream]}),(null===(t=null===(e=this.meetingSessionContext)||void 0===e?void 0:e.audioProfile)||void 0===t?void 0:t.hasRedundancyEnabled())&&this.setupAudioRedWorker()),this._localCameraTransceiver||(this._localCameraTransceiver=this.addTransceiver("video",{direction:"inactive",streams:[this.defaultMediaStream]})))}replaceAudioTrack(e){return i(this,void 0,void 0,(function*(){return this._localAudioTransceiver&&"sendrecv"===this._localAudioTransceiver.direction?(yield this._localAudioTransceiver.sender.replaceTrack(e),!0):(this.logger.info("audio transceiver direction is not set up or not activated"),!1)}))}setAudioInput(e){return i(this,void 0,void 0,(function*(){yield this.setTransceiverInput(this._localAudioTransceiver,e)}))}setVideoInput(e){return i(this,void 0,void 0,(function*(){yield this.setTransceiverInput(this._localCameraTransceiver,e)}))}updateVideoTransceivers(e,t){if(!this.useTransceivers())return t.array();const n=this.peer.getTransceivers();return this.videoSubscriptions=[0],t=t.clone(),this.updateTransceivers(n,e,t),this.logger.debug((()=>this.debugDumpTransceivers())),this.videoSubscriptions}updateTransceivers(e,t,n){const i=n.array();0===e.length||e[0].stop?0!==e.length&&this.updateTransceiverWithStop(e,t,i):(this.logger.info("Updating transceivers without `stop` function"),this.updateTransceiverWithoutStop(e,t,i));for(const e of i){const n=this.addTransceiver("video",{direction:"recvonly",streams:[new MediaStream]});this.streamIdToTransceiver.set(e,n),this.groupIdToTransceiver.set(t.groupIdForStreamId(e),n),this.videoSubscriptions.push(e),this.logger.info(`adding transceiver mid: ${n.mid} subscription: ${e} direction: recvonly`)}}updateTransceiverWithStop(e,t,n){let i=1;this.videoSubscriptions=[0];for(const r of e){if(r===this._localCameraTransceiver||!this.transceiverIsVideo(r)||!r.mid)continue;let e=!1;const a=t.streamIdForTrack("v_"+r.mid);if("inactive"!==r.direction&&void 0!==a)for(const[o,s]of n.entries())if(t.StreamIdsInSameGroup(a,s)){r.direction="recvonly",this.videoSubscriptions[i]=s,e=!0,this.streamIdToTransceiver.delete(a),this.streamIdToTransceiver.set(s,r),n.splice(o,1);break}if(!e){this.videoSubscriptions[i]=0,this.logger.info(`Stopping MID: ${r.mid}, direction: ${r.direction}, current direction: ${r.currentDirection}`),r.stop();for(const[e,n]of this.streamIdToTransceiver.entries())r.mid===n.mid&&(this.streamIdToTransceiver.delete(e),this.groupIdToTransceiver.delete(t.groupIdForStreamId(e)))}i+=1}}updateTransceiverWithoutStop(e,t,n){let i=1;for(const r of e)if(r!==this._localCameraTransceiver&&this.transceiverIsVideo(r)){if(this.videoSubscriptions[i]=0,"inactive"!==r.direction){const e=t.streamIdForTrack("v_"+r.mid);if(void 0!==e)for(const[a,o]of n.entries())if(t.StreamIdsInSameGroup(e,o)){r.direction="recvonly",this.videoSubscriptions[i]=o,this.streamIdToTransceiver.delete(e),this.streamIdToTransceiver.set(o,r),n.splice(a,1);break}}i+=1}i=1;for(const r of e)if(r!==this._localCameraTransceiver&&this.transceiverIsVideo(r)){if("inactive"===r.direction&&n.length>0){r.direction="recvonly";const e=n.shift();this.videoSubscriptions[i]=e,this.streamIdToTransceiver.set(e,r),this.groupIdToTransceiver.set(t.groupIdForStreamId(e),r)}else if(0===this.videoSubscriptions[i]){r.direction="inactive";for(const[e,n]of this.streamIdToTransceiver.entries())r===n&&(this.streamIdToTransceiver.delete(e),this.groupIdToTransceiver.delete(t.groupIdForStreamId(e)))}i+=1}}getMidForStreamId(e){var t;return null===(t=this.streamIdToTransceiver.get(e))||void 0===t?void 0:t.mid}setStreamIdForMid(e,t){for(const[n,i]of this.streamIdToTransceiver.entries())if(i.mid===e)return this.streamIdToTransceiver.delete(n),void this.streamIdToTransceiver.set(t,i)}getMidForGroupId(e){var t;return null===(t=this.groupIdToTransceiver.get(e))||void 0===t?void 0:t.mid}transceiverIsVideo(e){return e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind||e.sender&&e.sender.track&&"video"===e.sender.track.kind}debugDumpTransceivers(){let e="",t=0;for(const n of this.peer.getTransceivers())this.transceiverIsVideo(n)&&(e+=`transceiver index=${t} mid=${n.mid} subscription=${this.videoSubscriptions[t]} direction=${n.direction}\n`,t+=1);return e}setTransceiverInput(e,t){return i(this,void 0,void 0,(function*(){e&&(e.direction=t?"sendrecv":"inactive",yield e.sender.replaceTrack(t))}))}forEachRedMetricsObserver(e){for(const t of this.redMetricsObservers)l.default.nextTick((()=>{this.redMetricsObservers.has(t)&&t.recoveryMetricsDidReceive(e)}))}disableAudioRedundancy(){this.meetingSessionContext.audioProfile=new a.default(this.meetingSessionContext.audioProfile.audioBitrateBps,!1),this.meetingSessionContext.audioVideoController.setAudioProfile(this.meetingSessionContext.audioProfile)}setupAudioRedWorker(){var e,t;const n=!!window.RTCRtpScriptTransform,i=!!RTCRtpSender.prototype.createEncodedStreams;if(n)this.logger.info("[AudioRed] Supports encoded insertable streams using RTCRtpScriptTransform");else{if(!i)throw this.disableAudioRedundancy(),new Error("[AudioRed] Encoded insertable streams not supported. Recreating peer connection with audio redundancy disabled.");this.logger.info("[AudioRed] Supports encoded insertable streams using TransformStream")}try{this.audioRedWorkerURL=URL.createObjectURL(new Blob([c.default],{type:"application/javascript"})),this.logger.info(`[AudioRed] Redundant audio worker URL ${this.audioRedWorkerURL}`),this.audioRedWorker=new Worker(this.audioRedWorkerURL)}catch(e){throw this.logger.error(`[AudioRed] Unable to create audio red worker due to ${e}`),URL.revokeObjectURL(this.audioRedWorkerURL),this.audioRedWorkerURL=null,this.audioRedWorker=null,this.disableAudioRedundancy(),this.logger.info("[AudioRed] Recreating peer connection with audio redundancy disabled"),e}if(this.audioRedEnabled=!0,this.audioRedWorker.onmessage=e=>{if("REDWorkerLog"===e.data.type)this.logger.info(e.data.log);else if("RedundantAudioEncoderStats"===e.data.type){const t=new o.default;t.currentTimestampMs=Date.now(),t.ssrc=e.data.ssrc,t.totalAudioPacketsLost=e.data.totalAudioPacketsLost,t.totalAudioPacketsExpected=e.data.totalAudioPacketsExpected,t.totalAudioPacketsRecoveredRed=e.data.totalAudioPacketsRecoveredRed,t.totalAudioPacketsRecoveredFec=e.data.totalAudioPacketsRecoveredFec,this.forEachRedMetricsObserver(t)}},n)this._localAudioTransceiver.sender.transform=new RTCRtpScriptTransform(this.audioRedWorker,{type:"SenderTransform"}),this._localAudioTransceiver.receiver.transform=new RTCRtpScriptTransform(this.audioRedWorker,{type:"ReceiverTransform"});else if(i){const e=this._localAudioTransceiver.sender.createEncodedStreams(),t=this._localAudioTransceiver.receiver.createEncodedStreams();this.audioRedWorker.postMessage({msgType:"StartRedWorker",send:e,receive:t},[e.readable,e.writable,t.readable,t.writable])}null===(e=this.meetingSessionContext)||void 0===e||e.audioVideoController.addObserver(this),this.addRedundantAudioRecoveryMetricsObserver(null===(t=this.meetingSessionContext)||void 0===t?void 0:t.statsCollector)}addTransceiver(e,t){var n;const i=this.peer.addTransceiver(e,t);if(!(null===(n=this.peer.getConfiguration())||void 0===n?void 0:n.encodedInsertableStreams)||!this.audioRedWorker)return i;const r=!!window.RTCRtpScriptTransform,a=!!RTCRtpSender.prototype.createEncodedStreams;if(r)i.sender.transform=new RTCRtpScriptTransform(this.audioRedWorker,{type:"PassthroughTransform"}),i.receiver.transform=new RTCRtpScriptTransform(this.audioRedWorker,{type:"PassthroughTransform"});else if(a){const e=i.sender.createEncodedStreams(),t=i.receiver.createEncodedStreams();this.audioRedWorker.postMessage({msgType:"PassthroughTransform",send:e,receive:t},[e.readable,e.writable,t.readable,t.writable])}return i}destroyAudioRedWorkerAndStates(){var e,t;this.audioRedWorker&&(URL.revokeObjectURL(this.audioRedWorkerURL),this.audioRedWorkerURL=null,this.audioRedWorker=null,this.currentNumRedundantEncodings=0,this.lastRedHolddownTimerStartTimestampMs=0,this.lastAudioRedTurnOffTimestampMs=0,this.lastHighPacketLossEventTimestampMs=0,this.audioRedEnabled=!0,null===(e=this.meetingSessionContext)||void 0===e||e.audioVideoController.removeObserver(this),this.removeRedundantAudioRecoveryMetricsObserver(null===(t=this.meetingSessionContext)||void 0===t?void 0:t.statsCollector))}setAudioPayloadTypes(e){this.audioRedWorker&&(this.audioRedWorker.postMessage({msgType:"RedPayloadType",payloadType:e.get("red")}),this.audioRedWorker.postMessage({msgType:"OpusPayloadType",payloadType:e.get("opus")}))}metricsDidReceive(e){const{currentTimestampMs:t}=e,n=e.getRTCStatsReport();let i=0,r=0,a=0;n.forEach((e=>{"audio"===e.kind&&("outbound-rtp"===e.type?r=e.packetsSent:"remote-inbound-rtp"===e.type&&(i=e.timestamp,a=e.packetsLost))})),(0===this.audioMetricsHistory.length||i>this.audioMetricsHistory[this.audioMetricsHistory.length-1].timestampMs&&r>this.audioMetricsHistory[this.audioMetricsHistory.length-1].totalPacketsSent)&&this.audioMetricsHistory.push({timestampMs:i,totalPacketsSent:r,totalPacketsLost:a}),this.audioMetricsHistory.length>this.maxAudioMetricsHistory&&this.audioMetricsHistory.shift();const o=this.lossPercent(this.audioRedPacketLossShortEvalPeriodMs),c=this.lossPercent(this.audioRedPacketLossLongEvalPeriodMs),l=Math.max(o,c),[d,u]=s.default.getNumRedundantEncodingsForPacketLoss(l);if(u)return this.lastHighPacketLossEventTimestampMs=t,void(this.audioRedEnabled&&(this.audioRedWorker&&this.audioRedWorker.postMessage({msgType:"Disable"}),this.audioRedEnabled=!1,this.lastAudioRedTurnOffTimestampMs=t));if(!this.audioRedEnabled){const e=t-this.lastAudioRedTurnOffTimestampMs,n=t-this.lastHighPacketLossEventTimestampMs;if(e>=this.audioRedPacketLossLongEvalPeriodMs&&n0&&(this.lastRedHolddownTimerStartTimestampMs=e)}lossPercent(e){if(this.audioMetricsHistory.length<2)return 0;const t=this.audioMetricsHistory[this.audioMetricsHistory.length-1].timestampMs,n=this.audioMetricsHistory[this.audioMetricsHistory.length-1].totalPacketsSent,i=this.audioMetricsHistory[this.audioMetricsHistory.length-1].totalPacketsLost;for(let r=this.audioMetricsHistory.length-2;r>=0;r--)if(t-this.audioMetricsHistory[r].timestampMs>=e){const e=(i-this.audioMetricsHistory[r].totalPacketsLost)/(n-this.audioMetricsHistory[r].totalPacketsSent)*100;return Math.max(0,Math.min(e,100))}return 0}shouldUpdateAudioRedWorkerEncodings(e,t){return this.currentNumRedundantEncodings===t?(this.maybeResetHoldDownTimer(e),!1):!(t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TRANSCRIPTION_DATA_MESSAGE_TOPIC=void 0;const i=n(9837);t.TRANSCRIPTION_DATA_MESSAGE_TOPIC="aws:chime:transcription",t.default=class{constructor(e){this.realtimeController=e,this.transcriptEventCallbacks=new Set}subscribeToTranscriptEvent(e){0===this.transcriptEventCallbacks.size&&this.realtimeController.realtimeSubscribeToReceiveDataMessage(t.TRANSCRIPTION_DATA_MESSAGE_TOPIC,(e=>{for(const t of i.TranscriptEventConverter.from(e))for(const e of this.transcriptEventCallbacks)e(t)})),this.transcriptEventCallbacks.add(e)}unsubscribeFromTranscriptEvent(e){this.transcriptEventCallbacks.delete(e),0===this.transcriptEventCallbacks.size&&this.realtimeController.realtimeUnsubscribeFromReceiveDataMessage(t.TRANSCRIPTION_DATA_MESSAGE_TOPIC)}}},9705:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{}},7722:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{}},5870:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{}},9837:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TranscriptEventConverter=void 0;const r=n(4955),a=i(n(9705)),o=i(n(7301)),s=i(n(4373)),c=i(n(9182)),l={[r.SdkTranscriptionStatus.Type.STARTED]:s.default.STARTED,[r.SdkTranscriptionStatus.Type.INTERRUPTED]:s.default.INTERRUPTED,[r.SdkTranscriptionStatus.Type.RESUMED]:s.default.RESUMED,[r.SdkTranscriptionStatus.Type.STOPPED]:s.default.STOPPED,[r.SdkTranscriptionStatus.Type.FAILED]:s.default.FAILED};t.TranscriptEventConverter=class{static from(e){let t;try{t=r.SdkTranscriptFrame.decode(e.data)}catch(e){throw new Error("Cannot decode transcript data message: "+e)}const n=[];for(const e of t.events)if(e.status){const t=l[e.status.type];if(!t)continue;const i=new o.default;i.type=t,i.eventTimeMs=e.status.eventTime,i.transcriptionRegion=e.status.transcriptionRegion,i.transcriptionConfiguration=e.status.transcriptionConfiguration,e.status.message&&(i.message=e.status.message),n.push(i)}else if(e.transcript){const t=new a.default;t.results=[];for(const n of e.transcript.results){const e={channelId:n.channelId,isPartial:n.isPartial,resultId:n.resultId,startTimeMs:n.startTime,endTimeMs:n.endTime,alternatives:[]};if(n.languageCode&&(e.languageCode=n.languageCode),n.languageIdentification&&n.languageIdentification.length>0){e.languageIdentification=[];for(const t of n.languageIdentification){const n={languageCode:t.languageCode,score:t.score};e.languageIdentification.push(n)}}for(const t of n.alternatives){const n={items:[],transcript:t.transcript};for(const e of t.items){const t={content:e.content,attendee:{attendeeId:e.speakerAttendeeId,externalUserId:e.speakerExternalUserId},startTimeMs:e.startTime,endTimeMs:e.endTime,type:null};switch(e.vocabularyFilterMatch&&(t.vocabularyFilterMatch=e.vocabularyFilterMatch),e.hasOwnProperty("stable")&&(t.stable=e.stable),e.hasOwnProperty("confidence")&&(t.confidence=e.confidence),e.type){case r.SdkTranscriptItem.Type.PRONUNCIATION:t.type=c.default.PRONUNCIATION;break;case r.SdkTranscriptItem.Type.PUNCTUATION:t.type=c.default.PUNCTUATION}n.items.push(t)}for(const e of t.entities){n.entities||(n.entities=[]);const t={category:e.category,confidence:e.confidence,content:e.content,startTimeMs:e.startTime,endTimeMs:e.endTime};e.type&&(t.type=e.type),n.entities.push(t)}e.alternatives.push(n)}t.results.push(e)}n.push(t)}return n}}},8742:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{}},9182:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.PRONUNCIATION="pronunciation",e.PUNCTUATION="punctuation"}(n||(n={})),t.default=n},465:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{}},6788:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{}},7301:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{}},4373:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.STARTED="started",e.INTERRUPTED="interrupted",e.RESUMED="resumed",e.STOPPED="stopped",e.FAILED="failed"}(n||(n={})),t.default=n},3822:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=n(7232),a=i(n(6741));class o{constructor(e){var t,n,i,a,s,c,l;try{this.parserResult=navigator&&navigator.userAgent?new r.UAParser(navigator.userAgent).getResult():void 0}catch(t){e.error(t.message)}this.browserMajorVersion=(null===(i=null===(n=null===(t=this.parserResult)||void 0===t?void 0:t.browser)||void 0===n?void 0:n.version)||void 0===i?void 0:i.split(".")[0])||o.UNAVAILABLE,this.browserName=(null===(a=this.parserResult)||void 0===a?void 0:a.browser.name)||o.UNAVAILABLE,this.browserVersion=(null===(s=this.parserResult)||void 0===s?void 0:s.browser.version)||o.UNAVAILABLE,this.deviceName=[(null===(c=this.parserResult)||void 0===c?void 0:c.device.vendor)||"",(null===(l=this.parserResult)||void 0===l?void 0:l.device.model)||""].join(" ").trim()||o.UNAVAILABLE}getParserResult(){var e,t;return{browserMajorVersion:this.browserMajorVersion,browserName:this.browserName,browserVersion:this.browserVersion,deviceName:this.deviceName,osName:(null===(e=this.parserResult)||void 0===e?void 0:e.os.name)||o.UNAVAILABLE,osVersion:(null===(t=this.parserResult)||void 0===t?void 0:t.os.version)||o.UNAVAILABLE,sdkVersion:a.default.sdkVersion,sdkName:a.default.sdkName}}}t.default=o,o.UNAVAILABLE="Unavailable"},8988:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.queue=Promise.resolve()}add(e){return new Promise(((t,n)=>{this.queue=this.queue.then(e).then(t).catch(n)}))}}},8807:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.None=t.Some=t.Maybe=void 0;class n{static of(e){return null==e?r.of():i.of(e)}}t.Maybe=n;class i{constructor(e){this.value=e,this.isSome=!0,this.isNone=!1}map(e){return n.of(e(this.value))}flatMap(e){return e(this.value)}get(){return this.value}getOrElse(e){return this.value}defaulting(e){return n.of(this.getOrElse(e))}static of(e){if(null==e)throw new Error("value is ${value}");return new i(e)}}t.Some=i;class r{constructor(){this.isSome=!1,this.isNone=!0}get(){throw new Error("value is null")}getOrElse(e){return e}map(e){return new r}flatMap(e){return new r}defaulting(e){return n.of(this.getOrElse(e))}static of(){return new r}}t.None=r},9979:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getRandomValues=t.getFormattedOffset=t.getDefaultAssetSpec=t.toLowerCasePropertyNames=t.isIFramed=t.wait=void 0;const r=i(n(6741));t.wait=function(e){return new Promise((t=>setTimeout(t,e)))},t.isIFramed=function(){var e;try{return"IFRAME"===(null===(e=window.frameElement)||void 0===e?void 0:e.nodeName)||parent!==top}catch(e){return!0}},t.toLowerCasePropertyNames=function e(t){return null===t?null:"object"!=typeof t?t:Array.isArray(t)?t.map(e):Object.keys(t).reduce(((n,i)=>{const r=t[i],a="object"==typeof r?e(r):r;return n[i.toLowerCase()]=a,n}),{})},t.getDefaultAssetSpec=function(){const e=r.default.sdkVersionSemVer;return{assetGroup:`sdk-${e.major}.${e.minor}`}},t.getFormattedOffset=function(e){const t=Math.abs(e);return`${e<=0?"+":"-"}${Math.floor(t/60).toString().padStart(2,"0")}:${Math.floor(t%60).toString().padStart(2,"0")}`},t.getRandomValues=function(e){try{window.crypto.getRandomValues(e)}catch(t){new DataView(e.buffer).setUint32(0,Math.trunc(Math.random()*Math.pow(2,32)),!0)}}},6741:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(6244)),a=i(n(6561));class o{static get sdkName(){return"amazon-chime-sdk-js"}static get sdkVersion(){return a.default.semverString}static get sdkVersionSemVer(){var e,t,n,i;const r=a.default.semverString.match(/^(?[0-9]+)\.(?[0-9]+)((?:\.(?[0-9]+))(?:-(?[a-zA-Z]+(\.[0-9])*))?)?/);return{major:null===(e=null==r?void 0:r.groups)||void 0===e?void 0:e.major,minor:null===(t=null==r?void 0:r.groups)||void 0===t?void 0:t.minor,patch:null===(n=null==r?void 0:r.groups)||void 0===n?void 0:n.patch,preRelease:null===(i=null==r?void 0:r.groups)||void 0===i?void 0:i.preRelease}}static get buildSHA(){return a.default.hash.substr(1)}static get sdkUserAgentLowResolution(){const e=new r.default;return`${e.name()}-${e.majorVersion()}`}static urlWithVersion(e){const t=new URL(e);return t.searchParams.append(o.X_AMZN_VERSION,o.sdkVersion),t.searchParams.append(o.X_AMZN_USER_AGENT,o.sdkUserAgentLowResolution),t.toString()}}t.default=o,o.X_AMZN_VERSION="X-Amzn-Version",o.X_AMZN_USER_AGENT="X-Amzn-User-Agent"},6561:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={hash:"d477baf",raw:"v3.20.0",semverString:"3.20.0"}},8740:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n{constructor(e,t,n,i,r,a=1,o=!1){this.cameraWidth=e,this.cameraHeight=t,this.cameraFrameRate=n,this.maxEncodeBitrateKbps=i,this.isSimulcast=r,this.scaleResolutionDownBy=a,this.isSVC=o}equal(e){let t=e.captureWidth()===this.cameraWidth&&e.captureHeight()===this.cameraHeight&&e.captureFrameRate()===this.cameraFrameRate&&e.encodeBitrates().length===this.encodeBitrates().length&&e.encodeScaleResolutionDownBy().length===this.encodeScaleResolutionDownBy().length&&e.encodeWidths().length===this.encodeWidths().length&&e.encodeHeights().length===this.encodeHeights().length&&e.isSVCEncoding()===this.isSVC;if(t)for(let n=0;n{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.TargetDisplaySize=void 0,function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High",e[e.Maximum=3]="Maximum"}(n=t.TargetDisplaySize||(t.TargetDisplaySize={})),t.default=n},6804:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(5100)),a=i(n(9501)),o=n(9e3),s=i(n(5907));class c extends s.default{constructor(e){super(e),this.logger=e,super.shouldPauseTiles=!1,this.videoPreferences=void 0}reset(){super.reset(),super.shouldPauseTiles=!1,this.videoPreferences=void 0}updateIndex(e){super.updateIndex(e);const t=o.VideoPreferences.prepare();let n=!1;const i=e.remoteStreamDescriptions();for(const e of i)t.some((t=>t.attendeeId===e.attendeeId))||(e.attendeeId.endsWith(r.default.Modality)?(t.add(new a.default(e.attendeeId,1)),n=!0):t.add(new a.default(e.attendeeId,2)));n?(this.videoPreferences=t.build(),this.videoPreferencesUpdated=!0):this.videoPreferences=void 0}chooseRemoteVideoSources(e){this.logger.error("chooseRemoteVideoSources should not be called by VideoAdaptiveProbePolicy")}}t.default=c},9501:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(811)),a=i(n(1583));class o{constructor(e,t,n,i){this.attendeeId=e,this.priority=t,this.targetSize=void 0!==n?n:r.default.Maximum,this.degradationPreference=void 0!==i?i:a.default.Balanced}partialCompare(e){return this.priority-e.priority}equals(e){return this.attendeeId===e.attendeeId&&this.targetSize===e.targetSize&&this.priority===e.priority&&this.degradationPreference===e.degradationPreference}clone(){return new o(this.attendeeId,this.priority,this.targetSize,this.degradationPreference)}targetSizeToBitrateKbps(e){switch(e){case r.default.Maximum:return o.MAXIMUM_BITRATE_KBPS;case r.default.High:return o.HIGH_BITRATE_KBPS;case r.default.Medium:return o.MID_BITRATE_KBPS;case r.default.Low:return o.LOW_BITRATE_KBPS}}}t.default=o,o.LOW_BITRATE_KBPS=300,o.MID_BITRATE_KBPS=600,o.HIGH_BITRATE_KBPS=1500,o.MAXIMUM_BITRATE_KBPS=1e4},9e3:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.VideoPreferences=t.MutableVideoPreferences=t.convertVideoPreferencesToSignalingClientVideoSubscriptionConfiguration=void 0;const r=i(n(9171));t.convertVideoPreferencesToSignalingClientVideoSubscriptionConfiguration=function(e,t,n){if(void 0===e.transceiverController.getMidForGroupId||void 0===e.videoStreamIndex.attendeeIdForGroupId||void 0===n)return[];const i=new Array,a=new Map,o=new Map;for(const n of t){const t=e.transceiverController.getMidForGroupId(n);if(void 0===t)continue;const i=e.videoStreamIndex.attendeeIdForGroupId(n);a.set(i,t),o.set(i,n)}for(const e of n){const t=new r.default,n=a.get(e.attendeeId);void 0!==n&&(t.mid=n,t.attendeeId=e.attendeeId,t.groupId=o.get(e.attendeeId),t.priority=Number.MAX_SAFE_INTEGER-e.priority,t.targetBitrateKbps=e.targetSizeToBitrateKbps(e.targetSize),t.qualityAdaptationPreference=e.degradationPreference,i.push(t))}return i};class a{constructor(e=[]){this.items=e}static default(){return new a([])}[Symbol.iterator](){let e=0;const t=this.items;return{next:()=>e!t.equals(e)))}clear(){this.items=[]}isEmpty(){return 0===this.items.length}equals(e){if(e===this)return!0;if(e.items.length!==this.items.length)return!1;for(const t of this.items)if(!e.items.some((e=>e.equals(t))))return!1;return!0}has(e){return this.items.some((t=>t.equals(e)))}some(e){return this.items.some(e)}clone(){return new a([...this.items])}sort(){this.items.sort(((e,t)=>e.partialCompare(t)))}modify(){return new o(this)}}class o{constructor(e=new a){this.items=e,this.copied=!1}cow(){this.copied||(this.items=this.items.clone(),this.copied=!0)}add(e){this.items.has(e)||(this.cow(),this.items.add(e))}replaceFirst(e,t){this.items.has(e)&&!this.items.some(t)||(this.cow(),this.items.replaceFirst(e,t))}remove(e){this.items.has(e)&&(this.cow(),this.items.remove(e))}some(e){return this.items.some(e)}clear(){this.items.isEmpty()||(this.cow(),this.items.clear())}build(){return this.copied&&this.items.sort(),this.copied=!1,this.items}}class s{constructor(e){this.builder=e}add(e){this.builder.add(e)}replaceFirst(e,t){this.builder.replaceFirst(e,t)}remove(e){this.builder.remove(e)}some(e){return this.builder.some(e)}clear(){this.builder.clear()}build(){return new c(this.builder.build())}}t.MutableVideoPreferences=s;class c{constructor(e){this.items=e}static prepare(){return new s(new o)}static default(){return new c(a.default())}[Symbol.iterator](){return this.items[Symbol.iterator]()}highestPriority(){var e;return null===(e=this.items.first())||void 0===e?void 0:e.priority}sorted(){return this.items[Symbol.iterator]()}equals(e){return e===this||this.items.equals(e.items)}modify(){return new s(this.items.modify())}some(e){return this.items.some(e)}isEmpty(){return this.items.isEmpty()}clone(){const e=c.prepare();for(const t of this.items)e.add(t.clone());return e.build()}}t.VideoPreferences=c,t.default=c},5907:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=o(n(6309)),c=o(n(1066)),l=o(n(3760)),d=o(n(5100)),u=n(3293),f=a(n(980)),h=o(n(8931)),m=o(n(4996)),p=o(n(1876)),g=o(n(811)),v=o(n(9501)),b=n(9e3),y=o(n(7405)),S=o(n(1583));class C{constructor(){this.bandwidthEstimateKbps=0,this.usedBandwidthKbps=0,this.packetsLost=0,this.nackCount=0,this.rttMs=0}}class w{constructor(e,t=y.default.Default){this.logger=e,this.videoPriorityBasedPolicyConfig=t,this.shouldPauseTiles=!0,this.observerQueue=new Set,this.pausedBwAttendeeIds=new Set,this.wantsResubscribeObserver=void 0,this.reset()}reset(){this.allHighestPolicy=new p.default(""),this.optimalReceiveSet=new m.default,this.optimalReceiveStreams=[],this.optimalNonPausedReceiveStreams=[],this.subscribedReceiveSet=new m.default,this.subscribedReceiveStreams=[],this.videoPreferences=void 0,this.defaultVideoPreferences=void 0,this.shouldPauseTiles=!0,this.pausedStreamIds=new m.default,this.pausedBwAttendeeIds=new Set,this.videoPreferencesUpdated=!1,this.logCount=0,this.startupPeriod=!0,this.usingPrevTargetRate=!1,this.rateProbeState="Not Probing",this.firstEstimateTimestamp=0,this.lastUpgradeRateKbps=0,this.timeBeforeAllowSubscribeMs=w.MIN_TIME_BETWEEN_SUBSCRIBE_MS,this.lastProbeTimestamp=Date.now(),this.timeBeforeAllowProbeMs=w.MIN_TIME_BETWEEN_PROBE_MS,this.downlinkStats=new C,this.prevDownlinkStats=new C,this.probeFailed=!1,this.serverSideNetworkAdaption=this.videoPriorityBasedPolicyConfig.serverSideNetworkAdaption,this.pendingActionAfterUpdatedPreferences=!1}bindToTileController(e){this.tileController=e,this.logger.info("tileController bound")}setWantsResubscribeObserver(e){this.wantsResubscribeObserver=e}chooseRemoteVideoSources(e){var t;if(!(null===(t=this.videoPreferences)||void 0===t?void 0:t.equals(e)))if(this.videoPreferences=null==e?void 0:e.clone(),f.serverSideNetworkAdaptionIsNoneOrDefault(this.serverSideNetworkAdaption)||(this.pendingActionAfterUpdatedPreferences=!0,void 0!==this.wantsResubscribeObserver&&(this.wantsResubscribeObserver(),this.pendingActionAfterUpdatedPreferences=!1),this.serverSideNetworkAdaption!==f.default.BandwidthProbingAndRemoteVideoQualityAdaption))this.videoPreferencesUpdated=!0,this.logger.info(`bwe: setVideoPreferences bwe: new preferences: ${JSON.stringify(e)}`);else{const e=new Array;for(const t of this.videoPreferences){const n=new h.default;n.attendee=new s.default,n.attendee.attendeeId=t.attendeeId,e.push(n)}this.allHighestPolicy.chooseRemoteVideoSources(e)}}updateIndex(e){this.videoIndex=e,this.serverSideNetworkAdaption===f.default.BandwidthProbingAndRemoteVideoQualityAdaption&&this.allHighestPolicy.updateIndex(e),this.videoPreferences||this.updateDefaultVideoPreferences()}updateDefaultVideoPreferences(){const e=new Set;for(const t of this.videoIndex.remoteStreamDescriptions())e.add(t.attendeeId);const t=b.VideoPreferences.prepare(),n=e.size;let i=g.default.Maximum;n>8?i=g.default.Low:n>4&&(i=g.default.Medium);for(const n of e)t.add(new v.default(n,1,i));this.defaultVideoPreferences=t.build()}updateMetrics(e){if(!this.videoIndex||this.videoIndex.allStreams().empty())return;this.prevDownlinkStats=this.downlinkStats,this.downlinkStats=new C;const t=e.getObservableMetrics();this.downlinkStats.bandwidthEstimateKbps=t.availableIncomingBitrate/1e3;for(const t in e.streamMetricReports){const n=Number.parseInt(t,10),i=e.streamMetricReports[n];i.direction===c.default.DOWNSTREAM&&i.mediaType===l.default.VIDEO&&(i.currentMetrics.hasOwnProperty("nackCount")&&(this.downlinkStats.nackCount+=e.countPerSecond("nackCount",n)),i.currentMetrics.hasOwnProperty("packetsLost")&&(this.downlinkStats.packetsLost+=e.countPerSecond("packetsLost",n)),i.currentMetrics.hasOwnProperty("bytesReceived")&&(this.downlinkStats.usedBandwidthKbps+=e.bitsPerSecond("bytesReceived",n)/1e3))}}wantsResubscribe(){let e=!1;return f.serverSideNetworkAdaptionIsNoneOrDefault(this.serverSideNetworkAdaption)||(e||(e=this.pendingActionAfterUpdatedPreferences),this.serverSideNetworkAdaption!==f.default.BandwidthProbingAndRemoteVideoQualityAdaption)?(this.calculateOptimalReceiveSet(),e||(e=!this.subscribedReceiveSet.equal(this.optimalReceiveSet)),e):e||this.allHighestPolicy.wantsResubscribe()}chooseSubscriptions(){return f.serverSideNetworkAdaptionIsNoneOrDefault(this.serverSideNetworkAdaption)||(this.pendingActionAfterUpdatedPreferences=!1,this.serverSideNetworkAdaption!==f.default.BandwidthProbingAndRemoteVideoQualityAdaption)?(this.subscribedReceiveSet.equal(this.optimalReceiveSet)||(this.lastSubscribeTimestamp=Date.now()),this.subscribedReceiveSet=this.optimalReceiveSet.clone(),this.subscribedReceiveStreams=this.optimalReceiveStreams.slice(),this.subscribedReceiveSet.clone()):this.allHighestPolicy.chooseSubscriptions()}addObserver(e){this.observerQueue.add(e)}removeObserver(e){this.observerQueue.delete(e)}forEachObserver(e){for(const t of this.observerQueue)e(t)}setVideoPriorityBasedPolicyConfigs(e){this.videoPriorityBasedPolicyConfig=e}calculateOptimalReceiveStreams(){var e;const t=[],n=this.videoIndex.remoteStreamDescriptions();if(0===n.length||(null===(e=this.videoPreferences)||void 0===e?void 0:e.isEmpty()))return void(this.optimalReceiveStreams=[]);const i=this.rateProbeState;this.cleanBwPausedTiles(n),this.handleAppPausedStreams(t,n);const r=new Map;for(const e of this.getCurrentVideoPreferences())r.set(e.attendeeId,e);const a=n.filter((e=>r.has(e.attendeeId))),o=!this.streamsWithPreferenceDidChange(a),s=!this.startupPeriod&&o;if(s&&Date.now()-this.lastSubscribeTimestampe.maxBitrateKbps===t.maxBitrateKbps?e.streamId-t.streamId:e.maxBitrateKbps-t.maxBitrateKbps));for(const e of a)(0===e.avgBitrateKbps||e.avgBitrateKbps>e.maxBitrateKbps)&&(e.attendeeId.endsWith(d.default.Modality)&&e.maxBitrateKbps<100?e.maxBitrateKbps=e.avgBitrateKbps:e.avgBitrateKbps=e.maxBitrateKbps);const c=new Set;for(const e of this.getCurrentVideoPreferences()){const t=a.filter((t=>t.attendeeId===e.attendeeId));if(t.length<3)continue;let n,i=15,r=153600;t.forEach((e=>{i=Math.max(i,e.maxFrameRate),r=Math.max(r,e.totalPixels())})),t.sort(((t,n)=>{if(e.degradationPreference===S.default.MaintainResolution)return Math.abs(t.maxFrameRate-n.maxFrameRate)<2?t.totalPixels()-n.totalPixels():t.maxFrameRate-n.maxFrameRate;if(e.degradationPreference===S.default.MaintainFramerate)return t.totalPixels()===n.totalPixels()?t.maxFrameRate-n.maxFrameRate:t.totalPixels()-n.totalPixels();{const e=5,a=2,o=t=>t.avgBitrateKbps*Math.pow(2,e*t.maxFrameRate/i*Math.pow(2*a,t.totalPixels()/r));return o(t)-o(n)}}));for(const e of t)void 0!==n&&(e.maxFrameRate2||e.totalPixels()!c.has(e.streamId)));this.logger.info(`Filtered to ${JSON.stringify(l)}`);const h={targetDownlinkBitrate:0,chosenTotalBitrate:0,deltaToNextUpgrade:0};h.targetDownlinkBitrate=this.determineTargetRate();const m=this.subscribedReceiveSet.size(),p=this.downlinkStats.bandwidthEstimateKbps,g=!this.videoPriorityBasedPolicyConfig.allowSubscribe(m,p);if(this.probeFailed&&(this.probeFailed=!1,this.timeBeforeAllowSubscribeMs=w.MIN_TIME_BETWEEN_SUBSCRIBE_MS,s&&g))return;const v=this.priorityPolicy(h,l,t);let b=0;if(f.serverSideNetworkAdaptionIsNoneOrDefault(this.serverSideNetworkAdaption)&&!this.startupPeriod&&o?"Probing"===this.rateProbeState?b=this.handleProbe(t,h.targetDownlinkBitrate):0!==h.deltaToNextUpgrade&&(b=this.maybeOverrideOrProbe(t,h,v)):(this.setProbeState("Not Probing"),this.lastUpgradeRateKbps=0),this.previousStreamsWithPreference=a,this.videoPreferencesUpdated=!1,1===b)return this.logger.info(`bwe: keepSameSubscriptions stats:${JSON.stringify(this.downlinkStats)}`),void(this.prevTargetRateKbps=h.targetDownlinkBitrate);if(2===b){const e=this.calculateSubscribeRate(this.preProbeNonPausedReceiveStreams);return this.optimalReceiveStreams=this.preProbeReceiveStreams.slice(),this.processBwPausedStreams(a,this.preProbeNonPausedReceiveStreams),void this.logger.info("bwe: Use Pre-Probe subscription subscribedRate:"+e)}this.optimalNonPausedReceiveStreams=t.slice();const y=this.pausedBwAttendeeIds.size;this.processBwPausedStreams(a,t),this.logger.getLogLevel()<=u.LogLevel.INFO&&(this.logCount%15==0||this.rateProbeState!==i||this.optimalReceiveStreams.length!==t.length||y!==this.pausedBwAttendeeIds.size)&&(this.logger.info(this.policyStateLogStr(n,h.targetDownlinkBitrate)),this.logCount=0),this.logCount++,this.prevTargetRateKbps=h.targetDownlinkBitrate,this.optimalReceiveStreams=t.slice()}calculateOptimalReceiveSet(){const e=new m.default;this.calculateOptimalReceiveStreams();for(const t of this.optimalReceiveStreams)e.add(t.streamId);if(!this.optimalReceiveSet.equal(e)){const t=this.calculateSubscribeRate(this.optimalReceiveStreams);this.logger.info(`bwe: new streamSelection: ${JSON.stringify(e)} subscribedRate:${t}`)}this.optimalReceiveSet=e}determineTargetRate(){let e=0;const t=Date.now();return 0!==this.downlinkStats.bandwidthEstimateKbps?(0===this.firstEstimateTimestamp&&(this.firstEstimateTimestamp=t),this.startupPeriod&&(this.downlinkStats.bandwidthEstimateKbps>w.DEFAULT_BANDWIDTH_KBPS||this.downlinkStats.packetsLost>0||t-this.firstEstimateTimestamp>w.STARTUP_PERIOD_MS&&this.downlinkStats.bandwidthEstimateKbps<=this.prevDownlinkStats.bandwidthEstimateKbps)&&(this.startupPeriod=!1,this.prevTargetRateKbps=this.downlinkStats.bandwidthEstimateKbps),this.startupPeriod?e=w.DEFAULT_BANDWIDTH_KBPS:"Probing"===this.rateProbeState&&this.downlinkStats.usedBandwidthKbps>this.downlinkStats.bandwidthEstimateKbps&&this.downlinkStats.packetsLost"bwe: ValidateRate: Using Previous rate "+this.prevTargetRateKbps)),this.usingPrevTargetRate=!0,e=this.prevTargetRateKbps):this.usingPrevTargetRate=!1,e>15e3&&this.logger.warn("bwe: "+e+" exceeds maximum limit (15000). Limit TargetDisplaySize with VideoPreferences to avoid this."),Math.min(e,15e3)}setProbeState(e){if(this.rateProbeState===e)return!1;const t=Date.now();switch(e){case"Not Probing":this.probePendingStartTimestamp=0;break;case"Probe Pending":if(!(0===this.lastProbeTimestamp||t-this.lastProbeTimestamp>w.MIN_TIME_BETWEEN_PROBE_MS))return!1;this.probePendingStartTimestamp=t;break;case"Probing":if(!(t-this.probePendingStartTimestamp>this.timeBeforeAllowProbeMs))return!1;this.lastProbeTimestamp=t,this.preProbeReceiveStreams=this.subscribedReceiveStreams.slice(),this.preProbeNonPausedReceiveStreams=this.optimalNonPausedReceiveStreams,this.timeBeforeAllowProbeMs=Math.min(2*this.timeBeforeAllowProbeMs,w.MAX_HOLD_BEFORE_PROBE_MS)}return this.logger.info("bwe: setProbeState to "+e+" from "+this.rateProbeState),this.rateProbeState=e,!0}upgradeToStream(e,t){for(let n=0;nw.MAX_ALLOWED_PROBE_TIME_MS)return this.logger.info("bwe: Canceling probe due to timeout"),this.setProbeState("Not Probing"),0;if(this.downlinkStats.packetsLost>0&&(this.logger.info(`bwe: Probe encountering packets lost:${this.downlinkStats.packetsLost}`),this.downlinkStats.packetsLost>w.SPURIOUS_PACKET_LOST_THRESHOLD))return this.setProbeState("Not Probing"),this.logger.info(`bwe: Canceling probe due to packets lost:${this.downlinkStats.packetsLost}`),this.probeFailed=!0,this.timeBeforeAllowSubscribeMs=3*Math.max(w.MIN_TIME_BETWEEN_SUBSCRIBE_MS,this.timeBeforeAllowSubscribeMs),2;const n=this.calculateSubscribeRate(this.optimalReceiveStreams);return this.chosenStreamsSameAsLast(e)||t>n?(this.logger.info("bwe: Probe successful"),this.setProbeState("Not Probing"),this.timeBeforeAllowProbeMs=w.MIN_TIME_BETWEEN_PROBE_MS,0):1}maybeOverrideOrProbe(e,t,n){const i=this.chosenStreamsSameAsLast(e);let r=0;const a=t.targetDownlinkBitrate>w.LOW_BITRATE_THRESHOLD_KBPS?w.TARGET_RATE_CHANGE_TRIGGER_PERCENT:2*w.TARGET_RATE_CHANGE_TRIGGER_PERCENT,o=t.targetDownlinkBitrate*a/100;if(this.targetRateBaselineForDeltaCheckKbps=void 0!==this.targetRateBaselineForDeltaCheckKbps?this.targetRateBaselineForDeltaCheckKbps:this.prevTargetRateKbps,!i&&Math.abs(t.targetDownlinkBitrate-this.targetRateBaselineForDeltaCheckKbps)this.prevDownlinkStats.packetsLost)return this.setProbeState("Not Probing"),this.lastUpgradeRateKbps=0,r;if(i||1===r)switch(this.rateProbeState){case"Not Probing":this.setProbeState("Probe Pending");break;case"Probe Pending":this.setProbeState("Probing")&&(this.upgradeToStream(e,n),r=0)}else this.setProbeState("Not Probing");return r}calculateSubscribeRate(e){let t=0;for(const n of e)this.pausedStreamIds.contain(n.streamId)||this.pausedBwAttendeeIds.has(n.attendeeId)||(t+=n.maxBitrateKbps);return t}handleAppPausedStreams(e,t){if(!this.tileController)return void this.logger.warn("tileController not found!");this.pausedStreamIds=new m.default;const n=this.tileController.getAllRemoteVideoTiles();for(const i of n){const n=i.state();if(n.paused&&!this.pausedBwAttendeeIds.has(n.boundAttendeeId)){let i=t.length;for(;i--;)t[i].attendeeId===n.boundAttendeeId&&(this.logger.info("bwe: removed paused attendee "+n.boundAttendeeId+" streamId: "+t[i].streamId),this.pausedStreamIds.add(t[i].streamId),this.subscribedReceiveSet.contain(t[i].streamId)&&e.push(t[i]),t.splice(i,1))}}}processBwPausedStreams(e,t){if(!this.tileController)return void this.logger.warn("tileController not found!");const n=this.getCurrentVideoPreferences();if(n&&this.shouldPauseTiles){const i=this.tileController.getAllVideoTiles();for(const r of n){const n=this.getVideoTileForAttendeeId(r.attendeeId,i),a=(null==n?void 0:n.state().paused)||!1;if(t.some((e=>e.attendeeId===r.attendeeId)))a&&this.pausedBwAttendeeIds.has(r.attendeeId)&&(this.logger.info(`bwe: unpausing attendee ${r.attendeeId} due to bandwidth`),this.forEachObserver((e=>{e.tileWillBeUnpausedByDownlinkPolicy(n.id())})),this.tileController.unpauseVideoTile(n.id()),this.pausedBwAttendeeIds.delete(r.attendeeId));else{const i=e.some((e=>e.attendeeId===r.attendeeId));if(n&&i){const e=this.optimalReceiveStreams.find((e=>e.attendeeId===r.attendeeId));void 0!==e&&(a||(this.logger.info(`bwe: pausing streamId ${e.streamId} attendee ${r.attendeeId} due to bandwidth`),this.forEachObserver((e=>{e.tileWillBePausedByDownlinkPolicy(n.id())})),this.tileController.pauseVideoTile(n.id())),t.push(e)),this.pausedBwAttendeeIds.add(r.attendeeId)}else if(i){const e=this.tileController.addVideoTile();e.bindVideoStream(r.attendeeId,!1,null,0,0,0,null),this.forEachObserver((t=>{t.tileWillBePausedByDownlinkPolicy(e.id())})),e.pause(),this.logger.info(`bwe: Created video tile ${e.id()} for bw paused attendee ${r.attendeeId}`),this.pausedBwAttendeeIds.add(r.attendeeId)}}}}}cleanBwPausedTiles(e){if(!this.tileController)return void this.logger.warn("tileController not found!");const t=this.tileController.getAllRemoteVideoTiles(),n=this.getCurrentVideoPreferences();for(const i of t){const t=i.state();t.boundVideoStream||(e.some((e=>e.attendeeId===t.boundAttendeeId))?void 0===n||n.some((e=>e.attendeeId===t.boundAttendeeId))||this.tileController.removeVideoTile(t.tileId):(this.tileController.removeVideoTile(t.tileId),this.logger.info(`bwe: Removed video tile ${t.tileId} for bw paused attendee ${t.boundAttendeeId}`)))}}priorityPolicy(e,t,n){let i;const r=this.getCurrentVideoPreferences(),a=r.highestPriority();let o,s=a;for(;-1!==s;){o=-1;for(const a of r)if(a.priority===s)for(const r of t)r.attendeeId===a.attendeeId&&(n.some((e=>e.groupId===r.groupId))||(e.chosenTotalBitrate+r.avgBitrateKbps<=e.targetDownlinkBitrate?(n.push(r),e.chosenTotalBitrate+=r.avgBitrateKbps):0===e.deltaToNextUpgrade&&(e.deltaToNextUpgrade=r.avgBitrateKbps,i=r)));else if(a.priority>s){o=a.priority;break}for(const a of r)if(a.priority===s){for(const r of t)if(r.attendeeId===a.attendeeId){const o=n.findIndex((e=>e.groupId===r.groupId&&e.maxBitrateKbps<=r.maxBitrateKbps&&e.avgBitrateKbpss)break;if(s===a&&0!==e.deltaToNextUpgrade)break;s=o}return i}getVideoTileForAttendeeId(e,t){for(const n of t)if(n.state().boundAttendeeId===e)return n;return null}canUpgrade(e,t,n,i){let r=!1;return(t===g.default.High||!i&&e<=n||i&&t===g.default.Medium&&e<=n)&&(r=!0),r?(this.logger.info(`bwe: canUpgrade: bitrateKbps: ${e} targetBitrateKbps: ${n}`),!0):(this.logger.info(`bwe: cannot Upgrade: bitrateKbps: ${e} targetBitrateKbps: ${n}`),!1)}hasSimulcastStreams(e,t,n){let i=0;for(const r of e)r.attendeeId===t&&r.groupId===n&&i++;return this.logger.info(`bwe: attendeeId: ${t} groupId: ${n} hasSimulcastStreams: streamCount: ${i}`),i>1}streamsWithPreferenceDidChange(e){if(void 0===this.previousStreamsWithPreference||e.length!==this.previousStreamsWithPreference.length||!0===this.videoPreferencesUpdated)return!0;for(const t of e)if(void 0===this.previousStreamsWithPreference.find((e=>e.groupId===t.groupId&&e.streamId===t.streamId&&e.maxBitrateKbps===t.maxBitrateKbps)))return!0;return!1}chosenStreamsSameAsLast(e){if(this.optimalNonPausedReceiveStreams.length!==e.length)return!1;for(const t of this.optimalNonPausedReceiveStreams)if(!e.some((e=>e.streamId===t.streamId)))return!1;return!0}policyStateLogStr(e,t){const n={targetBitrate:t,subscribedRate:this.calculateSubscribeRate(this.optimalReceiveStreams),probeState:this.rateProbeState,startupPeriod:this.startupPeriod};let i="remoteInfos: [";for(const t of e)i+=`{grpId:${t.groupId} strId:${t.streamId} maxBr:${t.maxBitrateKbps} avgBr:${t.avgBitrateKbps}}, `;i+="]";let r=`bwe: optimalReceiveSet ${JSON.stringify(n)}\nbwe: prev ${JSON.stringify(this.prevDownlinkStats)}\nbwe: now ${JSON.stringify(this.downlinkStats)}\nbwe: ${i}\n`;return(this.pausedStreamIds.size()>0||this.pausedBwAttendeeIds.size>0)&&(r+=`bwe: paused: app stream ids ${JSON.stringify(this.pausedStreamIds)} bw attendees { ${Array.from(this.pausedBwAttendeeIds).join(" ")} }\n`),this.videoPreferences?r+=`bwe: preferences: ${JSON.stringify(this.videoPreferences)}`:r+=`bwe: default preferences: ${JSON.stringify(this.defaultVideoPreferences)}`,r}getCurrentVideoPreferences(){return this.videoPreferences||this.defaultVideoPreferences}getServerSideNetworkAdaption(){return this.serverSideNetworkAdaption}setServerSideNetworkAdaption(e){this.serverSideNetworkAdaption=e,this.setProbeState("Not Probing")}supportedServerSideNetworkAdaptions(){return[f.default.None,f.default.BandwidthProbing,f.default.BandwidthProbingAndRemoteVideoQualityAdaption]}getVideoPreferences(){let e=this.getCurrentVideoPreferences();return e||(e=b.VideoPreferences.prepare().build()),e}wantsAllTemporalLayersInIndex(){return!0}}t.default=w,w.DEFAULT_BANDWIDTH_KBPS=2800,w.STARTUP_PERIOD_MS=6e3,w.LARGE_RATE_CHANGE_TRIGGER_PERCENT=20,w.TARGET_RATE_CHANGE_TRIGGER_PERCENT=15,w.LOW_BITRATE_THRESHOLD_KBPS=300,w.MIN_TIME_BETWEEN_PROBE_MS=5e3,w.MIN_TIME_BETWEEN_SUBSCRIBE_MS=2e3,w.MAX_HOLD_BEFORE_PROBE_MS=3e4,w.MAX_ALLOWED_PROBE_TIME_MS=6e4,w.SPURIOUS_PACKET_LOST_THRESHOLD=2,w.USED_BANDWIDTH_OVERRIDE_BUFFER_KBPS=100},7405:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(980));class a{constructor(e=0,t=0){this.networkIssueResponseDelayFactor=e,this.networkIssueRecoveryDelayFactor=t,this.currentNetworkEvent=0,this.bandwidthDecreaseTimestamp=0,this.referenceBitrate=0,this.serverSideNetworkAdaption=r.default.Default,e<0?e=0:e>1&&(e=1),this.networkIssueResponseDelayFactor=e,t<0?t=0:t>1&&(t=1),this.networkIssueRecoveryDelayFactor=t}allowSubscribe(e,t){let n=0;const i=this.currentNetworkEvent;if(t>this.referenceBitrate)return this.currentNetworkEvent=2,this.referenceBitrate=t,!0;if(tn)return this.referenceBitrate=t,!0;return!1}return this.currentNetworkEvent=0,!1}getSubscribeDelay(e,t){let n=a.MINIMUM_DELAY_MS;const i=a.MAXIMUM_DELAY_MS-a.MINIMUM_DELAY_MS,r=this.networkIssueResponseDelayFactor;return 1===e&&(n+=i*r*(1+t/10),n=Math.min(a.MAXIMUM_DELAY_MS,n)),n}}t.default=a,a.MINIMUM_DELAY_MS=2e3,a.MAXIMUM_DELAY_MS=8e3,a.Default=new a(0,0),a.UnstableNetworkPreset=new a(0,1),a.StableNetworkPreset=new a(1,0)},1583:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.VideoQualityAdaptationPreference=void 0,function(e){e[e.Balanced=0]="Balanced",e[e.MaintainFramerate=1]="MaintainFramerate",e[e.MaintainResolution=2]="MaintainResolution"}(n=t.VideoQualityAdaptationPreference||(t.VideoQualityAdaptationPreference={})),t.default=n},6751:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{create(){const e={clientWidth:400,clientHeight:300,width:400,height:300,videoWidth:400,videoHeight:300,style:{transform:""},hasAttribute:()=>!1,removeAttribute:()=>{},setAttribute:()=>{},srcObject:!1,paused:!0,pause:()=>{e.paused=!0},play:()=>(e.paused=!1,Promise.resolve())};return e}}},2245:function(e,t){"use strict";var n=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e){this.canvas=e,this.destroyed=!1}destroy(){this.canvas=null,this.destroyed=!0}asCanvasImageSource(){return n(this,void 0,void 0,(function*(){return this.destroyed?Promise.reject("canvas buffer is destroyed"):Promise.resolve(this.canvas)}))}asCanvasElement(){return this.canvas}}},6930:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(2245)),o=r(n(6603));t.default=class{constructor(e,t,n=new o.default){this.logger=e,this.stages=t,this.fr=15,this.outputMediaStream=new MediaStream,this.videoInput=document.createElement("video"),this.canvasOutput=document.createElement("canvas"),this.outputCtx=this.canvasOutput.getContext("2d"),this.canvasInput=document.createElement("canvas"),this.inputCtx=this.canvasInput.getContext("2d"),this.inputVideoStream=null,this.sourceBuffers=[],this.destBuffers=[],this.observers=new Set,this.hasStarted=!1,this.process=e=>i(this,void 0,void 0,(function*(){if(!this.inputVideoStream)return;const e=performance.now();this.videoInput.videoWidth&&(this.canvasInput.width!==this.videoInput.videoWidth&&(this.canvasInput.width=this.videoInput.videoWidth,this.canvasInput.height=this.videoInput.videoHeight,this.sourceBuffers[0].height=this.canvasInput.height,this.sourceBuffers[0].width=this.canvasInput.width,this.sourceBuffers[0].framerate=this.framerate),this.inputCtx.drawImage(this.videoInput,0,0));let t,n=[];n.push(this.sourceBuffers[0]);try{for(const e of this.processors)n=yield e.process(n)}catch(e){return void this.forEachObserver((e=>{e.processingDidFailToStart&&e.processingDidFailToStart()}))}this.destBuffers=n;try{t=yield this.destBuffers[0].asCanvasImageSource()}catch(e){return void(this.inputVideoStream&&(this.logger.info("buffers are destroyed and pipeline could not start"),this.forEachObserver((e=>{e.processingDidFailToStart&&e.processingDidFailToStart()}))))}const i=t.width,r=t.height;0!==i&&0!==r&&(this.canvasOutput.width!==i&&this.canvasOutput.height!==r&&(this.canvasOutput.width=i,this.canvasOutput.height=r),this.outputCtx.drawImage(t,0,0,i,r,0,0,i,r),this.hasStarted||(this.hasStarted=!0,this.forEachObserver((e=>{e.processingDidStart&&e.processingDidStart()}))));const a=performance.now()-e,o=2e3/this.framerate-a,s=Math.max(0,1e3/this.framerate-a);o<=0&&this.forEachObserver((e=>{e.processingLatencyTooHigh&&e.processingLatencyTooHigh(a)})),yield this.timer.start(s,this.process.bind(this))})),this.timer=n}destroy(){if(this.stop(),this.stages)for(const e of this.stages)e.destroy();this.timer.destroy()}get framerate(){return this.fr}set framerate(e){this.fr=e<0?15:e}stop(){if(this.videoInput.removeEventListener("loadedmetadata",this.process),this.videoInput.srcObject=null,this.destroyInputMediaStreamAndBuffers(),this.outputMediaStream)for(const e of this.outputMediaStream.getVideoTracks())e.stop();this.hasStarted&&(this.hasStarted=!1,this.forEachObserver((e=>{e.processingDidStop&&e.processingDidStop()})))}addObserver(e){this.observers.add(e)}removeObserver(e){this.observers.delete(e)}getInputMediaStream(){return i(this,void 0,void 0,(function*(){return this.inputVideoStream}))}getActiveOutputMediaStream(){return this.isOutputMediaStreamActive()||(this.outputMediaStream=this.canvasOutput.captureStream(this.framerate),this.cloneInputAudioTracksToOutput()),this.outputMediaStream}setInputMediaStream(e){return i(this,void 0,void 0,(function*(){if(!e)return void this.stop();if(0===e.getVideoTracks().length)return void this.logger.error("No video tracks in input media stream, ignoring");this.inputVideoStream=e;const t=this.inputVideoStream.getVideoTracks()[0].getSettings();this.logger.info(`processing pipeline input stream settings ${JSON.stringify(t)}`),this.canvasOutput.width=t.width,this.canvasOutput.height=t.height,this.videoInput.addEventListener("loadedmetadata",this.process),this.videoInput.srcObject=this.inputVideoStream,this.videoInput.setAttribute("playsinline","true");const n=new a.default(this.canvasInput);this.sourceBuffers.push(n),this.videoInput.load();try{yield this.videoInput.play()}catch(e){this.logger.warn("Video element play() overrided by another load().")}this.cloneInputAudioTracksToOutput()}))}cloneInputAudioTracksToOutput(){if(this.isOutputMediaStreamActive()&&null!==this.inputVideoStream){for(const e of this.outputMediaStream.getAudioTracks())this.logger.info(`Removing audio track ${e.id} from output stream`),this.outputMediaStream.removeTrack(e);for(const e of this.inputVideoStream.getAudioTracks())this.logger.info(`Adding audio track ${e.id} to output stream`),this.outputMediaStream.addTrack(e)}else this.logger.info("Not cloning input audio tracks to output, do not have media streams ready")}isOutputMediaStreamActive(){return this.outputMediaStream&&this.outputMediaStream.active}set processors(e){this.stages=e}get processors(){return this.stages}forEachObserver(e){for(const t of this.observers)setTimeout((()=>{e(t)}),0)}destroyInputMediaStreamAndBuffers(){if(this.inputVideoStream)for(const e of this.inputVideoStream.getTracks())e.stop();this.inputVideoStream=null;for(const e of this.sourceBuffers)e.destroy();this.sourceBuffers=[]}}},6603:function(e,t){"use strict";var n=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.workerTimer=void 0,this.callback=void 0,this.workerTimer=this.createWorkerTimer()}createWorkerTimer(){try{const e=new Blob(["self.onmessage = async function(e){ \n var timerID = null;\n const awaitTimeout = delay => new Promise( resolve => {\n timerID = setTimeout(resolve, delay);\n })\n await awaitTimeout(e.data);\n postMessage(timerID);\n }"],{type:"application/javascript"});return new Worker(window.URL.createObjectURL(e))}catch(e){}}start(e,t){return n(this,void 0,void 0,(function*(){this.callback=t,this.workerTimer?(this.workerTimer.onmessage=e=>{this.lastTimeout=e.data,this.callback()},this.workerTimer.postMessage(e)):this.lastTimeout=setTimeout((()=>{this.callback()}),e)}))}destroy(){return n(this,void 0,void 0,(function*(){this.callback=void 0,this.lastTimeout&&(clearTimeout(this.lastTimeout),this.lastTimeout=void 0),this.workerTimer&&(this.workerTimer.terminate(),this.workerTimer=void 0)}))}}},1729:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(6244)),o=r(n(6930));class s{constructor(e,t,n,i=new a.default){this.logger=e,this.device=t,this.processors=n,this.browserBehavior=i,this.observers=new Set,this.pipe=new o.default(this.logger,this.processors),this.pipe.addObserver(this)}get outputMediaStream(){return this.pipe.outputMediaStream}passEventControllerToProcessors(e){if(this.pipe.processors)for(const t of this.pipe.processors)"function"==typeof t.setEventController&&t.setEventController(e)}chooseNewInnerDevice(e){const t=new s(this.logger,e,this.processors,this.browserBehavior);return t.pipe=this.pipe,t}getInnerDevice(){return this.device}intrinsicDevice(){return i(this,void 0,void 0,(function*(){return this.device}))}transformStream(e){return i(this,void 0,void 0,(function*(){return yield this.pipe.setInputMediaStream(e),this.inputMediaStream=e,this.pipe.getActiveOutputMediaStream()}))}onOutputStreamDisconnect(){this.logger.info("DefaultVideoTransformDevice: detach stopping input media stream");const e=this.device&&this.device.id;if(this.pipe.stop(),!e&&this.inputMediaStream)for(const e of this.inputMediaStream.getVideoTracks())e.stop()}stop(){return i(this,void 0,void 0,(function*(){if(this.inputMediaStream)for(const e of this.inputMediaStream.getVideoTracks())e.stop();this.pipe.destroy(),this.inputMediaStream=null}))}addObserver(e){this.observers.add(e)}removeObserver(e){this.observers.delete(e)}processingDidStart(){this.logger.info("video transform device processing started"),this.forEachObserver((e=>{e.processingDidStart&&e.processingDidStart()}))}processingLatencyTooHigh(e){this.forEachObserver((t=>{t.processingLatencyTooHigh&&t.processingLatencyTooHigh(e)}))}processingDidFailToStart(){this.logger.info("video transform device processing failed to start"),this.forEachObserver((e=>{e.processingDidFailToStart&&e.processingDidFailToStart()}))}processingDidStop(){this.logger.info("video transform device processing stopped"),this.forEachObserver((e=>{e.processingDidStop&&e.processingDidStop()}))}forEachObserver(e){for(const t of this.observers)setTimeout((()=>{e(t)}),0)}}t.default=s},255:function(e,t){"use strict";var n=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{process(e){return n(this,void 0,void 0,(function*(){return e}))}destroy(){return n(this,void 0,void 0,(function*(){}))}}},7530:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DeferredPromise=void 0,t.DeferredPromise=class{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}getPromise(){return this.promise}resolvePromise(e){this.resolve(e)}resolveAndReplacePromise(e){this.resolve(e),this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}rejectPromise(e){this.reject(e)}rejectAndReplacePromise(e){this.reject(e),this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}},2232:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.VideoFxCanvasOpsManager=void 0;const r=n(6938);t.VideoFxCanvasOpsManager=class{constructor(e,t){this.streamParameters=e,this.outputCanvas=t,this.configureCanvasPipeline()}getInferenceInputData(e){return this.inferenceCtx.save(),this.inferenceCtx.scale(this.horizontalResizeScalar,this.verticalResizeScalar),this.inferenceCtx.drawImage(e,0,0),this.inferenceCtx.restore(),this.inferenceCtx.getImageData(0,0,r.SEGMENTATION_MODEL.WIDTH_IN_PIXELS,r.SEGMENTATION_MODEL.HEIGHT_IN_PIXELS)}configureForStreamParameters(e){return i(this,void 0,void 0,(function*(){if(this.streamParameters=e,this.outputCanvas.width=this.streamParameters.width,this.outputCanvas.height=this.streamParameters.height,this.backgroundReplacementCanvas){const e=document.createElement("canvas");e.width=this.streamParameters.width,e.height=this.streamParameters.height,e.getContext("2d").drawImage(this.backgroundReplacementCanvas,0,0,this.streamParameters.width,this.streamParameters.height),this.backgroundReplacementCanvas=e}this.configureCanvasPipeline()}))}configureCanvasPipeline(){this.inferenceCanvas=document.createElement("canvas"),this.inferenceCtx=this.inferenceCanvas.getContext("2d",{willReadFrequently:!0}),this.inferenceCanvas.width=r.SEGMENTATION_MODEL.WIDTH_IN_PIXELS,this.inferenceCanvas.height=r.SEGMENTATION_MODEL.HEIGHT_IN_PIXELS,this.horizontalResizeScalar=r.SEGMENTATION_MODEL.WIDTH_IN_PIXELS/this.streamParameters.width,this.verticalResizeScalar=r.SEGMENTATION_MODEL.HEIGHT_IN_PIXELS/this.streamParameters.height}getBackgroundReplacementCanvas(){return this.backgroundReplacementCanvas}loadReplacementBackground(e){return i(this,void 0,void 0,(function*(){const t=e.backgroundReplacement.backgroundImageURL,n=e.backgroundReplacement.defaultColor;if(t)try{const e=yield this.loadImage(t);this.backgroundReplacementImage=e,this.resizeAndSetReplacementImage(this.backgroundReplacementImage)}catch(e){throw this.logger.error(e),new Error("Failed to set the replacement image.")}else this.resizeAndSetReplacementColor(n)}))}resizeAndSetReplacementImage(e){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=this.streamParameters.width,t.height=this.streamParameters.height,n.drawImage(e,0,0,this.streamParameters.width,this.streamParameters.height),this.backgroundReplacementCanvas=t}resizeAndSetReplacementColor(e){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=this.streamParameters.width,t.height=this.streamParameters.height,n.fillStyle=e,n.fillRect(0,0,this.streamParameters.width,this.streamParameters.height),this.backgroundReplacementCanvas=t}loadImage(e){return i(this,void 0,void 0,(function*(){const t=yield fetch(e).catch((e=>{throw this.logger.error(e.toString()),new Error("Failed to fetch image.")})),n=yield t.blob(),i=new Image;return i.src=URL.createObjectURL(n),new Promise(((e,t)=>{i.onload=()=>{e(i)},i.onerror=e=>{t(e)}}))}))}}},6938:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FXLIB_PATH=t.WORKER_PATH=t.CDN_BASE_PATH=t.RESOURCE_CONSTRAINTS=t.SEGMENTATION_MODEL=t.DEFAULT_STREAM_PARAMETERS=t.WORKER_MSG=void 0,t.WORKER_MSG={BUILD_ENGINE_REQUEST:"BuildEngineRequest",BUILD_ENGINE_RESPONSE:"BuildEngineResponse",PERFORM_SEGMENTATION_REQUEST:"PerformSegmentationRequest",PERFORM_SEGMENTATION_RESPONSE:"PerformSegmentationResponse",PERFORM_SEGMENTATION_SAB_REQUEST:"PerformSegmentationSABRequest",PERFORM_SEGMENTATION_SAB_RESPONSE:"PerformSegmentationSABResponse",DESTROY_ASSETS_REQUEST:"DestroyAssetsRequest",DESTROY_ASSETS_RESPONSE:"DestroyAssetsResponse",CLOSE_WORKER_REQUEST:"CloseWorkerRequest"},t.DEFAULT_STREAM_PARAMETERS={FRAMES_PER_SECOND:15,WIDTH_IN_PIXEL:960,HEIGHT_IN_PIXEL:540,CHANNEL_COUNT:4},t.SEGMENTATION_MODEL={LOAD_SUCCESS:2,WIDTH_IN_PIXELS:176,HEIGHT_IN_PIXELS:160},t.RESOURCE_CONSTRAINTS={DEFAULT_PROCESSING_BUDGET_PER_FRAME:50,SEGMENTATION_DEFAULT_FRAMES_PER_SEGMENTATION:1,SEGMENTATION_SAMPLING_PERIOD_FRAME_COUNT:500,BLUR_DEFAULT_CYCLE_PERCENTAGE:10,BLUR_SAMPLING_PERIOD_FRAME_COUNT:1e3,MIN_PROCESSING_BUDGET:0,MAX_PROCESSING_BUDGET:100},t.CDN_BASE_PATH="https://static.sdkassets.chime.aws";const n="/ml_media_fx/otherassets";t.WORKER_PATH=`${n}/worker.js`,t.FXLIB_PATH=`${n}/fxlib.js`},3239:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=n(9019),o=n(1364),s=n(5128),c=r(n(6244)),l=r(n(5785)),d=n(9979),u=r(n(6741)),f=r(n(2245)),h=n(7530),m=n(2232),p=n(6938),g=n(696);class v{constructor(e,t=p.RESOURCE_CONSTRAINTS.DEFAULT_PROCESSING_BUDGET_PER_FRAME,n){this.logger=e,this.outputCanvas=document.createElement("canvas"),this.canvasVideoFrameBuffer=new f.default(this.outputCanvas);try{this.validateProcessingBudgetPerFrame(t)}catch(e){throw this.logger.error(e),new Error(`Cannot instantiate VideoFxProcessor due to invalid processingBudgetPerFrame of ${t}`)}n&&(this.eventController=n),this.effectConfig={backgroundBlur:{isEnabled:!1,strength:"low"},backgroundReplacement:{isEnabled:!1,backgroundImageURL:null,defaultColor:"black"}},this.segmentationRequestPromise=new h.DeferredPromise,this.segmentationRateManager=new g.VideoFxSegmentationRateManager(this.logger,t),this.streamParameters={framerate:p.DEFAULT_STREAM_PARAMETERS.FRAMES_PER_SECOND,width:p.DEFAULT_STREAM_PARAMETERS.WIDTH_IN_PIXEL,height:p.DEFAULT_STREAM_PARAMETERS.HEIGHT_IN_PIXEL,channels:p.DEFAULT_STREAM_PARAMETERS.CHANNEL_COUNT},v.isSharedArrayBufferSupported&&(this.sharedImageBuffer=new SharedArrayBuffer(p.SEGMENTATION_MODEL.WIDTH_IN_PIXELS*p.SEGMENTATION_MODEL.HEIGHT_IN_PIXELS*this.streamParameters.channels),this.sharedImageData=new Uint8ClampedArray(this.sharedImageBuffer)),this.logger.info(`VideoFx supports Shared Array Buffer: ${v.isSharedArrayBufferSupported}`),this.canvasOpsManager=new m.VideoFxCanvasOpsManager(this.streamParameters,this.outputCanvas),this.outputCanvas.width=this.streamParameters.width,this.outputCanvas.height=this.streamParameters.height,this.segmentationMask=new ImageData(this.streamParameters.width,this.streamParameters.height),this.logger.info(`VideoFxProcessor instantiated with a processingBudgetPerFrame of ${t}`)}process(e){return i(this,void 0,void 0,(function*(){return e}))}fxProcess(e){return i(this,void 0,void 0,(function*(){const t=e[0].asCanvasElement();this.didStreamParametersChange(t)&&(yield this.adjustProcessorForNewStreamParameters(t));try{yield this.manageSegmentationMask(t)}catch(e){throw this.logger.error(e),new Error("Video stream could not be processed")}return yield this.renderer.render(t,this.segmentationMask),e[0]=this.canvasVideoFrameBuffer,e}))}noOpProcess(e){return i(this,void 0,void 0,(function*(){return e}))}didStreamParametersChange(e){return e.width!==this.streamParameters.width||e.height!==this.streamParameters.height}adjustProcessorForNewStreamParameters(e){return i(this,void 0,void 0,(function*(){this.streamParameters.width=e.width,this.streamParameters.height=e.height,yield this.canvasOpsManager.configureForStreamParameters(this.streamParameters),yield this.renderer.configure(this.streamParameters.width,this.streamParameters.height,this.effectConfig)}))}destroy(){return i(this,void 0,void 0,(function*(){this.canvasVideoFrameBuffer.destroy(),this.fxLibScript&&this.fxLibScript.parentNode&&this.fxLibScript.parentNode.removeChild(this.fxLibScript),this.engineWorker&&(this.destroyedAssetsPromise=new h.DeferredPromise,this.engineWorker.postMessage({msg:p.WORKER_MSG.DESTROY_ASSETS_REQUEST}),yield this.destroyedAssetsPromise.getPromise(),this.engineWorker.postMessage({msg:p.WORKER_MSG.CLOSE_WORKER_REQUEST})),this.logger.info("VideoFxProcessor destroyed.")}))}manageSegmentationMask(e){return i(this,void 0,void 0,(function*(){try{if(this.segmentationRateManager.submitFrame(),this.segmentationRateManager.shouldApplySegmentation()){this.segmentationRateManager.startSegmentation();const t=this.canvasOpsManager.getInferenceInputData(e);this.segmentationMask=yield this.generateSegmentationMask(t),this.segmentationRateManager.completeSegmentation()}}catch(e){throw this.logger.error(e.toString()),new Error("Can not properly manage the returned segmentation mask")}}))}generateSegmentationMask(e){return i(this,void 0,void 0,(function*(){v.isSharedArrayBufferSupported?(this.sharedImageData.set(e.data),this.engineWorker.postMessage({msg:p.WORKER_MSG.PERFORM_SEGMENTATION_SAB_REQUEST,payload:this.sharedImageBuffer})):this.engineWorker.postMessage({msg:p.WORKER_MSG.PERFORM_SEGMENTATION_REQUEST,payload:e},[e.data.buffer]);try{return yield this.segmentationRequestPromise.getPromise()}catch(e){throw this.logger.error(e.toString()),new Error("Segmentation mask could not be generated")}}))}cloneConfigFrom(e){return{backgroundBlur:{isEnabled:e.backgroundBlur.isEnabled,strength:e.backgroundBlur.strength},backgroundReplacement:{isEnabled:e.backgroundReplacement.isEnabled,backgroundImageURL:e.backgroundReplacement.backgroundImageURL,defaultColor:e.backgroundReplacement.defaultColor}}}setEffectConfig(e){return i(this,void 0,void 0,(function*(){if(this.sameVideoFxConfig(e,this.effectConfig))return;const t=this.cloneConfigFrom(e);try{yield this.validateEffectConfig(t)}catch(e){throw this.logger.error(e.toString()),new Error("Provided effect config is invalid, not updating VideoFxProcessor")}t.backgroundReplacement.isEnabled&&(yield this.canvasOpsManager.loadReplacementBackground(t),yield this.renderer.setBackgroundReplacementCanvas(this.canvasOpsManager.getBackgroundReplacementCanvas())),yield this.renderer.configure(this.streamParameters.width,this.streamParameters.height,t),this.effectConfig=t,this.effectConfig.backgroundBlur.isEnabled||this.effectConfig.backgroundReplacement.isEnabled?this.process=this.fxProcess:this.process=this.noOpProcess,this.logger.info(`VideoFxProcessor effect configuration updated to: ${JSON.stringify(this.effectConfig)}`),this.eventController&&this.publishVideoFxConfigEvent()}))}validateEffectConfig(e){return i(this,void 0,void 0,(function*(){if(e.backgroundBlur.isEnabled&&e.backgroundReplacement.isEnabled)throw new Error("Invalid VideoFx configuration: Background Blur and Background Replacement can not both be enabled");e.backgroundReplacement.isEnabled&&(yield this.validateReplacementConfig(e))}))}validateReplacementConfig(e){return i(this,void 0,void 0,(function*(){if(e.backgroundReplacement.backgroundImageURL&&e.backgroundReplacement.defaultColor)throw new Error("Invalid VideoFx configuration: Background Replacement can not have both an image URL and default color");if(!e.backgroundReplacement.backgroundImageURL&&!e.backgroundReplacement.defaultColor)throw new Error("Invalid VideoFx configuration: Background Replacement image URL and default can not both be null/undefined");try{e.backgroundReplacement.backgroundImageURL&&(yield this.canvasOpsManager.loadImage(e.backgroundReplacement.backgroundImageURL))}catch(e){throw this.logger.error(e.toString()),new Error("Invalid VideoFx configuration: backgroundImageURL failed to load")}const t=e.backgroundReplacement.defaultColor;if(t&&"black"!==t&&"#000000"!==t&&"#000"!==t){if(t.includes("#")&&!new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/).test(t))throw new Error(`Invalid hexadecimal color code for default replacement background: ${t}`);const e=document.createElement("canvas").getContext("2d"),n=e.fillStyle;if(e.fillStyle=t,e.fillStyle===n)throw new Error(`Invalid color for default replacement background: ${t}`)}}))}validateProcessingBudgetPerFrame(e){if(ep.RESOURCE_CONSTRAINTS.MAX_PROCESSING_BUDGET)throw new Error(`Invalid resource constraint: cycle percentage must be within range of ${p.RESOURCE_CONSTRAINTS.MIN_PROCESSING_BUDGET} and ${p.RESOURCE_CONSTRAINTS.MAX_PROCESSING_BUDGET}`)}loadAssets(){return i(this,void 0,void 0,(function*(){this.logger.info("Loading required assets for the VideoFxProcessor");try{const e=this.getVideoFxAssetParams();yield this.loadEngineWorker(e),yield this.buildEngine(e),yield this.loadFxLib(e),this.renderer=constructRenderer(p.SEGMENTATION_MODEL.WIDTH_IN_PIXELS,p.SEGMENTATION_MODEL.HEIGHT_IN_PIXELS,this.effectConfig,this.outputCanvas)}catch(e){throw this.logger.error(e.toString()),new Error("Failed to load necessary assets for the VideoFxProcessor")}this.logger.info("Finished loading of essential VideoFxProcessor assets.")}))}getVideoFxAssetParams(){const e=d.getDefaultAssetSpec();return{assetGroup:e.assetGroup,revisionID:e.revisionID,sdk:encodeURIComponent(u.default.sdkVersion),ua:encodeURIComponent(u.default.sdkUserAgentLowResolution)}}getPathFromVideoFxAssetParams(e,t){const n=new URL(e);for(const[e,i]of Object.entries(t))if(void 0!==i){const t=encodeURIComponent(e),r=encodeURIComponent(i);n.searchParams.set(t,r)}return n.toString()}loadEngineWorker(e){return i(this,void 0,void 0,(function*(){try{const t=this.getPathFromVideoFxAssetParams(p.CDN_BASE_PATH+p.WORKER_PATH,e);this.engineWorker=yield o.loadWorker(t,"VideoFxEngineWorker",{},null),this.logger.info("Successfully loaded the VideoFxProcessor's engine worker"),this.engineWorker.addEventListener("message",(e=>this.engineWorkerReceiver(e)))}catch(e){throw this.logger.error(e.toString()),new Error("Failed to load the VideoFxProcessor's engine worker")}}))}buildEngine(e){return i(this,void 0,void 0,(function*(){this.buildEnginePromise=new h.DeferredPromise,this.engineWorker.postMessage({msg:p.WORKER_MSG.BUILD_ENGINE_REQUEST,payload:{cdnBasePath:p.CDN_BASE_PATH,sdkVersioningParams:e}});try{yield this.buildEnginePromise.getPromise()}catch(e){throw this.logger.error(e.toString()),new Error("Failed to instantiate the VideoFxEngine")}}))}loadFxLib(e){return i(this,void 0,void 0,(function*(){const t=this.getPathFromVideoFxAssetParams(p.CDN_BASE_PATH+p.FXLIB_PATH,e),n={method:"GET",mode:"cors",credentials:"omit",redirect:"follow",referrerPolicy:"no-referrer"};try{const e=yield a.fetchWithBehavior(t,n,{});if(!e.ok)throw new Error("Fetch failed.");const i=window.URL.createObjectURL(yield e.blob());yield new Promise(((e,t)=>{this.fxLibScript=document.createElement("script"),this.fxLibScript.setAttribute("src",i),this.fxLibScript.setAttribute("type","module"),this.fxLibScript.setAttribute("async","false"),this.fxLibScript.addEventListener("load",e),this.fxLibScript.addEventListener("error",t),document.body.appendChild(this.fxLibScript)}))}catch(e){throw this.logger.error(e.toString()),new Error("Failed to load the fxlib")}}))}getEffectConfig(){return this.cloneConfigFrom(this.effectConfig)}engineWorkerReceiver(e){const t=e.data;switch(t.msg){case p.WORKER_MSG.BUILD_ENGINE_RESPONSE:this.settleEngineBuildPromise(t.payload);break;case p.WORKER_MSG.PERFORM_SEGMENTATION_RESPONSE:this.settleSegmentationPromise(t.payload.output);break;case p.WORKER_MSG.PERFORM_SEGMENTATION_SAB_RESPONSE:this.settleSegmentationPromiseSAB();break;case p.WORKER_MSG.DESTROY_ASSETS_RESPONSE:this.destroyedAssetsPromise.resolvePromise();break;default:this.logger.info(`VideoFx worker received unknown event msg: ${JSON.stringify(t)}`)}}settleEngineBuildPromise(e){e!==p.SEGMENTATION_MODEL.LOAD_SUCCESS?this.buildEnginePromise.rejectPromise(new Error("Failed to build VideoFxProcessor's engine")):(this.logger.info("Successfully built the VideoFxEngine"),this.buildEnginePromise.resolvePromise())}settleSegmentationPromise(e){e?this.segmentationRequestPromise.resolveAndReplacePromise(e):this.segmentationRequestPromise.rejectAndReplacePromise(new Error("Failed to perform a segmentation on the input image"))}settleSegmentationPromiseSAB(){try{const e=new ImageData(new Uint8ClampedArray(this.sharedImageData),p.SEGMENTATION_MODEL.WIDTH_IN_PIXELS,p.SEGMENTATION_MODEL.HEIGHT_IN_PIXELS);this.segmentationRequestPromise.resolveAndReplacePromise(e)}catch(e){this.segmentationRequestPromise.rejectAndReplacePromise(new Error("Failed to perform a segmentation with a shared array buffer on the input image"))}}setToNoOpProcess(){this.process=this.noOpProcess}static isSupported(e=new l.default,t=!0){return i(this,void 0,void 0,(function*(){let n=!0;const r=(t,i)=>{t&&(e.info(i),n=!1)};return r("undefined"==typeof globalThis,"Browser does not have globalThis."),r(!s.supportsWorker(globalThis,e),"Browser does not support web workers."),r(!s.supportsWASM(globalThis,e),"Browser does not support wasm."),r(!document.createElement("canvas").getContext("webgl2"),"Browser does not support webgl."),r(!(new c.default).isVideoFxSupportedBrowser(),"Browser is unsupported for VideoFxProcessor"),Promise.resolve(!!n&&(yield(()=>i(this,void 0,void 0,(function*(){if(t)try{const t=new v(e);yield t.loadAssets(),yield t.destroy()}catch(t){return e.info("Browser environment is unable to access the required external assets."),Promise.resolve(!1)}return Promise.resolve(!0)})))()))}))}static create(e,t,n=p.RESOURCE_CONSTRAINTS.DEFAULT_PROCESSING_BUDGET_PER_FRAME){return i(this,void 0,void 0,(function*(){const i=new v(e,n);try{return yield i.loadAssets(),yield i.setEffectConfig(t),i}catch(t){throw e.error(t.toString()),i.setToNoOpProcess(),new Error("VideoFxProcessor built with support for only NoOp processing")}}))}setEventController(e){this.eventController?this.eventController=e:(this.eventController=e,this.publishVideoFxConfigEvent())}publishVideoFxConfigEvent(){const e={backgroundBlurEnabled:this.effectConfig.backgroundBlur.isEnabled.toString(),backgroundBlurStrength:this.effectConfig.backgroundBlur.strength,backgroundReplacementEnabled:this.effectConfig.backgroundReplacement.isEnabled.toString(),backgroundFilterVersion:2};this.eventController.publishEvent("backgroundFilterConfigSelected",e)}sameVideoFxConfig(e,t){return e.backgroundBlur.isEnabled===t.backgroundBlur.isEnabled&&e.backgroundBlur.strength===t.backgroundBlur.strength&&e.backgroundReplacement.backgroundImageURL===t.backgroundReplacement.backgroundImageURL&&e.backgroundReplacement.defaultColor===t.backgroundReplacement.defaultColor&&e.backgroundReplacement.isEnabled===t.backgroundReplacement.isEnabled}}t.default=v,v.isSharedArrayBufferSupported="undefined"!=typeof SharedArrayBuffer},696:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VideoFxSegmentationRateManager=void 0;const i=n(6938);t.VideoFxSegmentationRateManager=class{constructor(e,t){this.logger=e,this.targetSegmentationCyclePercentage=t/100,this.frameCountOverSamplingPeriod=0,this.totalSegmentationDurationOverSamplingPeriod=0,this.samplingPeriodStartTime=performance.now(),this.framesPerSegmentation=i.RESOURCE_CONSTRAINTS.SEGMENTATION_DEFAULT_FRAMES_PER_SEGMENTATION}submitFrame(){this.frameCountOverSamplingPeriod++}shouldApplySegmentation(){return this.frameCountOverSamplingPeriod%this.framesPerSegmentation==0}startSegmentation(){this.frameSegmentationStartTime=performance.now()}completeSegmentation(){this.totalSegmentationDurationOverSamplingPeriod+=performance.now()-this.frameSegmentationStartTime,this.frameCountOverSamplingPeriod>=i.RESOURCE_CONSTRAINTS.SEGMENTATION_SAMPLING_PERIOD_FRAME_COUNT&&this.adjustFramesPerSegmentation(this.totalSegmentationDurationOverSamplingPeriod/(performance.now()-this.samplingPeriodStartTime))}adjustFramesPerSegmentation(e){e>this.targetSegmentationCyclePercentage?(this.framesPerSegmentation++,this.logger.info(`Segmentation cycle percentage above the configured maximal value. Decreasing segmentation rate to 1 segmentation per ${this.framesPerSegmentation} frames`)):this.framesPerSegmentation>1&&e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{}},4996:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n{constructor(e){this.ids=new Set(e)}add(e){this.ids.add(e)}array(){return Array.from(this.ids.values()).sort(((e,t)=>e-t))}contain(e){return this.ids.has(e)}forEach(e){this.ids.forEach(e)}empty(){return 0===this.ids.size}size(){return this.ids.size}equal(e){if(!e)return 0===this.ids.size;const t=this.array(),n=e.array();if(t.length!==n.length)return!1;for(let e=0;e0&&e<1e3?1:Math.trunc(e/1e3)}remoteStreamDescriptions(){if(!this.currentIndex||!this.currentIndex.sources)return[];const e=[];return this.currentIndex.sources.forEach((t=>{const n=new o.default;n.attendeeId=t.attendeeId,n.groupId=t.groupId,n.streamId=t.streamId,n.maxBitrateKbps=t.maxBitrateKbps,n.avgBitrateKbps=this.convertBpsToKbps(t.avgBitrateBps),n.width=t.width,n.height=t.height,n.maxFrameRate=t.framerate,e.push(n)})),e}integrateUplinkPolicyDecision(e){if(e&&e.length){const t=e[0];this.videoStreamDescription.maxBitrateKbps=t.maxBitrate/1e3,this.videoStreamDescription.maxFrameRate=t.maxFramerate}}integrateIndexFrame(e){if(this.currentIndex=e,!e)return;const t=new Map;let n=!1;for(const i of e.sources){if(!t.has(i.attendeeId)){t.set(i.attendeeId,i.groupId);continue}const e=t.get(i.attendeeId);et.get(e.attendeeId)===e.groupId))),this.streamToAttendeeMap=null,this.groupIdToAttendeeMap=null,this.streamToExternalUserIdMap=null}subscribeFrameSent(){this.indexForSubscribe=this.currentIndex}integrateSubscribeAckFrame(e){this.currentSubscribeAck=e,this.subscribeTrackToStreamMap=this.buildTrackToStreamMap(this.currentSubscribeAck),this.subscribeSsrcToStreamMap=this.buildSSRCToStreamMap(this.currentSubscribeAck),this.subscribeSsrcToGroupMap=this.buildSSRCToGroupMap(this.currentSubscribeAck),this.subscribeStreamToAttendeeMap=this.buildStreamToAttendeeMap(this.indexForSubscribe),this.subscribeStreamToExternalUserIdMap=this.buildStreamExternalUserIdMap(this.indexForSubscribe),this.sendVideoStreamId=0,e.allocations&&void 0!==e.allocations&&e.allocations.length>0&&(this.sendVideoStreamId=e.allocations[0].streamId)}integrateBitratesFrame(e){if(this.currentIndex)for(const t of e.bitrates){const e=this.currentIndex.sources.find((e=>e.streamId===t.sourceStreamId));void 0!==e&&(e.avgBitrateBps=t.avgBitrateBps)}}allStreams(){const e=new a.default;if(this.currentIndex)for(const t of this.currentIndex.sources)e.add(t.streamId);return e}allVideoSendingSourcesExcludingSelf(e){const t=[],n=new Set;if(this.currentIndex&&this.currentIndex.sources&&this.currentIndex.sources.length)for(const i of this.currentIndex.sources){const{attendeeId:a,externalUserId:o,mediaType:s}=i;a!==e&&s===r.SdkStreamMediaType.VIDEO&&(n.has(a)||(t.push({attendee:{attendeeId:a,externalUserId:o}}),n.add(a)))}return t}streamSelectionUnderBandwidthConstraint(e,t,n,i){const o=new Set;if(this.currentIndex)for(const i of this.currentIndex.sources)i.attendeeId!==e&&i.mediaType===r.SdkStreamMediaType.VIDEO&&(t.has(i.attendeeId)||n.has(i.attendeeId)||o.add(i.attendeeId));const s=this.buildAttendeeToSortedStreamDescriptorMapExcludingSelf(e),c=new Map;let l=0;s.forEach(((e,t)=>{c.set(t,e[0]),l+=e[0].maxBitrateKbps})),l=this.trySelectHighBitrateForAttendees(s,t,l,i,c),this.trySelectHighBitrateForAttendees(s,o,l,i,c);const d=new a.default;for(const e of c.values())d.add(e.streamId);return d}highestQualityStreamFromEachGroupExcludingSelf(e){const t=new a.default;if(this.currentIndex){const n=new Map;for(const t of this.currentIndex.sources)t.attendeeId!==e&&t.mediaType===r.SdkStreamMediaType.VIDEO&&(!n.has(t.groupId)||t.maxBitrateKbps>n.get(t.groupId).maxBitrateKbps)&&n.set(t.groupId,t);for(const e of n.values())t.add(e.streamId)}return t}numberOfVideoPublishingParticipantsExcludingSelf(e){return this.highestQualityStreamFromEachGroupExcludingSelf(e).array().length}numberOfParticipants(){return this.currentIndex.numParticipants?this.currentIndex.numParticipants:-1}attendeeIdForTrack(e){const t=this.streamIdForTrack(e);return void 0!==t&&this.subscribeStreamToAttendeeMap?this.subscribeStreamToAttendeeMap.get(t)||(this.logger.info(`track ${e} (stream ${t}) does not correspond to a known attendee`),""):(this.logger.warn(`no attendee found for track ${e}`),"")}externalUserIdForTrack(e){const t=this.streamIdForTrack(e);return void 0!==t&&this.subscribeStreamToExternalUserIdMap?this.subscribeStreamToExternalUserIdMap.get(t)||(this.logger.info(`track ${e} (stream ${t}) does not correspond to a known externalUserId`),""):(this.logger.warn(`no external user id found for track ${e}`),"")}attendeeIdForStreamId(e){if(!this.streamToAttendeeMap){if(!this.currentIndex)return"";this.streamToAttendeeMap=this.buildStreamToAttendeeMap(this.currentIndex)}return this.streamToAttendeeMap.get(e)||(this.logger.info(`stream ID ${e} does not correspond to a known attendee`),"")}attendeeIdForGroupId(e){if(!this.groupIdToAttendeeMap){if(!this.currentIndex)return"";this.groupIdToAttendeeMap=this.buildGroupIdToAttendeeMap(this.currentIndex)}return this.groupIdToAttendeeMap.get(e)||(this.logger.info(`group ID ${e} does not correspond to a known attendee`),"")}groupIdForStreamId(e){if(this.currentIndex&&this.currentIndex.sources){for(const t of this.currentIndex.sources)if(t.streamId===e)return t.groupId;if(this.indexForSubscribe)for(const t of this.indexForSubscribe.sources)if(t.streamId===e)return t.groupId}}StreamIdsInSameGroup(e,t){return this.groupIdForStreamId(e)===this.groupIdForStreamId(t)}streamIdForTrack(e){if(this.subscribeTrackToStreamMap)return this.subscribeTrackToStreamMap.get(e)}streamIdForSSRC(e){if(this.subscribeSsrcToStreamMap)return this.subscribeSsrcToStreamMap.get(e)}overrideStreamIdMappings(e,t){if(this.subscribeTrackToStreamMap)for(const[n,i]of this.subscribeTrackToStreamMap.entries())if(e===i){this.subscribeTrackToStreamMap.set(n,t);break}if(this.subscribeSsrcToStreamMap)for(const[n,i]of this.subscribeSsrcToStreamMap.entries())if(e===i){this.subscribeSsrcToStreamMap.set(n,t);break}}groupIdForSSRC(e){if(this.subscribeSsrcToGroupMap)return this.subscribeSsrcToGroupMap.get(e)}streamsPausedAtSource(){const e=new a.default;if(this.currentIndex)for(const t of this.currentIndex.pausedAtSourceIds)e.add(t);return e}sendVideoStreamIdFromRid(e){return this.sendVideoStreamId}buildTrackToStreamMap(e){const t=new Map;this.logger.debug((()=>`trackMap ${JSON.stringify(e.tracks)}`));for(const n of e.tracks)n.trackLabel.length>0&&n.streamId>0&&t.set(n.trackLabel,n.streamId);return t}buildSSRCToStreamMap(e){const t=new Map;this.logger.debug((()=>`ssrcMap ${JSON.stringify(e.tracks)}`));for(const n of e.tracks)n.trackLabel.length>0&&n.streamId>0&&t.set(n.ssrc,n.streamId);return t}buildSSRCToGroupMap(e){const t=new Map;for(const n of e.tracks)n.trackLabel.length>0&&n.streamId>0&&t.set(n.ssrc,this.groupIdForStreamId(n.streamId));return t}buildStreamToAttendeeMap(e){const t=new Map;if(e)for(const n of e.sources)t.set(n.streamId,n.attendeeId);return t}buildGroupIdToAttendeeMap(e){const t=new Map;for(const n of e.sources)t.set(n.groupId,n.attendeeId);return t}buildStreamExternalUserIdMap(e){const t=new Map;if(e)for(const n of e.sources)n.externalUserId&&t.set(n.streamId,n.externalUserId);return t}trySelectHighBitrateForAttendees(e,t,n,i,r){for(const a of t){if(n>=i)break;if(e.has(a)){const t=e.get(a);for(const e of t.reverse())if(n-r.get(a).maxBitrateKbps+e.maxBitrateKbps{e.sort(((e,t)=>e.maxBitrateKbps>t.maxBitrateKbps?1:e.maxBitrateKbps{e.push(t.clone())})),e}integrateUplinkPolicyDecision(e){let t=!0,n=0;for(let i=0;i0&&(this._localStreamInfos[n].timeEnabled=Date.now()),this._localStreamInfos[n].maxBitrateKbps=r,this._localStreamInfos[n].maxFrameRate=a,this._localStreamInfos[n].disabledByUplinkPolicy=0===r,!0===this._localStreamInfos[n].disabledByUplinkPolicy&&(this._localStreamInfos[n].disabledByWebRTC=!1),n++;else{t=!1;const s=new o.default;s.maxBitrateKbps=r,s.maxFrameRate=a,s.disabledByUplinkPolicy=0===r,s.rid=e[i].rid,0!==r&&(s.timeEnabled=Date.now()),this._localStreamInfos.push(s),n++}}t&&this._localStreamInfos.splice(n)}integrateBitratesFrame(e){super.integrateBitratesFrame(e);const t=new Set,n=new Set(this.streamIdToBitrateKbpsMap.keys());for(const n of e.bitrates)t.add(n.sourceStreamId),this.streamIdToBitrateKbpsMap.set(n.sourceStreamId,this.convertBpsToKbps(n.avgBitrateBps));for(const e of n)t.has(e)||(this.streamIdToBitrateKbpsMap.get(e)===s.UNSEEN_STREAM_BITRATE?this.streamIdToBitrateKbpsMap.set(e,s.RECENTLY_INACTIVE_STREAM_BITRATE):this.streamIdToBitrateKbpsMap.set(e,s.NOT_SENDING_STREAM_BITRATE));for(let e=0;es.BitratesMsgFrequencyMs&&(this._localStreamInfos[e].disabledByWebRTC=!0):this._lastBitRateMsgTime-this._localStreamInfos[e].timeEnabled>s.BitratesMsgFrequencyMs&&(this._localStreamInfos[e].disabledByWebRTC=!0))}this._lastBitRateMsgTime=Date.now(),this.logLocalStreamDescriptions()}logLocalStreamDescriptions(){let e="";for(const t of this._localStreamInfos)e+=`streamId=${t.streamId} maxBitrate=${t.maxBitrateKbps} disabledByWebRTC=${t.disabledByWebRTC} disabledByUplink=${t.disabledByUplinkPolicy}\n`;this.logger.debug((()=>e))}integrateIndexFrame(e){super.integrateIndexFrame(e);const t=new Set,n=new Set(this.streamIdToBitrateKbpsMap.keys());for(const e of this.currentIndex.sources)e.mediaType===r.SdkStreamMediaType.VIDEO&&(t.add(e.streamId),this.streamIdToBitrateKbpsMap.has(e.streamId)||this.streamIdToBitrateKbpsMap.set(e.streamId,s.UNSEEN_STREAM_BITRATE));for(const e of n)t.has(e)||this.streamIdToBitrateKbpsMap.delete(e)}integrateSubscribeAckFrame(e){if(super.integrateSubscribeAckFrame(e),!e.allocations||void 0===e.allocations)return;let t=0;this._sendRidToVideoStreamIdMap.clear();for(const n of e.allocations){if(this._localStreamInfos.length{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(4955);class r{constructor(e,t,n,i,r){this.attendeeId="",this.groupId=0,this.streamId=0,this.ssrc=0,this.trackLabel="",this.maxBitrateKbps=0,this.avgBitrateKbps=0,this.maxFrameRate=0,this.width=0,this.height=0,this.timeEnabled=0,this.disabledByWebRTC=!1,this.disabledByUplinkPolicy=!1,this.rid="",this.attendeeId=e,this.groupId=t,this.streamId=n,this.maxBitrateKbps=i,this.avgBitrateKbps=r}clone(){const e=new r;return e.attendeeId=this.attendeeId,e.groupId=this.groupId,e.streamId=this.streamId,e.ssrc=this.ssrc,e.trackLabel=this.trackLabel,e.maxBitrateKbps=this.maxBitrateKbps,e.avgBitrateKbps=this.avgBitrateKbps,e.maxFrameRate=this.maxFrameRate,e.timeEnabled=this.timeEnabled,e.disabledByWebRTC=this.disabledByWebRTC,e.disabledByUplinkPolicy=this.disabledByUplinkPolicy,e.width=this.width,e.height=this.height,e}toStreamDescriptor(){const e=i.SdkStreamDescriptor.create();return e.mediaType=i.SdkStreamMediaType.VIDEO,e.trackLabel=this.trackLabel,e.attendeeId=this.attendeeId,e.streamId=this.streamId,e.groupId=this.groupId,e.framerate=this.maxFrameRate,e.maxBitrateKbps=this.disabledByUplinkPolicy||this.disabledByWebRTC?0:this.maxBitrateKbps,e.avgBitrateBps=this.avgBitrateKbps,e}totalPixels(){return this.width*this.height}}t.default=r},8474:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(6244)),a=i(n(832)),o=i(n(1510));class s{constructor(e,t,n,i){this.tileController=n,this.devicePixelRatioMonitor=i,this.tileState=new o.default,this.tileState.tileId=e,this.tileState.localTile=t,this.devicePixelRatioMonitor.registerObserver(this)}static connectVideoStreamToVideoElement(e,t,n){const i=n&&"environment"!==e.getVideoTracks()[0].getSettings().facingMode?"rotateY(180deg)":"";if(s.setVideoElementFlag(t,"disablePictureInPicture",n),s.setVideoElementFlag(t,"disableRemotePlayback",n),t.style.transform!==i&&(t.style.transform=i),t.hasAttribute("controls")&&t.removeAttribute("controls"),t.hasAttribute("autoplay")||t.setAttribute("autoplay","true"),t.hasAttribute("playsinline")||t.setAttribute("playsinline","true"),t.hasAttribute("muted")||(t.setAttribute("muted","true"),t.muted=!0),t.srcObject!==e&&(t.srcObject=e,(new r.default).requiresVideoPlayWorkaround()&&t.paused)){const e=t.play();void 0!==e&&e.catch((e=>{console.warn("Error playing video in Safari",e)})).then((()=>{console.debug("Video played successfully in Safari")}))}}static disconnectVideoStreamFromVideoElement(e,t,n=!1){if(e)if(t)n||(e.srcObject=null,e.style.transform="");else{if(!e.srcObject)return;e.pause(),e.style.transform="",s.setVideoElementFlag(e,"disablePictureInPicture",!1),s.setVideoElementFlag(e,"disableRemotePlayback",!1),e.srcObject=null}}destroy(){this.devicePixelRatioMonitor.removeObserver(this),this.tileState.boundVideoElement&&this.tileState.boundVideoElement.srcObject===this.tileState.boundVideoStream&&s.disconnectVideoStreamFromVideoElement(this.tileState.boundVideoElement,!1),this.tileState=new o.default}devicePixelRatioChanged(e){this.tileState.devicePixelRatio=e,this.sendTileStateUpdate()}id(){return this.tileState.tileId}state(){return this.tileState.clone()}stateRef(){return this.tileState}bindVideoStream(e,t,n,i,r,o,s){let c=!1;this.tileState.boundAttendeeId!==e&&(this.tileState.boundAttendeeId=e,new a.default(e).hasModality(a.default.MODALITY_CONTENT)&&(this.tileState.isContent=!0),c=!0),this.tileState.boundExternalUserId!==s&&(this.tileState.boundExternalUserId=s,c=!0),this.tileState.localTile!==t&&(this.tileState.localTile=t,c=!0),this.tileState.boundVideoStream!==n&&(this.tileState.boundVideoStream=n,c=!0),this.tileState.videoStreamContentWidth!==i&&(this.tileState.videoStreamContentWidth=i,c=!0),this.tileState.videoStreamContentHeight!==r&&(this.tileState.videoStreamContentHeight=r,c=!0),this.tileState.streamId!==o&&(this.tileState.streamId=o,c=!0),c&&this.sendTileStateUpdate()}bindVideoElement(e){let t=!1;this.tileState.boundVideoElement!==e&&(this.tileState.boundVideoElement=e,t=!0),null!==this.tileState.boundVideoElement?(this.tileState.videoElementCSSWidthPixels!==e.clientWidth&&(this.tileState.videoElementCSSWidthPixels=e.clientWidth,t=!0),this.tileState.videoElementCSSHeightPixels!==e.clientHeight&&(this.tileState.videoElementCSSHeightPixels=e.clientHeight,t=!0)):(this.tileState.videoElementCSSWidthPixels=null,this.tileState.videoElementCSSHeightPixels=null),t&&this.sendTileStateUpdate()}pause(){this.tileState.paused||(this.tileState.paused=!0,this.sendTileStateUpdate())}unpause(){this.tileState.paused&&(this.tileState.paused=!1,this.sendTileStateUpdate())}markPoorConnection(){return!this.tileState.poorConnection&&(this.tileState.poorConnection=!0,this.sendTileStateUpdate(),!0)}unmarkPoorConnection(){return!!this.tileState.poorConnection&&(this.tileState.poorConnection=!1,this.sendTileStateUpdate(),!0)}capture(){if(!this.tileState.active)return null;const e=document.createElement("canvas"),t=this.tileState.boundVideoElement;e.width=t.videoWidth||t.width,e.height=t.videoHeight||t.height;const n=e.getContext("2d");return n.drawImage(t,0,0,e.width,e.height),n.getImageData(0,0,e.width,e.height)}setStreamId(e){this.tileState.streamId=e,this.tileController.sendTileStateUpdate(this.state())}sendTileStateUpdate(){this.updateActiveState(),this.updateVideoStreamOnVideoElement(),this.updateVideoElementPhysicalPixels(),this.tileController.sendTileStateUpdate(this.state())}updateActiveState(){this.tileState.active=!(this.tileState.paused||this.tileState.poorConnection||!this.tileState.boundAttendeeId||!this.tileState.boundVideoElement||!this.tileState.boundVideoStream)}updateVideoElementPhysicalPixels(){"number"==typeof this.tileState.videoElementCSSWidthPixels&&"number"==typeof this.tileState.videoElementCSSHeightPixels?(this.tileState.videoElementPhysicalWidthPixels=this.tileState.devicePixelRatio*this.tileState.videoElementCSSWidthPixels,this.tileState.videoElementPhysicalHeightPixels=this.tileState.devicePixelRatio*this.tileState.videoElementCSSHeightPixels):(this.tileState.videoElementPhysicalWidthPixels=null,this.tileState.videoElementPhysicalHeightPixels=null)}updateVideoStreamOnVideoElement(){this.tileState.active?s.connectVideoStreamToVideoElement(this.tileState.boundVideoStream,this.tileState.boundVideoElement,this.tileState.localTile):s.disconnectVideoStreamFromVideoElement(this.tileState.boundVideoElement,this.tileState.paused,this.tileController.keepLastFrameWhenPaused)}static setVideoElementFlag(e,t,n){t in e&&(e[t]=n)}}t.default=s},1510:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n{constructor(){this.tileId=null,this.localTile=!1,this.localTileStarted=!1,this.isContent=!1,this.active=!1,this.paused=!1,this.poorConnection=!1,this.boundAttendeeId=null,this.boundExternalUserId=null,this.boundVideoStream=null,this.boundVideoElement=null,this.nameplate=null,this.videoStreamContentWidth=null,this.videoStreamContentHeight=null,this.videoElementCSSWidthPixels=null,this.videoElementCSSHeightPixels=null,this.devicePixelRatio=0,this.videoElementPhysicalWidthPixels=null,this.videoElementPhysicalHeightPixels=null,this.streamId=null}clone(){const e=new n;return e.tileId=this.tileId,e.localTile=this.localTile,e.isContent=this.isContent,e.active=this.active,e.paused=this.paused,e.poorConnection=this.poorConnection,e.boundAttendeeId=this.boundAttendeeId,e.boundExternalUserId=this.boundExternalUserId,e.boundVideoStream=this.boundVideoStream,e.boundVideoElement=this.boundVideoElement,e.nameplate=this.nameplate,e.videoStreamContentWidth=this.videoStreamContentWidth,e.videoStreamContentHeight=this.videoStreamContentHeight,e.videoElementCSSWidthPixels=this.videoElementCSSWidthPixels,e.videoElementCSSHeightPixels=this.videoElementCSSHeightPixels,e.devicePixelRatio=this.devicePixelRatio,e.videoElementPhysicalWidthPixels=this.videoElementPhysicalWidthPixels,e.videoElementPhysicalHeightPixels=this.videoElementPhysicalHeightPixels,e.streamId=this.streamId,e}}t.default=n},3038:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(7094)),o=r(n(4926)),s=r(n(6009)),c=n(8807),l=r(n(8474));t.default=class{constructor(e,t,n){this.tileFactory=e,this.audioVideoController=t,this.logger=n,this.tileMap=new Map,this.nextTileId=1,this.currentLocalTile=null,this.currentPausedTilesByIds=new Set,this.keepLastFrameWhenPaused=!1,this.keepLastFrameWhenPaused=t.configuration.keepLastFrameWhenPaused}createDevicePixelRatioMonitorIfNeeded(){this.devicePixelRatioMonitor||(this.devicePixelRatioMonitor=new o.default(new s.default,this.logger))}discardDevicePixelRatioMonitorIfNotNeeded(){return i(this,void 0,void 0,(function*(){if(this.tileMap.size||!this.devicePixelRatioMonitor)return;const e=this.devicePixelRatioMonitor;return this.devicePixelRatioMonitor=void 0,e.destroy()}))}bindVideoElement(e,t){const n=this.getVideoTile(e);null!==n?n.bindVideoElement(t):this.logger.warn(`Ignoring video element binding for unknown tile id ${e}`)}unbindVideoElement(e,t=!0){const n=this.getVideoTile(e);if(null===n)return void this.logger.warn(`Ignoring video element unbinding for unknown tile id ${e}`);this.logger.info("Unbinding the video element");const i=n.stateRef().boundVideoElement;n.bindVideoElement(null),t&&(this.logger.info("Cleaning up the video element"),l.default.disconnectVideoStreamFromVideoElement(i,!1))}startLocalVideoTile(){if(this.audioVideoController.configuration.meetingFeatures.videoMaxResolution===a.default.VideoDisabled)return this.logger.warn("Could not start camera video because max video resolution was set to None"),-1;const e=this.findOrCreateLocalVideoTile();return this.currentLocalTile.stateRef().localTileStarted=!0,this.audioVideoController.update({needsRenegotiation:!0}),e.id()}stopLocalVideoTile(){this.currentLocalTile&&(this.currentLocalTile.stateRef().localTileStarted=!1,this.currentLocalTile.bindVideoStream(this.audioVideoController.configuration.credentials.attendeeId,!0,null,null,null,null,this.audioVideoController.configuration.credentials.externalUserId),this.audioVideoController.update({needsRenegotiation:!0}))}hasStartedLocalVideoTile(){return!(!this.currentLocalTile||!this.currentLocalTile.stateRef().localTileStarted)}removeLocalVideoTile(){this.currentLocalTile&&this.removeVideoTile(this.currentLocalTile.id())}getLocalVideoTile(){return this.currentLocalTile}pauseVideoTile(e){const t=this.getVideoTile(e);t&&(this.currentPausedTilesByIds.has(e)||(this.audioVideoController.pauseReceivingStream(t.stateRef().streamId),this.currentPausedTilesByIds.add(e)),t.pause())}unpauseVideoTile(e){const t=this.getVideoTile(e);t&&(this.currentPausedTilesByIds.has(e)&&(this.audioVideoController.resumeReceivingStream(t.stateRef().streamId),this.currentPausedTilesByIds.delete(e)),t.unpause())}getVideoTile(e){return this.tileMap.has(e)?this.tileMap.get(e):null}getVideoTileArea(e){const t=e.state();let n=0,i=0;return t.boundVideoElement&&(n=t.boundVideoElement.clientHeight*t.devicePixelRatio,i=t.boundVideoElement.clientWidth*t.devicePixelRatio),n*i}getAllRemoteVideoTiles(){const e=new Array;return this.tileMap.forEach(((t,n)=>{this.currentLocalTile&&n===this.currentLocalTile.id()||e.push(t)})),e}getAllVideoTiles(){return Array.from(this.tileMap.values())}addVideoTile(e=!1){const t=this.nextTileId;this.nextTileId+=1,this.createDevicePixelRatioMonitorIfNeeded();const n=this.tileFactory.makeTile(t,e,this,this.devicePixelRatioMonitor);return this.tileMap.set(t,n),n}removeVideoTile(e){if(!this.tileMap.has(e))return;const t=this.tileMap.get(e);this.currentLocalTile===t&&(this.currentLocalTile=null),t.destroy(),this.tileMap.delete(e),this.audioVideoController.forEachObserver((t=>{c.Maybe.of(t.videoTileWasRemoved).map((n=>n.bind(t)(e)))})),this.discardDevicePixelRatioMonitorIfNotNeeded()}removeVideoTilesByAttendeeId(e){const t=[];for(const n of this.getAllVideoTiles()){const i=n.state();i.boundAttendeeId===e&&(this.removeVideoTile(i.tileId),t.push(i.tileId))}return t}removeAllVideoTiles(){const e=Array.from(this.tileMap.keys());for(const t of e)this.removeVideoTile(t)}sendTileStateUpdate(e){this.audioVideoController.forEachObserver((t=>{c.Maybe.of(t.videoTileDidUpdate).map((n=>n.bind(t)(e)))}))}haveVideoTilesWithStreams(){for(const e of this.getAllVideoTiles())if(e.state().boundVideoStream)return!0;return!1}haveVideoTileForAttendeeId(e){return!!this.getVideoTileForAttendeeId(e)}getVideoTileForAttendeeId(e){for(const t of this.getAllVideoTiles())if(t.state().boundAttendeeId===e)return t}captureVideoTile(e){const t=this.getVideoTile(e);return t?t.capture():null}findOrCreateLocalVideoTile(){return this.currentLocalTile||(this.currentLocalTile=this.addVideoTile(!0),this.currentLocalTile.bindVideoStream(this.audioVideoController.configuration.credentials.attendeeId,!0,null,null,null,null,this.audioVideoController.configuration.credentials.externalUserId)),this.currentLocalTile}}},5196:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(8474));t.default=class{makeTile(e,t,n,i){return new r.default(e,t,n,i)}}},9473:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{}},6243:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(1455)),a=i(n(8020)),o=n(8807),s=i(n(8740)),c=i(n(9473));class l{constructor(e,t){this.selfAttendeeId=e,this.logger=t,this.numSenders=0,this.shouldDisableSimulcast=!1,this.newQualityMap=new Map,this.currentQualityMap=new Map,this.newActiveStreams=1,this.currentActiveStreams=1,this.lastUplinkBandwidthKbps=l.defaultUplinkBandwidthKbps,this.startTimeMs=0,this.lastUpdatedMs=Date.now(),this.videoIndex=null,this.currLocalDescriptions=[],this.nextLocalDescriptions=[],this.observerQueue=new Set,this.hiDisabledRate=l.kHiDisabledRateHd,this.midDisabledRate=l.kMidDisabledRateHd,this.hiTargetBitrateKbps=l.kHiTargetBitrateKbpsHd,this.midTargetBitrateKbps=l.kMidTargetBitrateKbpsHd,this.lowTargetBitrateKbps=l.kLowTargetBitrateKbpsHd,this.enableFhdVideo=!1,this.optimalParameters=new s.default(0,0,0,0,!0),this.parametersInEffect=new s.default(0,0,0,0,!0),this.lastUplinkBandwidthKbps=l.defaultUplinkBandwidthKbps,this.currentQualityMap=this.fillEncodingParamWithBitrates([this.lowTargetBitrateKbps,0,this.hiTargetBitrateKbps]),this.newQualityMap=this.fillEncodingParamWithBitrates([this.lowTargetBitrateKbps,0,this.hiTargetBitrateKbps])}updateConnectionMetric({uplinkKbps:e=0}){if(isNaN(e))return;0===this.startTimeMs&&(this.startTimeMs=Date.now()),Date.now()-this.startTimeMs`simulcast: uplink policy update metrics ${this.lastUplinkBandwidthKbps}`));let t=l.holdDownDurationMs;3===this.currentActiveStreams?t=2*l.holdDownDurationMs:(2===this.currentActiveStreams&&e<=this.midDisabledRate||1===this.currentActiveStreams&&e<=this.hiDisabledRate)&&(t=l.holdDownDurationMs/2),Date.now()=n||this.lastUplinkBandwidthKbps<=i){this.shouldDisableSimulcast?(this.newActiveStreams=0,t[0].maxBitrateKbps=0,t[1].maxBitrateKbps=this.hiTargetBitrateKbps,t[2].maxBitrateKbps=0):this.numSenders<=4&&this.lastUplinkBandwidthKbps>=this.hiDisabledRate?(this.newActiveStreams=1,t[0].maxBitrateKbps=this.lowTargetBitrateKbps,t[1].maxBitrateKbps=0,t[2].maxBitrateKbps=this.hiTargetBitrateKbps):this.lastUplinkBandwidthKbps>=this.midDisabledRate?(this.newActiveStreams=2,t[0].maxBitrateKbps=this.lastUplinkBandwidthKbps>=.7*this.midTargetBitrateKbps?2*this.lowTargetBitrateKbps/3:this.lowTargetBitrateKbps/2,t[1].maxBitrateKbps=this.numSenders<=6?this.midTargetBitrateKbps:.6*this.midTargetBitrateKbps,t[2].maxBitrateKbps=0):(this.newActiveStreams=3,t[0].maxBitrateKbps=this.lowTargetBitrateKbps,t[1].maxBitrateKbps=0,t[2].maxBitrateKbps=0);const e=t.map(((e,t,n)=>e.maxBitrateKbps));this.newQualityMap=this.fillEncodingParamWithBitrates(e),this.encodingParametersEqual()||this.logger.info(`simulcast: policy:calculateEncodingParameters bw:${this.lastUplinkBandwidthKbps} numSources:${this.numSenders} shouldDisableSimulcast:${this.shouldDisableSimulcast} newQualityMap: ${this.getQualityMapString(this.newQualityMap)}`)}return this.newQualityMap}chooseMediaTrackConstraints(){return{width:{ideal:this.enableFhdVideo?1920:1280},height:{ideal:this.enableFhdVideo?1080:768},frameRate:{ideal:15}}}chooseEncodingParameters(){return this.currentQualityMap=this.newQualityMap,this.currentActiveStreams=this.newActiveStreams,this.activeStreamsToPublish!==this.newActiveStreams&&(this.activeStreamsToPublish=this.newActiveStreams,this.publishEncodingSimulcastLayer()),this.currentQualityMap}updateIndex(e){const t=e.numberOfVideoPublishingParticipantsExcludingSelf(this.selfAttendeeId)+1,n=t!==this.numSenders,i=e.numberOfParticipants(),r=i>=0&&i<=2,a=this.shouldDisableSimulcast!==r;this.numSenders=t,this.shouldDisableSimulcast=r,this.optimalParameters=new s.default(this.captureWidth(),this.captureHeight(),this.captureFrameRate(),this.maxBandwidthKbps(),!1),this.videoIndex=e,this.newQualityMap=this.calculateEncodingParameters(n||a)}wantsResubscribe(){let e=!this.encodingParametersEqual();this.nextLocalDescriptions=this.videoIndex.localStreamDescriptions();for(let t=0;te.streamId===n));-1!==i&&this.nextLocalDescriptions[t].disabledByWebRTC!==this.currLocalDescriptions[i].disabledByWebRTC&&(e=!0)}}return e&&(this.lastUpdatedMs=Date.now()),this.currLocalDescriptions=this.nextLocalDescriptions,e}compareEncodingParameter(e,t){return JSON.stringify(e)===JSON.stringify(t)}encodingParametersEqual(){let e=!1;for(const t of a.default.NAME_ARR_ASCENDING)if(e=e||!this.compareEncodingParameter(this.newQualityMap.get(t),this.currentQualityMap.get(t)),e)break;return!e}chooseCaptureAndEncodeParameters(){return this.parametersInEffect=this.optimalParameters.clone(),this.parametersInEffect.clone()}captureWidth(){return this.enableFhdVideo?1920:1280}captureHeight(){return this.enableFhdVideo?1080:768}captureFrameRate(){return 15}maxBandwidthKbps(){return this.enableFhdVideo?2500:1400}setIdealMaxBandwidthKbps(e){}setHasBandwidthPriority(e){}setHighResolutionFeatureEnabled(e){this.enableFhdVideo=e,this.hiDisabledRate=e?l.kHiDisabledRateFhd:l.kHiDisabledRateHd,this.midDisabledRate=e?l.kMidDisabledRateFhd:l.kMidDisabledRateHd,this.hiTargetBitrateKbps=e?l.kHiTargetBitrateKbpsFhd:l.kHiTargetBitrateKbpsHd,this.midTargetBitrateKbps=e?l.kMidTargetBitrateKbpsFhd:l.kMidTargetBitrateKbpsHd,this.lowTargetBitrateKbps=e?l.kLowTargetBitrateKbpsFhd:l.kLowTargetBitrateKbpsHd}wantsVideoDependencyDescriptorRtpHeaderExtension(){return!0}fillEncodingParamWithBitrates(e){const t=new Map,n=a.default.NAME_ARR_ASCENDING,i=e;let r=this.shouldDisableSimulcast?1:4;for(let e=0;e0,scaleResolutionDownBy:Math.max(r,1),maxBitrate:1e3*i[e]}),r/=2}return t}getQualityMapString(e){let t="";const n=this.videoIndex.localStreamDescriptions();return 3===n.length&&e.forEach((e=>{let i=!1;i="low"===e.rid?n[0].disabledByWebRTC:"mid"===e.rid?n[1].disabledByWebRTC:n[2].disabledByWebRTC,t+=`{ rid: ${e.rid} active:${e.active} disabledByWebRTC: ${i} maxBitrate:${e.maxBitrate}}`})),t}getEncodingSimulcastLayer(e){switch(e){case 0:return r.default.High;case 1:return r.default.LowAndHigh;case 2:return r.default.LowAndMedium;case 3:return r.default.Low}}publishEncodingSimulcastLayer(){const e=this.getEncodingSimulcastLayer(this.activeStreamsToPublish);this.forEachObserver((t=>{o.Maybe.of(t.encodingSimulcastLayersDidChange).map((n=>n.bind(t)(e)))}))}addObserver(e){this.logger.info("adding simulcast uplink observer"),this.observerQueue.add(e)}removeObserver(e){this.logger.info("removing simulcast uplink observer"),this.observerQueue.delete(e)}forEachObserver(e){for(const t of this.observerQueue)e(t)}}t.default=l,l.defaultUplinkBandwidthKbps=1200,l.startupDurationMs=6e3,l.holdDownDurationMs=4e3,l.defaultMaxFrameRate=15,l.kHiDisabledRateHd=700,l.kMidDisabledRateHd=240,l.kHiDisabledRateFhd=1200,l.kMidDisabledRateFhd=400,l.kHiTargetBitrateKbpsHd=1200,l.kMidTargetBitrateKbpsHd=600,l.kLowTargetBitrateKbpsHd=300,l.kHiTargetBitrateKbpsFhd=2e3,l.kMidTargetBitrateKbpsFhd=1e3,l.kLowTargetBitrateKbpsFhd=500},8172:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(2032));t.default=class{constructor(e,t){this.logger=e,this.encodingParams=t,this.videoIndex=null,this.currLocalDescriptions=[],this.nextLocalDescriptions=[],this.enableUhdContent=!1,this.defaultHiTargetBitrateKbps=1200,this.defaultLowTargetBitrateKbps=300}updateConnectionMetric(e){}chooseMediaTrackConstraints(){}chooseEncodingParameters(){var e,t,n,i,a,o,s,c,l,d,u,f;const h=new Map,m=r.default.NAME_ARR_ASCENDING;return h.set(m[0],{rid:m[0],active:!0,scaleResolutionDownBy:(null===(t=null===(e=this.encodingParams)||void 0===e?void 0:e.low)||void 0===t?void 0:t.scaleResolutionDownBy)||2,maxBitrate:1e3*((null===(i=null===(n=this.encodingParams)||void 0===n?void 0:n.low)||void 0===i?void 0:i.maxBitrateKbps)||this.defaultLowTargetBitrateKbps),maxFramerate:(null===(o=null===(a=this.encodingParams)||void 0===a?void 0:a.low)||void 0===o?void 0:o.maxFramerate)||5}),h.set(m[1],{rid:m[1],active:!0,scaleResolutionDownBy:(null===(c=null===(s=this.encodingParams)||void 0===s?void 0:s.high)||void 0===c?void 0:c.scaleResolutionDownBy)||1,maxBitrate:1e3*((null===(d=null===(l=this.encodingParams)||void 0===l?void 0:l.high)||void 0===d?void 0:d.maxBitrateKbps)||this.defaultHiTargetBitrateKbps),maxFramerate:null===(f=null===(u=this.encodingParams)||void 0===u?void 0:u.high)||void 0===f?void 0:f.maxFramerate}),this.getQualityMapString(h),h}updateIndex(e){this.videoIndex=e}wantsResubscribe(){var e,t;let n=!1;this.nextLocalDescriptions=null===(e=this.videoIndex)||void 0===e?void 0:e.localStreamDescriptions();for(let e=0;e<(null===(t=this.nextLocalDescriptions)||void 0===t?void 0:t.length);e++){const t=this.nextLocalDescriptions[e].streamId;if(0!==t&&t){const i=this.currLocalDescriptions.findIndex((e=>e.streamId===t));-1!==i&&this.nextLocalDescriptions[e].disabledByWebRTC!==this.currLocalDescriptions[i].disabledByWebRTC&&(n=!0)}}return this.currLocalDescriptions=this.nextLocalDescriptions,n}chooseCaptureAndEncodeParameters(){}maxBandwidthKbps(){return this.enableUhdContent?2e3:1200}setIdealMaxBandwidthKbps(e){}setHasBandwidthPriority(e){}setHighResolutionFeatureEnabled(e){this.enableUhdContent=e,this.defaultHiTargetBitrateKbps=e?2e3:1200,this.defaultLowTargetBitrateKbps=e?500:300}getQualityMapString(e){var t;let n="";const i=null===(t=this.videoIndex)||void 0===t?void 0:t.localStreamDescriptions();(null==i?void 0:i.length)>0&&(e.forEach((e=>{let t=!1;t="low"===e.rid?i[0].disabledByWebRTC:i[1].disabledByWebRTC,n+=`{ rid: ${e.rid} active:${e.active} disabledByWebRTC: ${t} maxBitrate:${e.maxBitrate} scaleResolutionDownBy:${e.scaleResolutionDownBy} maxFrameRate:${e.maxFramerate}`})),this.logger.info(`simulcast: content policy:chooseEncodingParameters newQualityMap: ${n}`))}addObserver(e){}removeObserver(e){}forEachObserver(e){}}},7719:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(8740));class o{constructor(e,t=!0,n=void 0,i=void 0){this.selfAttendeeId=e,this.scaleResolution=t,this.logger=n,this.browserBehavior=i,this.numberOfPublishedVideoSources=void 0,this.idealMaxBandwidthKbps=1500,this.hasBandwidthPriority=!1,this.encodingParamMap=new Map,this.enableHighResolutionFeature=!1,this.enableSVC=!1,this.isUsingSVCCodec=!0,this.numParticipants=0,this.reset()}reset(){this.numberOfPublishedVideoSources=void 0,this.optimalParameters=new a.default(0,0,0,0,!1),this.parametersInEffect=new a.default(0,0,0,0,!1),this.encodingParamMap.set(o.encodingMapKey,{maxBitrate:0})}updateConnectionMetric(e){}chooseMediaTrackConstraints(){return{}}chooseEncodingParameters(){return new Map}updateIndex(e){var t;let n=!0;this.transceiverController&&(n=this.transceiverController.hasVideoInput());const i=e.numberOfVideoPublishingParticipantsExcludingSelf(this.selfAttendeeId)+(n?1:0),r=e.numberOfParticipants();this.numParticipants!==r||this.numberOfPublishedVideoSources!==i?(this.numberOfPublishedVideoSources=i,this.numParticipants=r,this.updateOptimalParameters()):null===(t=this.logger)||void 0===t||t.debug("Skipping update index; Number of participants has not changed")}wantsResubscribe(){return!this.parametersInEffect.equal(this.optimalParameters)}chooseCaptureAndEncodeParameters(){return this.parametersInEffect=this.optimalParameters.clone(),this.parametersInEffect.clone()}updateOptimalParameters(){let e=1;if(this.transceiverController){const t=this.getStreamCaptureSetting();t&&(e=this.calculateEncodingParameters(t).scaleResolutionDownBy)}this.optimalParameters=new a.default(this.captureWidth(),this.captureHeight(),this.captureFrameRate(),this.maxBandwidthKbps(),!1,e,this.enableSVC&&this.numParticipants>2&&this.isUsingSVCCodec)}captureWidth(){let e=640;return this.getNumberOfPublishedVideoSources()>4&&(e=320),e}captureHeight(){let e=384;return this.getNumberOfPublishedVideoSources()>4&&(e=192),e}captureFrameRate(){return 15}maxBandwidthKbps(){if(this.hasBandwidthPriority)return Math.trunc(this.idealMaxBandwidthKbps);let e=0;return e=this.getNumberOfPublishedVideoSources()<=2?this.idealMaxBandwidthKbps:this.getNumberOfPublishedVideoSources()<=4?2*this.idealMaxBandwidthKbps/3:(544/11+14880/(11*this.getNumberOfPublishedVideoSources()))/600*this.idealMaxBandwidthKbps,Math.trunc(e)}setIdealMaxBandwidthKbps(e){this.idealMaxBandwidthKbps=e}setHasBandwidthPriority(e){this.hasBandwidthPriority=e}setTransceiverController(e){this.transceiverController=e}setSVCEnabled(e){var t;this.enableSVC=e,null===(t=this.logger)||void 0===t||t.info(`setSVCEnabled, enable: ${e}}`)}setHighResolutionFeatureEnabled(e){this.enableHighResolutionFeature=e}updateTransceiverController(){return i(this,void 0,void 0,(function*(){const e=this.getStreamCaptureSetting();if(!e)return;const t=this.calculateEncodingParameters(e);this.shouldUpdateEndcodingParameters(t)&&(this.encodingParamMap.set(o.encodingMapKey,t),this.transceiverController.setEncodingParameters(this.encodingParamMap))}))}shouldUpdateEndcodingParameters(e){var t,n;const i=null===(n=null===(t=this.transceiverController.localVideoTransceiver().sender.getParameters())||void 0===t?void 0:t.encodings)||void 0===n?void 0:n[0];return e.maxBitrate!==(null==i?void 0:i.maxBitrate)||e.scaleResolutionDownBy!==(null==i?void 0:i.scaleResolutionDownBy)||(null==e?void 0:e.scalabilityMode)!==(null==i?void 0:i.scalabilityMode)}calculateEncodingParameters(e){var t,n,i;const r=1e3*this.maxBandwidthKbps();let a=1,s=720;if(void 0!==e.height&&void 0!==e.width&&this.scaleResolution&&!this.hasBandwidthPriority&&this.getNumberOfPublishedVideoSources()>2&&(s=o.targetHeightArray[Math.min(this.getNumberOfPublishedVideoSources(),o.targetHeightArray.length-1)][this.enableHighResolutionFeature?1:0],480===s&&(null===(t=this.browserBehavior)||void 0===t?void 0:t.disable480pResolutionScaleDown())&&(s=360),a=Math.max(Math.min(e.height,e.width)/s,1),null===(n=this.logger)||void 0===n||n.info(`Resolution scale factor is ${a} for capture resolution ${e.width}x${e.height}. New dimension is ${e.width/a}x${e.height/a}`)),this.enableSVC){let e;return e=this.numParticipants>=0&&this.numParticipants<3||!this.isUsingSVCCodec?"L1T1":s>=720?"L3T3":s>=360?"L2T3":"L1T3",null===(i=this.logger)||void 0===i||i.info(`calculateEncodingParameters: SVC: ${this.enableSVC} participants: ${this.numParticipants} publishers: ${this.getNumberOfPublishedVideoSources()} bitrate: ${r} targetHeight: ${s} scalabilityMode: ${e} isUsingSVCCodec: ${this.isUsingSVCCodec}`),{scaleResolutionDownBy:a,maxBitrate:r,scalabilityMode:e}}return{scaleResolutionDownBy:a,maxBitrate:r}}getStreamCaptureSetting(){var e,t,n,i;return null===(i=null===(n=null===(t=null===(e=this.transceiverController)||void 0===e?void 0:e.localVideoTransceiver())||void 0===t?void 0:t.sender)||void 0===n?void 0:n.track)||void 0===i?void 0:i.getSettings()}getNumberOfPublishedVideoSources(){var e;return null!==(e=this.numberOfPublishedVideoSources)&&void 0!==e?e:0}wantsVideoDependencyDescriptorRtpHeaderExtension(){return this.enableSVC}setMeetingSupportedVideoSendCodecs(e,t){const n=null!=e?e:t,i=n.length>0&&o.SVCCodecNames.includes(n[0].codecName);i!==this.isUsingSVCCodec&&(this.isUsingSVCCodec=i,this.updateOptimalParameters())}}t.default=o,o.encodingMapKey="video",o.targetHeightArray=[[0,0],[0,0],[0,0],[540,720],[540,720],[480,540],[480,540],[480,540],[480,540],[360,480],[360,480],[360,480],[360,480],[270,360],[270,360],[270,360],[270,360],[180,270],[180,270],[180,270],[180,270],[180,270],[180,270],[180,270],[180,270],[180,270]],o.SVCCodecNames=["VP9"]},7880:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(8740));t.default=class{constructor(){}updateConnectionMetric(e){}chooseMediaTrackConstraints(){return{}}chooseEncodingParameters(){return new Map}updateIndex(e){}wantsResubscribe(){return!1}chooseCaptureAndEncodeParameters(){return new r.default(0,0,0,0,!1)}maxBandwidthKbps(){return 0}setIdealMaxBandwidthKbps(e){}setHasBandwidthPriority(e){}setHighResolutionFeatureEnabled(e){}wantsVideoDependencyDescriptorRtpHeaderExtension(){return!1}}},9848:(e,t)=>{"use strict";function n(e){return e.map((e=>"object"==typeof e?JSON.stringify(e):`${e}`)).join(" ")}Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e){this.base=e}debug(...e){this.base.debug(n(e))}info(...e){this.base.info(n(e))}warn(...e){this.base.warn(n(e))}error(...e){this.base.error(n(e))}}},4392:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.VoiceFocusDeviceTransformer=void 0;const a=n(1677),o=n(9979),s=r(n(6741)),c=r(n(9848)),l=r(n(2087)),d=r(n(5028));class u{constructor(e,{preload:t=!0,logger:n,fetchBehavior:i=u.defaultFetchBehavior()},r){this.spec=e,this.supported=!0,this.logger=n,this.vfLogger=n?new c.default(n):void 0,this.preload=t,this.fetchBehavior=i,this.spec=u.augmentSpec(this.spec),r&&(this.configuration=Promise.resolve(r))}static isSupported(e,t){var n,i;const r={fetchBehavior:u.defaultFetchBehavior(),logger:(null==t?void 0:t.logger)?new c.default(t.logger):void 0};if(o.isIFramed()){if(!1===(null==t?void 0:t.allowIFrame))return null===(n=null==t?void 0:t.logger)||void 0===n||n.error("Amazon Voice Focus support check inside iframe: not supported."),Promise.resolve(!1);null===(i=null==t?void 0:t.logger)||void 0===i||i.warn("Amazon Voice Focus support check inside iframe: not recommended.")}return a.VoiceFocus.isSupported(u.augmentSpec(e),r)}static create(e={},t={},n,r,a){var o,s,c;return i(this,void 0,void 0,(function*(){r&&r.Meeting.Meeting&&(r=r.Meeting);const i="AVAILABLE"===(null===(c=null===(s=null===(o=null==r?void 0:r.Meeting)||void 0===o?void 0:o.MeetingFeatures)||void 0===s?void 0:s.Audio)||void 0===c?void 0:c.EchoReduction),a=n&&!0===n.supported&&"ns_es"===n.model.name&&!i,l="ns_es"===e.name&&!i;if(a||l)throw new Error("Echo Reduction requested but not enabled.");const d=new u(e,t,n);return yield d.init(),d}))}static configure(e={},t={}){return i(this,void 0,void 0,(function*(){return new u(e,t,void 0).configure(!0)}))}getConfiguration(){return this.configuration}isSupported(){return this.supported}createTransformDevice(e,t){return i(this,void 0,void 0,(function*(){if(this.supported)try{const n=!0,[i,r]=yield this.allocateVoiceFocus(n),a=Object.assign(Object.assign({},t),{es:"ns_es"===this.spec.name});return new l.default(e,i,r,a)}catch(e){return}}))}static destroyVoiceFocus(e){var t;return i(this,void 0,void 0,(function*(){null===(t=null==e?void 0:e.vf)||void 0===t||t.destroy()}))}static augmentSpec(e){return e&&(e.assetGroup||e.revisionID)?e:Object.assign(Object.assign({},e),{assetGroup:u.currentSDKAssetGroup()})}configure(e=!1){return i(this,void 0,void 0,(function*(){const t={fetchBehavior:this.fetchBehavior,preResolve:e,logger:this.vfLogger};return a.VoiceFocus.configure(this.spec,t)}))}init(){var e;return i(this,void 0,void 0,(function*(){this.configuration||(this.configuration=this.configure());const t=yield this.configuration;if(t.supported){this.pendingVoiceFocus=this.createVoiceFocus(t,this.preload);try{yield this.pendingVoiceFocus}catch(t){null===(e=this.logger)||void 0===e||e.error(`Unable to initialize Amazon Voice Focus: ${t}`),this.supported=!1}}else this.supported=!1}))}createVoiceFocus(e,t){return i(this,void 0,void 0,(function*(){const n=new d.default;return this.vf=yield a.VoiceFocus.init(e,{delegate:n,preload:t,logger:this.vfLogger}),[this.vf,n]}))}allocateVoiceFocus(e){return i(this,void 0,void 0,(function*(){if(!this.supported)throw new Error("Not supported.");if(this.pendingVoiceFocus){const e=this.pendingVoiceFocus;return this.pendingVoiceFocus=void 0,e}return this.createVoiceFocus(yield this.configuration,e)}))}static majorVersion(){return s.default.sdkVersion.match(/^[1-9][0-9]*\.(?:0|[1-9][0-9]*)/)[0]}static majorMinorVersion(){return s.default.sdkVersion.match(/^[1-9][0-9]*\.(?:0|(?:[1-9][0-9]*))\.(?:0|[1-9][0-9]*)/)[0]}static currentSDKAssetGroup(){const e=this.majorVersion();return e?`sdk-${e}`:"stable-v1"}static defaultFetchBehavior(){const e=u.majorMinorVersion()||"unknown",t=s.default.sdkUserAgentLowResolution;return{escapedQueryString:`sdk=${encodeURIComponent(e)}&ua=${encodeURIComponent(t)}`}}}t.VoiceFocusDeviceTransformer=u,t.default=u},2087:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(6244));class o{constructor(e,t,n,i,r=!1,o=void 0,s=new a.default,c=new Map,l=void 0,d=void 0){this.device=e,this.voiceFocus=t,this.delegate=n,this.nodeOptions=i,this.failed=r,this.node=o,this.browserBehavior=s,this.farEndStreamToAudioSourceNode=c,this.mixDestNode=l,this.mixSourceNode=d}getInnerDevice(){return this.device}mute(e){return i(this,void 0,void 0,(function*(){this.node&&(e?yield this.node.disable():yield this.node.enable())}))}stop(){return i(this,void 0,void 0,(function*(){this.node&&(this.node.disconnect(),yield this.node.stop())}))}chooseNewInnerDevice(e){return i(this,void 0,void 0,(function*(){return this.device!==e||"default"===(t=e)||t&&"object"==typeof t&&("deviceId"in t&&"default"===t.deviceId||"id"in t&&"default"===t.id)?new o(e,this.voiceFocus,this.delegate,this.nodeOptions,this.failed,this.node,this.browserBehavior,this.farEndStreamToAudioSourceNode,this.mixDestNode,this.mixSourceNode):this;var t}))}intrinsicDevice(){return i(this,void 0,void 0,(function*(){if(this.failed)return this.device;const e=this.nodeOptions.es,t={echoCancellation:!e,googEchoCancellation:!e,googEchoCancellation2:!e,noiseSuppression:!1,googNoiseSuppression:!1,googHighpassFilter:!1,googNoiseSuppression2:!1};let n;return n=!this.nodeOptions||void 0===this.nodeOptions.agc||this.nodeOptions.agc.useBuiltInAGC,t.autoGainControl=n,t.googAutoGainControl=n,t.googAutoGainControl2=n,this.device?"string"==typeof this.device?(this.browserBehavior.requiresNoExactMediaStreamConstraints()?t.deviceId=this.device:t.deviceId={exact:this.device},t):this.device.id?this.device:Object.assign(Object.assign({},this.device),t):t}))}createAudioNode(e){var t,n;return i(this,void 0,void 0,(function*(){if((null===(t=this.node)||void 0===t?void 0:t.context)===e)return{start:this.node,end:this.node};const i=Object.assign({enabled:!0,agc:{useVoiceFocusAGC:!1}},this.nodeOptions);try{if(null===(n=this.node)||void 0===n||n.disconnect(),this.node=yield this.voiceFocus.createNode(e,i),this.nodeOptions.es){this.mixDestNode=new MediaStreamAudioDestinationNode(e,{channelCount:1,channelCountMode:"explicit"});for(const e of this.farEndStreamToAudioSourceNode.keys())this.assignFarEndStreamToAudioSourceNode(e);this.createMixSourceNode()}return{start:this.node,end:this.node}}catch(e){throw this.failed=!0,this.delegate.onFallback(this,e),e}}))}observeMeetingAudio(e){return i(this,void 0,void 0,(function*(){if(!this.nodeOptions.es)return;e.addAudioMixObserver(this);const t=yield e.getCurrentMeetingAudioStream();t&&this.addFarEndStream(t)}))}unObserveMeetingAudio(e){return i(this,void 0,void 0,(function*(){if(!this.nodeOptions.es)return;e.removeAudioMixObserver(this);const t=yield e.getCurrentMeetingAudioStream();t&&this.removeFarendStream(t)}))}addObserver(e){this.delegate.addObserver(e)}removeObserver(e){this.delegate.removeObserver(e)}addFarEndStream(e){return i(this,void 0,void 0,(function*(){this.nodeOptions.es&&e&&!this.farEndStreamToAudioSourceNode.has(e)&&(this.node?this.assignFarEndStreamToAudioSourceNode(e):this.farEndStreamToAudioSourceNode.set(e,null))}))}removeFarendStream(e){var t;return i(this,void 0,void 0,(function*(){null===(t=this.farEndStreamToAudioSourceNode.get(e))||void 0===t||t.disconnect(),this.farEndStreamToAudioSourceNode.delete(e)}))}meetingAudioStreamBecameActive(e){return i(this,void 0,void 0,(function*(){this.addFarEndStream(e)}))}meetingAudioStreamBecameInactive(e){return i(this,void 0,void 0,(function*(){this.removeFarendStream(e)}))}assignFarEndStreamToAudioSourceNode(e){const t=this.node.context.createMediaStreamSource(e);t.channelCount=1,t.channelCountMode="explicit",this.farEndStreamToAudioSourceNode.set(e,t),t.connect(this.mixDestNode,0)}createMixSourceNode(){this.mixSourceNode=this.node.context.createMediaStreamSource(this.mixDestNode.stream),this.mixSourceNode.channelCount=1,this.mixSourceNode.channelCountMode="explicit",this.mixSourceNode.connect(this.node,0,1)}}t.default=o},5028:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.observers=new Set}addObserver(e){this.observers.add(e)}removeObserver(e){this.observers.delete(e)}onFallback(e,t){var n;for(const i of this.observers)null===(n=i.voiceFocusFellBackToInnerStream)||void 0===n||n.call(i,e,t)}onCPUWarning(){var e;for(const t of this.observers)null===(e=t.voiceFocusInsufficientResources)||void 0===e||e.call(t)}}},9164:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n{constructor(e,t,n,i,r){this.logger=e,this.realtimeController=t,this.minVolumeDecibels=n,this.maxVolumeDecibels=i,this.selfAttendeeId=r,this.streamIdToAttendeeId={},this.streamIdToExternalUserId={},this.warnedAboutMissingStreamIdMapping={},this.attendeeIdToStreamId={},this.sessionReconnected=!1}onReconnect(){this.sessionReconnected=!0}sendRealtimeUpdatesForAudioStreamIdInfo(e){let t=0;for(const n of e.streams){const i=!!n.attendeeId,r=!!n.externalUserId,a=n.hasOwnProperty("muted"),o=!!n.dropped;if(i){this.attendeeIdToStreamId[n.attendeeId]&&this.attendeeIdToStreamId[n.attendeeId]n.audioStreamId&&this.streamIdToAttendeeId[t]===i){a=!0;break}}a||this.realtimeController.realtimeSetAttendeeIdPresence(i,!1,r,o,{attendeeIndex:t++,attendeesInFrame:e.streams.length})}}}this.sessionReconnected&&(this.cleanUpState(e),this.sessionReconnected=!1)}cleanUpState(e){const t=Object.values(this.streamIdToAttendeeId),n=e.streams.map((e=>e.attendeeId)),i=t.filter((e=>!n.includes(e)));for(const[e,t]of i.entries()){const n=this.attendeeIdToStreamId[t],i=this.streamIdToExternalUserId[n];delete this.streamIdToAttendeeId[n],delete this.streamIdToExternalUserId[n],delete this.warnedAboutMissingStreamIdMapping[n],delete this.attendeeIdToStreamId[t],t!==this.selfAttendeeId?this.realtimeController.realtimeSetAttendeeIdPresence(t,!1,i,!1,{attendeeIndex:e,attendeesInFrame:t.length}):this.logger.warn("the volume indicator adapter cleans up the current attendee (presence = false) after reconnection")}}sendRealtimeUpdatesForAudioMetadata(e){let t=null,n=null;for(const i of e.attendeeStates){const e=this.attendeeIdForStreamId(i.audioStreamId);i.hasOwnProperty("volume")&&(null===t&&(t={}),null!==e&&(t[e]=this.normalizedVolume(i))),i.hasOwnProperty("signalStrength")&&(null===n&&(n={}),null!==e&&(n[e]=this.normalizedSignalStrength(i)))}this.applyRealtimeUpdatesForAudioMetadata(t,n)}normalizedVolume(e){const t=1-(-e.volume-this.maxVolumeDecibels)/(this.minVolumeDecibels-this.maxVolumeDecibels);return Math.min(Math.max(t,0),1)}normalizedSignalStrength(e){const t=e.signalStrength/n.MAX_SIGNAL_STRENGTH_LEVELS;return Math.min(Math.max(t,0),1)}applyRealtimeUpdatesForAudioMetadata(e,t){for(const i in this.streamIdToAttendeeId){const r=this.streamIdToAttendeeId[i],a=this.streamIdToExternalUserId[i];let o=null,s=null;null!==e&&(o=e.hasOwnProperty(r)?e[r]:n.IMPLICIT_VOLUME),null!==t&&(s=t.hasOwnProperty(r)?t[r]:n.IMPLICIT_SIGNAL_STRENGTH),null===o&&null===s||this.realtimeController.realtimeUpdateVolumeIndicator(r,o,null,s,a)}}attendeeIdForStreamId(e){return 0===e?null:this.streamIdToAttendeeId[e]||(this.warnedAboutMissingStreamIdMapping[e]||(this.warnedAboutMissingStreamIdMapping[e]=!0,this.logger.warn(`volume indicator stream id ${e} seen before being defined`)),null)}}t.default=n,n.MAX_SIGNAL_STRENGTH_LEVELS=2,n.IMPLICIT_VOLUME=0,n.IMPLICIT_SIGNAL_STRENGTH=1},388:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=i(n(6741)),a=i(n(4696));t.default=class{constructor(e){this.logger=e}create(e,t,n){this.connection=new WebSocket(n?e:r.default.urlWithVersion(e),t),this.connection.binaryType="arraybuffer"}send(e){if(!this.connection)return this.logger.error("WebSocket not yet created or already destroyed."),!1;try{return e instanceof Uint8Array?this.connection.send(e.buffer):this.connection.send(e),!0}catch(e){return this.logger.debug((()=>`send error: ${e.message}, websocket state=${a.default[this.readyState()]}`)),!1}}close(e,t){var n;null===(n=this.connection)||void 0===n||n.close(e,t)}destroy(){this.connection=void 0}addEventListener(e,t){this.connection?this.connection.addEventListener(e,t):this.logger.warn("Cannot add event listener with no WebSocket connection.")}removeEventListener(e,t){var n;null===(n=this.connection)||void 0===n||n.removeEventListener(e,t)}readyState(){if(!this.connection)return a.default.None;switch(this.connection.readyState){case WebSocket.CONNECTING:return a.default.Connecting;case WebSocket.OPEN:return a.default.Open;case WebSocket.CLOSING:return a.default.Closing;case WebSocket.CLOSED:return a.default.Closed}}}},4696:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.WebSocketReadyState=void 0,function(e){e[e.None=0]="None",e[e.Connecting=1]="Connecting",e[e.Open=2]="Open",e[e.Closing=3]="Closing",e[e.Closed=4]="Closed"}(n=t.WebSocketReadyState||(t.WebSocketReadyState={})),t.default=n},7845:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.decideModel=t.measureAndDecideExecutionApproach=void 0;const r=n(1364),a=n(5128),o={wasm:{noSupport:.07,inline:{c100:1,c50:.36,c20:.16,c10:.07},worker:{c100:.5,c50:.18,c20:.08,c10:.06}},simd:{noSupport:.1,inline:{c100:1,c50:.43,c20:.3,c10:.2},worker:{c100:.5,c50:.21,c20:.15,c10:.1}}};class s{constructor(e,t){this.fetchConfig=e,this.logger=t;const n=`${e.paths.workers}estimator-v1.js`;this.fetchBehavior={headers:e.headers,escapedQueryString:e.escapedQueryString},this.worker=r.loadWorker(n,"VoiceFocusEstimator",this.fetchBehavior,t)}roundtrip(e,t,n){return new Promise(((i,r)=>{this.worker.then((r=>{let a;a=e=>{const{message:o,key:s}=e.data;o===t&&s===n&&(r.removeEventListener("message",a),i(e.data))},r.addEventListener("message",a),r.postMessage(e)})).catch((e=>{var t;null===(t=this.logger)||void 0===t||t.error("Failed to load worker.",e),r(e)}))}))}supportsSIMD(e){const t="simd",n=e||`${this.fetchConfig.paths.wasm}simd-v1.wasm`,i={message:"supports-simd",fetchBehavior:this.fetchBehavior,path:n,key:t};return this.roundtrip(i,"simd-support",t).then((e=>e.supports))}measure(e,t){const n=`${this.fetchConfig.paths.wasm}bench-v1.wasm`,i=`${this.fetchConfig.paths.wasm}bench-v1_simd.wasm`,r=e?i:n,a=`bench:${e}`,o={message:"measure",fetchBehavior:this.fetchBehavior,budget:t,path:r,key:a};return this.roundtrip(o,"measurement",a).then((e=>{if(e.measurement)return e.measurement;throw new Error("Failed to measure.")}))}stop(){this.worker.then((e=>{var t;null===(t=this.logger)||void 0===t||t.debug("Stopping estimator worker."),e.terminate()})).catch((e=>{}))}}const c=(e,t,n,r)=>i(void 0,void 0,void 0,(function*(){const i={supportsSIMD:e,supportsSAB:a.supportsSharedArrayBuffer(globalThis,window,n),duration:-1};if(e)return null==n||n.info("Supports SIMD: true (force)"),i;const o=!r,c=r||new s(t,n);try{const t=!a.isOldChrome(window,n)&&(yield c.supportsSIMD());return null==n||n.info(`Supports SIMD: ${t} (force: ${e})`),i.supportsSIMD=t,i}finally{o&&c.stop()}}));t.measureAndDecideExecutionApproach=(e,t,n,r=o)=>i(void 0,void 0,void 0,(function*(){let l=e.executionPreference;const{usagePreference:d,variantPreference:u,namePreference:f,simdPreference:h,estimatorBudget:m,executionQuantaPreference:p}=e;"interactivity"===d&&"inline"!==l&&(null==n||n.debug(`Overriding execution preference ${l} to reflect interactivity preference.`),l="inline");const g="force"===h,v="auto"!==u,b="auto"!==l;let y;try{y=v&&b?yield c(g,t,n):yield((e,t,n,r)=>i(void 0,void 0,void 0,(function*(){const i=new s(t,r);try{const a=yield c(e,t,r,i);if(a.supportsSIMD)try{return a.duration=yield i.measure(!0,n),null==r||r.info("SIMD timing:",a.duration),a}catch(e){null==r||r.warn("Failed SIMD estimation; falling back to non-SIMD."),a.supportsSIMD=!1}return a.duration=yield i.measure(!1,n),null==r||r.info("No-SIMD timing:",a.duration),a}catch(e){throw null==r||r.error("Could not feature check.",e),e}finally{i.stop()}})))(g,t,m,n)}catch(e){throw null==n||n.error("Could not load estimator.",e),new Error("Could not load Voice Focus estimator.")}return(({supportsSIMD:e,supportsSAB:t,duration:n,executionPreference:i="auto",simdPreference:r,variantPreference:s="auto",namePreference:c="default",usagePreference:l,executionQuantaPreference:d=3},u=o,f)=>{const h="force"===r||"disable"!==r&&e,m=-1!==n,p=m?(h?2.5:2.63)/n:0,g=h?u.simd:u.wasm,v=m?((e,t)=>1===e?.6:"quality"===t?.65*e:.5*e)(d,l)*p:0,b=m?.7*p:0,y=c,S=e=>({supported:!1,reason:e});if(m){if(p({supported:!0,useSIMD:h,processor:e,executionApproach:t,variant:n,executionQuanta:"inline"===t?d:void 0,name:y}),w=(e,t,n)=>"auto"!==t?!m||e>n[t]?t:"failed":e>n.c100?"c100":e>n.c50?"c50":e>n.c20?"c20":e>n.c10?"c10":"failed",M=e=>{switch(e||"auto"){case"auto":{let e=M("inline"),t=M("worker");return null==f||f.debug(`Reducing auto preference: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),!1===e.supported||!1===t.supported?t:e.variant===t.variant||"c50"===e.variant?e:t}case"worker":return a.supportsSharedArrayBuffer(globalThis,window,f)?M("worker-sab"):M("worker-postMessage");case"inline":{const e=w(v,s,g.inline);return"failed"===e?S(`Performance score ${v} not sufficient for inline use with variant preference ${s}.`):C("voicefocus-inline-processor","inline",e)}case"worker-sab":{if(!t){const e="Requested worker-sab but no SharedArrayBuffer support.";return null==f||f.warn(e),{supported:!1,reason:e}}const e=w(b,s,g.worker);return"failed"===e?S(`Performance score ${b} not sufficient for worker use with variant preference ${s}.`):C("voicefocus-worker-sab-processor","worker-sab",e)}case"worker-postMessage":{const e=w(b,s,g.worker);if("failed"===e)return S(`Performance score ${b} not sufficient for worker use.`);if("ns_es"===y){const e="Requested echo suppression but postMessage executor does not support it.";return null==f||f.warn(e),{supported:!1,reason:e}}return C("voicefocus-worker-postMessage-processor","worker-postMessage",e)}}};return M(i)})(Object.assign(Object.assign({},y),{simdPreference:h,executionPreference:l,variantPreference:u,namePreference:f,usagePreference:d,executionQuantaPreference:p}),r,n)})),t.decideModel=({category:e,name:t,variant:n,simd:i,url:r})=>`${e}-${t}-${n}-v1${i?"_simd":""}`},9019:(e,t)=>{"use strict";function n(e,t,n){if(!n)return fetch(e,t);const a=r(e,n),o=i(t,n);return fetch(a,o)}function i(e,t){return(null==t?void 0:t.headers)?e?Object.assign(Object.assign({},e),{headers:Object.assign(Object.assign({},e.headers||{}),t.headers)}):{headers:t.headers}:e}function r(e,t){if(!(null==t?void 0:t.escapedQueryString))return e;const n=-1!==e.lastIndexOf("?");return`${e}${n?"&":"?"}${t.escapedQueryString}`}Object.defineProperty(t,"__esModule",{value:!0}),t.isValidRevisionID=t.isValidAssetGroup=t.resolveURL=t.addQueryParams=t.withQueryString=t.withRequestHeaders=t.fetchWithBehavior=void 0,t.fetchWithBehavior=n,t.withRequestHeaders=i,t.withQueryString=r,t.addQueryParams=function(e,t){const n=Object.keys(t);if(!n.length)return e;const i=new URLSearchParams(null==e?void 0:e.escapedQueryString);for(const e of n)i.append(e,t[e]);return Object.assign(Object.assign({},e),{escapedQueryString:i.toString()})};const a={method:"HEAD",mode:"cors",credentials:"omit",redirect:"follow",referrerPolicy:"origin"};t.resolveURL=function(e,t){return n(e,a,t).then((t=>t.redirected?t.url:e))},t.isValidAssetGroup=function(e){return!!e&&/^[-.a-zA-Z0-9]+$/.test(e)},t.isValidRevisionID=function(e){return!!e&&/^[123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ]{22}$/.test(e)}},1364:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.loadWorker=void 0;const i=n(9019),r={method:"GET",mode:"cors",credentials:"omit",redirect:"follow",referrerPolicy:"no-referrer"};t.loadWorker=(e,t,n,a)=>{null==a||a.debug(`Loading ${t} worker from ${e}.`);let o=!1;try{o=self.origin===new URL(e).origin}catch(e){null==a||a.error("Could not compare origins.",e)}if(o){const r=i.withQueryString(e,n);return Promise.resolve(new Worker(r,{name:t}))}return i.fetchWithBehavior(e,r,n).then((e=>{if(e.ok)return e.blob().then((e=>new Worker(window.URL.createObjectURL(e))));throw new Error("Fetch failed.")}))}},5128:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.isOldChrome=t.supportsWASMStreaming=t.supportsSharedArrayBuffer=t.supportsWASM=t.supportsAudioWorklet=t.supportsWorker=t.supportsVoiceFocusWorker=t.supportsWASMPostMessage=t.isSafari=void 0;const r=n(1364);t.isSafari=(e=globalThis)=>{const t=e.navigator.userAgent,n=t.match(/Safari\//),i=t.match(/Chrom(?:e|ium)\//);return!(!n||i)},t.supportsWASMPostMessage=(e=globalThis)=>!t.isSafari(e)&&(!((e=globalThis)=>!!e.navigator.userAgent.match(/Chrom(?:e|ium)\/([0-9]+)/))(e)||(a(e)||0)<95),t.supportsVoiceFocusWorker=(e=globalThis,n,a)=>i(void 0,void 0,void 0,(function*(){if(!t.supportsWorker(e,a))return!1;const i=`${n.paths.workers}worker-v1.js`;try{const e=yield r.loadWorker(i,"VoiceFocusTestWorker",n,a);try{e.terminate()}catch(e){null==a||a.debug("Failed to terminate worker.",e)}return!0}catch(e){return null==a||a.info("Failed to fetch and instantiate test worker",e),!1}})),t.supportsWorker=(e=globalThis,t)=>{try{return!!e.Worker}catch(e){return null==t||t.info("Does not support Worker",e),!1}},t.supportsAudioWorklet=(e=globalThis,t)=>{try{return!!e.AudioWorklet&&!!e.AudioWorkletNode}catch(e){return null==t||t.info("Does not support Audio Worklet",e),!1}},t.supportsWASM=(e=globalThis,t)=>{try{return!(!e.WebAssembly||!e.WebAssembly.compile&&!e.WebAssembly.compileStreaming)}catch(e){return null==t||t.info("Does not support WASM",e),!1}},t.supportsSharedArrayBuffer=(e=globalThis,t=globalThis,n)=>{try{return!(!e.SharedArrayBuffer||!t.chrome&&!e.crossOriginIsolated)}catch(e){return null==n||n.info("Does not support SharedArrayBuffer."),!1}},t.supportsWASMStreaming=(e=globalThis,t)=>{var n;try{return!!(null===(n=e.WebAssembly)||void 0===n?void 0:n.compileStreaming)}catch(e){return null==t||t.info("Does not support WASM streaming compilation",e),!1}};const a=(e=globalThis)=>{try{if(!e.chrome)return}catch(e){}const t=e.navigator.userAgent.match(/Chrom(?:e|ium)\/([0-9]+)/);if(t)return parseInt(t[1],10)};t.isOldChrome=(e=globalThis,t)=>{const n=a(e);return!!n&&n<90&&(null==t||t.debug(`Chrome ${n} has incomplete SIMD support.`),!0)}},7614:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VoiceFocusAudioWorkletNode=void 0;class n extends("undefined"!=typeof globalThis&&globalThis.AudioWorkletNode||class{}){}t.VoiceFocusAudioWorkletNode=n},1677:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.getAudioInput=t.createAudioContext=t.VoiceFocus=void 0;const r=n(7845),a=n(9019),o=n(1364),s=n(5128),c=n(3596),l=n(1104),d=n(2297),u={useVoiceFocusAGC:!1,useBuiltInAGC:!0},f="stable-v1",h="https://static.sdkassets.chime.aws",m={processors:`${h}/processors/`,workers:`${h}/workers/`,wasm:`${h}/wasm/`,models:`${h}/wasm/`},p={latencyHint:0},g={channelCount:1,echoCancellation:!0,googEchoCancellation:!0,noiseSuppression:!1,googNoiseSuppression:!1,googHighpassFilter:!1,googTypingNoiseDetection:!1},v=Object.assign(Object.assign({},g),{autoGainControl:!0,googAutoGainControl:!0,googAutoGainControl2:!0}),b=Object.assign(Object.assign({},g),{autoGainControl:!1,googAutoGainControl:!1,googAutoGainControl2:!1}),y={"voicefocus-worker-sab-processor":{file:"worklet-worker-sab-processor-v1.js",node:l.default},"voicefocus-worker-postMessage-processor":{file:"worklet-worker-postMessage-processor-v1.js",node:d.default},"voicefocus-inline-processor":{file:"worklet-inline-processor-v1.js",node:c.default}},S=(e,t)=>{if(void 0!==e&&!a.isValidAssetGroup(e))throw new Error(`Invalid asset group ${e}`);if(void 0!==t&&!a.isValidRevisionID(t))throw new Error(`Invalid revision ID ${t}`)},C=(e,t)=>`${t.models}${r.decideModel(e)}.wasm`;class w{constructor(e,t,n,i,r){this.processorURL=t,this.nodeConstructor=n,this.nodeOptions=i,this.executionQuanta=r,this.internal={worker:e,nodeOptions:i,isDestroyed:!1}}static isSupported(e,t){const{fetchBehavior:n,logger:i}=t||{};if("undefined"==typeof globalThis)return null==i||i.debug("Browser does not have globalThis."),Promise.resolve(!1);if(!s.supportsAudioWorklet(globalThis,i))return null==i||i.debug("Browser does not support Audio Worklet."),Promise.resolve(!1);if(!s.supportsWASM(globalThis,i))return null==i||i.debug("Browser does not support WASM."),Promise.resolve(!1);s.supportsWASMStreaming(globalThis,i)||null==i||i.debug("Browser does not support streaming WASM compilation.");const{assetGroup:r=f,revisionID:o,paths:c=m}=e||{};S(r,o);const l=o?{revisionID:o}:{assetGroup:r},d=a.addQueryParams(n,l),u=Object.assign(Object.assign({},d),{paths:c});return s.supportsVoiceFocusWorker(globalThis,u,i)}static mungeExecutionPreference(e,t){const n=void 0===e||"auto"===e;if(s.isSafari(globalThis)){if(n||"inline"===e)return"inline";if(!n)throw new Error(`Unsupported execution preference ${e}`)}if("worker-sab"===e&&!s.supportsSharedArrayBuffer(globalThis,globalThis,t))throw new Error(`Unsupported execution preference ${e}`);return e||"auto"}static configure(e,t){return i(this,void 0,void 0,(function*(){const{fetchBehavior:n,preResolve:i,logger:o}=t||{},{category:s="voicefocus",name:c="default",variant:l="auto",assetGroup:d=f,revisionID:u,simd:h="detect",executionPreference:p="auto",executionQuantaPreference:g,usagePreference:v="interactivity",estimatorBudget:b=100,paths:y=m,thresholds:w}=e||{};if(null==o||o.debug("Configuring Voice Focus with spec",e),void 0!==s&&"voicefocus"!==s)throw new Error(`Unrecognized category ${s}`);if(void 0!==c&&"default"!==c&&"ns_es"!==c)throw new Error(`Unrecognized feature name ${c}`);if(void 0!==l&&!["auto","c100","c50","c20","c10"].includes(l))throw new Error(`Unrecognized feature variant ${l}`);if(void 0!==g&&![1,2,3].includes(g))throw new Error(`Unrecognized execution quanta preference ${g}`);if(S(d,u),void 0!==h&&!["detect","force","disable"].includes(h))throw new Error(`Unrecognized SIMD option ${h}`);if(void 0!==p&&!["auto","inline","worker","worker-sab","worker-postMessage"].includes(p))throw new Error(`Unrecognized execution preference ${p}`);if(void 0!==v&&!["quality","interactivity"].includes(v))throw new Error(`Unrecognized usage preference ${v}`);const M={executionPreference:this.mungeExecutionPreference(p,o),usagePreference:v,executionQuantaPreference:g,variantPreference:l,namePreference:c,simdPreference:h,estimatorBudget:b},z=u?{revisionID:u}:{assetGroup:d},k=a.addQueryParams(n,z),x=Object.assign({paths:y},k),V=yield r.measureAndDecideExecutionApproach(M,x,o,w);if(!1===V.supported)return{supported:!1,reason:V.reason};null==o||o.info("Decided execution approach",V);const{useSIMD:H,processor:E,variant:L,executionQuanta:T}=V,A={category:s||"voicefocus",name:c||"default",variant:L,simd:H};if(i){const e=C(A,y);A.url=yield a.resolveURL(e,k)}return{fetchConfig:x,model:A,processor:E,executionQuanta:T,supported:!0}}))}static init(e,{delegate:t,preload:n=!0,logger:r}){return i(this,void 0,void 0,(function*(){if(!1===e.supported)throw new Error("Voice Focus not supported. Reason: "+e.reason);const{model:i,processor:a,fetchConfig:c,executionQuanta:l}=e,{simd:d,name:u}=i,{paths:f}=c;if("voicefocus-inline-processor"!==a&&"voicefocus-worker-postMessage-processor"!==a&&"voicefocus-worker-sab-processor"!==a)throw new Error(`Unknown processor ${a}`);const h=i.url||C(i,f);null==r||r.debug(`Using model URL ${h}.`);const m=`${f.wasm}audio_buffer-v1${d?"_simd":""}.wasm`,p=`${f.wasm}resampler-v1${d?"_simd":""}.wasm`,g=`${f.workers}worker-v1.js`,{file:v,node:b}=y[a],S=`${f.processors}${v}`,M=yield o.loadWorker(g,"VoiceFocusWorker",c,r);if(n){null==r||r.debug("Preloading",h);let e=s.supportsWASMPostMessage(globalThis)?"get-module":"get-module-buffer";M.postMessage({message:e,preload:!0,key:"model",fetchBehavior:c,path:h})}const z=new w(M,S,b,{processor:a,worker:M,audioBufferURL:m,resamplerURL:p,fetchBehavior:c,modelURL:h,delegate:t,logger:r,numberOfInputs:"ns_es"===u?2:1},l);return Promise.resolve(z)}))}createNode(e,t){var n;if(this.internal.isDestroyed)throw new Error("Unable to create node because VoiceFocus worker has been destroyed.");const{voiceFocusSampleRate:i=(16e3===e.sampleRate?16e3:48e3),enabled:r=!0,agc:o=u}=t||{},s=null==t?void 0:t.es,c={voiceFocusSampleRate:i,enabled:r,sendBufferCount:10,prefill:6,agc:o,executionQuanta:this.executionQuanta,supportFarendStream:s},l=a.withQueryString(this.processorURL,null===(n=this.nodeOptions)||void 0===n?void 0:n.fetchBehavior);return e.audioWorklet.addModule(l).then((()=>new this.nodeConstructor(e,Object.assign(Object.assign({},this.nodeOptions),{processorOptions:c}))))}applyToStream(e,t,n){return i(this,void 0,void 0,(function*(){if(this.internal.isDestroyed)throw new Error("Unable to apply stream because VoiceFocus worker has been destroyed");const i=t.createMediaStreamSource(e),r=yield this.applyToSourceNode(i,t,n),a=t.createMediaStreamDestination();return r.connect(a),{node:r,source:i,destination:a,stream:a.stream}}))}applyToSourceNode(e,t,n){return i(this,void 0,void 0,(function*(){const i=yield this.createNode(t,n);return e.connect(i),i}))}destroy(){this.internal.worker&&this.internal.worker.terminate(),this.internal.isDestroyed=!0}}t.VoiceFocus=w,t.createAudioContext=(e=p)=>new(window.AudioContext||window.webkitAudioContext)(e),t.getAudioInput=(e,t,n)=>i(void 0,void 0,void 0,(function*(){var i,r;const{constraints:a,spec:o,delegate:s,preload:c=!0,options:l}=t,{logger:d}=n,f=yield w.configure(o,n);if(!f.supported)return null===(i=n.logger)||void 0===i||i.warn("Voice Focus not supported; returning standard stream."),window.navigator.mediaDevices.getUserMedia(a);const h=yield w.init(f,{delegate:s,preload:c,logger:d}),m=(null===(r=t.options)||void 0===r?void 0:r.agc)||u,p=yield window.navigator.mediaDevices.getUserMedia(((e,t)=>{let n;if(n=t.useBuiltInAGC?v:b,!e)return{audio:n};if(!e.audio)return e;if(e.video)throw new Error("Not adding Voice Focus to multi-device getUserMedia call.");return Object.assign(Object.assign({},e),{audio:!0===e.audio?n:Object.assign(Object.assign({},e.audio),n)})})(a,m));return h.applyToStream(p,e,l).then((e=>e.stream))}))},3596:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});const r=n(5128),a=n(7614);class o extends a.VoiceFocusAudioWorkletNode{constructor(e,t){super(e,t.processor,t),this.cpuWarningCount=0,this.channelCountMode="explicit",this.channelCount=1;const{modelURL:n,worker:i,fetchBehavior:a,logger:o,delegate:s}=t;this.logger=o,this.port.onmessage=this.onProcessorMessage.bind(this),this.delegate=s,o&&o.debug("VoiceFocusInlineNode:",n),this.worker=i,this.worker.onmessage=this.onWorkerMessage.bind(this);const c=r.supportsWASMPostMessage(globalThis)?"get-module":"get-module-buffer";this.worker.postMessage({message:c,key:"model",fetchBehavior:a,path:n})}onModuleBufferLoaded(e,t){this.port.postMessage({message:"module-buffer",buffer:e,key:t})}onModuleLoaded(e,t){this.port.postMessage({message:"module",module:e,key:t})}enable(){return i(this,void 0,void 0,(function*(){this.port.postMessage({message:"enable"})}))}disable(){return i(this,void 0,void 0,(function*(){this.port.postMessage({message:"disable"})}))}stop(){var e;return i(this,void 0,void 0,(function*(){this.port.postMessage({message:"stop"});try{null===(e=this.worker)||void 0===e||e.terminate()}catch(e){console.error("failed to terminate worker:",e)}this.disconnect()}))}onProcessorMessage(e){var t,n,i;const r=e.data;if("cpu"===r.message){this.cpuWarningCount++;const e=Date.now(),i=this.cpuWarningLastTriggered||e,a=Math.abs(e-i);(!this.cpuWarningLastTriggered||a>5e3)&&(null===(t=this.logger)||void 0===t||t.warn(`CPU warning (count: ${this.cpuWarningCount}):`,r.message),this.cpuWarningCount=0,this.cpuWarningLastTriggered=e),null===(n=this.delegate)||void 0===n||n.onCPUWarning()}else null===(i=this.logger)||void 0===i||i.debug("Ignoring processor message.")}onWorkerMessage(e){const t=e.data;switch(t.message){case"module-buffer":if(!t.buffer||!t.key)return;this.onModuleBufferLoaded(t.buffer,t.key);break;case"module":if(!t.module||!t.key)return;this.onModuleLoaded(t.module,t.key);break;case"stopped":this.worker&&this.worker.terminate();break;default:return}}}t.default=o},2297:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});const r=n(5128),a=n(7614);class o extends a.VoiceFocusAudioWorkletNode{constructor(e,t){super(e,t.processor,t),this.channelCountMode="explicit",this.channelCount=1;const{modelURL:n,audioBufferURL:i,worker:a,fetchBehavior:o,delegate:s}=t;this.delegate=s,this.worker=a,this.worker.onmessage=this.onWorkerMessage.bind(this),this.port.onmessage=this.onProcessorMessage.bind(this);const{enabled:c,agc:l,supportFarendStream:d}=t.processorOptions;this.worker.postMessage({message:"init",approach:"postMessage",frames:16e3===e.sampleRate?160:480,enabled:c,agc:l,fetchBehavior:o,model:n,supportFarendStream:d});const u=r.supportsWASMPostMessage(globalThis)?"get-module":"get-module-buffer";this.worker.postMessage({message:u,key:"buffer",fetchBehavior:o,path:i})}enable(){return i(this,void 0,void 0,(function*(){this.worker.postMessage({message:"enable"})}))}disable(){return i(this,void 0,void 0,(function*(){this.worker.postMessage({message:"disable"})}))}stop(){return i(this,void 0,void 0,(function*(){try{this.worker.postMessage({message:"stop"})}catch(e){}this.disconnect()}))}onWorkerMessage(e){var t;const n=e.data;switch(n.message){case"ready":this.port.postMessage({message:"ready",shared:n.shared},n.shared?Object.values(n.shared):[]);break;case"data":if(!n.buffer)return;this.port.postMessage({message:"data",buffer:n.buffer},[n.buffer]);break;case"stopped":this.worker.terminate();break;case"module-buffer":case"module":case"processing":this.port.postMessage(n);break;case"cpu":null===(t=this.delegate)||void 0===t||t.onCPUWarning();break;default:return}}onProcessorMessage(e){var t;const n=e.data;switch(n.message){case"data":if(!n.buffer)return;this.worker.postMessage({message:"data",buffer:n.buffer},[n.buffer]);break;case"cpu":null===(t=this.delegate)||void 0===t||t.onCPUWarning();break;case"prepare-for-frames":this.worker.postMessage(n);break;default:return}}}t.default=o},1104:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});const r=n(5128),a=n(7614);class o extends a.VoiceFocusAudioWorkletNode{constructor(e,t){super(e,t.processor,t),this.channelCountMode="explicit",this.channelCount=1;const{modelURL:n,resamplerURL:i,worker:a,fetchBehavior:o,delegate:s}=t;this.delegate=s,this.worker=a,this.worker.onmessage=this.onWorkerMessage.bind(this),this.port.onmessage=this.onProcessorMessage.bind(this);const{enabled:c,supportFarendStream:l}=t.processorOptions;this.worker.postMessage({message:"init",approach:"sab",frames:16e3===e.sampleRate?160:480,enabled:c,model:n,supportFarendStream:l});const d=r.supportsWASMPostMessage(globalThis)?"get-module":"get-module-buffer";this.worker.postMessage({message:d,key:"resampler",fetchBehavior:o,path:i})}enable(){return i(this,void 0,void 0,(function*(){this.state?(Atomics.store(this.state,1,1),Atomics.notify(this.state,0,1)):this.worker.postMessage({message:"enable"})}))}disable(){return i(this,void 0,void 0,(function*(){this.state?(Atomics.store(this.state,1,0),Atomics.notify(this.state,0,1)):this.worker.postMessage({message:"disable"})}))}stop(){return i(this,void 0,void 0,(function*(){if(this.state)Atomics.store(this.state,1,2),Atomics.notify(this.state,0,1);else try{this.worker.postMessage({message:"stop"})}catch(e){}this.disconnect()}))}onWorkerMessage(e){var t;const n=e.data;switch(n.message){case"ready":if(!n.shared)throw new Error("No shared state.");this.state=new Int32Array(n.shared.state),this.port.postMessage(n);break;case"stopped":this.worker.terminate();break;case"module-buffer":case"module":case"processing":this.port.postMessage(n);break;case"cpu":null===(t=this.delegate)||void 0===t||t.onCPUWarning();break;default:return}}onProcessorMessage(e){var t;const n=e.data;switch(n.message){case"cpu":null===(t=this.delegate)||void 0===t||t.onCPUWarning();break;case"prepare-for-frames":this.worker.postMessage(n)}}}t.default=o},7526:(e,t)=>{"use strict";t.byteLength=function(e){var t=s(e),n=t[0],i=t[1];return 3*(n+i)/4-i},t.toByteArray=function(e){var t,n,a=s(e),o=a[0],c=a[1],l=new r(function(e,t,n){return 3*(t+n)/4-n}(0,o,c)),d=0,u=c>0?o-4:o;for(n=0;n>16&255,l[d++]=t>>8&255,l[d++]=255&t;return 2===c&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,l[d++]=255&t),1===c&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,l[d++]=t>>8&255,l[d++]=255&t),l},t.fromByteArray=function(e){for(var t,i=e.length,r=i%3,a=[],o=16383,s=0,l=i-r;sl?l:s+o));return 1===r?(t=e[i-1],a.push(n[t>>2]+n[t<<4&63]+"==")):2===r&&(t=(e[i-2]<<8)+e[i-1],a.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),a.join("")};for(var n=[],i=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)n[o]=a[o],i[a.charCodeAt(o)]=o;function s(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function c(e,t,i){for(var r,a,o=[],s=t;s>18&63]+n[a>>12&63]+n[a>>6&63]+n[63&a]);return o.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},4499:function(e){e.exports=function(e){var t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(i,r,function(t){return e[t]}.bind(null,r));return i},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=90)}({17:function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var i=n(18),r=function(){function e(){}return e.getFirstMatch=function(e,t){var n=t.match(e);return n&&n.length>0&&n[1]||""},e.getSecondMatch=function(e,t){var n=t.match(e);return n&&n.length>1&&n[2]||""},e.matchAndReturnConst=function(e,t,n){if(e.test(t))return n},e.getWindowsVersionName=function(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0},e.getVersionPrecision=function(e){return e.split(".").length},e.compareVersions=function(t,n,i){void 0===i&&(i=!1);var r=e.getVersionPrecision(t),a=e.getVersionPrecision(n),o=Math.max(r,a),s=0,c=e.map([t,n],(function(t){var n=o-e.getVersionPrecision(t),i=t+new Array(n+1).join(".0");return e.map(i.split("."),(function(e){return new Array(20-e.length).join("0")+e})).reverse()}));for(i&&(s=o-Math.min(r,a)),o-=1;o>=s;){if(c[0][o]>c[1][o])return 1;if(c[0][o]===c[1][o]){if(o===s)return 0;o-=1}else if(c[0][o]1?r-1:0),o=1;o0){var o=Object.keys(n),c=s.default.find(o,(function(e){return t.isOS(e)}));if(c){var l=this.satisfies(n[c]);if(void 0!==l)return l}var d=s.default.find(o,(function(e){return t.isPlatform(e)}));if(d){var u=this.satisfies(n[d]);if(void 0!==u)return u}}if(a>0){var f=Object.keys(r),h=s.default.find(f,(function(e){return t.isBrowser(e,!0)}));if(void 0!==h)return this.compareVersion(r[h])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var n=this.getBrowserName().toLowerCase(),i=e.toLowerCase(),r=s.default.getBrowserTypeByAlias(i);return t&&r&&(i=r.toLowerCase()),i===n},t.compareVersion=function(e){var t=[0],n=e,i=!1,r=this.getBrowserVersion();if("string"==typeof r)return">"===e[0]||"<"===e[0]?(n=e.substr(1),"="===e[1]?(i=!0,n=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?n=e.substr(1):"~"===e[0]&&(i=!0,n=e.substr(1)),t.indexOf(s.default.compareVersions(r,n,i))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e,t){return void 0===t&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some((function(e){return t.is(e)}))},e}();t.default=l,e.exports=t.default},92:function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var i,r=(i=n(17))&&i.__esModule?i:{default:i},a=/version\/(\d+(\.?_?\d+)+)/i,o=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},n=r.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},n=r.default.getFirstMatch(a,e)||r.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},n=r.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},n=r.default.getFirstMatch(a,e)||r.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},n=r.default.getFirstMatch(a,e)||r.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},n=r.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},n=r.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},n=r.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},n=r.default.getFirstMatch(a,e)||r.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:"Opera Touch"},n=r.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},n=r.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},n=r.default.getFirstMatch(a,e)||r.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},n=r.default.getFirstMatch(a,e)||r.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},n=r.default.getFirstMatch(a,e)||r.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},n=r.default.getFirstMatch(a,e)||r.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},n=r.default.getFirstMatch(a,e)||r.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},n=r.default.getFirstMatch(a,e)||r.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},n=r.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},n=r.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},n=r.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},n=r.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},n=r.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},n=r.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},n=r.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},n=r.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return n&&(t.version=n),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},n=r.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},n=r.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},n=r.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},n=r.default.getFirstMatch(a,e)||r.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},n=r.default.getFirstMatch(a,e)||r.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},n=r.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},n=r.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},n=r.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},n=r.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},n=r.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:"Miui"},n=r.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},n=r.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},n=r.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},n=r.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:function(e){var t=!e.test(/like android/i),n=e.test(/android/i);return t&&n},describe:function(e){var t={name:"Android Browser"},n=r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},n=r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},n=r.default.getFirstMatch(a,e);return n&&(t.version=n),t}},{test:[/.*/i],describe:function(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:r.default.getFirstMatch(t,e),version:r.default.getSecondMatch(t,e)}}}];t.default=o,e.exports=t.default},93:function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var i,r=(i=n(17))&&i.__esModule?i:{default:i},a=n(18),o=[{test:[/Roku\/DVP/],describe:function(e){var t=r.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:a.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=r.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=r.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),n=r.default.getWindowsVersionName(t);return{name:a.OS_MAP.Windows,version:t,versionName:n}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:a.OS_MAP.iOS},n=r.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return n&&(t.version=n),t}},{test:[/macintosh/i],describe:function(e){var t=r.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),n=r.default.getMacOSVersionName(t),i={name:a.OS_MAP.MacOS,version:t};return n&&(i.versionName=n),i}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=r.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:a.OS_MAP.iOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),n=e.test(/android/i);return t&&n},describe:function(e){var t=r.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),n=r.default.getAndroidVersionName(t),i={name:a.OS_MAP.Android,version:t};return n&&(i.versionName=n),i}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=r.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),n={name:a.OS_MAP.WebOS};return t&&t.length&&(n.version=t),n}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=r.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||r.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||r.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:a.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=r.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=r.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:a.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:a.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=r.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:a.OS_MAP.PlayStation4,version:t}}}];t.default=o,e.exports=t.default},94:function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var i,r=(i=n(17))&&i.__esModule?i:{default:i},a=n(18),o=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e){var t=r.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",n={type:a.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(n.model=t),n}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:a.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),n=e.test(/like (ipod|iphone)/i);return t&&!n},describe:function(e){var t=r.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:a.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:a.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:a.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:a.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:function(){return{type:a.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.mobile}}},{test:function(e){return"macos"===e.getOSName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(!0)},describe:function(){return{type:a.PLATFORMS_MAP.tv}}}];t.default=o,e.exports=t.default},95:function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var i,r=(i=n(17))&&i.__esModule?i:{default:i},a=n(18),o=[{test:function(e){return"microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return{name:a.ENGINE_MAP.Blink};var t=r.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:a.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:a.ENGINE_MAP.Trident},n=r.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:a.ENGINE_MAP.Presto},n=r.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:function(e){var t=e.test(/gecko/i),n=e.test(/like gecko/i);return t&&!n},describe:function(e){var t={name:a.ENGINE_MAP.Gecko},n=r.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:a.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:a.ENGINE_MAP.WebKit},n=r.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}}];t.default=o,e.exports=t.default}})},8287:(e,t,n)=>{"use strict";const i=n(7526),r=n(251),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=c,t.IS=50;const o=2147483647;function s(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,c.prototype),t}function c(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return l(e,t,n)}function l(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!c.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|p(e,t);let i=s(n);const r=i.write(e,t);return r!==n&&(i=i.slice(0,r)),i}(e,t);if(ArrayBuffer.isView(e))return function(e){if(J(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return f(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(J(e,ArrayBuffer)||e&&J(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(J(e,SharedArrayBuffer)||e&&J(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return c.from(i,t,n);const r=function(e){if(c.isBuffer(e)){const t=0|m(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||Z(e.length)?s(0):f(e):"Buffer"===e.type&&Array.isArray(e.data)?f(e.data):void 0}(e);if(r)return r;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return c.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function d(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return d(e),s(e<0?0:0|m(e))}function f(e){const t=e.length<0?0:0|m(e.length),n=s(t);for(let i=0;i=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function p(e,t){if(c.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||J(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;let r=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return $(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return G(e).length;default:if(r)return i?-1:$(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return L(this,t,n);case"utf8":case"utf-8":return x(this,t,n);case"ascii":return H(this,t,n);case"latin1":case"binary":return E(this,t,n);case"base64":return k(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,n);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function v(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}function b(e,t,n,i,r){if(0===e.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Z(n=+n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=c.from(t,i)),c.isBuffer(t))return 0===t.length?-1:y(e,t,n,i,r);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,i,r);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,i,r){let a,o=1,s=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;o=2,s/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(r){let i=-1;for(a=n;as&&(n=s-c),a=n;a>=0;a--){let n=!0;for(let i=0;ir&&(i=r):i=r;const a=t.length;let o;for(i>a/2&&(i=a/2),o=0;o>8,r=n%256,a.push(r),a.push(i);return a}(t,e.length-n),e,n,i)}function k(e,t,n){return 0===t&&n===e.length?i.fromByteArray(e):i.fromByteArray(e.slice(t,n))}function x(e,t,n){n=Math.min(e.length,n);const i=[];let r=t;for(;r239?4:t>223?3:t>191?2:1;if(r+o<=n){let n,i,s,c;switch(o){case 1:t<128&&(a=t);break;case 2:n=e[r+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(a=c));break;case 3:n=e[r+1],i=e[r+2],128==(192&n)&&128==(192&i)&&(c=(15&t)<<12|(63&n)<<6|63&i,c>2047&&(c<55296||c>57343)&&(a=c));break;case 4:n=e[r+1],i=e[r+2],s=e[r+3],128==(192&n)&&128==(192&i)&&128==(192&s)&&(c=(15&t)<<18|(63&n)<<12|(63&i)<<6|63&s,c>65535&&c<1114112&&(a=c))}}null===a?(a=65533,o=1):a>65535&&(a-=65536,i.push(a>>>10&1023|55296),a=56320|1023&a),i.push(a),r+=o}return function(e){const t=e.length;if(t<=V)return String.fromCharCode.apply(String,e);let n="",i=0;for(;ii.length?(c.isBuffer(t)||(t=c.from(t)),t.copy(i,r)):Uint8Array.prototype.set.call(i,t,r);else{if(!c.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,r)}r+=t.length}return i},c.byteLength=p,c.prototype._isBuffer=!0,c.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tn&&(e+=" ... "),""},a&&(c.prototype[a]=c.prototype.inspect),c.prototype.compare=function(e,t,n,i,r){if(J(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===r&&(r=this.length),t<0||n>e.length||i<0||r>this.length)throw new RangeError("out of range index");if(i>=r&&t>=n)return 0;if(i>=r)return-1;if(t>=n)return 1;if(this===e)return 0;let a=(r>>>=0)-(i>>>=0),o=(n>>>=0)-(t>>>=0);const s=Math.min(a,o),l=this.slice(i,r),d=e.slice(t,n);for(let e=0;e>>=0,isFinite(n)?(n>>>=0,void 0===i&&(i="utf8")):(i=n,n=void 0)}const r=this.length-t;if((void 0===n||n>r)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let a=!1;for(;;)switch(i){case"hex":return S(this,e,t,n);case"utf8":case"utf-8":return C(this,e,t,n);case"ascii":case"latin1":case"binary":return w(this,e,t,n);case"base64":return M(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),a=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const V=4096;function H(e,t,n){let i="";n=Math.min(e.length,n);for(let r=t;ri)&&(n=i);let r="";for(let i=t;in)throw new RangeError("Trying to access beyond buffer length")}function _(e,t,n,i,r,a){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||te.length)throw new RangeError("Index out of range")}function N(e,t,n,i,r){U(t,i,r,e,n,7);let a=Number(t&BigInt(4294967295));e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a,a>>=8,e[n++]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function I(e,t,n,i,r){U(t,i,r,e,n,7);let a=Number(t&BigInt(4294967295));e[n+7]=a,a>>=8,e[n+6]=a,a>>=8,e[n+5]=a,a>>=8,e[n+4]=a;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}function P(e,t,n,i,r,a){if(n+i>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function O(e,t,n,i,a){return t=+t,n>>>=0,a||P(e,0,n,4),r.write(e,t,n,i,23,4),n+4}function R(e,t,n,i,a){return t=+t,n>>>=0,a||P(e,0,n,8),r.write(e,t,n,i,52,8),n+8}c.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t>>=0,t>>>=0,n||A(e,t,this.length);let i=this[e],r=1,a=0;for(;++a>>=0,t>>>=0,n||A(e,t,this.length);let i=this[e+--t],r=1;for(;t>0&&(r*=256);)i+=this[e+--t]*r;return i},c.prototype.readUint8=c.prototype.readUInt8=function(e,t){return e>>>=0,t||A(e,1,this.length),this[e]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||A(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||A(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||A(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||A(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readBigUInt64LE=Y((function(e){j(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||q(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,r=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(i)+(BigInt(r)<>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||q(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],r=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(i)<>>=0,t>>>=0,n||A(e,t,this.length);let i=this[e],r=1,a=0;for(;++a=r&&(i-=Math.pow(2,8*t)),i},c.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||A(e,t,this.length);let i=t,r=1,a=this[e+--i];for(;i>0&&(r*=256);)a+=this[e+--i]*r;return r*=128,a>=r&&(a-=Math.pow(2,8*t)),a},c.prototype.readInt8=function(e,t){return e>>>=0,t||A(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||A(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){e>>>=0,t||A(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||A(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||A(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readBigInt64LE=Y((function(e){j(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||q(e,this.length-8);const i=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(i)<>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||q(e,this.length-8);const i=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(i)<>>=0,t||A(e,4,this.length),r.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||A(e,4,this.length),r.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||A(e,8,this.length),r.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||A(e,8,this.length),r.read(this,e,!1,52,8)},c.prototype.writeUintLE=c.prototype.writeUIntLE=function(e,t,n,i){e=+e,t>>>=0,n>>>=0,i||_(this,e,t,n,Math.pow(2,8*n)-1,0);let r=1,a=0;for(this[t]=255&e;++a>>=0,n>>>=0,i||_(this,e,t,n,Math.pow(2,8*n)-1,0);let r=n-1,a=1;for(this[t+r]=255&e;--r>=0&&(a*=256);)this[t+r]=e/a&255;return t+n},c.prototype.writeUint8=c.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigUInt64LE=Y((function(e,t=0){return N(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeBigUInt64BE=Y((function(e,t=0){return I(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);_(this,e,t,n,i-1,-i)}let r=0,a=1,o=0;for(this[t]=255&e;++r>0)-o&255;return t+n},c.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);_(this,e,t,n,i-1,-i)}let r=n-1,a=1,o=0;for(this[t+r]=255&e;--r>=0&&(a*=256);)e<0&&0===o&&0!==this[t+r+1]&&(o=1),this[t+r]=(e/a>>0)-o&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||_(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigInt64LE=Y((function(e,t=0){return N(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeBigInt64BE=Y((function(e,t=0){return I(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeFloatLE=function(e,t,n){return O(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return O(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return R(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return R(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,i){if(!c.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(r=t;r=i+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function U(e,t,n,i,r,a){if(e>n||e3?0===t||t===BigInt(0)?`>= 0${i} and < 2${i} ** ${8*(a+1)}${i}`:`>= -(2${i} ** ${8*(a+1)-1}${i}) and < 2 ** ${8*(a+1)-1}${i}`:`>= ${t}${i} and <= ${n}${i}`,new D.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){j(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||q(t,e.length-(n+1))}(i,r,a)}function j(e,t){if("number"!=typeof e)throw new D.ERR_INVALID_ARG_TYPE(t,"number",e)}function q(e,t,n){if(Math.floor(e)!==e)throw j(e,n),new D.ERR_OUT_OF_RANGE(n||"offset","an integer",e);if(t<0)throw new D.ERR_BUFFER_OUT_OF_BOUNDS;throw new D.ERR_OUT_OF_RANGE(n||"offset",`>= ${n?1:0} and <= ${t}`,e)}F("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),F("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),F("ERR_OUT_OF_RANGE",(function(e,t,n){let i=`The value of "${e}" is out of range.`,r=n;return Number.isInteger(n)&&Math.abs(n)>2**32?r=B(String(n)):"bigint"==typeof n&&(r=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(r=B(r)),r+="n"),i+=` It must be ${t}. Received ${r}`,i}),RangeError);const W=/[^+/0-9A-Za-z-_]/g;function $(e,t){let n;t=t||1/0;const i=e.length;let r=null;const a=[];for(let o=0;o55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(o+1===i){(t-=3)>-1&&a.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&a.push(239,191,189);if(r=null,n<128){if((t-=1)<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return a}function G(e){return i.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function K(e,t,n,i){let r;for(r=0;r=t.length||r>=e.length);++r)t[r+n]=e[r];return r}function J(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Z(e){return e!=e}const Q=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const i=16*n;for(let r=0;r<16;++r)t[i+r]=e[n]+e[r]}return t}();function Y(e){return"undefined"==typeof BigInt?X:e}function X(){throw new Error("BigInt not supported")}},8468:(e,t,n)=>{"use strict";n.r(t),n.d(t,{BotInfo:()=>s,BrowserInfo:()=>r,NodeInfo:()=>a,ReactNativeInfo:()=>c,SearchBotDeviceInfo:()=>o,browserName:()=>p,detect:()=>h,detectOS:()=>v,getNodeVersion:()=>b,parseUserAgent:()=>g});var i=function(e,t,n){if(n||2===arguments.length)for(var i,r=0,a=t.length;r{t.read=function(e,t,n,i,r){var a,o,s=8*r-i-1,c=(1<>1,d=-7,u=n?r-1:0,f=n?-1:1,h=e[t+u];for(u+=f,a=h&(1<<-d)-1,h>>=-d,d+=s;d>0;a=256*a+e[t+u],u+=f,d-=8);for(o=a&(1<<-d)-1,a>>=-d,d+=i;d>0;o=256*o+e[t+u],u+=f,d-=8);if(0===a)a=1-l;else{if(a===c)return o?NaN:1/0*(h?-1:1);o+=Math.pow(2,i),a-=l}return(h?-1:1)*o*Math.pow(2,a-i)},t.write=function(e,t,n,i,r,a){var o,s,c,l=8*a-r-1,d=(1<>1,f=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,h=i?0:a-1,m=i?1:-1,p=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=d):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+u>=1?f/c:f*Math.pow(2,1-u))*c>=2&&(o++,c/=2),o+u>=d?(s=0,o=d):o+u>=1?(s=(t*c-1)*Math.pow(2,r),o+=u):(s=t*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;e[n+h]=255&s,h+=m,s/=256,r-=8);for(o=o<0;e[n+h]=255&o,h+=m,o/=256,l-=8);e[n+h-m]|=128*p}},3790:(e,t,n)=>{e.exports=function e(t,n,i){function r(o,s){if(!n[o]){if(!t[o]){if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[o]={exports:{}};t[o][0].call(l.exports,(function(e){return r(t[o][1][e]||e)}),l,l.exports,e,t,n,i)}return n[o].exports}for(var a=void 0,o=0;o=43)}})).catch((function(){return!1}))}(e).then((function(e){return f=e}))}function y(e){var t=h[e.name],n={};n.promise=new o((function(e,t){n.resolve=e,n.reject=t})),t.deferredOperations.push(n),t.dbReady?t.dbReady=t.dbReady.then((function(){return n.promise})):t.dbReady=n.promise}function S(e){var t=h[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function C(e,t){var n=h[e.name].deferredOperations.pop();if(n)return n.reject(t),n.promise}function w(e,t){return new o((function(n,i){if(h[e.name]=h[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return n(e.db);y(e),e.db.close()}var a=[e.name];t&&a.push(e.version);var o=r.open.apply(r,a);t&&(o.onupgradeneeded=function(t){var n=o.result;try{n.createObjectStore(e.storeName),t.oldVersion<=1&&n.createObjectStore(u)}catch(n){if("ConstraintError"!==n.name)throw n;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),o.onerror=function(e){e.preventDefault(),i(o.error)},o.onsuccess=function(){var t=o.result;t.onversionchange=function(e){e.target.close()},n(t),S(e)}}))}function M(e){return w(e,!1)}function z(e){return w(e,!0)}function k(e,t){if(!e.db)return!0;var n=!e.db.objectStoreNames.contains(e.storeName),i=e.versione.db.version;if(i&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),r||n){if(n){var a=e.db.version+1;a>e.version&&(e.version=a)}return!0}return!1}function x(e){return a([v(atob(e.data))],{type:e.type})}function V(e){return e&&e.__local_forage_encoded_blob}function H(e){var t=this,n=t._initReady().then((function(){var e=h[t._dbInfo.name];if(e&&e.dbReady)return e.dbReady}));return c(n,e,e),n}function E(e,t,n,i){void 0===i&&(i=1);try{var r=e.db.transaction(e.storeName,t);n(null,r)}catch(r){if(i>0&&(!e.db||"InvalidStateError"===r.name||"NotFoundError"===r.name))return o.resolve().then((function(){if(!e.db||"NotFoundError"===r.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),z(e)})).then((function(){return function(e){y(e);for(var t=h[e.name],n=t.forages,i=0;i>4,d[c++]=(15&i)<<4|r>>2,d[c++]=(3&r)<<6|63&a;return l}function G(e){var t,n=new Uint8Array(e),i="";for(t=0;t>2],i+=T[(3&n[t])<<4|n[t+1]>>4],i+=T[(15&n[t+1])<<2|n[t+2]>>6],i+=T[63&n[t+2]];return n.length%3==2?i=i.substring(0,i.length-1)+"=":n.length%3==1&&(i=i.substring(0,i.length-2)+"=="),i}var K={serialize:function(e,t){var n="";if(e&&(n=W.call(e)),e&&("[object ArrayBuffer]"===n||e.buffer&&"[object ArrayBuffer]"===W.call(e.buffer))){var i,r=_;e instanceof ArrayBuffer?(i=e,r+=N):(i=e.buffer,"[object Int8Array]"===n?r+=P:"[object Uint8Array]"===n?r+=O:"[object Uint8ClampedArray]"===n?r+=R:"[object Int16Array]"===n?r+=D:"[object Uint16Array]"===n?r+=B:"[object Int32Array]"===n?r+=F:"[object Uint32Array]"===n?r+=U:"[object Float32Array]"===n?r+=j:"[object Float64Array]"===n?r+=q:t(new Error("Failed to get type for BinaryArray"))),t(r+G(i))}else if("[object Blob]"===n){var a=new FileReader;a.onload=function(){var n="~~local_forage_type~"+e.type+"~"+G(this.result);t(_+I+n)},a.readAsArrayBuffer(e)}else try{t(JSON.stringify(e))}catch(n){console.error("Couldn't convert value into a JSON string: ",e),t(null,n)}},deserialize:function(e){if(e.substring(0,9)!==_)return JSON.parse(e);var t,n=e.substring(13),i=e.substring(9,13);if(i===I&&A.test(n)){var r=n.match(A);t=r[1],n=n.substring(r[0].length)}var o=$(n);switch(i){case N:return o;case I:return a([o],{type:t});case P:return new Int8Array(o);case O:return new Uint8Array(o);case R:return new Uint8ClampedArray(o);case D:return new Int16Array(o);case B:return new Uint16Array(o);case F:return new Int32Array(o);case U:return new Uint32Array(o);case j:return new Float32Array(o);case q:return new Float64Array(o);default:throw new Error("Unkown type: "+i)}},stringToBuffer:$,bufferToString:G};function J(e,t,n,i){e.executeSql("CREATE TABLE IF NOT EXISTS "+t.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],n,i)}function Z(e,t,n,i,r,a){e.executeSql(n,i,r,(function(e,o){o.code===o.SYNTAX_ERR?e.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[t.storeName],(function(e,s){s.rows.length?a(e,o):J(e,t,(function(){e.executeSql(n,i,r,a)}),a)}),a):a(e,o)}),a)}function Q(e,t,n,i){var r=this;e=l(e);var a=new o((function(a,o){r.ready().then((function(){void 0===t&&(t=null);var s=t,c=r._dbInfo;c.serializer.serialize(t,(function(t,l){l?o(l):c.db.transaction((function(n){Z(n,c,"INSERT OR REPLACE INTO "+c.storeName+" (key, value) VALUES (?, ?)",[e,t],(function(){a(s)}),(function(e,t){o(t)}))}),(function(t){if(t.code===t.QUOTA_ERR){if(i>0)return void a(Q.apply(r,[e,s,n,i-1]));o(t)}}))}))})).catch(o)}));return s(a,n),a}var Y={_driver:"webSQLStorage",_initStorage:function(e){var t=this,n={db:null};if(e)for(var i in e)n[i]="string"!=typeof e[i]?e[i].toString():e[i];var r=new o((function(e,i){try{n.db=openDatabase(n.name,String(n.version),n.description,n.size)}catch(e){return i(e)}n.db.transaction((function(r){J(r,n,(function(){t._dbInfo=n,e()}),(function(e,t){i(t)}))}),i)}));return n.serializer=K,r},_support:"function"==typeof openDatabase,iterate:function(e,t){var n=this,i=new o((function(t,i){n.ready().then((function(){var r=n._dbInfo;r.db.transaction((function(n){Z(n,r,"SELECT * FROM "+r.storeName,[],(function(n,i){for(var a=i.rows,o=a.length,s=0;s '__WebKitDatabaseInfoTable__'",[],(function(n,i){for(var r=[],a=0;a0?(this._dbInfo=t,t.serializer=K,o.resolve()):o.reject()},_support:function(){try{return"undefined"!=typeof localStorage&&"setItem"in localStorage&&!!localStorage.setItem}catch(e){return!1}}(),iterate:function(e,t){var n=this,i=n.ready().then((function(){for(var t=n._dbInfo,i=t.keyPrefix,r=i.length,a=localStorage.length,o=1,s=0;s=0;n--){var i=localStorage.key(n);0===i.indexOf(e)&&localStorage.removeItem(i)}}));return s(n,e),n},length:function(e){var t=this.keys().then((function(e){return e.length}));return s(t,e),t},key:function(e,t){var n=this,i=n.ready().then((function(){var t,i=n._dbInfo;try{t=localStorage.key(e)}catch(e){t=null}return t&&(t=t.substring(i.keyPrefix.length)),t}));return s(i,t),i},keys:function(e){var t=this,n=t.ready().then((function(){for(var e=t._dbInfo,n=localStorage.length,i=[],r=0;r=0;t--){var n=localStorage.key(t);0===n.indexOf(e)&&localStorage.removeItem(n)}})):o.reject("Invalid arguments"),s(i,t),i}},te=function(e,t){for(var n=e.length,i=0;i{"use strict";const{Deflate:i,deflate:r,deflateRaw:a,gzip:o}=n(3303),{Inflate:s,inflate:c,inflateRaw:l,ungzip:d}=n(7083),u=n(9681);e.exports.Deflate=i,e.exports.deflate=r,e.exports.deflateRaw=a,e.exports.gzip=o,e.exports.Inflate=s,e.exports.inflate=c,e.exports.inflateRaw=l,e.exports.ungzip=d,e.exports.constants=u},3303:(e,t,n)=>{"use strict";const i=n(8411),r=n(9805),a=n(1996),o=n(4674),s=n(4442),c=Object.prototype.toString,{Z_NO_FLUSH:l,Z_SYNC_FLUSH:d,Z_FULL_FLUSH:u,Z_FINISH:f,Z_OK:h,Z_STREAM_END:m,Z_DEFAULT_COMPRESSION:p,Z_DEFAULT_STRATEGY:g,Z_DEFLATED:v}=n(9681);function b(e){this.options=r.assign({level:p,method:v,chunkSize:16384,windowBits:15,memLevel:8,strategy:g},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new s,this.strm.avail_out=0;let n=i.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==h)throw new Error(o[n]);if(t.header&&i.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?a.string2buf(t.dictionary):"[object ArrayBuffer]"===c.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,n=i.deflateSetDictionary(this.strm,e),n!==h)throw new Error(o[n]);this._dict_set=!0}}function y(e,t){const n=new b(t);if(n.push(e,!0),n.err)throw n.msg||o[n.err];return n.result}b.prototype.push=function(e,t){const n=this.strm,r=this.options.chunkSize;let o,s;if(this.ended)return!1;for(s=t===~~t?t:!0===t?f:l,"string"==typeof e?n.input=a.string2buf(e):"[object ArrayBuffer]"===c.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;)if(0===n.avail_out&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),(s===d||s===u)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if(o=i.deflate(n,s),o===m)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),o=i.deflateEnd(this.strm),this.onEnd(o),this.ended=!0,o===h;if(0!==n.avail_out){if(s>0&&n.next_out>0)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else if(0===n.avail_in)break}else this.onData(n.output)}return!0},b.prototype.onData=function(e){this.chunks.push(e)},b.prototype.onEnd=function(e){e===h&&(this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},e.exports.Deflate=b,e.exports.deflate=y,e.exports.deflateRaw=function(e,t){return(t=t||{}).raw=!0,y(e,t)},e.exports.gzip=function(e,t){return(t=t||{}).gzip=!0,y(e,t)},e.exports.constants=n(9681)},7083:(e,t,n)=>{"use strict";const i=n(3828),r=n(9805),a=n(1996),o=n(4674),s=n(4442),c=n(7414),l=Object.prototype.toString,{Z_NO_FLUSH:d,Z_FINISH:u,Z_OK:f,Z_STREAM_END:h,Z_NEED_DICT:m,Z_STREAM_ERROR:p,Z_DATA_ERROR:g,Z_MEM_ERROR:v}=n(9681);function b(e){this.options=r.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new s,this.strm.avail_out=0;let n=i.inflateInit2(this.strm,t.windowBits);if(n!==f)throw new Error(o[n]);if(this.header=new c,i.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=a.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=i.inflateSetDictionary(this.strm,t.dictionary),n!==f)))throw new Error(o[n])}function y(e,t){const n=new b(t);if(n.push(e),n.err)throw n.msg||o[n.err];return n.result}b.prototype.push=function(e,t){const n=this.strm,r=this.options.chunkSize,o=this.options.dictionary;let s,c,b;if(this.ended)return!1;for(c=t===~~t?t:!0===t?u:d,"[object ArrayBuffer]"===l.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(0===n.avail_out&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),s=i.inflate(n,c),s===m&&o&&(s=i.inflateSetDictionary(n,o),s===f?s=i.inflate(n,c):s===g&&(s=m));n.avail_in>0&&s===h&&n.state.wrap>0&&0!==e[n.next_in];)i.inflateReset(n),s=i.inflate(n,c);switch(s){case p:case g:case m:case v:return this.onEnd(s),this.ended=!0,!1}if(b=n.avail_out,n.next_out&&(0===n.avail_out||s===h))if("string"===this.options.to){let e=a.utf8border(n.output,n.next_out),t=n.next_out-e,i=a.buf2string(n.output,e);n.next_out=t,n.avail_out=r-t,t&&n.output.set(n.output.subarray(e,e+t),0),this.onData(i)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(s!==f||0!==b){if(s===h)return s=i.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===n.avail_in)break}}return!0},b.prototype.onData=function(e){this.chunks.push(e)},b.prototype.onEnd=function(e){e===f&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},e.exports.Inflate=b,e.exports.inflate=y,e.exports.inflateRaw=function(e,t){return(t=t||{}).raw=!0,y(e,t)},e.exports.ungzip=y,e.exports.constants=n(9681)},9805:e=>{"use strict";const t=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);e.exports.assign=function(e){const n=Array.prototype.slice.call(arguments,1);for(;n.length;){const i=n.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const n in i)t(i,n)&&(e[n]=i[n])}}return e},e.exports.flattenChunks=e=>{let t=0;for(let n=0,i=e.length;n{"use strict";let t=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){t=!1}const n=new Uint8Array(256);for(let e=0;e<256;e++)n[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;n[254]=n[254]=1,e.exports.string2buf=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,n,i,r,a,o=e.length,s=0;for(r=0;r>>6,t[a++]=128|63&n):n<65536?(t[a++]=224|n>>>12,t[a++]=128|n>>>6&63,t[a++]=128|63&n):(t[a++]=240|n>>>18,t[a++]=128|n>>>12&63,t[a++]=128|n>>>6&63,t[a++]=128|63&n);return t},e.exports.buf2string=(e,i)=>{const r=i||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,i));let a,o;const s=new Array(2*r);for(o=0,a=0;a4)s[o++]=65533,a+=i-1;else{for(t&=2===i?31:3===i?15:7;i>1&&a1?s[o++]=65533:t<65536?s[o++]=t:(t-=65536,s[o++]=55296|t>>10&1023,s[o++]=56320|1023&t)}}return((e,n)=>{if(n<65534&&e.subarray&&t)return String.fromCharCode.apply(null,e.length===n?e:e.subarray(0,n));let i="";for(let t=0;t{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+n[e[i]]>t?i:t}},3269:e=>{"use strict";e.exports=(e,t,n,i)=>{let r=65535&e|0,a=e>>>16&65535|0,o=0;for(;0!==n;){o=n>2e3?2e3:n,n-=o;do{r=r+t[i++]|0,a=a+r|0}while(--o);r%=65521,a%=65521}return r|a<<16|0}},9681:e=>{"use strict";e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},4823:e=>{"use strict";const t=new Uint32Array((()=>{let e,t=[];for(var n=0;n<256;n++){e=n;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t})());e.exports=(e,n,i,r)=>{const a=t,o=r+i;e^=-1;for(let t=r;t>>8^a[255&(e^n[t])];return-1^e}},8411:(e,t,n)=>{"use strict";const{_tr_init:i,_tr_stored_block:r,_tr_flush_block:a,_tr_tally:o,_tr_align:s}=n(3665),c=n(3269),l=n(4823),d=n(4674),{Z_NO_FLUSH:u,Z_PARTIAL_FLUSH:f,Z_FULL_FLUSH:h,Z_FINISH:m,Z_BLOCK:p,Z_OK:g,Z_STREAM_END:v,Z_STREAM_ERROR:b,Z_DATA_ERROR:y,Z_BUF_ERROR:S,Z_DEFAULT_COMPRESSION:C,Z_FILTERED:w,Z_HUFFMAN_ONLY:M,Z_RLE:z,Z_FIXED:k,Z_DEFAULT_STRATEGY:x,Z_UNKNOWN:V,Z_DEFLATED:H}=n(9681),E=258,L=262,T=42,A=113,_=666,N=(e,t)=>(e.msg=d[t],t),I=e=>2*e-(e>4?9:0),P=e=>{let t=e.length;for(;--t>=0;)e[t]=0},O=e=>{let t,n,i,r=e.w_size;t=e.hash_size,i=t;do{n=e.head[--i],e.head[i]=n>=r?n-r:0}while(--t);t=r,i=t;do{n=e.prev[--i],e.prev[i]=n>=r?n-r:0}while(--t)};let R=(e,t,n)=>(t<{const t=e.state;let n=t.pending;n>e.avail_out&&(n=e.avail_out),0!==n&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+n),e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,0===t.pending&&(t.pending_out=0))},F=(e,t)=>{a(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,D(e.strm)},B=(e,t)=>{e.pending_buf[e.pending++]=t},U=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},j=(e,t,n,i)=>{let r=e.avail_in;return r>i&&(r=i),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),n),1===e.state.wrap?e.adler=c(e.adler,t,r,n):2===e.state.wrap&&(e.adler=l(e.adler,t,r,n)),e.next_in+=r,e.total_in+=r,r)},q=(e,t)=>{let n,i,r=e.max_chain_length,a=e.strstart,o=e.prev_length,s=e.nice_match;const c=e.strstart>e.w_size-L?e.strstart-(e.w_size-L):0,l=e.window,d=e.w_mask,u=e.prev,f=e.strstart+E;let h=l[a+o-1],m=l[a+o];e.prev_length>=e.good_match&&(r>>=2),s>e.lookahead&&(s=e.lookahead);do{if(n=t,l[n+o]===m&&l[n+o-1]===h&&l[n]===l[a]&&l[++n]===l[a+1]){a+=2,n++;do{}while(l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&ao){if(e.match_start=t,o=i,i>=s)break;h=l[a+o-1],m=l[a+o]}}}while((t=u[t&d])>c&&0!=--r);return o<=e.lookahead?o:e.lookahead},W=e=>{const t=e.w_size;let n,i,r;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-L)&&(e.window.set(e.window.subarray(t,t+t-i),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),O(e),i+=t),0===e.strm.avail_in)break;if(n=j(e.strm,e.window,e.strstart+e.lookahead,i),e.lookahead+=n,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=R(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=R(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead{let n,i,a,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,s=0,c=e.strm.avail_in;do{if(n=65535,a=e.bi_valid+42>>3,e.strm.avail_outi+e.strm.avail_in&&(n=i+e.strm.avail_in),n>a&&(n=a),n>8,e.pending_buf[e.pending-2]=~n,e.pending_buf[e.pending-1]=~n>>8,D(e.strm),i&&(i>n&&(i=n),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+i),e.strm.next_out),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i,e.block_start+=i,n-=i),n&&(j(e.strm,e.strm.output,e.strm.next_out,n),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n)}while(0===s);return c-=e.strm.avail_in,c&&(c>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=c&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-c,e.strm.next_in),e.strstart),e.strstart+=c,e.insert+=c>e.w_size-e.insert?e.w_size-e.insert:c),e.block_start=e.strstart),e.high_watera&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,a+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),a>e.strm.avail_in&&(a=e.strm.avail_in),a&&(j(e.strm,e.window,e.strstart,a),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.high_water>3,a=e.pending_buf_size-a>65535?65535:e.pending_buf_size-a,o=a>e.w_size?e.w_size:a,i=e.strstart-e.block_start,(i>=o||(i||t===m)&&t!==u&&0===e.strm.avail_in&&i<=a)&&(n=i>a?a:i,s=t===m&&0===e.strm.avail_in&&n===i?1:0,r(e,e.block_start,n,s),e.block_start+=n,D(e.strm)),s?3:1)},G=(e,t)=>{let n,i;for(;;){if(e.lookahead=3&&(e.ins_h=R(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==n&&e.strstart-n<=e.w_size-L&&(e.match_length=q(e,n)),e.match_length>=3)if(i=o(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=R(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=R(e,e.ins_h,e.window[e.strstart+1]);else i=o(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(F(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===m?(F(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(F(e,!1),0===e.strm.avail_out)?1:2},K=(e,t)=>{let n,i,r;for(;;){if(e.lookahead=3&&(e.ins_h=R(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==n&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,i=o(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=R(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,i&&(F(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(i=o(e,0,e.window[e.strstart-1]),i&&F(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(i=o(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===m?(F(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(F(e,!1),0===e.strm.avail_out)?1:2};function J(e,t,n,i,r){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=i,this.func=r}const Z=[new J(0,0,0,0,$),new J(4,4,8,4,G),new J(4,5,16,8,G),new J(4,6,32,32,G),new J(4,4,16,16,K),new J(8,16,32,32,K),new J(8,16,128,128,K),new J(8,32,128,256,K),new J(32,128,258,1024,K),new J(32,258,258,4096,K)];function Q(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=H,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),P(this.dyn_ltree),P(this.dyn_dtree),P(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),P(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),P(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const Y=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==T&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==A&&t.status!==_?1:0},X=e=>{if(Y(e))return N(e,b);e.total_in=e.total_out=0,e.data_type=V;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?T:A,e.adler=2===t.wrap?0:1,t.last_flush=-2,i(t),g},ee=e=>{const t=X(e);var n;return t===g&&((n=e.state).window_size=2*n.w_size,P(n.head),n.max_lazy_match=Z[n.level].max_lazy,n.good_match=Z[n.level].good_length,n.nice_match=Z[n.level].nice_length,n.max_chain_length=Z[n.level].max_chain,n.strstart=0,n.block_start=0,n.lookahead=0,n.insert=0,n.match_length=n.prev_length=2,n.match_available=0,n.ins_h=0),t},te=(e,t,n,i,r,a)=>{if(!e)return b;let o=1;if(t===C&&(t=6),i<0?(o=0,i=-i):i>15&&(o=2,i-=16),r<1||r>9||n!==H||i<8||i>15||t<0||t>9||a<0||a>k||8===i&&1!==o)return N(e,b);8===i&&(i=9);const s=new Q;return e.state=s,s.strm=e,s.status=T,s.wrap=o,s.gzhead=null,s.w_bits=i,s.w_size=1<te(e,t,H,15,8,x),e.exports.deflateInit2=te,e.exports.deflateReset=ee,e.exports.deflateResetKeep=X,e.exports.deflateSetHeader=(e,t)=>Y(e)||2!==e.state.wrap?b:(e.state.gzhead=t,g),e.exports.deflate=(e,t)=>{if(Y(e)||t>p||t<0)return e?N(e,b):b;const n=e.state;if(!e.output||0!==e.avail_in&&!e.input||n.status===_&&t!==m)return N(e,0===e.avail_out?S:b);const i=n.last_flush;if(n.last_flush=t,0!==n.pending){if(D(e),0===e.avail_out)return n.last_flush=-1,g}else if(0===e.avail_in&&I(t)<=I(i)&&t!==m)return N(e,S);if(n.status===_&&0!==e.avail_in)return N(e,S);if(n.status===T&&0===n.wrap&&(n.status=A),n.status===T){let t=H+(n.w_bits-8<<4)<<8,i=-1;if(i=n.strategy>=M||n.level<2?0:n.level<6?1:6===n.level?2:3,t|=i<<6,0!==n.strstart&&(t|=32),t+=31-t%31,U(n,t),0!==n.strstart&&(U(n,e.adler>>>16),U(n,65535&e.adler)),e.adler=1,n.status=A,D(e),0!==n.pending)return n.last_flush=-1,g}if(57===n.status)if(e.adler=0,B(n,31),B(n,139),B(n,8),n.gzhead)B(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),B(n,255&n.gzhead.time),B(n,n.gzhead.time>>8&255),B(n,n.gzhead.time>>16&255),B(n,n.gzhead.time>>24&255),B(n,9===n.level?2:n.strategy>=M||n.level<2?4:0),B(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(B(n,255&n.gzhead.extra.length),B(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=l(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69;else if(B(n,0),B(n,0),B(n,0),B(n,0),B(n,0),B(n,9===n.level?2:n.strategy>=M||n.level<2?4:0),B(n,3),n.status=A,D(e),0!==n.pending)return n.last_flush=-1,g;if(69===n.status){if(n.gzhead.extra){let t=n.pending,i=(65535&n.gzhead.extra.length)-n.gzindex;for(;n.pending+i>n.pending_buf_size;){let r=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+r),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>t&&(e.adler=l(e.adler,n.pending_buf,n.pending-t,t)),n.gzindex+=r,D(e),0!==n.pending)return n.last_flush=-1,g;t=0,i-=r}let r=new Uint8Array(n.gzhead.extra);n.pending_buf.set(r.subarray(n.gzindex,n.gzindex+i),n.pending),n.pending+=i,n.gzhead.hcrc&&n.pending>t&&(e.adler=l(e.adler,n.pending_buf,n.pending-t,t)),n.gzindex=0}n.status=73}if(73===n.status){if(n.gzhead.name){let t,i=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>i&&(e.adler=l(e.adler,n.pending_buf,n.pending-i,i)),D(e),0!==n.pending)return n.last_flush=-1,g;i=0}t=n.gzindexi&&(e.adler=l(e.adler,n.pending_buf,n.pending-i,i)),n.gzindex=0}n.status=91}if(91===n.status){if(n.gzhead.comment){let t,i=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>i&&(e.adler=l(e.adler,n.pending_buf,n.pending-i,i)),D(e),0!==n.pending)return n.last_flush=-1,g;i=0}t=n.gzindexi&&(e.adler=l(e.adler,n.pending_buf,n.pending-i,i))}n.status=103}if(103===n.status){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(D(e),0!==n.pending))return n.last_flush=-1,g;B(n,255&e.adler),B(n,e.adler>>8&255),e.adler=0}if(n.status=A,D(e),0!==n.pending)return n.last_flush=-1,g}if(0!==e.avail_in||0!==n.lookahead||t!==u&&n.status!==_){let i=0===n.level?$(n,t):n.strategy===M?((e,t)=>{let n;for(;;){if(0===e.lookahead&&(W(e),0===e.lookahead)){if(t===u)return 1;break}if(e.match_length=0,n=o(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(F(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===m?(F(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(F(e,!1),0===e.strm.avail_out)?1:2})(n,t):n.strategy===z?((e,t)=>{let n,i,r,a;const s=e.window;for(;;){if(e.lookahead<=E){if(W(e),e.lookahead<=E&&t===u)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,i=s[r],i===s[++r]&&i===s[++r]&&i===s[++r])){a=e.strstart+E;do{}while(i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(n=o(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=o(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(F(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===m?(F(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(F(e,!1),0===e.strm.avail_out)?1:2})(n,t):Z[n.level].func(n,t);if(3!==i&&4!==i||(n.status=_),1===i||3===i)return 0===e.avail_out&&(n.last_flush=-1),g;if(2===i&&(t===f?s(n):t!==p&&(r(n,0,0,!1),t===h&&(P(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),D(e),0===e.avail_out))return n.last_flush=-1,g}return t!==m?g:n.wrap<=0?v:(2===n.wrap?(B(n,255&e.adler),B(n,e.adler>>8&255),B(n,e.adler>>16&255),B(n,e.adler>>24&255),B(n,255&e.total_in),B(n,e.total_in>>8&255),B(n,e.total_in>>16&255),B(n,e.total_in>>24&255)):(U(n,e.adler>>>16),U(n,65535&e.adler)),D(e),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?g:v)},e.exports.deflateEnd=e=>{if(Y(e))return b;const t=e.state.status;return e.state=null,t===A?N(e,y):g},e.exports.deflateSetDictionary=(e,t)=>{let n=t.length;if(Y(e))return b;const i=e.state,r=i.wrap;if(2===r||1===r&&i.status!==T||i.lookahead)return b;if(1===r&&(e.adler=c(e.adler,t,n,0)),i.wrap=0,n>=i.w_size){0===r&&(P(i.head),i.strstart=0,i.block_start=0,i.insert=0);let e=new Uint8Array(i.w_size);e.set(t.subarray(n-i.w_size,n),0),t=e,n=i.w_size}const a=e.avail_in,o=e.next_in,s=e.input;for(e.avail_in=n,e.next_in=0,e.input=t,W(i);i.lookahead>=3;){let e=i.strstart,t=i.lookahead-2;do{i.ins_h=R(i,i.ins_h,i.window[e+3-1]),i.prev[e&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=e,e++}while(--t);i.strstart=e,i.lookahead=2,W(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,e.next_in=o,e.input=s,e.avail_in=a,i.wrap=r,g},e.exports.deflateInfo="pako deflate (from Nodeca project)"},7414:e=>{"use strict";e.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}},7293:e=>{"use strict";const t=16209;e.exports=function(e,n){let i,r,a,o,s,c,l,d,u,f,h,m,p,g,v,b,y,S,C,w,M,z,k,x;const V=e.state;i=e.next_in,k=e.input,r=i+(e.avail_in-5),a=e.next_out,x=e.output,o=a-(n-e.avail_out),s=a+(e.avail_out-257),c=V.dmax,l=V.wsize,d=V.whave,u=V.wnext,f=V.window,h=V.hold,m=V.bits,p=V.lencode,g=V.distcode,v=(1<>>24,h>>>=S,m-=S,S=y>>>16&255,0===S)x[a++]=65535&y;else{if(!(16&S)){if(0==(64&S)){y=p[(65535&y)+(h&(1<>>=S,m-=S),m<15&&(h+=k[i++]<>>24,h>>>=S,m-=S,S=y>>>16&255,!(16&S)){if(0==(64&S)){y=g[(65535&y)+(h&(1<c){e.msg="invalid distance too far back",V.mode=t;break e}if(h>>>=S,m-=S,S=a-o,w>S){if(S=w-S,S>d&&V.sane){e.msg="invalid distance too far back",V.mode=t;break e}if(M=0,z=f,0===u){if(M+=l-S,S2;)x[a++]=z[M++],x[a++]=z[M++],x[a++]=z[M++],C-=3;C&&(x[a++]=z[M++],C>1&&(x[a++]=z[M++]))}else{M=a-w;do{x[a++]=x[M++],x[a++]=x[M++],x[a++]=x[M++],C-=3}while(C>2);C&&(x[a++]=x[M++],C>1&&(x[a++]=x[M++]))}break}}break}}while(i>3,i-=C,m-=C<<3,h&=(1<{"use strict";const i=n(3269),r=n(4823),a=n(7293),o=n(1998),{Z_FINISH:s,Z_BLOCK:c,Z_TREES:l,Z_OK:d,Z_STREAM_END:u,Z_NEED_DICT:f,Z_STREAM_ERROR:h,Z_DATA_ERROR:m,Z_MEM_ERROR:p,Z_BUF_ERROR:g,Z_DEFLATED:v}=n(9681),b=16180,y=16190,S=16191,C=16192,w=16194,M=16199,z=16200,k=16206,x=16209,V=16210,H=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function E(){this.strm=null,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 Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const L=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode16211?1:0},T=e=>{if(L(e))return h;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=b,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,d},A=e=>{if(L(e))return h;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,T(e)},_=(e,t)=>{let n;if(L(e))return h;const i=e.state;return t<0?(n=0,t=-t):(n=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?h:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=n,i.wbits=t,A(e))},N=(e,t)=>{if(!e)return h;const n=new E;e.state=n,n.strm=e,n.window=null,n.mode=b;const i=_(e,t);return i!==d&&(e.state=null),i};let I,P,O=!0;const R=e=>{if(O){I=new Int32Array(512),P=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(o(1,e.lens,0,288,I,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;o(2,e.lens,0,32,P,0,e.work,{bits:5}),O=!1}e.lencode=I,e.lenbits=9,e.distcode=P,e.distbits=5},D=(e,t,n,i)=>{let r;const a=e.state;return null===a.window&&(a.wsize=1<=a.wsize?(a.window.set(t.subarray(n-a.wsize,n),0),a.wnext=0,a.whave=a.wsize):(r=a.wsize-a.wnext,r>i&&(r=i),a.window.set(t.subarray(n-i,n-i+r),a.wnext),(i-=r)?(a.window.set(t.subarray(n-i,n),0),a.wnext=i,a.whave=a.wsize):(a.wnext+=r,a.wnext===a.wsize&&(a.wnext=0),a.whaveN(e,15),e.exports.inflateInit2=N,e.exports.inflate=(e,t)=>{let n,E,T,A,_,N,I,P,O,F,B,U,j,q,W,$,G,K,J,Z,Q,Y,X=0;const ee=new Uint8Array(4);let te,ne;const ie=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(L(e)||!e.output||!e.input&&0!==e.avail_in)return h;n=e.state,n.mode===S&&(n.mode=C),_=e.next_out,T=e.output,I=e.avail_out,A=e.next_in,E=e.input,N=e.avail_in,P=n.hold,O=n.bits,F=N,B=I,Y=d;e:for(;;)switch(n.mode){case b:if(0===n.wrap){n.mode=C;break}for(;O<16;){if(0===N)break e;N--,P+=E[A++]<>>8&255,n.check=r(n.check,ee,2,0),P=0,O=0,n.mode=16181;break}if(n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&P)<<8)+(P>>8))%31){e.msg="incorrect header check",n.mode=x;break}if((15&P)!==v){e.msg="unknown compression method",n.mode=x;break}if(P>>>=4,O-=4,Q=8+(15&P),0===n.wbits&&(n.wbits=Q),Q>15||Q>n.wbits){e.msg="invalid window size",n.mode=x;break}n.dmax=1<>8&1),512&n.flags&&4&n.wrap&&(ee[0]=255&P,ee[1]=P>>>8&255,n.check=r(n.check,ee,2,0)),P=0,O=0,n.mode=16182;case 16182:for(;O<32;){if(0===N)break e;N--,P+=E[A++]<>>8&255,ee[2]=P>>>16&255,ee[3]=P>>>24&255,n.check=r(n.check,ee,4,0)),P=0,O=0,n.mode=16183;case 16183:for(;O<16;){if(0===N)break e;N--,P+=E[A++]<>8),512&n.flags&&4&n.wrap&&(ee[0]=255&P,ee[1]=P>>>8&255,n.check=r(n.check,ee,2,0)),P=0,O=0,n.mode=16184;case 16184:if(1024&n.flags){for(;O<16;){if(0===N)break e;N--,P+=E[A++]<>>8&255,n.check=r(n.check,ee,2,0)),P=0,O=0}else n.head&&(n.head.extra=null);n.mode=16185;case 16185:if(1024&n.flags&&(U=n.length,U>N&&(U=N),U&&(n.head&&(Q=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(E.subarray(A,A+U),Q)),512&n.flags&&4&n.wrap&&(n.check=r(n.check,E,U,A)),N-=U,A+=U,n.length-=U),n.length))break e;n.length=0,n.mode=16186;case 16186:if(2048&n.flags){if(0===N)break e;U=0;do{Q=E[A+U++],n.head&&Q&&n.length<65536&&(n.head.name+=String.fromCharCode(Q))}while(Q&&U>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=S;break;case 16189:for(;O<32;){if(0===N)break e;N--,P+=E[A++]<>>=7&O,O-=7&O,n.mode=k;break}for(;O<3;){if(0===N)break e;N--,P+=E[A++]<>>=1,O-=1,3&P){case 0:n.mode=16193;break;case 1:if(R(n),n.mode=M,t===l){P>>>=2,O-=2;break e}break;case 2:n.mode=16196;break;case 3:e.msg="invalid block type",n.mode=x}P>>>=2,O-=2;break;case 16193:for(P>>>=7&O,O-=7&O;O<32;){if(0===N)break e;N--,P+=E[A++]<>>16^65535)){e.msg="invalid stored block lengths",n.mode=x;break}if(n.length=65535&P,P=0,O=0,n.mode=w,t===l)break e;case w:n.mode=16195;case 16195:if(U=n.length,U){if(U>N&&(U=N),U>I&&(U=I),0===U)break e;T.set(E.subarray(A,A+U),_),N-=U,A+=U,I-=U,_+=U,n.length-=U;break}n.mode=S;break;case 16196:for(;O<14;){if(0===N)break e;N--,P+=E[A++]<>>=5,O-=5,n.ndist=1+(31&P),P>>>=5,O-=5,n.ncode=4+(15&P),P>>>=4,O-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=x;break}n.have=0,n.mode=16197;case 16197:for(;n.have>>=3,O-=3}for(;n.have<19;)n.lens[ie[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,te={bits:n.lenbits},Y=o(0,n.lens,0,19,n.lencode,0,n.work,te),n.lenbits=te.bits,Y){e.msg="invalid code lengths set",n.mode=x;break}n.have=0,n.mode=16198;case 16198:for(;n.have>>24,$=X>>>16&255,G=65535&X,!(W<=O);){if(0===N)break e;N--,P+=E[A++]<>>=W,O-=W,n.lens[n.have++]=G;else{if(16===G){for(ne=W+2;O>>=W,O-=W,0===n.have){e.msg="invalid bit length repeat",n.mode=x;break}Q=n.lens[n.have-1],U=3+(3&P),P>>>=2,O-=2}else if(17===G){for(ne=W+3;O>>=W,O-=W,Q=0,U=3+(7&P),P>>>=3,O-=3}else{for(ne=W+7;O>>=W,O-=W,Q=0,U=11+(127&P),P>>>=7,O-=7}if(n.have+U>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=x;break}for(;U--;)n.lens[n.have++]=Q}}if(n.mode===x)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=x;break}if(n.lenbits=9,te={bits:n.lenbits},Y=o(1,n.lens,0,n.nlen,n.lencode,0,n.work,te),n.lenbits=te.bits,Y){e.msg="invalid literal/lengths set",n.mode=x;break}if(n.distbits=6,n.distcode=n.distdyn,te={bits:n.distbits},Y=o(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,te),n.distbits=te.bits,Y){e.msg="invalid distances set",n.mode=x;break}if(n.mode=M,t===l)break e;case M:n.mode=z;case z:if(N>=6&&I>=258){e.next_out=_,e.avail_out=I,e.next_in=A,e.avail_in=N,n.hold=P,n.bits=O,a(e,B),_=e.next_out,T=e.output,I=e.avail_out,A=e.next_in,E=e.input,N=e.avail_in,P=n.hold,O=n.bits,n.mode===S&&(n.back=-1);break}for(n.back=0;X=n.lencode[P&(1<>>24,$=X>>>16&255,G=65535&X,!(W<=O);){if(0===N)break e;N--,P+=E[A++]<>K)],W=X>>>24,$=X>>>16&255,G=65535&X,!(K+W<=O);){if(0===N)break e;N--,P+=E[A++]<>>=K,O-=K,n.back+=K}if(P>>>=W,O-=W,n.back+=W,n.length=G,0===$){n.mode=16205;break}if(32&$){n.back=-1,n.mode=S;break}if(64&$){e.msg="invalid literal/length code",n.mode=x;break}n.extra=15&$,n.mode=16201;case 16201:if(n.extra){for(ne=n.extra;O>>=n.extra,O-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=16202;case 16202:for(;X=n.distcode[P&(1<>>24,$=X>>>16&255,G=65535&X,!(W<=O);){if(0===N)break e;N--,P+=E[A++]<>K)],W=X>>>24,$=X>>>16&255,G=65535&X,!(K+W<=O);){if(0===N)break e;N--,P+=E[A++]<>>=K,O-=K,n.back+=K}if(P>>>=W,O-=W,n.back+=W,64&$){e.msg="invalid distance code",n.mode=x;break}n.offset=G,n.extra=15&$,n.mode=16203;case 16203:if(n.extra){for(ne=n.extra;O>>=n.extra,O-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=x;break}n.mode=16204;case 16204:if(0===I)break e;if(U=B-I,n.offset>U){if(U=n.offset-U,U>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=x;break}U>n.wnext?(U-=n.wnext,j=n.wsize-U):j=n.wnext-U,U>n.length&&(U=n.length),q=n.window}else q=T,j=_-n.offset,U=n.length;U>I&&(U=I),I-=U,n.length-=U;do{T[_++]=q[j++]}while(--U);0===n.length&&(n.mode=z);break;case 16205:if(0===I)break e;T[_++]=n.length,I--,n.mode=z;break;case k:if(n.wrap){for(;O<32;){if(0===N)break e;N--,P|=E[A++]<{if(L(e))return h;let t=e.state;return t.window&&(t.window=null),e.state=null,d},e.exports.inflateGetHeader=(e,t)=>{if(L(e))return h;const n=e.state;return 0==(2&n.wrap)?h:(n.head=t,t.done=!1,d)},e.exports.inflateSetDictionary=(e,t)=>{const n=t.length;let r,a,o;return L(e)?h:(r=e.state,0!==r.wrap&&r.mode!==y?h:r.mode===y&&(a=1,a=i(a,t,n,0),a!==r.check)?m:(o=D(e,t,n,n),o?(r.mode=V,p):(r.havedict=1,d)))},e.exports.inflateInfo="pako inflate (from Nodeca project)"},1998:e=>{"use strict";const t=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),n=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),i=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),r=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);e.exports=(e,a,o,s,c,l,d,u)=>{const f=u.bits;let h,m,p,g,v,b,y=0,S=0,C=0,w=0,M=0,z=0,k=0,x=0,V=0,H=0,E=null;const L=new Uint16Array(16),T=new Uint16Array(16);let A,_,N,I=null;for(y=0;y<=15;y++)L[y]=0;for(S=0;S=1&&0===L[w];w--);if(M>w&&(M=w),0===w)return c[l++]=20971520,c[l++]=20971520,u.bits=1,0;for(C=1;C0&&(0===e||1!==w))return-1;for(T[1]=0,y=1;y<15;y++)T[y+1]=T[y]+L[y];for(S=0;S852||2===e&&V>592)return 1;for(;;){A=y-k,d[S]+1=b?(_=I[d[S]-b],N=E[d[S]-b]):(_=96,N=0),h=1<>k)+m]=A<<24|_<<16|N|0}while(0!==m);for(h=1<>=1;if(0!==h?(H&=h-1,H+=h):H=0,S++,0==--L[y]){if(y===w)break;y=a[o+d[S]]}if(y>M&&(H&g)!==p){for(0===k&&(k=M),v+=C,z=y-k,x=1<852||2===e&&V>592)return 1;p=H&g,c[p]=M<<24|z<<16|v-l|0}}return 0!==H&&(c[v+H]=y-k<<24|64<<16|0),u.bits=M,0}},4674:e=>{"use strict";e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},3665:e=>{"use strict";function t(e){let t=e.length;for(;--t>=0;)e[t]=0}const n=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),i=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),r=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),a=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),o=new Array(576);t(o);const s=new Array(60);t(s);const c=new Array(512);t(c);const l=new Array(256);t(l);const d=new Array(29);t(d);const u=new Array(30);function f(e,t,n,i,r){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=i,this.max_length=r,this.has_stree=e&&e.length}let h,m,p;function g(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}t(u);const v=e=>e<256?c[e]:c[256+(e>>>7)],b=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},y=(e,t,n)=>{e.bi_valid>16-n?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=n-16):(e.bi_buf|=t<{y(e,n[2*t],n[2*t+1])},C=(e,t)=>{let n=0;do{n|=1&e,e>>>=1,n<<=1}while(--t>0);return n>>>1},w=(e,t,n)=>{const i=new Array(16);let r,a,o=0;for(r=1;r<=15;r++)o=o+n[r-1]<<1,i[r]=o;for(a=0;a<=t;a++){let t=e[2*a+1];0!==t&&(e[2*a]=C(i[t]++,t))}},M=e=>{let t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},z=e=>{e.bi_valid>8?b(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},k=(e,t,n,i)=>{const r=2*t,a=2*n;return e[r]{const i=e.heap[n];let r=n<<1;for(;r<=e.heap_len&&(r{let a,o,s,c,f=0;if(0!==e.sym_next)do{a=255&e.pending_buf[e.sym_buf+f++],a+=(255&e.pending_buf[e.sym_buf+f++])<<8,o=e.pending_buf[e.sym_buf+f++],0===a?S(e,o,t):(s=l[o],S(e,s+256+1,t),c=n[s],0!==c&&(o-=d[s],y(e,o,c)),a--,s=v(a),S(e,s,r),c=i[s],0!==c&&(a-=u[s],y(e,a,c)))}while(f{const n=t.dyn_tree,i=t.stat_desc.static_tree,r=t.stat_desc.has_stree,a=t.stat_desc.elems;let o,s,c,l=-1;for(e.heap_len=0,e.heap_max=573,o=0;o>1;o>=1;o--)x(e,n,o);c=a;do{o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],x(e,n,1),s=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=s,n[2*c]=n[2*o]+n[2*s],e.depth[c]=(e.depth[o]>=e.depth[s]?e.depth[o]:e.depth[s])+1,n[2*o+1]=n[2*s+1]=c,e.heap[1]=c++,x(e,n,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const n=t.dyn_tree,i=t.max_code,r=t.stat_desc.static_tree,a=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,c=t.stat_desc.max_length;let l,d,u,f,h,m,p=0;for(f=0;f<=15;f++)e.bl_count[f]=0;for(n[2*e.heap[e.heap_max]+1]=0,l=e.heap_max+1;l<573;l++)d=e.heap[l],f=n[2*n[2*d+1]+1]+1,f>c&&(f=c,p++),n[2*d+1]=f,d>i||(e.bl_count[f]++,h=0,d>=s&&(h=o[d-s]),m=n[2*d],e.opt_len+=m*(f+h),a&&(e.static_len+=m*(r[2*d+1]+h)));if(0!==p){do{for(f=c-1;0===e.bl_count[f];)f--;e.bl_count[f]--,e.bl_count[f+1]+=2,e.bl_count[c]--,p-=2}while(p>0);for(f=c;0!==f;f--)for(d=e.bl_count[f];0!==d;)u=e.heap[--l],u>i||(n[2*u+1]!==f&&(e.opt_len+=(f-n[2*u+1])*n[2*u],n[2*u+1]=f),d--)}})(e,t),w(n,l,e.bl_count)},E=(e,t,n)=>{let i,r,a=-1,o=t[1],s=0,c=7,l=4;for(0===o&&(c=138,l=3),t[2*(n+1)+1]=65535,i=0;i<=n;i++)r=o,o=t[2*(i+1)+1],++s{let i,r,a=-1,o=t[1],s=0,c=7,l=4;for(0===o&&(c=138,l=3),i=0;i<=n;i++)if(r=o,o=t[2*(i+1)+1],!(++s{y(e,0+(i?1:0),3),z(e),b(e,n),b(e,~n),n&&e.pending_buf.set(e.window.subarray(t,t+n),e.pending),e.pending+=n};e.exports._tr_init=e=>{T||((()=>{let e,t,a,g,v;const b=new Array(16);for(a=0,g=0;g<28;g++)for(d[g]=a,e=0;e<1<>=7;g<30;g++)for(u[g]=v<<7,e=0;e<1<{let r,c,l=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,n=4093624447;for(t=0;t<=31;t++,n>>>=1)if(1&n&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),H(e,e.l_desc),H(e,e.d_desc),l=(e=>{let t;for(E(e,e.dyn_ltree,e.l_desc.max_code),E(e,e.dyn_dtree,e.d_desc.max_code),H(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*a[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,c=e.static_len+3+7>>>3,c<=r&&(r=c)):r=c=n+5,n+4<=r&&-1!==t?A(e,t,n,i):4===e.strategy||c===r?(y(e,2+(i?1:0),3),V(e,o,s)):(y(e,4+(i?1:0),3),((e,t,n,i)=>{let r;for(y(e,t-257,5),y(e,n-1,5),y(e,i-4,4),r=0;r(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=n,0===t?e.dyn_ltree[2*n]++:(e.matches++,t--,e.dyn_ltree[2*(l[n]+256+1)]++,e.dyn_dtree[2*v(t)]++),e.sym_next===e.sym_end),e.exports._tr_align=e=>{y(e,2,3),S(e,256,o),(e=>{16===e.bi_valid?(b(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)}},4442:e=>{"use strict";e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},6946:(e,t,n)=>{"use strict";e.exports=n(4394)},4394:(e,t,n)=>{"use strict";var i=t;function r(){i.util._configure(),i.Writer._configure(i.BufferWriter),i.Reader._configure(i.BufferReader)}i.build="minimal",i.Writer=n(3449),i.BufferWriter=n(818),i.Reader=n(6237),i.BufferReader=n(3158),i.util=n(3610),i.rpc=n(5047),i.roots=n(4529),i.configure=r,r()},6237:(e,t,n)=>{"use strict";e.exports=c;var i,r=n(3610),a=r.LongBits,o=r.utf8;function s(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var l,d="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},u=function(){return r.Buffer?function(e){return(c.create=function(e){return r.Buffer.isBuffer(e)?new i(e):d(e)})(e)}:d};function f(){var e=new a(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw s(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw s(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function h(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function m(){if(this.pos+8>this.len)throw s(this,8);return new a(h(this.buf,this.pos+=4),h(this.buf,this.pos+=4))}c.create=u(),c.prototype._slice=r.Array.prototype.subarray||r.Array.prototype.slice,c.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return l;if((this.pos+=5)>this.len)throw this.pos=this.len,s(this,10);return l}),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw s(this,4);return h(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw s(this,4);return 0|h(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw s(this,4);var e=r.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw s(this,4);var e=r.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw s(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,n);if(t===n){var i=r.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,n)},c.prototype.string=function(){var e=this.bytes();return o.read(e,0,e.length)},c.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw s(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw s(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c._configure=function(e){i=e,c.create=u(),i._configure();var t=r.Long?"toLong":"toNumber";r.merge(c.prototype,{int64:function(){return f.call(this)[t](!1)},uint64:function(){return f.call(this)[t](!0)},sint64:function(){return f.call(this).zzDecode()[t](!1)},fixed64:function(){return m.call(this)[t](!0)},sfixed64:function(){return m.call(this)[t](!1)}})}},3158:(e,t,n)=>{"use strict";e.exports=a;var i=n(6237);(a.prototype=Object.create(i.prototype)).constructor=a;var r=n(3610);function a(e){i.call(this,e)}a._configure=function(){r.Buffer&&(a.prototype._slice=r.Buffer.prototype.slice)},a.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},a._configure()},4529:e=>{"use strict";e.exports={}},5047:(e,t,n)=>{"use strict";t.Service=n(7595)},7595:(e,t,n)=>{"use strict";e.exports=r;var i=n(3610);function r(e,t,n){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");i.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(n)}(r.prototype=Object.create(i.EventEmitter.prototype)).constructor=r,r.prototype.rpcCall=function e(t,n,r,a,o){if(!a)throw TypeError("request must be specified");var s=this;if(!o)return i.asPromise(e,s,t,n,r,a);if(s.rpcImpl)try{return s.rpcImpl(t,n[s.requestDelimited?"encodeDelimited":"encode"](a).finish(),(function(e,n){if(e)return s.emit("error",e,t),o(e);if(null!==n){if(!(n instanceof r))try{n=r[s.responseDelimited?"decodeDelimited":"decode"](n)}catch(e){return s.emit("error",e,t),o(e)}return s.emit("data",n,t),o(null,n)}s.end(!0)}))}catch(e){return s.emit("error",e,t),void setTimeout((function(){o(e)}),0)}else setTimeout((function(){o(Error("already ended"))}),0)},r.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},2239:(e,t,n)=>{"use strict";e.exports=r;var i=n(3610);function r(e,t){this.lo=e>>>0,this.hi=t>>>0}var a=r.zero=new r(0,0);a.toNumber=function(){return 0},a.zzEncode=a.zzDecode=function(){return this},a.length=function(){return 1};var o=r.zeroHash="\0\0\0\0\0\0\0\0";r.fromNumber=function(e){if(0===e)return a;var t=e<0;t&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new r(n,i)},r.from=function(e){if("number"==typeof e)return r.fromNumber(e);if(i.isString(e)){if(!i.Long)return r.fromNumber(parseInt(e,10));e=i.Long.fromString(e)}return e.low||e.high?new r(e.low>>>0,e.high>>>0):a},r.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+4294967296*n)}return this.lo+4294967296*this.hi},r.prototype.toLong=function(e){return i.Long?new i.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var s=String.prototype.charCodeAt;r.fromHash=function(e){return e===o?a:new r((s.call(e,0)|s.call(e,1)<<8|s.call(e,2)<<16|s.call(e,3)<<24)>>>0,(s.call(e,4)|s.call(e,5)<<8|s.call(e,6)<<16|s.call(e,7)<<24)>>>0)},r.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},r.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},r.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},r.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}},3610:function(e,t,n){"use strict";var i=t;function r(e,t,n){for(var i=Object.keys(t),r=0;r0)},i.Buffer=function(){try{var e=i.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),i._Buffer_from=null,i._Buffer_allocUnsafe=null,i.newBuffer=function(e){return"number"==typeof e?i.Buffer?i._Buffer_allocUnsafe(e):new i.Array(e):i.Buffer?i._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},i.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,i.Long=i.global.dcodeIO&&i.global.dcodeIO.Long||i.global.Long||i.inquire("long"),i.key2Re=/^true|false|0|1$/,i.key32Re=/^-?(?:0|[1-9][0-9]*)$/,i.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,i.longToHash=function(e){return e?i.LongBits.from(e).toHash():i.LongBits.zeroHash},i.longFromHash=function(e,t){var n=i.LongBits.fromHash(e);return i.Long?i.Long.fromBits(n.lo,n.hi,t):n.toNumber(Boolean(t))},i.merge=r,i.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},i.newError=a,i.ProtocolError=a("ProtocolError"),i.oneOfGetter=function(e){for(var t={},n=0;n-1;--n)if(1===t[e[n]]&&void 0!==this[e[n]]&&null!==this[e[n]])return e[n]}},i.oneOfSetter=function(e){return function(t){for(var n=0;n{"use strict";e.exports=u;var i,r=n(3610),a=r.LongBits,o=r.base64,s=r.utf8;function c(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}function l(){}function d(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function u(){this.len=0,this.head=new c(l,0,0),this.tail=this.head,this.states=null}var f=function(){return r.Buffer?function(){return(u.create=function(){return new i})()}:function(){return new u}};function h(e,t,n){t[n]=255&e}function m(e,t){this.len=e,this.next=void 0,this.val=t}function p(e,t,n){for(;e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function g(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}u.create=f(),u.alloc=function(e){return new r.Array(e)},r.Array!==Array&&(u.alloc=r.pool(u.alloc,r.Array.prototype.subarray)),u.prototype._push=function(e,t,n){return this.tail=this.tail.next=new c(e,t,n),this.len+=t,this},m.prototype=Object.create(c.prototype),m.prototype.fn=function(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e},u.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new m((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},u.prototype.int32=function(e){return e<0?this._push(p,10,a.fromNumber(e)):this.uint32(e)},u.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},u.prototype.uint64=function(e){var t=a.from(e);return this._push(p,t.length(),t)},u.prototype.int64=u.prototype.uint64,u.prototype.sint64=function(e){var t=a.from(e).zzEncode();return this._push(p,t.length(),t)},u.prototype.bool=function(e){return this._push(h,1,e?1:0)},u.prototype.fixed32=function(e){return this._push(g,4,e>>>0)},u.prototype.sfixed32=u.prototype.fixed32,u.prototype.fixed64=function(e){var t=a.from(e);return this._push(g,4,t.lo)._push(g,4,t.hi)},u.prototype.sfixed64=u.prototype.fixed64,u.prototype.float=function(e){return this._push(r.float.writeFloatLE,4,e)},u.prototype.double=function(e){return this._push(r.float.writeDoubleLE,8,e)};var v=r.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var i=0;i>>0;if(!t)return this._push(h,1,0);if(r.isString(e)){var n=u.alloc(t=o.length(e));o.decode(e,n,0),e=n}return this.uint32(t)._push(v,t,e)},u.prototype.string=function(e){var t=s.length(e);return t?this.uint32(t)._push(s.write,t,e):this._push(h,1,0)},u.prototype.fork=function(){return this.states=new d(this),this.head=this.tail=new c(l,0,0),this.len=0,this},u.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(l,0,0),this.len=0),this},u.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this},u.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t},u._configure=function(e){i=e,u.create=f(),i._configure()}},818:(e,t,n)=>{"use strict";e.exports=a;var i=n(3449);(a.prototype=Object.create(i.prototype)).constructor=a;var r=n(3610);function a(){i.call(this)}function o(e,t,n){e.length<40?r.utf8.write(e,t,n):t.utf8Write?t.utf8Write(e,n):t.write(e,n)}a._configure=function(){a.alloc=r._Buffer_allocUnsafe,a.writeBytesBuffer=r.Buffer&&r.Buffer.prototype instanceof Uint8Array&&"set"===r.Buffer.prototype.set.name?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var i=0;i>>0;return this.uint32(t),t&&this._push(a.writeBytesBuffer,t,e),this},a.prototype.string=function(e){var t=r.Buffer.byteLength(e);return this.uint32(t),t&&this._push(o,t,e),this},a._configure()},5215:(e,t,n)=>{"use strict";n.r(t),n.d(t,{__assign:()=>a,__asyncDelegator:()=>S,__asyncGenerator:()=>y,__asyncValues:()=>C,__await:()=>b,__awaiter:()=>d,__classPrivateFieldGet:()=>k,__classPrivateFieldSet:()=>x,__createBinding:()=>f,__decorate:()=>s,__exportStar:()=>h,__extends:()=>r,__generator:()=>u,__importDefault:()=>z,__importStar:()=>M,__makeTemplateObject:()=>w,__metadata:()=>l,__param:()=>c,__read:()=>p,__rest:()=>o,__spread:()=>g,__spreadArrays:()=>v,__values:()=>m});var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},i(e,t)};function r(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var a=function(){return a=Object.assign||function(e){for(var t,n=1,i=arguments.length;n=0;s--)(r=e[s])&&(o=(a<3?r(o):a>3?r(t,n,o):r(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o}function c(e,t){return function(n,i){t(n,i,e)}}function l(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function d(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))}function u(e,t){var n,i,r,a,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,i&&(r=2&a[0]?i.return:a[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,a[1])).done)return r;switch(i=0,r&&(a=[2&a[0],r.value]),a[0]){case 0:case 1:r=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,i=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function p(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,r,a=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=a.next()).done;)o.push(i.value)}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return o}function g(){for(var e=[],t=0;t1||s(e,t)}))})}function s(e,t){try{(n=r[e](t)).value instanceof b?Promise.resolve(n.value.v).then(c,l):d(a[0][2],n)}catch(e){d(a[0][3],e)}var n}function c(e){s("next",e)}function l(e){s("throw",e)}function d(e,t){e(t),a.shift(),a.length&&s(a[0][0],a[0][1])}}function S(e){var t,n;return t={},i("next"),i("throw",(function(e){throw e})),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,r){t[i]=e[i]?function(t){return(n=!n)?{value:b(e[i](t)),done:"return"===i}:r?r(t):t}:r}}function C(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=m(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=e[n]&&function(t){return new Promise((function(i,r){!function(e,t,n,i){Promise.resolve(i).then((function(t){e({value:t,done:n})}),t)}(i,r,(t=e[n](t)).done,t.value)}))}}}function w(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function M(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function z(e){return e&&e.__esModule?e:{default:e}}function k(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function x(e,t,n){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,n),n}},7232:function(e,t,n){var i;!function(r,a){"use strict";var o="function",s="undefined",c="object",l="string",d="major",u="model",f="name",h="type",m="vendor",p="version",g="architecture",v="console",b="mobile",y="tablet",S="smarttv",C="wearable",w="embedded",M="Amazon",z="Apple",k="ASUS",x="BlackBerry",V="Browser",H="Chrome",E="Firefox",L="Google",T="Huawei",A="LG",_="Microsoft",N="Motorola",I="Opera",P="Samsung",O="Sharp",R="Sony",D="Xiaomi",F="Zebra",B="Facebook",U="Chromium OS",j="Mac OS",q=function(e){for(var t={},n=0;n0?2===s.length?typeof s[1]==o?this[s[0]]=s[1].call(this,d):this[s[0]]=s[1]:3===s.length?typeof s[1]!==o||s[1].exec&&s[1].test?this[s[0]]=d?d.replace(s[1],s[2]):a:this[s[0]]=d?s[1].call(this,d,s[2]):a:4===s.length&&(this[s[0]]=d?s[3].call(this,d.replace(s[1],s[2])):a):this[s]=d||a;u+=2}},J=function(e,t){for(var n in t)if(typeof t[n]===c&&t[n].length>0){for(var i=0;i2&&(e[u]="iPad",e[h]=y),e},this.getEngine=function(){var e={};return e[f]=a,e[p]=a,K.call(e,i,S.engine),e},this.getOS=function(){var e={};return e[f]=a,e[p]=a,K.call(e,i,S.os),C&&!e[f]&&v&&"Unknown"!=v.platform&&(e[f]=v.platform.replace(/chrome os/i,U).replace(/macos/i,j)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return i},this.setUA=function(e){return i=typeof e===l&&e.length>500?G(e,500):e,this},this.setUA(i),this};Y.VERSION="1.0.37",Y.BROWSER=q([f,p,d]),Y.CPU=q([g]),Y.DEVICE=q([u,m,h,v,b,S,y,C,w]),Y.ENGINE=Y.OS=q([f,p]),typeof t!==s?(e.exports&&(t=e.exports=Y),t.UAParser=Y):n.amdO?(i=function(){return Y}.call(t,n,t,e))===a||(e.exports=i):typeof r!==s&&(r.UAParser=Y);var X=typeof r!==s&&(r.jQuery||r.Zepto);if(X&&!X.ua){var ee=new Y;X.ua=ee.getResult(),X.ua.get=function(){return ee.getUA()},X.ua.set=function(e){ee.setUA(e);var t=ee.getResult();for(var n in t)X.ua[n]=t[n]}}}("object"==typeof window?window:this)},9155:e=>{"use strict";e.exports=__WEBPACK_EXTERNAL_MODULE__9155__}},__webpack_module_cache__={};function __nested_webpack_require_1236903__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__nested_webpack_require_1236903__),n.exports}__nested_webpack_require_1236903__.amdO={},__nested_webpack_require_1236903__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __nested_webpack_require_1236903__.d(t,{a:t}),t},__nested_webpack_require_1236903__.d=(e,t)=>{for(var n in t)__nested_webpack_require_1236903__.o(t,n)&&!__nested_webpack_require_1236903__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__nested_webpack_require_1236903__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__nested_webpack_require_1236903__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__nested_webpack_require_1236903__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __nested_webpack_exports__={};return(()=>{"use strict";__nested_webpack_require_1236903__.r(__nested_webpack_exports__),__nested_webpack_require_1236903__.d(__nested_webpack_exports__,{CrossFadeOverlapSize:()=>a,DefaultClientSettng:()=>p,DefaultServerSetting:()=>d,DiffMethod:()=>s,DownSamplingMode:()=>h,F0Detector:()=>o,INDEXEDDB_DB_APP_NAME:()=>v,INDEXEDDB_DB_NAME:()=>b,INDEXEDDB_KEY_CLIENT:()=>y,INDEXEDDB_KEY_MODEL_DATA:()=>C,INDEXEDDB_KEY_SERVER:()=>S,InputSampleRate:()=>i,ModelAssetName:()=>at,ModelFileKind:()=>ot,ModelLoadException:()=>w,ModelSamplingRate:()=>r,Protocol:()=>u,RVCModelType:()=>c,SampleRate:()=>m,SendingSampleRate:()=>f,ServerSettingKey:()=>l,StaticModel:()=>n,VOICE_CHANGER_CLIENT_EXCEPTION:()=>g,VoiceChangerClient:()=>et,VoiceChangerType:()=>t,createDummyMediaStream:()=>Ke,fileSelector:()=>Je,fileSelectorAsDataURL:()=>Ze,useClient:()=>lt,useIndexedDB:()=>rt,useServerSetting:()=>st,validateUrl:()=>Qe});var e={};__nested_webpack_require_1236903__.r(e),__nested_webpack_require_1236903__.d(e,{Decoder:()=>Ie,Encoder:()=>_e,PacketType:()=>Ae,protocol:()=>Te});const t={MMVCv15:"MMVCv15",MMVCv13:"MMVCv13","so-vits-svc-40":"so-vits-svc-40","DDSP-SVC":"DDSP-SVC",RVC:"RVC","Diffusion-SVC":"Diffusion-SVC",Beatrice:"Beatrice",LLVC:"LLVC",WebModel:"WebModel",EasyVC:"EasyVC"},n={BeatriceJVS:"Beatrice-JVS"},i={48e3:48e3,44100:44100,24e3:24e3},r={48e3:48e3,4e4:4e4,32e3:32e3},a={128:128,256:256,512:512,1024:1024,2048:2048,4096:4096},o={dio:"dio",harvest:"harvest",crepe:"crepe",crepe_full:"crepe_full",crepe_tiny:"crepe_tiny",rmvpe:"rmvpe",rmvpe_onnx:"rmvpe_onnx",fcpe:"fcpe"},s={pndm:"pndm","dpm-solver":"dpm-solver"},c={pyTorchRVC:"pyTorchRVC",pyTorchRVCNono:"pyTorchRVCNono",pyTorchRVCv2:"pyTorchRVCv2",pyTorchRVCv2Nono:"pyTorchRVCv2Nono",pyTorchWebUI:"pyTorchWebUI",pyTorchWebUINono:"pyTorchWebUINono",onnxRVC:"onnxRVC",onnxRVCNono:"onnxRVCNono"},l={passThrough:"passThrough",srcId:"srcId",dstId:"dstId",gpu:"gpu",crossFadeOffsetRate:"crossFadeOffsetRate",crossFadeEndRate:"crossFadeEndRate",crossFadeOverlapSize:"crossFadeOverlapSize",framework:"framework",onnxExecutionProvider:"onnxExecutionProvider",f0Factor:"f0Factor",f0Detector:"f0Detector",recordIO:"recordIO",enableServerAudio:"enableServerAudio",serverAudioStated:"serverAudioStated",serverAudioSampleRate:"serverAudioSampleRate",serverInputAudioSampleRate:"serverInputAudioSampleRate",serverOutputAudioSampleRate:"serverOutputAudioSampleRate",serverMonitorAudioSampleRate:"serverMonitorAudioSampleRate",serverInputAudioBufferSize:"serverInputAudioBufferSize",serverOutputAudioBufferSize:"serverOutputAudioBufferSize",serverInputDeviceId:"serverInputDeviceId",serverOutputDeviceId:"serverOutputDeviceId",serverMonitorDeviceId:"serverMonitorDeviceId",serverReadChunkSize:"serverReadChunkSize",serverInputAudioGain:"serverInputAudioGain",serverOutputAudioGain:"serverOutputAudioGain",serverMonitorAudioGain:"serverMonitorAudioGain",tran:"tran",noiseScale:"noiseScale",predictF0:"predictF0",silentThreshold:"silentThreshold",extraConvertSize:"extraConvertSize",clusterInferRatio:"clusterInferRatio",indexRatio:"indexRatio",protect:"protect",rvcQuality:"rvcQuality",modelSamplingRate:"modelSamplingRate",silenceFront:"silenceFront",modelSlotIndex:"modelSlotIndex",useEnhancer:"useEnhancer",useDiff:"useDiff",diffMethod:"diffMethod",useDiffSilence:"useDiffSilence",diffAcc:"diffAcc",diffSpkId:"diffSpkId",kStep:"kStep",threshold:"threshold",speedUp:"speedUp",skipDiffusion:"skipDiffusion",inputSampleRate:"inputSampleRate",enableDirectML:"enableDirectML"},d={passThrough:!1,inputSampleRate:48e3,crossFadeOffsetRate:0,crossFadeEndRate:1,crossFadeOverlapSize:a[1024],recordIO:0,enableServerAudio:0,serverAudioStated:0,serverAudioSampleRate:48e3,serverInputAudioSampleRate:48e3,serverOutputAudioSampleRate:48e3,serverMonitorAudioSampleRate:48e3,serverInputAudioBufferSize:24576,serverOutputAudioBufferSize:24576,serverInputDeviceId:-1,serverOutputDeviceId:-1,serverMonitorDeviceId:-1,serverReadChunkSize:256,serverInputAudioGain:1,serverOutputAudioGain:1,serverMonitorAudioGain:1,srcId:0,dstId:1,gpu:0,f0Factor:1,f0Detector:o.rmvpe_onnx,tran:0,noiseScale:0,predictF0:0,silentThreshold:0,extraConvertSize:0,clusterInferRatio:0,indexRatio:0,protect:.5,rvcQuality:0,modelSamplingRate:48e3,silenceFront:1,modelSlotIndex:0,sampleModels:[],gpus:[],useEnhancer:0,useDiff:1,diffMethod:"dpm-solver",useDiffSilence:0,diffAcc:20,diffSpkId:1,kStep:120,threshold:-45,speedUp:10,skipDiffusion:1,enableDirectML:0,status:"ok",modelSlots:[],serverAudioInputDevices:[],serverAudioOutputDevices:[],maxInputLength:262144,voiceChangerParams:{model_dir:""}},u={sio:"sio",rest:"rest",internal:"internal"},f={48e3:48e3,44100:44100,24e3:24e3},h={decimate:"decimate",average:"average"},m={48e3:48e3},p={workletSetting:{numTrancateTreshold:100,volTrancateThreshold:5e-4,volTrancateLength:32},workletNodeSetting:{serverUrl:"",protocol:"sio",sendingSampleRate:48e3,inputChunkNum:192,downSamplingMode:"average"},voiceChangerClientSetting:{audioInput:null,sampleRate:48e3,echoCancel:!1,noiseSuppression:!1,noiseSuppression2:!1,inputGain:1,outputGain:1,monitorGain:1,passThroughConfirmationSkip:!1}},g={ERR_SIO_CONNECT_FAILED:"ERR_SIO_CONNECT_FAILED",ERR_SIO_INVALID_RESPONSE:"ERR_SIO_INVALID_RESPONSE",ERR_REST_INVALID_RESPONSE:"ERR_REST_INVALID_RESPONSE",ERR_MIC_STREAM_NOT_INITIALIZED:"ERR_MIC_STREAM_NOT_INITIALIZED",ERR_INTERNAL_AUDIO_PROCESS_CALLBACK_IS_NOT_INITIALIZED:"ERR_INTERNAL_AUDIO_PROCESS_CALLBACK_IS_NOT_INITIALIZED"},v="INDEXEDDB_KEY_VOICE_CHANGER",b="INDEXEDDB_KEY_VOICE_CHANGER_DB",y="INDEXEDDB_KEY_VOICE_CHANGER_LIB_CLIENT",S="INDEXEDDB_KEY_VOICE_CHANGER_LIB_SERVER",C="INDEXEDDB_KEY_VOICE_CHANGER_LIB_MODEL_DATA";class w extends Error{constructor(e){super(`Model Load Exception:${e}`),this.causeFileType="",this.causeFileType=e,this.name=this.constructor.name,Error.captureStackTrace(this)}}const M=Object.create(null);M.open="0",M.close="1",M.ping="2",M.pong="3",M.message="4",M.upgrade="5",M.noop="6";const z=Object.create(null);Object.keys(M).forEach((e=>{z[M[e]]=e}));const k={type:"error",data:"parser error"},x="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),V="function"==typeof ArrayBuffer,H=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,E=({type:e,data:t},n,i)=>x&&t instanceof Blob?n?i(t):L(t,i):V&&(t instanceof ArrayBuffer||H(t))?n?i(t):L(new Blob([t]),i):i(M[e]+(t||"")),L=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function T(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let A;const _="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)_["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;const N="function"==typeof ArrayBuffer,I=(e,t)=>{if("string"!=typeof e)return{type:"message",data:O(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:P(e.substring(1),t)}:z[n]?e.length>1?{type:z[n],data:e.substring(1)}:{type:z[n]}:k},P=(e,t)=>{if(N){const n=(e=>{let t,n,i,r,a,o=.75*e.length,s=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const l=new ArrayBuffer(o),d=new Uint8Array(l);for(t=0;t>4,d[c++]=(15&i)<<4|r>>2,d[c++]=(3&r)<<6|63&a;return l})(e);return O(n,t)}return{base64:!0,data:e}},O=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,R=String.fromCharCode(30);let D;function F(e){return e.reduce(((e,t)=>e+t.length),0)}function B(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let i=0;for(let r=0;r(e.hasOwnProperty(n)&&(t[n]=e[n]),t)),{})}const W=j.setTimeout,$=j.clearTimeout;function G(e,t){t.useNativeTimers?(e.setTimeoutFn=W.bind(j),e.clearTimeoutFn=$.bind(j)):(e.setTimeoutFn=j.setTimeout.bind(j),e.clearTimeoutFn=j.clearTimeout.bind(j))}class K extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class J extends U{constructor(e){super(),this.writable=!1,G(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,n){return super.emitReserved("error",new K(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=I(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}const Z="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),Q=64,Y={};let X,ee=0,te=0;function ne(e){let t="";do{t=Z[e%Q]+t,e=Math.floor(e/Q)}while(e>0);return t}function ie(){const e=ne(+new Date);return e!==X?(ee=0,X=e):e+"."+ne(ee++)}for(;te{var e;3===n.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(n)),4===n.readyState&&(200===n.status||1223===n.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof n.status?n.status:0)}),0))},n.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=le.requestsCount++,le.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=se,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete le.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}function de(){for(let e in le.requests)le.requests.hasOwnProperty(e)&&le.requests[e].abort()}le.requestsCount=0,le.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",de):"function"==typeof addEventListener&&addEventListener("onpagehide"in j?"pagehide":"unload",de,!1));const ue="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),fe=j.WebSocket||j.MozWebSocket;__nested_webpack_require_1236903__(8287).hp;const he="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),me={websocket:class extends J{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,n=he?{}:q(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=he?new fe(e,t,n):t?new fe(e,t):new fe(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t{try{this.ws.send(e)}catch(e){}i&&ue((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ie()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!fe}},webtransport:class extends J{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{this.onClose()})).catch((e=>{this.onError("webtransport error",e)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((e=>{const t=function(e,t){D||(D=new TextDecoder);const n=[];let i=0,r=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(0===i){if(F(n)<1)break;const e=B(n,1);a=128==(128&e[0]),r=127&e[0],i=r<126?3:126===r?1:2}else if(1===i){if(F(n)<2)break;const e=B(n,2);r=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(F(n)<8)break;const e=B(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>Math.pow(2,21)-1){s.enqueue(k);break}r=a*Math.pow(2,32)+t.getUint32(4),i=3}else{if(F(n)e){s.enqueue(k);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=new TransformStream({transform(e,t){!function(e,t){x&&e.data instanceof Blob?e.data.arrayBuffer().then(T).then(t):V&&(e.data instanceof ArrayBuffer||H(e.data))?t(T(e.data)):E(e,!1,(e=>{A||(A=new TextEncoder),t(A.encode(e))}))}(e,(n=>{const i=n.length;let r;if(i<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,i);else if(i<65536){r=new Uint8Array(3);const e=new DataView(r.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{r=new Uint8Array(9);const e=new DataView(r.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(r[0]|=128),t.enqueue(r),t.enqueue(n)}))}});i.readable.pipeTo(e.writable),this.writer=i.writable.getWriter();const r=()=>{n.read().then((({done:e,value:t})=>{e||(this.onPacket(t),r())})).catch((e=>{}))};r();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this.writer.write(a).then((()=>this.onOpen()))}))})))}write(e){this.writable=!1;for(let t=0;t{i&&ue((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends J{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}const t=e&&e.forceBase64;this.supportsBinary=ce&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(R),i=[];for(let e=0;e{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,i=new Array(n);let r=0;e.forEach(((e,a)=>{E(e,!1,(e=>{i[a]=e,++r===n&&t(i.join(R))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=ie()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new le(this.uri(),e)}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},pe=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ge=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ve(e){if(e.length>2e3)throw"URI too long";const t=e,n=e.indexOf("["),i=e.indexOf("]");-1!=n&&-1!=i&&(e=e.substring(0,n)+e.substring(n,i).replace(/:/g,";")+e.substring(i,e.length));let r=pe.exec(e||""),a={},o=14;for(;o--;)a[ge[o]]=r[o]||"";return-1!=n&&-1!=i&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,a.path),a.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,i){t&&(n[t]=i)})),n}(0,a.query),a}class be extends U{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=ve(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=ve(t.host).host),G(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,i=n.length;e{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new me[e](n)}open(){let e;if(this.opts.rememberUpgrade&&be.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){let t=this.createTransport(e),n=!1;be.priorWebsocketSuccess=!1;const i=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",(e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;be.priorWebsocketSuccess="websocket"===t.name,this.transport.pause((()=>{n||"closed"!==this.readyState&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}})))};function r(){n||(n=!0,l(),t.close(),t=null)}const a=e=>{const n=new Error("probe error: "+e);n.transport=t.name,r(),this.emitReserved("upgradeError",n)};function o(){a("transport closed")}function s(){a("socket closed")}function c(e){t&&e.name!==t.name&&r()}const l=()=>{t.removeListener("open",i),t.removeListener("error",a),t.removeListener("close",o),this.off("close",s),this.off("upgrading",c)};t.once("open",i),t.once("error",a),t.once("close",o),this.once("close",s),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn((()=>{n||t.open()}),200):t.open()}onOpen(){if(this.readyState="open",be.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let n=0;n=57344?n+=3:(i++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))),n>0&&e>this.maxPayload)return this.writeBuffer.slice(0,n);e+=2}var t;return this.writeBuffer}write(e,t,n){return this.sendPacket("message",e,t,n),this}send(e,t,n){return this.sendPacket("message",e,t,n),this}sendPacket(e,t,n,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof n&&(i=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const r={type:e,data:t,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?n():e()})):this.upgrading?n():e()),this}onError(e){be.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let n=0;const i=e.length;for(;n"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Ce=Object.prototype.toString,we="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Ce.call(Blob),Me="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Ce.call(File);function ze(e){return ye&&(e instanceof ArrayBuffer||Se(e))||we&&e instanceof Blob||Me&&e instanceof File}function ke(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t=0&&e.num{delete this.acks[e];for(let t=0;t{this.io.clearTimeoutFn(r),t.apply(this,[null,...e])}}emitWithAck(e,...t){const n=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((i,r)=>{t.push(((e,t)=>n?e?r(e):i(t):i(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...i)=>{if(n===this._queue[0])return null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),n.pending=!1,this._drainQueue()})),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Ae.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Ae.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ae.EVENT:case Ae.BINARY_EVENT:this.onevent(e);break;case Ae.ACK:case Ae.BINARY_ACK:this.onack(e);break;case Ae.DISCONNECT:this.ondisconnect();break;case Ae.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...i){n||(n=!0,t.packet({type:Ae.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Ae.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n0&&e.jitter<=1?e.jitter:0,this.attempts=0}Fe.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-n:e+n}return 0|Math.min(e,this.max)},Fe.prototype.reset=function(){this.attempts=0},Fe.prototype.setMin=function(e){this.ms=e},Fe.prototype.setMax=function(e){this.max=e},Fe.prototype.setJitter=function(e){this.jitter=e};class Be extends U{constructor(t,n){var i;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(n=t,t=void 0),(n=n||{}).path=n.path||"/socket.io",this.opts=n,G(this,n),this.reconnection(!1!==n.reconnection),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(i=n.randomizationFactor)&&void 0!==i?i:.5),this.backoff=new Fe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==n.timeout?2e4:n.timeout),this._readyState="closed",this.uri=t;const r=n.parser||e;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==n.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new be(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=Oe(t,"open",(function(){n.onopen(),e&&e()})),r=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},a=Oe(t,"error",r);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn((()=>{i(),r(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&n.unref(),this.subs.push((()=>{this.clearTimeoutFn(n)}))}return this.subs.push(i),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Oe(e,"ping",this.onping.bind(this)),Oe(e,"data",this.ondata.bind(this)),Oe(e,"error",this.onerror.bind(this)),Oe(e,"close",this.onclose.bind(this)),Oe(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){ue((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new De(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t)if(this.nsps[e].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;ne())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn((()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()})))}),t);this.opts.autoUnref&&n.unref(),this.subs.push((()=>{this.clearTimeoutFn(n)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Ue={};function je(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let i=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),i=ve(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const r=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+r+":"+i.port+t,i.href=i.protocol+"://"+r+(n&&n.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=n.source,r=n.id,a=n.path,o=Ue[r]&&a in Ue[r].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?s=new Be(i,t):(Ue[r]||(Ue[r]=new Be(i,t)),s=Ue[r]),n.query&&!t.query&&(t.query=n.queryKey),s.socket(n.path,t)}Object.assign(je,{Manager:Be,Socket:De,io:je,connect:je});var qe=__nested_webpack_require_1236903__(8287).hp;class We{constructor(e){this.serverUrl="",this.getSettings=async()=>{const e=this.serverUrl+"/info";return await new Promise((t=>{const n=new Request(e,{method:"GET"});fetch(n).then((async e=>{const n=await e.json();t(n)}))}))},this.getPerformance=async()=>{const e=this.serverUrl+"/performance";return await new Promise((t=>{const n=new Request(e,{method:"GET"});fetch(n).then((async e=>{const n=await e.json();t(n)}))}))},this.updateSettings=async(e,t)=>{const n=this.serverUrl+"/update_settings";return await new Promise((async i=>{const r=new FormData;r.append("key",e),r.append("val",t);const a=new Request(n,{method:"POST",body:r});i(await(await fetch(a)).json())}))},this.uploadFile2=async(e,t,n)=>{const i=this.serverUrl+"/upload_file";n(0,!1);const r=1048576;let a=0;const o=t.size,s=e+t.name,c=Math.ceil(o/r);for(;;){const e=[];for(let n=0;n<10&&!(a*r>=o);n++){const n=t.slice(a*r,(a+1)*r),o=new Promise((e=>{const t=new FormData;t.append("file",new Blob([n])),t.append("filename",`${s}_${a}`);const r=new Request(i,{method:"POST",body:t});fetch(r).then((async t=>{e()}))}));a+=1,e.push(o)}if(await Promise.all(e),a*r>=o)break;n(Math.floor(a/(c+1)*100),!1)}return c},this.uploadFile=async(e,t,n)=>{const i=this.serverUrl+"/upload_file";n(0,!1);const r=1048576,a=[];let o=0;for(let t=0;t{const r=new FormData;r.append("file",new Blob([n.chunk])),r.append("filename",`${t}_${n.hash}`);const a=new Request(i,{method:"POST",body:r});fetch(a).then((async t=>{e()}))}));e.push(r)}if(await Promise.all(e),0==a.length)break;n(Math.floor((s-a.length)/(s+1)*100),!1)}return s},this.concatUploadedFile=async(e,t)=>{const n=this.serverUrl+"/concat_uploaded_file";await new Promise((i=>{const r=new FormData;r.append("filename",e),r.append("filenameChunkNum",""+t);const a=new Request(n,{method:"POST",body:r});fetch(a).then((async e=>{console.log(await e.text()),i()}))}))},this.loadModel=async(e,t,n="{}")=>{null!=t&&null!=t||(console.warn("isHalf is invalid value",t),t=!1);const i=this.serverUrl+"/load_model",r=new Promise((async r=>{const a=new FormData;a.append("slot",""+e),a.append("isHalf",""+t),a.append("params",n);const o=new Request(i,{method:"POST",body:a});r(await(await fetch(o)).json())}));return await r},this.uploadAssets=async e=>{const t=this.serverUrl+"/upload_model_assets",n=new Promise((async n=>{const i=new FormData;i.append("params",e);const r=new Request(t,{method:"POST",body:i});n(await(await fetch(r)).json())}));return await n},this.getModelType=async()=>{const e=this.serverUrl+"/model_type",t=new Promise((async t=>{const n=new Request(e,{method:"GET"});t(await(await fetch(n)).json())}));return await t},this.export2onnx=async()=>{const e=this.serverUrl+"/onnx",t=new Promise((async t=>{const n=new Request(e,{method:"GET"});t(await(await fetch(n)).json())}));return await t},this.mergeModel=async e=>{const t=this.serverUrl+"/merge_model",n=new Promise((async n=>{const i=new FormData;i.append("request",JSON.stringify(e));const r=new Request(t,{method:"POST",body:i}),a=await(await fetch(r)).json();console.log("RESPONSE",a),n(a)}));return await n},this.updateModelDefault=async()=>{const e=this.serverUrl+"/update_model_default",t=new Promise((async t=>{const n=new Request(e,{method:"POST"}),i=await(await fetch(n)).json();console.log("RESPONSE",i),t(i)}));return await t},this.updateModelInfo=async(e,t,n)=>{const i=this.serverUrl+"/update_model_info",r={slot:e,key:t,val:n},a=new Promise((async e=>{const t=new FormData;t.append("newData",JSON.stringify(r));const n=new Request(i,{method:"POST",body:t}),a=await(await fetch(n)).json();console.log("RESPONSE",a),e(a)}));return await a},this.postVoice=async(e,t)=>{const n=this.serverUrl+"/test",i={timestamp:e,buffer:qe.from(t).toString("base64")},r=JSON.stringify(i),a=await fetch(`${n}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:r});try{const e=(await a.json()).changedVoiceBase64,t=qe.from(e,"base64"),n=new ArrayBuffer(t.length),i=new Uint8Array(n);for(let e=0;e{this.outputNode=e},this.updateSetting=e=>{console.log("[WorkletNode] Updating WorkletNode Setting,",this.setting,e);let t=!1;this.setting.serverUrl==e.serverUrl&&this.setting.protocol==e.protocol||(t=!0),this.setting=e,t&&this.createSocketIO()},this.setInternalAudioProcessCallback=e=>{this.internalCallback=e},this.getSettings=()=>this.setting,this.getSocketId=()=>this.socket?.id,this.createSocketIO=()=>{this.socket&&this.socket.close(),"sio"===this.setting.protocol&&(this.socket=je(this.setting.serverUrl+"/test"),this.socket.on("connect_error",(e=>{this.listener.notifyException(g.ERR_SIO_CONNECT_FAILED,`[SIO] rconnection failed ${e}`)})),this.socket.on("connect",(()=>{console.log(`[SIO] connect to ${this.setting.serverUrl}`),console.log(`[SIO] ${this.socket?.id}`)})),this.socket.on("close",(function(e){console.log(`[SIO] close ${e.id}`)})),this.socket.on("message",(e=>{console.log("message:",e)})),this.socket.on("response",(e=>{const t=Date.now()-e[0],n=e[1],i=e[2];0!=e[0]?n.byteLength<256?this.listener.notifyException(g.ERR_SIO_INVALID_RESPONSE,`[SIO] recevied data is too short ${n.byteLength}`):(null!=this.outputNode?this.outputNode.postReceivedVoice(e[1]):this.postReceivedVoice(e[1]),this.listener.notifyResponseTime(t,i)):this.listener.notifyResponseTime(Math.round(1e3*i[0]),i.slice(1,4))})))},this.postReceivedVoice=e=>{const t=new Int16Array(e),n=new Float32Array(t.length);t.forEach(((e,t)=>{const i=e>=32768?-(65536-e)/32768:e/32767;n[t]=i}));let i=null;if(48e3==this.setting.sendingSampleRate)i=n;else{i=new Float32Array(2*n.length);for(let e=0;e{const t=Date.now();if("sio"===this.setting.protocol){if(!this.socket)return void console.warn("sio is not initialized");this.socket.emit("request_message",[t,e.buffer])}else if("rest"===this.setting.protocol){const n=new We(this.setting.serverUrl),i=await n.postVoice(t,e.buffer);i.byteLength<256?this.listener.notifyException(g.ERR_REST_INVALID_RESPONSE,`[REST] recevied data is too short ${i.byteLength}`):(null!=this.outputNode?this.outputNode.postReceivedVoice(i):this.postReceivedVoice(i),this.listener.notifyResponseTime(Date.now()-t))}else{if("internal"!=this.setting.protocol)throw"unknown protocol";if(!this.internalCallback)return void this.listener.notifyException(g.ERR_INTERNAL_AUDIO_PROCESS_CALLBACK_IS_NOT_INITIALIZED,"[AudioWorkletNode] internal audio process callback is not initialized");this.internalCallback.processAudio(e).then((e=>{e.length<256||(null!=this.outputNode?this.outputNode.postReceivedVoice(e.buffer):this.postReceivedVoice(e.buffer))}))}},this.configure=e=>{const t={requestType:"config",voice:new Float32Array(1),numTrancateTreshold:e.numTrancateTreshold,volTrancateThreshold:e.volTrancateThreshold,volTrancateLength:e.volTrancateLength};this.port.postMessage(t)},this.start=async()=>{const e=new Promise((e=>{this.startPromiseResolve=e})),t={requestType:"start",voice:new Float32Array(1),numTrancateTreshold:0,volTrancateThreshold:0,volTrancateLength:0};this.port.postMessage(t),await e},this.stop=async()=>{const e=new Promise((e=>{this.stopPromiseResolve=e})),t={requestType:"stop",voice:new Float32Array(1),numTrancateTreshold:0,volTrancateThreshold:0,volTrancateLength:0};this.port.postMessage(t),await e},this.trancateBuffer=()=>{const e={requestType:"trancateBuffer",voice:new Float32Array(1),numTrancateTreshold:0,volTrancateThreshold:0,volTrancateLength:0};this.port.postMessage(e)},this.startOutputRecording=()=>{this.recordingOutputChunk=[],this.isOutputRecording=!0},this.stopOutputRecording=()=>{this.isOutputRecording=!1;const e=this.recordingOutputChunk.reduce(((e,t)=>e+t.length),0),t=new Float32Array(e);let n=0;for(let e=0;et)throw"downsampling rate show be smaller than original sample rate";const i=t/n,r=Math.round(e.length/i),a=new Float32Array(r);let o=0,s=0;for(;oe+t.byteLength),0),r=new Uint8Array(i);this.requestChunks.reduce(((e,t)=>(r.set(new Uint8Array(t),e),e+t.byteLength)),0),this.sendBuffer(r),this.requestChunks=[],this.listener.notifySendBufferingTime(Date.now()-this.bufferStart),this.bufferStart=Date.now()}else console.warn(`[worklet_node][voice-changer-worklet-processor] unknown response ${e.data.responseType}`,e.data)}}var Ge=__nested_webpack_require_1236903__(1016);const Ke=e=>{const t=e.createMediaStreamDestination(),n=e.createGain();n.gain.value=0,n.connect(t);const i=e.createOscillator();return i.frequency.value=440,i.connect(n),i.start(),t.stream},Je=async e=>{const t=document.createElement("input");t.type="file";const n=new Promise(((n,i)=>{t.onchange=t=>{if(t.target instanceof HTMLInputElement==0)return console.log("invalid target!",t.target),i("invalid target"),null;const r=t.target;return r.files&&0!=r.files.length?""!=e&&r.files[0].type.match(e)?(i(`not target file type ${r.files[0].type}`),null):(n(r.files[0]),null):(i("no file selected"),null)},t.click()}));return await n},Ze=async e=>{const t=await Je(e);return t?await new Promise((e=>{const n=new FileReader;n.onload=()=>{console.log("load data",n.result),e(n.result)},n.readAsDataURL(t)})):t},Qe=e=>e?.endsWith("/")?e.substring(0,e.length-1):e;class Ye{constructor(e){this.getSettings=async()=>this.restClient.getSettings(),this.getPerformance=async()=>this.restClient.getPerformance(),this.updateSettings=async(e,t)=>this.restClient.updateSettings(e,t),this.uploadFile2=async(e,t,n)=>this.restClient.uploadFile2(e,t,n),this.uploadFile=async(e,t,n)=>this.restClient.uploadFile(e,t,n),this.concatUploadedFile=async(e,t)=>this.restClient.concatUploadedFile(e,t),this.loadModel=async(e,t,n="{}")=>this.restClient.loadModel(e,t,n),this.uploadAssets=async e=>this.restClient.uploadAssets(e),this.getModelType=async()=>this.restClient.getModelType(),this.export2onnx=async()=>this.restClient.export2onnx(),this.mergeModel=async e=>this.restClient.mergeModel(e),this.updateModelDefault=async()=>this.restClient.updateModelDefault(),this.updateModelInfo=async(e,t,n)=>this.restClient.updateModelInfo(e,t,n),this.restClient=new We(e)}}class Xe{constructor(){this._resolvers=[],this._promises=[]}_add(){this._promises.push(new Promise((e=>{this._resolvers.push(e)})))}enqueue(e){0==this._resolvers.length&&this._add(),this._resolvers.shift()(e)}dequeue(){return 0==this._promises.length&&this._add(),this._promises.shift()}isEmpty(){return 0==this._promises.length}isBlocked(){return 0!=this._resolvers.length}get length(){return this._promises.length-this._resolvers.length}}class et{constructor(e,t,n){this.vfEnable=!1,this.vf=null,this.currentDevice=null,this.currentMediaStream=null,this.currentMediaStreamAudioSourceNode=null,this.inputGainNode=null,this.outputGainNode=null,this.monitorGainNode=null,this._isVoiceChanging=!1,this.setting=p.voiceChangerClientSetting,this.sslCertified=[],this.sem=new Xe,this.lock=async()=>await this.sem.dequeue(),this.unlock=e=>{this.sem.enqueue(e+1)},this.isInitialized=async()=>(this.promiseForInitialize&&await this.promiseForInitialize,!0),this.setup=async()=>{const e=await this.lock();if(console.log(`Input Setup=> echo: ${this.setting.echoCancel}, noise1: ${this.setting.noiseSuppression}, noise2: ${this.setting.noiseSuppression2}`),!this.vcInNode)throw console.warn("vc node is not initialized."),"vc node is not initialized.";if(this.currentMediaStream&&(this.currentMediaStream.getTracks().forEach((e=>{e.stop()})),this.currentMediaStream=null),!this.setting.audioInput)return console.log(`Input Setup=> client mic is disabled. ${this.setting.audioInput}`),this.vcInNode.stop(),void await this.unlock(e);if("string"==typeof this.setting.audioInput)try{"none"==this.setting.audioInput?this.currentMediaStream=Ke(this.ctx):this.currentMediaStream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:this.setting.audioInput,channelCount:1,sampleRate:this.setting.sampleRate,sampleSize:16,autoGainControl:!1,echoCancellation:this.setting.echoCancel,noiseSuppression:this.setting.noiseSuppression}})}catch(t){throw console.warn(t),this.vcInNode.stop(),await this.unlock(e),t}else this.currentMediaStream=this.setting.audioInput;if(this.currentMediaStreamAudioSourceNode=this.ctx.createMediaStreamSource(this.currentMediaStream),this.inputGainNode=this.ctx.createGain(),this.inputGainNode.gain.value=this.setting.inputGain,this.currentMediaStreamAudioSourceNode.connect(this.inputGainNode),this.currentDevice&&this.setting.noiseSuppression2){this.currentDevice.chooseNewInnerDevice(this.currentMediaStream);const e=await this.currentDevice.createAudioNode(this.ctx);this.inputGainNode.connect(e.start),e.end.connect(this.vcInNode)}else this.inputGainNode.connect(this.vcInNode);this.vcInNode.setOutputNode(this.vcOutNode),console.log("Input Setup=> success"),await this.unlock(e)},this.start=async()=>{await this.vcInNode.start(),this._isVoiceChanging=!0},this.stop=async()=>{await this.vcInNode.stop(),this._isVoiceChanging=!1},this.setServerUrl=(e,t=!1)=>{const n=Qe(e);n!=`${location.protocol}//${location.host}`&&0!=n.length&&"https:"==location.protocol&&0==this.sslCertified.includes(n)&&t&&(window.confirm("MMVC Server is different from this page's origin. Open tab to open ssl connection. OK? (You can close the opened tab after ssl connection succeed.)")?(window.open(n,"_blank"),this.sslCertified.push(n)):alert("Your voice conversion may fail...")),this.vcInNode.updateSetting({...this.vcInNode.getSettings(),serverUrl:n}),this.configurator=new Ye(n)},this.updateClientSetting=async e=>{let t=!1;this.setting.audioInput==e.audioInput&&this.setting.echoCancel==e.echoCancel&&this.setting.noiseSuppression==e.noiseSuppression&&this.setting.noiseSuppression2==e.noiseSuppression2&&this.setting.sampleRate==e.sampleRate||(t=!0),this.setting.inputGain!=e.inputGain&&this.setInputGain(e.inputGain),this.setting.outputGain!=e.outputGain&&this.setOutputGain(e.outputGain),this.setting.monitorGain!=e.monitorGain&&this.setMonitorGain(e.monitorGain),this.setting=e,t&&await this.setup()},this.setInputGain=e=>{this.setting.inputGain=e,this.inputGainNode&&e&&(this.inputGainNode.gain.value=e)},this.setOutputGain=e=>{this.outputGainNode&&e&&(this.outputGainNode.gain.value=e)},this.setMonitorGain=e=>{this.monitorGainNode&&e&&(this.monitorGainNode.gain.value=e)},this.getModelType=()=>this.configurator.getModelType(),this.getOnnx=async()=>this.configurator.export2onnx(),this.mergeModel=async e=>this.configurator.mergeModel(e),this.updateModelDefault=async()=>this.configurator.updateModelDefault(),this.updateModelInfo=async(e,t,n)=>this.configurator.updateModelInfo(e,t,n),this.updateServerSettings=(e,t)=>this.configurator.updateSettings(e,t),this.uploadFile=(e,t,n)=>this.configurator.uploadFile(e,t,n),this.uploadFile2=(e,t,n)=>this.configurator.uploadFile2(e,t,n),this.concatUploadedFile=(e,t)=>this.configurator.concatUploadedFile(e,t),this.loadModel=(e,t,n)=>this.configurator.loadModel(e,t,n),this.uploadAssets=e=>this.configurator.uploadAssets(e),this.configureWorklet=e=>{this.vcInNode.configure(e),this.vcOutNode.configure(e)},this.startOutputRecording=()=>{this.vcOutNode.startOutputRecording()},this.stopOutputRecording=()=>this.vcOutNode.stopOutputRecording(),this.trancateBuffer=()=>{this.vcOutNode.trancateBuffer()},this.updateWorkletNodeSetting=e=>{this.vcInNode.updateSetting(e),this.vcOutNode.updateSetting(e)},this.setInternalAudioProcessCallback=e=>{this.vcInNode.setInternalAudioProcessCallback(e)},this.getClientSettings=()=>this.vcInNode.getSettings(),this.getServerSettings=()=>this.configurator.getSettings(),this.getPerformance=()=>this.configurator.getPerformance(),this.getSocketId=()=>this.vcInNode.getSocketId(),this.sem.enqueue(0),this.configurator=new Ye(""),this.ctx=e,this.vfEnable=t,this.promiseForInitialize=new Promise((async e=>{const t=URL.createObjectURL(new Blob(['(()=>{"use strict";class t extends AudioWorkletProcessor{constructor(){super(),this.BLOCK_SIZE=128,this.initialized=!1,this.volume=0,this.isRecording=!1,this.playBuffer=[],this.unpushedF32Data=new Float32Array(0),this.calcVol=(t,e)=>{const s=t.reduce(((t,e)=>t+e*e),0),r=Math.sqrt(s/t.length);return Math.max(r,.95*e)},this.trancateBuffer=()=>{for(console.log("[worklet] Buffer truncated");this.playBuffer.length>2;)this.playBuffer.shift()},this.pushData=t=>{const e={responseType:"inputData",inputData:t};this.port.postMessage(e)},console.log("[AudioWorkletProcessor] created."),this.initialized=!0,this.port.onmessage=this.handleMessage.bind(this)}handleMessage(t){const e=t.data;if("config"===e.requestType)return void console.log("[worklet] worklet configured",e);if("start"===e.requestType){if(this.isRecording)return void console.warn("[worklet] recoring is already started");this.isRecording=!0;const t={responseType:"start_ok"};return void this.port.postMessage(t)}if("stop"===e.requestType){if(!this.isRecording)return void console.warn("[worklet] recoring is not started");this.isRecording=!1;const t={responseType:"stop_ok"};return void this.port.postMessage(t)}if("trancateBuffer"===e.requestType)return void this.trancateBuffer();const s=e.voice;this.playBuffer.length>s.length/this.BLOCK_SIZE*1.5&&(console.log(`[worklet] Truncate ${this.playBuffer.length} > ${s.length/this.BLOCK_SIZE}`),this.trancateBuffer());const r=new Float32Array(this.unpushedF32Data.length+s.length);r.set(this.unpushedF32Data),r.set(s,this.unpushedF32Data.length);const i=Math.floor(r.length/this.BLOCK_SIZE);for(let t=0;t0&&t[0].length>0&&this.pushData(t[0][0]),0===this.playBuffer.length)return!0;let r=this.playBuffer.shift();if(r){this.volume=this.calcVol(r,this.volume);const t={responseType:"volume",volume:this.volume};this.port.postMessage(t),e[0][0].set(r),2==e[0].length&&e[0][1].set(r)}return!0}}registerProcessor("voice-changer-worklet-processor",t)})();'],{type:"text/javascript"}));try{this.vcInNode=new $e(this.ctx,n)}catch(e){await this.ctx.audioWorklet.addModule(t),this.vcInNode=new $e(this.ctx,n)}const i=new AudioContext({sampleRate:48e3});console.log("audio out:",i);try{this.vcOutNode=new $e(i,n)}catch(e){await i.audioWorklet.addModule(t),this.vcOutNode=new $e(i,n)}if(this.currentMediaStreamAudioDestinationNode=i.createMediaStreamDestination(),this.outputGainNode=i.createGain(),this.outputGainNode.gain.value=this.setting.outputGain,this.vcOutNode.connect(this.outputGainNode),this.outputGainNode.connect(this.currentMediaStreamAudioDestinationNode),this.currentMediaStreamAudioDestinationMonitorNode=i.createMediaStreamDestination(),this.monitorGainNode=i.createGain(),this.monitorGainNode.gain.value=this.setting.monitorGain,this.vcOutNode.connect(this.monitorGainNode),this.monitorGainNode.connect(this.currentMediaStreamAudioDestinationMonitorNode),this.vfEnable){this.vf=await Ge.VoiceFocusDeviceTransformer.create({variant:"c20"});const e=Ke(this.ctx);this.currentDevice=await this.vf.createTransformDevice(e)||null}e()}))}get stream(){return this.currentMediaStreamAudioDestinationNode.stream}get monitorStream(){return this.currentMediaStreamAudioDestinationMonitorNode.stream}get isVoiceChanging(){return this._isVoiceChanging}}var tt=__nested_webpack_require_1236903__(9155),nt=__nested_webpack_require_1236903__(3790),it=__nested_webpack_require_1236903__.n(nt);const rt=e=>{const t=e.clientType||"default";it().config({driver:it().INDEXEDDB,name:v,version:1,storeName:`${b}`,description:"appStorage"});const n=(0,tt.useMemo)((()=>async(e,n)=>{const i=`${t}_${e}`;await it().setItem(i,n)}),[e.clientType]);return{dummy:"",setItem:n,getItem:(0,tt.useMemo)((()=>async e=>{const n=`${t}_${e}`;return await it().getItem(n)}),[e.clientType]),removeItem:(0,tt.useMemo)((()=>async e=>{const n=`${t}_${e}`;return console.log("remove key:",n),await it().removeItem(n)}),[e.clientType]),removeDB:(0,tt.useMemo)((()=>async()=>{const e=await it().keys();for(const t of e)console.log("remove key:",t),await it().removeItem(t)}),[e.clientType])}},at={iconFile:"iconFile"},ot={mmvcv13Config:"mmvcv13Config",mmvcv13Model:"mmvcv13Model",mmvcv15Config:"mmvcv15Config",mmvcv15Model:"mmvcv15Model",mmvcv15Correspondence:"mmvcv15Correspondence",soVitsSvc40Config:"soVitsSvc40Config",soVitsSvc40Model:"soVitsSvc40Model",soVitsSvc40Cluster:"soVitsSvc40Cluster",rvcModel:"rvcModel",rvcIndex:"rvcIndex",ddspSvcModel:"ddspSvcModel",ddspSvcModelConfig:"ddspSvcModelConfig",ddspSvcDiffusion:"ddspSvcDiffusion",ddspSvcDiffusionConfig:"ddspSvcDiffusionConfig",diffusionSVCModel:"diffusionSVCModel",beatriceModel:"beatriceModel",llvcModel:"llvcModel",llvcConfig:"llvcConfig",easyVCModel:"easyVCModel"},st=e=>{const[t,n]=(0,tt.useState)(d),i=e=>{e.modelSlots&&n(e)},r=(0,tt.useMemo)((()=>async n=>{if(e.voiceChangerClient)for(let r=0;rasync(t,n,i="")=>{if(!e.voiceChangerClient)return;const r=await e.voiceChangerClient.uploadFile2(i,t,n),a=await e.voiceChangerClient.concatUploadedFile(i+t.name,r);console.log("uploaded",r,a)}),[e.voiceChangerClient]),f=(0,tt.useMemo)((()=>async t=>{if(!e.voiceChangerClient)return;if(o(0),c(!0),0==t.isSampleMode){const e=1/t.files.length;for(let n=0;n{o(t*e+i)}),t.files[n].dir)}}const n={...t,files:t.files.map((e=>({name:e.file.name,kind:e.kind,dir:e.dir})))},i=e.voiceChangerClient.loadModel(0,!1,JSON.stringify(n));await i,o(0),c(!1),m()}),[e.voiceChangerClient]),h=(0,tt.useMemo)((()=>async(t,n,i)=>{if(!e.voiceChangerClient)return;await u(i,((e,t)=>{console.log(e,t)}));const r={slot:t,name:n,file:i.name};await e.voiceChangerClient.uploadAssets(JSON.stringify(r)),m()}),[e.voiceChangerClient]),m=(0,tt.useMemo)((()=>async()=>{if(!e.voiceChangerClient)return;const t=await e.voiceChangerClient.getServerSettings();i(t)}),[e.voiceChangerClient]);return{serverSetting:t,updateServerSettings:r,reloadServerInfo:m,uploadModel:f,uploadProgress:a,isUploading:s,getOnnx:async()=>e.voiceChangerClient.getOnnx(),mergeModel:async t=>{const n=await e.voiceChangerClient.mergeModel(t);return i(n),n},updateModelDefault:async()=>{const t=await e.voiceChangerClient.updateModelDefault();return i(t),t},updateModelInfo:async(t,n,r)=>{const a=await e.voiceChangerClient.updateModelInfo(t,n,r);return i(a),a},uploadAssets:h}},ct={responseTime:0,preprocessTime:0,mainprocessTime:0,postprocessTime:0},lt=e=>{const[t,n]=(0,tt.useState)(!1),[i,r]=(0,tt.useState)(p),a=(0,tt.useRef)(null),[o,s]=(0,tt.useState)(a.current),c=(0,tt.useRef)(),l=(0,tt.useMemo)((()=>new Promise((e=>{c.current=e}))),[]),d=(e=>{const[t,n]=(0,tt.useState)(e.voiceChangerClientSetting);return(0,tt.useEffect)((()=>{(async()=>{if(e.voiceChangerClient)for(let i in e.voiceChangerClientSetting)if(t[i]!=e.voiceChangerClientSetting[i]){n(e.voiceChangerClientSetting),await e.voiceChangerClient.updateClientSetting(e.voiceChangerClientSetting);break}})()}),[e.voiceChangerClient,e.voiceChangerClientSetting]),{setServerUrl:(0,tt.useMemo)((()=>t=>{e.voiceChangerClient&&e.voiceChangerClient.setServerUrl(t,!0)}),[e.voiceChangerClient]),start:(0,tt.useMemo)((()=>async()=>{e.voiceChangerClient&&await e.voiceChangerClient.start()}),[e.voiceChangerClient]),stop:(0,tt.useMemo)((()=>async()=>{e.voiceChangerClient&&await e.voiceChangerClient.stop()}),[e.voiceChangerClient]),reloadClientSetting:(0,tt.useMemo)((()=>async()=>{e.voiceChangerClient&&await e.voiceChangerClient.getClientSettings()}),[e.voiceChangerClient])}})({voiceChangerClient:o,voiceChangerClientSetting:i.voiceChangerClientSetting}),u=(e=>{const[t,n]=(0,tt.useState)(e.workletNodeSetting);return(0,tt.useEffect)((()=>{if(e.voiceChangerClient)for(let i in e.workletNodeSetting)if(t[i]!=e.workletNodeSetting[i]){n(e.workletNodeSetting),e.voiceChangerClient.updateWorkletNodeSetting(e.workletNodeSetting);break}}),[e.voiceChangerClient,e.workletNodeSetting]),{startOutputRecording:(0,tt.useMemo)((()=>()=>{e.voiceChangerClient&&e.voiceChangerClient.startOutputRecording()}),[e.voiceChangerClient]),stopOutputRecording:(0,tt.useMemo)((()=>async()=>e.voiceChangerClient?e.voiceChangerClient.stopOutputRecording():new Float32Array),[e.voiceChangerClient]),trancateBuffer:(0,tt.useMemo)((()=>async()=>{e.voiceChangerClient&&e.voiceChangerClient.trancateBuffer()}),[e.voiceChangerClient]),setInternalAudioProcessCallback:(0,tt.useMemo)((()=>async t=>{e.voiceChangerClient&&e.voiceChangerClient.setInternalAudioProcessCallback(t)}),[e.voiceChangerClient])}})({voiceChangerClient:o,workletNodeSetting:i.workletNodeSetting});(e=>{const[t,n]=(0,tt.useState)(e.workletSetting);(0,tt.useEffect)((()=>{e.voiceChangerClient&&e.voiceChangerClient.configureWorklet(t)}),[e.voiceChangerClient,e.workletSetting])})({voiceChangerClient:o,workletSetting:i.workletSetting});const f=st({voiceChangerClient:o}),h=rt({clientType:null}),[m,g]=(0,tt.useState)(0),[v,b]=(0,tt.useState)(ct),[y,S]=(0,tt.useState)(0),[C,w]=(0,tt.useState)(0),M=(0,tt.useMemo)((()=>a.current?async()=>{if(a.current){const e=await a.current.getPerformance(),t=e[0],n=e[1],i=e[2],r=e[3];b({responseTime:t,preprocessTime:n,mainprocessTime:i,postprocessTime:r})}else b({responseTime:0,preprocessTime:0,mainprocessTime:0,postprocessTime:0})}:null),[a.current]),z=(0,tt.useRef)(0),{setItem:k,getItem:x,removeItem:V}=rt({clientType:null}),H=e=>{const t={...e};t.voiceChangerClientSetting={...t.voiceChangerClientSetting},"string"!=typeof t.voiceChangerClientSetting.audioInput&&(t.voiceChangerClientSetting.audioInput="none"),k("clientSetting",t),r(e)};(0,tt.useEffect)((()=>{o&&(async()=>{const e=await x("clientSetting");e&&(r(e),f.reloadServerInfo())})()}),[o]),(0,tt.useEffect)((()=>{(async()=>{if(!e.audioContext)return;const t=new et(e.audioContext,!0,{notifySendBufferingTime:e=>{g(e)},notifyResponseTime:(e,t)=>{const n=e,i=t?Math.ceil(1e3*t[0]):0,r=t?Math.ceil(1e3*t[1]):0,a=t?Math.ceil(1e3*t[2]):0;b({responseTime:n,preprocessTime:i,mainprocessTime:r,postprocessTime:a})},notifyException:e=>{e.length>0&&(console.log(`error:${e}`),z.current+=1,w(z.current))},notifyVolume:e=>{S(e)}});await t.isInitialized(),a.current=t,s(a.current),console.log("[useClient] client initialized"),c.current(),n(!0)})()}),[e.audioContext]);const E=(0,tt.useMemo)((()=>async()=>{await l,await d.reloadClientSetting(),await f.reloadServerInfo()}),[d.reloadClientSetting,f.reloadServerInfo]);return{initialized:t,setting:i,setVoiceChangerClientSetting:e=>{i.voiceChangerClientSetting=e,console.log("setting.voiceChangerClientSetting",i.voiceChangerClientSetting),H({...i})},setServerUrl:d.setServerUrl,start:d.start,stop:d.stop,reloadClientSetting:d.reloadClientSetting,setWorkletNodeSetting:e=>{i.workletNodeSetting=e,console.log("setting.workletNodeSetting",i.workletNodeSetting),H({...i})},startOutputRecording:u.startOutputRecording,stopOutputRecording:u.stopOutputRecording,trancateBuffer:u.trancateBuffer,setInternalAudioProcessCallback:u.setInternalAudioProcessCallback,setWorkletSetting:e=>{i.workletSetting=e,console.log("setting.workletSetting",i.workletSetting),H({...i})},serverSetting:f,indexedDBState:h,bufferingTime:m,volume:y,performance:v,updatePerformance:M,getInfo:E,clearSetting:async()=>{await V("clientSetting")},setAudioOutputElementId:e=>{if(!a.current)return void console.warn("[voiceChangerClient] is not ready for set audio output.");const t=document.getElementById(e);t.paused&&(t.srcObject=a.current.stream,t.play())},setAudioMonitorElementId:e=>{if(!a.current)return void console.warn("[voiceChangerClient] is not ready for set audio output.");const t=document.getElementById(e);t.paused&&(t.srcObject=a.current.monitorStream,t.play())},ioErrorCount:C,resetIoErrorCount:()=>{z.current=0,w(z.current)}}}})(),__nested_webpack_exports__})(),module.exports=t(__webpack_require__(540))},236:function(module){var factory;"undefined"!=typeof self&&self,factory=()=>(()=>{"use strict";var __webpack_modules__={"./src/index.ts":(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ info: () => (/* binding */ info)\n/* harmony export */ });\nconst info = "not implemented";\n\n\n//# sourceURL=webpack://@dannadori/voice-changer-js/./src/index.ts?')}},__nested_webpack_require_1707__={d:(e,t)=>{for(var n in t)__nested_webpack_require_1707__.o(t,n)&&!__nested_webpack_require_1707__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},__nested_webpack_exports__={};return __webpack_modules__["./src/index.ts"](0,__nested_webpack_exports__,__nested_webpack_require_1707__),__nested_webpack_exports__})(),module.exports=factory()},32:(e,t,n)=>{"use strict";n.d(t,{A:()=>s});var i=n(601),r=n.n(i),a=n(314),o=n.n(a)()(r());o.push([e.id,"/* 前提条件 */\n\n.rotate-button-container {\n height: var(--header-height);\n width: var(--header-height);\n position: relative;\n}\n.rotate-button {\n display: none;\n}\n.rotate-button ~ .rotate-lable {\n padding: 2px;\n position: absolute;\n transition: all 0.3s;\n cursor: pointer;\n height: var(--header-height);\n width: var(--header-height);\n}\n.rotate-button ~ .rotate-lable > * {\n width: 100%;\n height: 100%;\n float: left;\n transition: all 0.3s;\n}\n.rotate-button ~ .rotate-lable > * .spin-on {\n width: 100%;\n height: 100%;\n display: none;\n }\n.rotate-button ~ .rotate-lable > * .spin-off {\n width: 100%;\n height: 100%;\n display: blcok;\n }\n.rotate-button ~ .rotate-lable > .colored {\n color: rgba(200, 200, 200, 0.8);\n background: rgba(0, 0, 0, 1);\n transition: all 0.3s;\n}\n.rotate-button ~ .rotate-lable > .colored .spin-on {\n display: none;\n }\n.rotate-button ~ .rotate-lable > .colored .spin-off {\n display: block;\n }\n.rotate-button:checked ~ .rotate-lable > .colored {\n color: rgba(50, 240, 50, 0.8);\n background: rgba(60, 60, 60, 1);\n transition: all 0.3s;\n}\n.rotate-button:checked ~ .rotate-lable > .colored .spin-on {\n display: block;\n }\n.rotate-button:checked ~ .rotate-lable > .colored .spin-off {\n display: none;\n }\n\n.rotate-button:checked ~ .rotate-lable > .spinner {\n width: 100%;\n height: 100%;\n transform: rotate(180deg);\n transition: all 0.3s;\n box-sizing: border-box;\n}\n\n.rotate-button:checked ~ .rotate-lable > .spinner .spin-on {\n display: block;\n }\n\n.rotate-button:checked ~ .rotate-lable > .spinner .spin-off {\n display: none;\n }\n",""]);const s=o},603:(e,t,n)=>{"use strict";n.d(t,{A:()=>d});var i=n(601),r=n.n(i),a=n(314),o=n.n(a),s=n(32),c=n(52),l=o()(r());l.push([e.id,"@import url(https://fonts.googleapis.com/css2?family=Chicle&family=Poppins:ital,wght@0,200;0,400;0,600;1,200;1,400;1,600&display=swap);"]),l.push([e.id,"@import url(https://fonts.googleapis.com/css2?family=Yusei+Magic&display=swap);"]),l.i(s.A),l.i(c.A),l.push([e.id,':root {\n --text-color: #333;\n --company-color1: rgba(64, 119, 187, 1);\n --company-color2: rgba(29, 47, 78, 1);\n --company-color3: rgba(255, 255, 255, 1);\n --company-color1-alpha: rgba(64, 119, 187, 0.3);\n --company-color2-alpha: rgba(29, 47, 78, 0.3);\n --company-color3-alpha: rgba(255, 255, 255, 0.3);\n --global-shadow-color: rgba(0, 0, 0, 0.4);\n\n --sidebar-transition-time: 0.2s;\n --sidebar-transition-time-quick: 0.1s;\n --sidebar-transition-animation: ease-in-out;\n\n --header-height: 1.5rem;\n --right-sidebar-width: 320px;\n\n --dialog-border-color: rgba(100, 100, 100, 1);\n --dialog-shadow-color: rgba(0, 0, 0, 0.3);\n --dialog-background-color: rgba(255, 255, 255, 1);\n --dialog-primary-color: rgba(19, 70, 209, 1);\n --dialog-active-color: rgba(40, 70, 209, 1);\n --dialog-input-border-color: rgba(200, 200, 200, 1);\n --dialog-submit-button-color: rgba(180, 190, 230, 1);\n --dialog-cancel-button-color: rgba(235, 80, 80, 1);\n\n --body-video-seeker-height: 3rem;\n}\n\n* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n font-family: "Poppins", sans-serif;\n}\nhtml {\n font-size: 16px;\n}\nbody {\n height: 100%;\n width: 100%;\n overflow-y: scroll;\n overflow-x: hidden;\n color: var(--text-color);\n /* background: linear-gradient(45deg, var(--company-color1) 0, 5%, var(--company-color2) 5% 10%, var(--company-color3) 10% 80%, var(--company-color1) 80% 85%, var(--company-color2) 85% 100%); */\n background: linear-gradient(45deg, var(--company-color1) 0, 1%, var(--company-color2) 1% 5%, var(--company-color3) 5% 90%, var(--company-color1) 90% 95%, var(--company-color2) 95% 100%);\n}\n#app {\n height: 100%;\n width: 100%;\n}\n.first-gesture {\n background: rgba(200, 0, 0, 0.2);\n width: 100%;\n height: 100%;\n position: absolute;\n}\n\n/* Main + Section Partition*/\n.main-body {\n height: 100%;\n width: 100%;\n padding: 2rem;\n font-family: "Yusei Magic", sans-serif;\n display: flex;\n flex-direction: column;\n font-size: 1rem;\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n}\n/* Title */\n.main-body .top-title .title {\n font-size: 3rem;\n }\n.main-body .top-title .top-title-version {\n margin-left: 2rem;\n font-size: 1.2rem;\n background: linear-gradient(transparent 60%, yellow 30%);\n }\n.main-body .top-title .top-title-version-number {\n margin-left: 0.3rem;\n font-size: 0.8rem;\n }\n.main-body .top-title .belongings {\n margin-left: 1rem;\n margin-right: 1rem;\n }\n.main-body .top-title .belongings .link {\n margin-left: 1rem;\n font-weight: 700;\n text-decoration: underline;\n }\n/* Partition */\n.main-body .partition {\n width: 100%;\n }\n.main-body .partition .partition-header {\n font-weight: 700;\n color: rgb(71, 69, 69);\n display: flex;\n }\n.main-body .partition .partition-header .caret {\n width: 2rem;\n }\n.main-body .partition .partition-header .title {\n font-size: 1.1rem;\n }\n.main-body .partition .partition-header .belongings {\n font-weight: 400;\n font-size: 0.8rem;\n display: flex;\n flex-direction: row;\n align-items: flex-end;\n margin-left: 10px;\n }\n.main-body .partition .partition-header .belongings .belongings-checkbox {\n margin-bottom: 3px;\n }\n.main-body .partition .partition-content {\n position: static;\n overflow-y: hidden;\n }\n.main-body .partition .row-split {\n }\n.state-control-checkbox:checked + .partition .partition-content {\n max-height: 700px;\n background: rgba(255, 255, 255, 0.3);\n transition: all var(--sidebar-transition-time) var(--sidebar-transition-animation);\n}\n.state-control-checkbox + .partition .partition-content {\n max-height: 0px;\n background: rgba(233, 233, 255, 0.3);\n transition: all var(--sidebar-transition-time) var(--sidebar-transition-animation);\n}\n/* ROW */\n\n.split-8-2 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n\n.split-8-2 > div:nth-child(1) {\n left: 0px;\n width: 80%;\n }\n\n.split-8-2 > div:nth-child(2) {\n left: 80%;\n width: 20%;\n }\n.split-6-4 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-6-4 > div:nth-child(1) {\n left: 0px;\n width: 60%;\n }\n.split-6-4 > div:nth-child(2) {\n left: 60%;\n width: 40%;\n }\n.split-5-5 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-5-5 > div:nth-child(1) {\n left: 0px;\n width: 50%;\n }\n.split-5-5 > div:nth-child(2) {\n left: 50%;\n width: 50%;\n }\n.split-4-6 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-4-6 > div:nth-child(1) {\n left: 0px;\n width: 40%;\n }\n.split-4-6 > div:nth-child(2) {\n left: 40%;\n width: 60%;\n }\n.split-3-7 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-3-7 > div:nth-child(1) {\n left: 0px;\n width: 30%;\n }\n.split-3-7 > div:nth-child(2) {\n left: 30%;\n width: 70%;\n }\n\n.split-2-8 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n\n.split-2-8 > div:nth-child(1) {\n left: 0px;\n width: 20%;\n }\n\n.split-2-8 > div:nth-child(2) {\n left: 20%;\n width: 80%;\n }\n\n.split-1-8-1 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n\n.split-1-8-1 > div:nth-child(1) {\n left: 0px;\n width: 10%;\n }\n\n.split-1-8-1 > div:nth-child(2) {\n left: 10%;\n width: 80%;\n }\n\n.split-1-8-1 > div:nth-child(3) {\n left: 90%;\n width: 10%;\n }\n.split-2-2-6 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-2-2-6 > div:nth-child(1) {\n left: 0px;\n width: 20%;\n }\n.split-2-2-6 > div:nth-child(2) {\n left: 20%;\n width: 20%;\n }\n.split-2-2-6 > div:nth-child(3) {\n left: 40%;\n width: 60%;\n }\n.split-3-3-4 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-3-3-4 > div:nth-child(1) {\n left: 0px;\n width: 30%;\n }\n.split-3-3-4 > div:nth-child(2) {\n left: 30%;\n width: 30%;\n }\n.split-3-3-4 > div:nth-child(3) {\n left: 60%;\n width: 40%;\n }\n\n.split-3-4-3 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n\n.split-3-4-3 > div:nth-child(1) {\n left: 0px;\n width: 30%;\n }\n\n.split-3-4-3 > div:nth-child(2) {\n left: 30%;\n width: 40%;\n }\n\n.split-3-4-3 > div:nth-child(3) {\n left: 70%;\n width: 30%;\n }\n.split-2-5-3 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-2-5-3 > div:nth-child(1) {\n left: 0px;\n width: 20%;\n }\n.split-2-5-3 > div:nth-child(2) {\n left: 20%;\n width: 50%;\n }\n.split-2-5-3 > div:nth-child(3) {\n left: 70%;\n width: 30%;\n }\n.split-4-4-2 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-4-4-2 > div:nth-child(1) {\n left: 0px;\n width: 40%;\n }\n.split-4-4-2 > div:nth-child(2) {\n left: 40%;\n width: 40%;\n }\n.split-4-4-2 > div:nth-child(3) {\n left: 80%;\n width: 20%;\n }\n.split-1-4-4-1 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-1-4-4-1 > div:nth-child(1) {\n left: 0px;\n width: 10%;\n }\n.split-1-4-4-1 > div:nth-child(2) {\n left: 10%;\n width: 40%;\n }\n.split-1-4-4-1 > div:nth-child(3) {\n left: 50%;\n width: 40%;\n }\n.split-1-4-4-1 > div:nth-child(4) {\n left: 90%;\n width: 10%;\n }\n\n.split-3-2-2-3 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n\n.split-3-2-2-3 > div:nth-child(1) {\n left: 0px;\n width: 30%;\n }\n\n.split-3-2-2-3 > div:nth-child(2) {\n left: 30%;\n width: 20%;\n }\n\n.split-3-2-2-3 > div:nth-child(3) {\n left: 50%;\n width: 20%;\n }\n\n.split-3-2-2-3 > div:nth-child(4) {\n left: 70%;\n width: 30%;\n }\n.split-3-2-3-2 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-3-2-3-2 > div:nth-child(1) {\n left: 0px;\n width: 30%;\n }\n.split-3-2-3-2 > div:nth-child(2) {\n left: 30%;\n width: 20%;\n }\n.split-3-2-3-2 > div:nth-child(3) {\n left: 50%;\n width: 30%;\n }\n.split-3-2-3-2 > div:nth-child(4) {\n left: 80%;\n width: 20%;\n }\n.split-3-1-2-4 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-3-1-2-4 > div:nth-child(1) {\n left: 0px;\n width: 30%;\n }\n.split-3-1-2-4 > div:nth-child(2) {\n left: 30%;\n width: 10%;\n }\n.split-3-1-2-4 > div:nth-child(3) {\n left: 40%;\n width: 20%;\n }\n.split-3-1-2-4 > div:nth-child(4) {\n left: 60%;\n width: 40%;\n }\n.split-3-2-1-4 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-3-2-1-4 > div:nth-child(1) {\n left: 0px;\n width: 30%;\n }\n.split-3-2-1-4 > div:nth-child(2) {\n left: 30%;\n width: 20%;\n }\n.split-3-2-1-4 > div:nth-child(3) {\n left: 50%;\n width: 10%;\n }\n.split-3-2-1-4 > div:nth-child(4) {\n left: 60%;\n width: 40%;\n }\n.split-3-2-2-2-1 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-3-2-2-2-1 > div:nth-child(1) {\n left: 0px;\n width: 30%;\n }\n.split-3-2-2-2-1 > div:nth-child(2) {\n left: 30%;\n width: 20%;\n }\n.split-3-2-2-2-1 > div:nth-child(3) {\n left: 50%;\n width: 20%;\n }\n.split-3-2-2-2-1 > div:nth-child(4) {\n left: 70%;\n width: 20%;\n }\n.split-3-2-2-2-1 > div:nth-child(5) {\n left: 90%;\n width: 10%;\n }\n.split-3-1-1-1-4 {\n display: flex;\n width: 100%;\n justify-content: center;\n margin: 1px 0px 1px 0px;\n}\n.split-3-1-1-1-4 > div:nth-child(1) {\n left: 0px;\n width: 30%;\n }\n.split-3-1-1-1-4 > div:nth-child(2) {\n left: 30%;\n width: 10%;\n }\n.split-3-1-1-1-4 > div:nth-child(3) {\n left: 40%;\n width: 10%;\n }\n.split-3-1-1-1-4 > div:nth-child(4) {\n left: 50%;\n width: 10%;\n }\n.split-3-1-1-1-4 > div:nth-child(5) {\n left: 60%;\n width: 40%;\n }\n.w20 {\n width: 20%;\n}\n.bold {\n font-weight: 700;\n}\n.w40 {\n width: 40%;\n}\n\n.underline {\n border-bottom: 3px solid #333;\n}\n.left-padding-05 {\n padding-left: 0.5rem;\n}\n.left-padding-1 {\n padding-left: 1rem;\n}\n.left-padding-2 {\n padding-left: 2rem;\n}\n.left-margin-1 {\n margin-left: 1rem;\n}\n.left-margin-2 {\n margin-left: 2rem;\n}\n.highlight {\n background-color: rgba(200, 200, 255, 0.3);\n}\n.guided {\n /* background-color: rgba(9, 133, 67, 0.3); */\n background-color: rgba(159, 165, 162, 0.1);\n /* border-bottom: 1px solid rgba(9, 133, 67, 0.3); */\n}\n\n.divider {\n height: 0.8rem;\n /* background-color: rgba(16, 210, 113, 0.1); */\n background-color: rgba(31, 42, 36, 0.1);\n}\n\n.body-section-title {\n font-size: 1.5rem;\n color: rgb(51, 49, 49);\n}\n.body-sub-section-title {\n font-size: 1.1rem;\n font-weight: 700;\n color: rgb(3, 53, 12);\n}\n\n.body-item-title {\n color: rgb(51, 99, 49);\n display: flex;\n}\n.body-item-text {\n color: rgb(30, 30, 30);\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.body-item-text .body-item-text-item {\n padding-left: 1rem;\n }\n.body-item-text-small {\n color: rgb(30, 30, 30);\n font-size: 0.7rem;\n}\n.body-item-text-em {\n color: rgb(250, 30, 30);\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n font-weight: 700;\n}\n\n.body-input-container {\n display: flex;\n}\n.body-item-input {\n width: 60%;\n}\n.body-item-input-slider {\n width: 60%;\n}\n.body-item-input-slider-label {\n margin-right: 1rem;\n}\n.body-item-input-slider-val {\n margin-left: 1rem;\n}\n.body-item-input-slider-2nd {\n width: 60%;\n accent-color: #33f;\n}\n\n.body-button-container {\n display: flex;\n flex-direction: row;\n align-items: center;\n}\n\n.body-button-container > div {\n margin-left: 5px;\n margin-right: 5px;\n padding-left: 20px;\n padding-right: 20px;\n }\n\n.body-button-container .body-button {\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: solid 1px #999;\n border-radius: 2px;\n cursor: pointer;\n vertical-align: middle;\n text-align: center;\n }\n\n.body-button-container .body-button:hover {\n border: solid 1px #000;\n }\n\n.body-button-container .body-button-disabled {\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: solid 1px #999;\n border-radius: 2px;\n vertical-align: middle;\n background: #ddd;\n }\n\n.body-button-container .body-button-active {\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: solid 1px #333;\n border-radius: 2px;\n background: #ada;\n }\n\n.body-button-container .body-button-stanby {\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: solid 1px #999;\n border-radius: 2px;\n background: #aba;\n cursor: pointer;\n }\n\n.body-button-container .body-button-stanby:hover {\n border: solid 1px #000;\n }\n\n.body-button-container-space-around {\n justify-content: space-around;\n}\n\n.body-select {\n color: rgb(30, 30, 30);\n max-width: 100%;\n}\n\n.body-select-50 {\n color: rgb(30, 30, 30);\n max-width: 50%;\n height: 1.5rem;\n}\n.select-option-red {\n color: #f66;\n font-weight: 700;\n}\n\n.body-image-container,\n.body-wav-container {\n display: flex;\n width: 100%;\n}\n\n.body-image-container .body-image-container-title,\n .body-image-container .body-wav-container-title,\n .body-wav-container .body-image-container-title,\n .body-wav-container .body-wav-container-title {\n width: 20%;\n }\n\n.body-image-container .body-image-container-img,\n .body-image-container .body-wav-container-wav,\n .body-wav-container .body-image-container-img,\n .body-wav-container .body-wav-container-wav {\n width: 80%;\n }\n\n.donate-img {\n border-radius: 35px;\n height: 1.5rem;\n}\n\n/* Dialog */\n.dialog-container,\n.dialog-container2 {\n justify-content: center;\n align-items: center;\n position: absolute;\n top: 0px;\n left: 0px;\n width: 100vw;\n height: 100vh;\n z-index: -1;\n display: none;\n}\n.dialog-container .dialog-frame, .dialog-container2 .dialog-frame {\n color: var(--company-color2);\n width: 40rem;\n max-height: 80vh;\n border: 2px solid var(--dialog-border-color);\n border-radius: 20px;\n flex-direction: column;\n align-items: center;\n box-shadow: 5px 5px 5px var(--dialog-shadow-color);\n background: var(--dialog-background-color);\n overflow: hidden;\n display: flex;\n }\n.dialog-container .dialog-frame .dialog-title, .dialog-container2 .dialog-frame .dialog-title {\n margin-top: 20px;\n background: var(--company-color2);\n color: #fff;\n width: 100%;\n text-align: center;\n }\n.dialog-container .dialog-frame .dialog-content, .dialog-container2 .dialog-frame .dialog-content {\n width: 90%;\n }\n.dialog-container .dialog-frame .dialog-content .dialog-application-title, .dialog-container2 .dialog-frame .dialog-content .dialog-application-title {\n font-family: "Chicle", cursive;\n font-size: 3rem;\n text-align: center;\n }\n.dialog-container .dialog-frame .dialog-content .dialog-content-part, .dialog-container2 .dialog-frame .dialog-content .dialog-content-part {\n margin-top: 1rem;\n margin-bottom: 1rem;\n }\n.dialog-container .dialog-frame .dialog-content .input-text-container, .dialog-container2 .dialog-frame .dialog-content .input-text-container {\n display: flex;\n flex-direction: row;\n margin: 20px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content, .dialog-container2 .dialog-frame .dialog-fixed-size-content {\n width: 90%;\n max-height: 70vh;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-header,\n .dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-header,\n .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-header,\n .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-header {\n font-weight: 700;\n margin: 5px 5px 5px 5px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-header .model-slot-header-button,\n .dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-header .file-uploader-header-button,\n .dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-header .model-slot-header-button,\n .dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-header .file-uploader-header-button,\n .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-header .model-slot-header-button,\n .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-header .file-uploader-header-button,\n .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-header .model-slot-header-button,\n .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-header .file-uploader-header-button {\n font-weight: 400;\n font-size: 0.8rem;\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: solid 1px #999;\n border-radius: 2px;\n cursor: pointer;\n vertical-align: middle;\n text-align: center;\n padding: 1px 5px 1px 5px;\n margin-left: 1rem;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-header .model-slot-header-button:hover, .dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-header .file-uploader-header-button:hover, .dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-header .model-slot-header-button:hover, .dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-header .file-uploader-header-button:hover, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-header .model-slot-header-button:hover, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-header .file-uploader-header-button:hover, .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-header .model-slot-header-button:hover, .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-header .file-uploader-header-button:hover {\n border: solid 1px #000;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container {\n max-height: 60vh;\n width: 100%;\n overflow-y: scroll;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container::-webkit-scrollbar, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container::-webkit-scrollbar {\n width: 10px;\n height: 10px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container::-webkit-scrollbar-track, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container::-webkit-scrollbar-track {\n background-color: #eee;\n border-radius: 3px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container::-webkit-scrollbar-thumb, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container::-webkit-scrollbar-thumb {\n background: #f7cfec80;\n border-radius: 3px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot {\n height: 5rem;\n display: flex;\n flex-direction: row;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-icon, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-icon {\n width: 5rem;\n height: 5rem;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-icon-pointable, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-icon-pointable {\n width: 5rem;\n height: 5rem;\n cursor: pointer;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail {\n display: flex;\n flex-direction: column;\n font-size: 0.8rem;\n border-bottom: solid 1px #aaa;\n width: 80%;\n overflow-y: scroll;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail::-webkit-scrollbar, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail::-webkit-scrollbar {\n width: 10px;\n height: 10px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail::-webkit-scrollbar-track, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail::-webkit-scrollbar-track {\n background-color: #eee;\n border-radius: 3px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail::-webkit-scrollbar-thumb, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail::-webkit-scrollbar-thumb {\n background: #f7cfec80;\n border-radius: 3px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row {\n display: flex;\n flex-direction: row;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row .model-slot-detail-row-label, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row .model-slot-detail-row-label {\n width: 20%;\n white-space: nowrap;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row .model-slot-detail-row-value, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row .model-slot-detail-row-value {\n width: 55%;\n white-space: nowrap;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row .model-slot-detail-row-value-download, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row .model-slot-detail-row-value-download {\n width: 55%;\n white-space: nowrap;\n cursor: pointer;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row .model-slot-detail-row-value-pointable, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row .model-slot-detail-row-value-pointable {\n width: 55%;\n white-space: nowrap;\n cursor: pointer;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row .model-slot-detail-row-value-edit, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row .model-slot-detail-row-value-edit {\n width: 55%;\n font-weight: 700;\n color: #f00;\n white-space: nowrap;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row .model-slot-detail-row-button, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-detail .model-slot-detail-row .model-slot-detail-row-button {\n width: 15%;\n height: 90%;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-buttons, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-buttons {\n display: flex;\n flex-direction: column;\n border-bottom: solid 1px #a00;\n width: 20%;\n font-size: 0.8rem;\n padding: 4px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-button, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-button {\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: solid 1px #999;\n border-radius: 2px;\n cursor: pointer;\n vertical-align: middle;\n text-align: center;\n padding: 1px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-button:hover, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-button:hover {\n border: solid 1px #000;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-button-disabled, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-button-disabled {\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: solid 1px #999;\n border-radius: 2px;\n vertical-align: middle;\n background: #ddd;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-button-active, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-button-active {\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: solid 1px #333;\n border-radius: 2px;\n background: #ada;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-button-stanby, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-button-stanby {\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: solid 1px #999;\n border-radius: 2px;\n background: #aba;\n cursor: pointer;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-button-stanby:hover, .dialog-container2 .dialog-frame .dialog-fixed-size-content .model-slot-container .model-slot .model-slot-button-stanby:hover {\n border: solid 1px #000;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-voice-changer-select,\n .dialog-container .dialog-frame .dialog-fixed-size-content .edit-model-slot-title,\n .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-voice-changer-select,\n .dialog-container2 .dialog-frame .dialog-fixed-size-content .edit-model-slot-title {\n font-size: 1rem;\n padding-left: 0.5rem;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-container, .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-container {\n font-size: 0.9rem;\n padding-left: 1rem;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-container .file-uploader-file-select-row, .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-container .file-uploader-file-select-row {\n display: flex;\n flex-direction: row;\n margin: 0.2rem;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-container .file-uploader-file-select-row .file-uploader-file-select-row-label, .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-container .file-uploader-file-select-row .file-uploader-file-select-row-label {\n width: 10rem;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-container .file-uploader-file-select-row .file-uploader-file-select-row-value, .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-container .file-uploader-file-select-row .file-uploader-file-select-row-value {\n width: 15rem;\n color: #f00;\n white-space: nowrap;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-container .file-uploader-file-select-row .file-uploader-file-select-row-button, .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-container .file-uploader-file-select-row .file-uploader-file-select-row-button {\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: solid 1px #999;\n border-radius: 2px;\n cursor: pointer;\n vertical-align: middle;\n text-align: center;\n padding: 1px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-container .file-uploader-file-select-row .file-uploader-file-select-row-button:hover, .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-container .file-uploader-file-select-row .file-uploader-file-select-row-button:hover {\n border: solid 1px #000;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-upload-button-container, .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-upload-button-container {\n display: flex;\n flex-direction: row;\n margin-top: 1rem;\n margin-bottom: 0.5rem;\n justify-content: center;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-upload-button-container .file-uploader-file-select-upload-button, .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-upload-button-container .file-uploader-file-select-upload-button {\n /* width: 12rem; */\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: solid 1px #999;\n border-radius: 2px;\n cursor: pointer;\n vertical-align: middle;\n text-align: center;\n padding: 1px 10px 1px 10px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-upload-button-container .file-uploader-file-select-upload-button:hover, .dialog-container2 .dialog-frame .dialog-fixed-size-content .file-uploader-file-select-upload-button-container .file-uploader-file-select-upload-button:hover {\n border: solid 1px #000;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .edit-model-slot-row, .dialog-container2 .dialog-frame .dialog-fixed-size-content .edit-model-slot-row {\n display: flex;\n flex-direction: row;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-title, .dialog-container2 .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-title {\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-speakers, .dialog-container2 .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-speakers {\n display: flex;\n flex-direction: row;\n margin: 0px 0px 0px 1rem;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-speakers .edit-model-slot-speakers-id-label,\n .dialog-container .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-speakers .edit-model-slot-speakers-name-label,\n .dialog-container2 .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-speakers .edit-model-slot-speakers-id-label,\n .dialog-container2 .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-speakers .edit-model-slot-speakers-name-label {\n margin: 0px 0px 0px 0.5rem;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-speakers .edit-model-slot-speakers-buttons, .dialog-container2 .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-speakers .edit-model-slot-speakers-buttons {\n margin: 0px 0px 0px 0.5rem;\n display: flex;\n flex-direction: row;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-speakers .edit-model-slot-speakers-buttons .edit-model-slot-speakers-button, .dialog-container2 .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-speakers .edit-model-slot-speakers-buttons .edit-model-slot-speakers-button {\n margin: 0px 0.5rem 0px 0.5rem;\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n border: solid 1px #999;\n border-radius: 2px;\n cursor: pointer;\n vertical-align: middle;\n text-align: center;\n padding: 0px 10px 0px 10px;\n }\n.dialog-container .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-speakers .edit-model-slot-speakers-buttons .edit-model-slot-speakers-button:hover, .dialog-container2 .dialog-frame .dialog-fixed-size-content .edit-model-slot-row .edit-model-slot-speakers .edit-model-slot-speakers-buttons .edit-model-slot-speakers-button:hover {\n border: solid 1px #000;\n }\n.dialog-container-show {\n display: flex;\n}\n\n.state-control-checkbox:checked ~ .dialog-container {\n background: rgba(200, 200, 200, 0.4);\n animation-name: dialog-show;\n animation-duration: 0.4s;\n animation-iteration-count: 1;\n animation-fill-mode: forwards;\n animation-direction: normal;\n}\n.state-control-checkbox ~ .dialog-container {\n background: rgba(100, 100, 100, 0.4);\n animation-name: dialog-hide;\n animation-duration: 0.4s;\n animation-iteration-count: 1;\n animation-fill-mode: forwards;\n animation-direction: normal;\n}\n.state-control-checkbox:checked + .dialog-frame {\n display: flex;\n}\n.state-control-checkbox + .dialog-frame {\n display: none;\n}\n\n@keyframes dialog-hide {\n from {\n opacity: 1;\n z-index: 200;\n }\n 90% {\n opacity: 0;\n z-index: -1;\n }\n to {\n opacity: 0;\n z-index: -1;\n }\n}\n\n@keyframes dialog-show {\n from {\n opacity: 0;\n z-index: -1;\n }\n 10% {\n z-index: 200;\n }\n to {\n opacity: 1;\n z-index: 200;\n }\n}\n\n.state-control-checkbox:checked ~ .dialog-container2 {\n background: rgba(200, 200, 200, 0.4);\n animation-name: dialog-show2;\n animation-duration: 0.4s;\n animation-iteration-count: 1;\n animation-fill-mode: forwards;\n animation-direction: normal;\n}\n.state-control-checkbox ~ .dialog-container2 {\n background: rgba(100, 100, 100, 0.4);\n animation-name: dialog-hide2;\n animation-duration: 0.4s;\n animation-iteration-count: 1;\n animation-fill-mode: forwards;\n animation-direction: normal;\n}\n/* .state-control-checkbox:checked + .dialog-frame {\n display: flex;\n}\n.state-control-checkbox + .dialog-frame {\n display: none;\n} */\n\n@keyframes dialog-hide2 {\n from {\n opacity: 1;\n z-index: 400;\n }\n 90% {\n opacity: 0;\n z-index: -1;\n }\n to {\n opacity: 0;\n z-index: -1;\n }\n}\n\n@keyframes dialog-show2 {\n from {\n opacity: 0;\n z-index: -1;\n }\n 10% {\n z-index: 400;\n }\n to {\n opacity: 1;\n z-index: 400;\n }\n}\n\n.tooltip-text {\n display: none;\n position: absolute;\n padding: 4px;\n font-size: 0.7rem;\n line-height: 2rem;\n color: #ddd;\n border-radius: 5px;\n background: #444;\n /* width: 100px; */\n}\n.tooltip-text-100px {\n width: 100px;\n}\n.tooltip-text-thin {\n line-height: 1rem;\n}\n.tooltip-text-right {\n line-height: 1rem;\n}\n.tooltip-text:before {\n content: "";\n position: absolute;\n top: -1.4rem;\n border: 12px solid transparent;\n border-top: 16px solid #444;\n margin-left: 0rem;\n transform: rotateZ(180deg);\n}\n.tooltip:hover .tooltip-text {\n display: inline-block;\n top: 30px;\n left: 0px;\n}\n.tooltip:hover .tooltip-text-lower {\n display: inline-block;\n top: 60px;\n left: 0px;\n}\n\n.tooltip {\n position: relative;\n cursor: pointer;\n display: inline-block;\n z-index: 10;\n}\n\n/* ################## */\n.merge-field-container {\n display: flex;\n flex-direction: column;\n}\n.merge-field-container .merge-field {\n display: flex;\n flex-direction: row;\n }\n.merge-field-container .merge-field .merge-field-elem {\n padding-left: 5px;\n }\n.merge-field-container .merge-field .red {\n color: #f00;\n }\n.merge-field-container .merge-field .purple {\n color: #33f;\n }\n.merge-field-container .merge-field .grey-bold {\n color: #555;\n font-weight: 800;\n }\n.model-slot-area {\n display: inline-block;\n background: var(--company-color2);\n border-radius: 10px;\n padding: 20px;\n}\n.model-slot-area .model-slot-panel {\n display: flex;\n flex-direction: row;\n gap: 5px;\n }\n.model-slot-area .model-slot-panel .model-slot-tiles-container {\n display: flex;\n flex-direction: row;\n gap: 2px;\n flex-wrap: wrap;\n overflow-y: scroll;\n max-height: 12rem;\n\n /* width: calc(30rem + 40px + 10px); */\n }\n.model-slot-area .model-slot-panel .model-slot-tiles-container::-webkit-scrollbar {\n width: 10px;\n height: 10px;\n }\n.model-slot-area .model-slot-panel .model-slot-tiles-container::-webkit-scrollbar-track {\n background-color: #eee;\n border-radius: 3px;\n }\n.model-slot-area .model-slot-panel .model-slot-tiles-container::-webkit-scrollbar-thumb {\n background: #f7cfec80;\n border-radius: 3px;\n }\n.model-slot-area .model-slot-panel .model-slot-buttons {\n display: flex;\n gap: 5px;\n flex-direction: column;\n justify-content: space-between;\n width: 4rem;\n }\n.model-slot-area .model-slot-panel .model-slot-buttons .model-slot-button {\n border: solid 2px #999;\n color: white;\n font-size: 0.8rem;\n border-radius: 2px;\n background: #333;\n cursor: pointer;\n padding: 5px;\n text-align: center;\n width: 3rem;\n }\n.model-slot-area .model-slot-panel .model-slot-buttons .model-slot-button:hover {\n border: solid 2px #faa;\n }\n.model-slot-area .model-slot-panel .model-slot-buttons .model-slot-sort-buttons {\n height: 50%;\n }\n.model-slot-area .model-slot-panel .model-slot-buttons .model-slot-sort-buttons .model-slot-sort-button {\n color: white;\n font-size: 0.8rem;\n border-radius: 4px;\n background: #333;\n border: solid 2px #444;\n cursor: pointer;\n padding: 1px;\n text-align: center;\n width: 3rem;\n }\n.model-slot-area .model-slot-panel .model-slot-buttons .model-slot-sort-buttons .model-slot-sort-button-active {\n color: white;\n font-size: 0.8rem;\n border-radius: 4px;\n background: #595;\n border: solid 2px #595;\n cursor: pointer;\n padding: 1px;\n text-align: center;\n width: 3rem;\n }\n.model-slot-area .model-slot-panel .model-slot-buttons .model-slot-sort-buttons .model-slot-sort-button:hover {\n border: solid 2px #faa;\n background: #343;\n }\n.model-slot-tile-container,\n.model-slot-tile-container-selected {\n width: 6rem;\n height: 6rem;\n border-radius: 2px;\n display: flex;\n flex-direction: column;\n align-items: center;\n}\n.model-slot-tile-container-selected {\n background: #43030c;\n}\n.model-slot-tile-container:hover {\n background: #43030c;\n}\n\n.model-slot-tile-icon-div {\n width: 5rem;\n height: 5rem;\n padding-top: 4px;\n position: relative;\n}\n.model-slot-tile-icon {\n width: 5rem;\n height: 5rem;\n -o-object-fit: contain;\n object-fit: contain;\n border-radius: 10px;\n position: absolute;\n}\n.model-slot-tile-vctype {\n position: absolute;\n font-size: 0.6rem;\n font-weight: 800;\n top: 5px;\n left: 2px;\n background: RGBA(10, 200, 100, 0.6);\n border-radius: 5px;\n padding: 0px 2px 0px 2px;\n}\n.model-slot-tile-icon-no-entry {\n color: gray;\n position: absolute;\n top: 2rem;\n}\n.model-slot-tile-dscription {\n font-size: 0.7rem;\n font-weight: 700;\n color: navajowhite;\n padding-top: 4px;\n}\n\n.character-area {\n display: flex;\n gap: 5px;\n padding: 20px;\n}\n\n.character-area .portrait-area {\n width: 20rem;\n height: 20rem;\n }\n\n.character-area .portrait-area .portrait-container {\n position: relative;\n width: 20rem;\n height: 20rem;\n }\n\n.character-area .portrait-area .portrait-container .portrait {\n width: 20rem;\n height: 20rem;\n -o-object-fit: contain;\n object-fit: contain;\n border-radius: 10px;\n position: absolute;\n }\n\n.character-area .portrait-area .portrait-container .portrait-area-status {\n width: 5rem;\n background: rgba(100, 100, 100, 0.5);\n color: white;\n position: absolute;\n padding: 0px 0px 0px 3px;\n font-size: 0.7rem;\n left: 5px;\n top: 5px;\n border-radius: 2px;\n }\n\n.character-area .portrait-area .portrait-container .portrait-area-status .portrait-area-status-vctype {\n font-weight: 800;\n color: #866;\n }\n\n.character-area .portrait-area .portrait-container .portrait-area-terms-of-use {\n width: 5rem;\n background: rgba(100, 100, 100, 0.5);\n color: white;\n position: absolute;\n padding: 2px;\n font-size: 0.7rem;\n right: 5px;\n bottom: 5px;\n }\n\n.character-area .portrait-area .portrait-container .portrait-area-terms-of-use .portrait-area-terms-of-use-link {\n color: white;\n }\n\n.character-area .character-area-control-area {\n display: flex;\n flex-direction: column;\n gap: 10px;\n }\n\n.character-area .character-area-control-area .character-area-control {\n display: flex;\n gap: 3px;\n align-items: center;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-buttons {\n display: flex;\n flex-direction: row;\n gap: 10px;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-buttons .character-area-control-button-active {\n width: 5rem;\n border: solid 1px #333;\n border-radius: 2px;\n background: #ada;\n font-weight: 700;\n text-align: center;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-buttons .character-area-control-button-stanby {\n width: 5rem;\n border: solid 1px #999;\n border-radius: 2px;\n background: #aba;\n cursor: pointer;\n font-weight: 700;\n text-align: center;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-buttons .character-area-control-button-stanby:hover {\n border: solid 1px #000;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-buttons .character-area-control-button-disable {\n width: 5rem;\n border: solid 1px #333;\n border-radius: 2px;\n background: #d3d7d3;\n font-weight: 700;\n text-align: center;\n color: grey;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-buttons .character-area-control-passthru-button-stanby {\n width: 5rem;\n border: solid 1px #999;\n border-radius: 15px;\n padding: 2px;\n background: #aba;\n cursor: pointer;\n font-weight: 700;\n font-size: 0.8rem;\n text-align: center;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-buttons .character-area-control-passthru-button-stanby:hover {\n border: solid 1px #000;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-buttons .character-area-control-passthru-button-active {\n width: 5rem;\n border: solid 1px #955;\n border-radius: 15px;\n padding: 2px;\n background: #fdd;\n cursor: pointer;\n font-weight: 700;\n font-size: 0.8rem;\n text-align: center;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-buttons .character-area-control-passthru-button-active:hover {\n border: solid 1px #000;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-title {\n width: 4rem;\n font-weight: 700;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field {\n /* width: 20rem; */\n display: flex;\n flex-direction: column;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field .character-area-text {\n font-size: 0.9rem;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field .character-area-slider-control {\n display: flex;\n flex-direction: row;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field .character-area-slider-control .character-area-slider-control-kind {\n width: 2rem;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field .character-area-slider-control .character-area-slider-control-slider {\n width: 10rem;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field .character-area-slider-control .character-area-slider-control-val {\n width: 3rem;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field .character-area-slider-control .character-area-slider-control-text {\n padding: 0px 1px 0px 1px;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field .character-area-buttons {\n display: flex;\n flex-direction: row;\n gap: 5px;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field .character-area-buttons .character-area-button {\n border: solid 2px #999;\n color: white;\n font-size: 0.8rem;\n border-radius: 2px;\n background: #666;\n cursor: pointer;\n padding: 5px;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field .character-area-buttons .character-area-button:hover {\n border: solid 2px #faa;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field .character-area-buttons .character-area-toggle-button {\n border: solid 2px #999;\n color: white;\n background: #666;\n\n cursor: pointer;\n\n font-size: 0.8rem;\n border-radius: 5px;\n height: 1.2rem;\n padding-left: 2px;\n padding-right: 2px;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field .character-area-buttons .character-area-toggle-button:hover {\n border: solid 2px #faa;\n }\n\n.character-area .character-area-control-area .character-area-control .character-area-control-field .character-area-buttons .character-area-toggle-button-active {\n border: solid 2px #999;\n color: white;\n background: #844;\n\n cursor: pointer;\n\n font-size: 0.8rem;\n border-radius: 5px;\n height: 1.2rem;\n padding-left: 2px;\n padding-right: 2px;\n }\n\n/* audio::-webkit-media-controls-play-button,\naudio::-webkit-media-controls-panel {\n background-color: #ff0;\n height: 1rem;\n}\naudio::-webkit-media-controls-enclosure {\n max-height: 1rem;\n}\naudio::-webkit-media-controls {\n justify-content: start;\n}\naudio::-webkit-media-controls-overlay-enclosure{\n height: 1rem;\n} */\n\n.config-area {\n display: flex;\n gap: 5px;\n padding: 20px;\n}\n\n.config-area .config-sub-area {\n display: flex;\n flex-direction: column;\n gap: 3px;\n }\n\n.config-area .config-sub-area .config-sub-area-control {\n display: flex;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-title {\n width: 5rem;\n font-weight: 700;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-title-long {\n width: 20rem;\n font-weight: 700;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field {\n width: 15rem;\n display: flex;\n flex-direction: column;\n justify-content: center;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-noise-container {\n display: flex;\n gap: 10px;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-noise-container .config-sub-area-noise-checkbox-container {\n display: flex;\n gap: 5px;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-slider-control {\n display: flex;\n flex-direction: row;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-slider-control .config-sub-area-slider-control-kind {\n width: 1rem;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-slider-control .config-sub-area-slider-control-slider {\n width: 10rem;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-slider-control .config-sub-area-slider-control-val {\n width: 3rem;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-buttons {\n display: flex;\n flex-direction: row;\n gap: 5px;\n align-items: center;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-buttons .config-sub-area-button {\n border: solid 2px #999;\n color: white;\n background: #666;\n\n cursor: pointer;\n\n font-size: 0.8rem;\n border-radius: 5px;\n height: 1.2rem;\n padding-left: 2px;\n padding-right: 2px;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-buttons .config-sub-area-button:hover {\n border: solid 2px #faa;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-buttons .config-sub-area-button-active {\n border: solid 2px #999;\n color: white;\n background: #844;\n\n cursor: pointer;\n\n font-size: 0.8rem;\n border-radius: 5px;\n height: 1.2rem;\n padding-left: 2px;\n padding-right: 2px;\n white-space: nowrap;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-buttons .config-sub-area-button-text-small {\n font-size: 0.5rem;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-control-field-auido-io {\n display: flex;\n flex-direction: row;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-control-field-auido-io .config-sub-area-control-field-auido-io-filter {\n max-width: 30%;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-control-field-auido-io .config-sub-area-control-field-auido-io-select {\n max-width: 70%;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-control-field-screen-select {\n display: flex;\n flex-direction: row-reverse;\n gap: 5px;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-control-field-screen-select .config-sub-area-control-field-screen-select-button-active {\n font-size: 0.8rem;\n border: solid 1px #333;\n border-radius: 5px;\n background: #ada;\n height: 1.2rem;\n padding-left: 2px;\n padding-right: 2px;\n cursor: pointer;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-control-field-screen-select .config-sub-area-control-field-screen-select-button {\n border: solid 1px #333;\n background: #fff;\n font-size: 0.8rem;\n border-radius: 5px;\n height: 1.2rem;\n padding-left: 2px;\n padding-right: 2px;\n cursor: pointer;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-control-field-wav-file {\n display: flex;\n flex-direction: row;\n gap: 5px;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-control-field-wav-file .config-sub-area-control-field-wav-file-audio-container {\n height: 1rem;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-control-field-wav-file .config-sub-area-control-field-wav-file-audio-container .config-sub-area-control-field-wav-file-audio {\n height: 1rem;\n width: 15rem;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-control-field-wav-file .config-sub-area-control-field-wav-file-folder {\n height: 1rem;\n width: 1rem;\n cursor: pointer;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-control-field-wav-file .config-sub-area-control-field-wav-file-echoback-button {\n border: solid 1px #333;\n background: #fff;\n font-size: 0.8rem;\n border-radius: 5px;\n height: 1.2rem;\n padding-left: 2px;\n padding-right: 2px;\n cursor: pointer;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field .config-sub-area-control-field-wav-file .config-sub-area-control-field-wav-file-echoback-button-active {\n font-size: 0.8rem;\n border: solid 1px #333;\n border-radius: 5px;\n background: #ada;\n height: 1.2rem;\n padding-left: 2px;\n padding-right: 2px;\n cursor: pointer;\n }\n\n.config-area .config-sub-area .config-sub-area-control .config-sub-area-control-field-long {\n width: 30rem;\n }\n\n.headerArea {\n display: flex;\n flex-direction: column;\n}\n\n.headerArea .title1 {\n display: flex;\n flex-direction: row;\n gap: 5px;\n align-items: flex-end;\n }\n\n.headerArea .title1 .title {\n font-size: 1.8rem;\n font-weight: 700;\n color: #333;\n text-shadow: 0 0 2px #333;\n }\n\n.headerArea .title1 .title-version {\n font-size: 0.9rem;\n }\n\n.headerArea .title1 .title-version-number {\n font-size: 0.7rem;\n }\n\n.headerArea .icons {\n display: flex;\n flex-direction: row;\n gap: 20px;\n }\n\n.headerArea .icons .belongings {\n display: flex;\n flex-direction: row;\n gap: 3px;\n }\n\n.headerArea .icons .belongings .belongings-button {\n border: solid 2px #999;\n color: white;\n font-size: 0.8rem;\n border-radius: 5px;\n background: #666;\n cursor: pointer;\n padding: 5px;\n height: 1.7rem;\n top: -2px;\n }\n\n.headerArea .icons .belongings .belongings-button:hover {\n border: solid 2px #cc6;\n }\n\n.advanced-setting-container {\n display: flex;\n flex-direction: column;\n gap: 5px;\n margin: 10px;\n}\n\n.advanced-setting-container .advanced-setting-container-row {\n display: flex;\n flex-direction: row;\n gap: 5px;\n }\n\n.advanced-setting-container .advanced-setting-container-row .advanced-setting-container-row-title {\n width: 7rem;\n font-weight: 700;\n font-size: 0.9rem;\n }\n\n.advanced-setting-container .advanced-setting-container-row .advanced-setting-container-row-title-long {\n width: 20rem;\n font-weight: 700;\n font-size: 0.9rem;\n }\n\n.advanced-setting-container .advanced-setting-container-row .advanced-setting-container-row-field {\n width: 15rem;\n font-size: 0.9rem;\n }\n\n.advanced-setting-container .advanced-setting-container-row .advanced-setting-container-row-field .advanced-setting-container-row-field-crossfade-container {\n display: flex;\n flex-direction: row;\n gap: 5px;\n width: 10rem;\n }\n\n.advanced-setting-container .advanced-setting-container-row .advanced-setting-container-row-field .advanced-setting-container-row-field-crossfade-container > div {\n display: flex;\n flex-direction: row;\n gap: 3px;\n }\n\n.advanced-setting-container .advanced-setting-container-row .advanced-setting-container-row-field .advanced-setting-container-row-field-crossfade-container > div > div:nth-child(1) {\n color: #333;\n }\n\n.advanced-setting-container .advanced-setting-container-row .advanced-setting-container-row-field .advanced-setting-container-row-field-crossfade-container > div > div:nth-child(2) {\n }\n.get-server-information-container {\n margin: 10px;\n}\n.get-server-information-container .get-server-information-text-area {\n width: 100%;\n height: 20rem;\n }\n.merge-lab-container {\n display: flex;\n flex-direction: column;\n margin: 10px;\n gap: 10px;\n}\n.merge-lab-container .merge-lab-type-filter {\n display: flex;\n flex-direction: row;\n }\n.merge-lab-container .merge-lab-type-filter > div:nth-child(1) {\n width: 50%;\n }\n.merge-lab-container .merge-lab-type-filter > div:nth-child(2) {\n width: 50%;\n }\n.merge-lab-container .merge-lab-manipulator {\n display: flex;\n flex-direction: row;\n }\n.merge-lab-container .merge-lab-manipulator .merge-lab-model-list {\n width: 70%;\n overflow-y: scroll;\n max-height: 20rem;\n }\n.merge-lab-container .merge-lab-manipulator .merge-lab-model-list::-webkit-scrollbar {\n width: 10px;\n height: 10px;\n }\n.merge-lab-container .merge-lab-manipulator .merge-lab-model-list::-webkit-scrollbar-track {\n background-color: #eee;\n border-radius: 3px;\n }\n.merge-lab-container .merge-lab-manipulator .merge-lab-model-list::-webkit-scrollbar-thumb {\n background: #f7cfec80;\n border-radius: 3px;\n }\n.merge-lab-container .merge-lab-manipulator .merge-lab-model-list .merge-lab-model-item {\n display: flex;\n flex-direction: row;\n }\n.merge-lab-container .merge-lab-manipulator .merge-lab-model-list .merge-lab-model-item > div:nth-child(1) {\n width: 50%;\n }\n.merge-lab-container .merge-lab-manipulator .merge-lab-model-list .merge-lab-model-item > div:nth-child(2) {\n width: 50%;\n }\n.merge-lab-container .merge-lab-manipulator .merge-lab-merge-buttons {\n display: flex;\n flex-direction: column-reverse;\n width: 30%;\n }\n.merge-lab-container .merge-lab-manipulator .merge-lab-merge-buttons .merge-lab-merge-button {\n border: solid 2px #ddd;\n color: black;\n font-size: 0.8rem;\n border-radius: 5px;\n background: #eee;\n cursor: pointer;\n padding: 5px;\n height: 1.7rem;\n text-align: center;\n }\n.merge-lab-container .merge-lab-manipulator .merge-lab-merge-buttons .merge-lab-merge-button:hover {\n border: solid 2px #aaa;\n }\n.merge-lab-container .merge-lab-manipulator .merge-lab-merge-buttons .merge-lab-merge-buttons-notice {\n font-size: 0.7rem;\n font-weight: 700;\n color: #333;\n text-align: center;\n }\n\n.blinking {\n animation: flash 0.7s cubic-bezier(0.91, -0.14, 0, 1.4) infinite;\n}\n\n@keyframes flash {\n 0%,\n 100% {\n opacity: 1;\n }\n\n 50% {\n opacity: 0.5;\n }\n}\n\n.blink {\n animation: blinking 0.8s ease-in-out infinite alternate;\n}\n\n@keyframes blinking {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n\n.beatrice-portrait-title {\n font-size: 1rem;\n font-weight: 700;\n color: #333;\n text-shadow: 0 0 2px #333;\n text-align: center;\n}\n\n.beatrice-portrait-title .edition {\n font-size: 0.6rem;\n }\n.beatrice-portrait-select {\n display: flex;\n justify-content: center;\n}\n.beatrice-portrait-select .button {\n /* border: solid 2px #999; */\n color: #615454;\n font-weight: 700;\n font-size: 0.8rem;\n border-radius: 2px;\n background: #adafad;\n cursor: pointer;\n padding: 0px 5px 0px 5px;\n margin: 0px 5px 0px 5px;\n line-height: 140%;\n height: 1.1rem;\n }\n.beatrice-portrait-select .button-selected {\n /* border: solid 2px #999; */\n color: #615454;\n font-weight: 700;\n font-size: 0.8rem;\n border-radius: 2px;\n background: #62b574;\n cursor: pointer;\n padding: 0px 5px 0px 5px;\n margin: 0px 5px 0px 5px;\n line-height: 140%;\n height: 1.1rem;\n }\n.beatrice-speaker-graph-container {\n width: 20rem;\n height: 19rem;\n border: none;\n}\n',""]);const d=l},52:(e,t,n)=>{"use strict";n.d(t,{A:()=>s});var i=n(601),r=n.n(i),a=n(314),o=n.n(a)()(r());o.push([e.id,".error-container {\n margin: 2rem;\n}\n .error-container .top-error-message {\n color: #44a;\n font-size: 2rem;\n font-weight: 100;\n }\n .error-container .top-error-description {\n color: #444;\n font-size: 1rem;\n font-weight: 100;\n }\n .error-container .error-detail {\n margin-top: 2rem;\n padding: 1rem;\n border: 1px solid;\n }\n .error-container .error-detail .error-name {\n font-weight: 700;\n }\n .error-container .error-detail .error-message {\n margin-top: 0.5rem;\n }\n .error-container .error-detail .error-info-container {\n margin-top: 0.5rem;\n font-size: 0.8rem;\n }\n .error-container .error-detail .error-info-container .error-info-line {\n }\n",""]);const s=o},314:e=>{"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n="",i=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),i&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),i&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n})).join("")},t.i=function(e,n,i,r,a){"string"==typeof e&&(e=[[null,e,void 0]]);var o={};if(i)for(var s=0;s0?" ".concat(d[5]):""," {").concat(d[1],"}")),d[5]=a),n&&(d[2]?(d[1]="@media ".concat(d[2]," {").concat(d[1],"}"),d[2]=n):d[2]=n),r&&(d[4]?(d[1]="@supports (".concat(d[4],") {").concat(d[1],"}"),d[4]=r):d[4]="".concat(r)),t.push(d))}},t}},601:e=>{"use strict";e.exports=function(e){return e[1]}},694:(e,t,n)=>{"use strict";var i=n(925);function r(){}function a(){}a.resetWarningCache=r,e.exports=function(){function e(e,t,n,r,a,o){if(o!==i){var s=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name="Invariant Violation",s}}function t(){return e}e.isRequired=e;var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:a,resetWarningCache:r};return n.PropTypes=n,n}},556:(e,t,n)=>{e.exports=n(694)()},925:e=>{"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},551:(e,t,n)=>{"use strict";var i=n(540),r=n(982);function a(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n