Анализ сайта github.dev
Основное Готовность: 85%
Домен
github.dev
Состояние доменного имени
?
Проверяем корректность доменного имени и наличие технических проблем на уровне домена.
Домен второго уровня идеален для продвижения.
Отличный запоминающийся домен.
Ответ сервера
200 Успешный ответ
HTTP-код ответа и цепочка редиректов
?
Код 200 — страница доступна. Коды 3xx — редиректы (цепочки замедляют загрузку и размывают ссылочный вес). Коды 4xx/5xx — ошибки, поисковик не сможет проиндексировать страницу.
Кол-во редиректов 3 слишком большое! Проверьте настройки сайта и веб-сервера!
Цепочка редиректов:
http://github.dev
308 PermanentRedirect
https://github.dev/
302 Found
https://vscode.dev/github/
200 OK
Безопасность
Сайт безопасен
Использование HTTPS и SSL-сертификат
?
HTTPS — обязательный стандарт. Google и Яндекс отдают предпочтение защищённым сайтам. Отсутствие SSL или просроченный сертификат ведут к предупреждениям в браузере и снижению позиций.
На сайте работает защищенный протокол ssl и сайт открывается по https.
Ssl-сертификат действителен до 10.11.2026 6:29:38.
Включён HSTS (Strict-Transport-Security) — защита от подмены на http.
HTTP автоматически перенаправляется на HTTPS.
Поздравляем! Сайт не содержится в реестре РКН.
Кодировка
utf-8
Кодировка символов страницы
?
Стандарт — UTF-8. Неправильная кодировка вызывает нечитаемые символы и мешает поисковику корректно распознать текст страницы.
Указана кодировка на странице utf-8.
Язык
Атрибут lang в HTML-теге
?
Атрибут lang (<html lang="ru">) сообщает поисковикам и браузерам, на каком языке написана страница. Помогает при ранжировании в региональном поиске.
Язык страницы не указан. Рекомендуется явно указать язык документа!
Скорость загрузки
~0,75сек
Время отклика сервера (TTFB)
?
Time To First Byte — время до получения первого байта от сервера. Норма до 200 мс. Медленный отклик ухудшает пользовательский опыт и ранжирование: Яндекс и Google учитывают скорость страниц.
Скорость загрузки сайта 0,75сек оптимальна.
Объем документа
333Кб
Размер HTML-кода страницы
?
Слишком большой HTML замедляет парсинг браузером и сканирование поисковым роботом. Рекомендуется не более 200 Кб.
Объем html-документа 333Кб оптимален.
Структура html-документа корректна.
Ресурсы
Ресурсы: 3
Внешние ресурсы страницы (CSS, JS, изображения)
?
Количество и тип подключённых ресурсов влияют на скорость загрузки. Большое число запросов увеличивает время рендеринга страницы.
Кол-во файлов ресурсов 3 достаточно.
Показать полный список ресурсов
| Тип | Название | Значение |
|---|---|---|
| stylesheet | https://main.vscode-cdn.net/stable/110a328ea54b42367b803ec53ee0bf52ef26b419/out/vs/workbench/workbench.web.main.internal.css | |
| js | https://main.vscode-cdn.net/nlsmetadata/110a328ea54b42367b803ec53ee0bf52ef26b419/nls.messages.js | |
| js |
Серверные заголовки
Кол-во: 15
HTTP-заголовки ответа сервера
?
Заголовки сервера передают браузеру и поисковику служебную информацию: кеширование, безопасность (CSP, HSTS), сжатие (gzip). Правильная настройка ускоряет загрузку и повышает защищённость.
Найдены серверные заголовки 15шт. Подробнее про серверные заголовки.
Показать полный список серверных заголовков
| Ключ | Значение |
|---|---|
| Date | Fri, 21 Aug 2026 04:15:44 GMT |
| Cache-Control | max-age=150 |
| ETag | "53905-R66etqOqELYU9fiA7ewP0tQehrY" |
| Vary | Origin |
| Strict-Transport-Security | max-age=31536000; includeSubDomains |
| x-commit | 386b5a0b2fc68944d28a5e633bf7664bbf55f910 |
| Content-Security-Policy | frame-ancestors 'none' |
| X-Content-Type-Options | nosniff |
| cross-origin-opener-policy | same-origin |
| cross-origin-embedder-policy | require-corp |
| x-azure-ref | 20260821T041544Z-17dfdc794f96876lhC1HELwdgw0000000dh0000000005t6w |
| x-fd-int-roxy-purgeid | 0 |
| X-Cache | TCP_HIT |
| x-cache-info | L1_T2 |
| Accept-Ranges | bytes |
CMS
Не определена
Система управления сайтом (движок)
?
CMS — это движок, на котором работает сайт (WordPress, 1C-Bitrix, Tilda и др.). Знание CMS помогает понять возможности SEO-оптимизации и подобрать подходящие инструменты. «Не определена» — вероятно, самописный сайт или нестандартная сборка.
CMS не определена. Вероятно, сайт самописный либо движок надёжно скрыт. Это не ошибка.
Веб-сервер
Не определён
Программное обеспечение сервера
?
Веб-сервер — это ПО, которое отдаёт страницы посетителям (nginx, Apache, IIS, LiteSpeed и др.). Определяется по серверным заголовкам ответа (Server, X-Powered-By и т.п.). «Не определён» — сервер намеренно скрывает эти заголовки, это нормальная практика безопасности.
Веб-сервер не определён — заголовок Server скрыт. Это не ошибка: часто так настраивают из соображений безопасности.
Мета-теги Готовность: 38%
Title
Заголовок страницы в браузере и поисковой выдаче
?
Title — главный SEO-заголовок страницы. Влияет на CTR в поиске и ранжирование. Оптимальная длина: 50–70 символов. Ключевые слова — ближе к началу.
Пропишите тег title!
Description
Описание страницы в поисковой выдаче (сниппет)
?
Meta Description — текст под заголовком в выдаче. Напрямую на позиции не влияет, но влияет на CTR. Оптимальная длина: 120–160 символов.
Установите мета-тег description!
Keywords
Список ключевых слов страницы (устаревший тег)
?
Meta Keywords не учитывается Яндексом и Google для ранжирования с 2009–2012 годов. Заполнение не обязательно, но не вредит. Конкурент может использовать содержимое для анализа.
Установите мета-тег keywords!
Канонический Url
Указывает поисковику основную версию страницы
?
Canonical (rel=canonical) предотвращает проблему дублей страниц. Должен точно совпадать с URL проверяемой страницы. Неправильный canonical может передать ссылочный вес на другую страницу.
Рекомендуем прописать канонический Url.
Robots
Ошибок нет
Директивы для поисковых роботов на уровне страницы
?
Meta Robots управляет индексацией конкретной страницы: index/noindex — индексировать ли, follow/nofollow — следовать ли по ссылкам. Noindex полностью исключает страницу из поиска.
Meta-тег robots не указан. Страница свободна для индексации.
Адаптивность
width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no
Настройка масштабирования на мобильных устройствах
?
Тег viewport (<meta name="viewport">) сообщает браузеру, как масштабировать страницу на мобильных. Стандарт: width=device-width, initial-scale=1. Отсутствие — признак отсутствия мобильной версии.
Meta-тег viewport со значением-константой width=device-width задаёт ширину страницы в соответствии с размером экрана.
Meta-тег viewport со значением initial-scale=1.0 определяет масштаб 1:1, т.е. «не масштабировать».
Meta-тег viewport со значением user-scalable определяет доступность масштабирования страницы пользователем.
Meta-тег viewport со значением minimum-scale определяет минимальный масштаб области просмотра.
Meta-тег viewport со значением maximum-scale определяет максимальный масштаб области просмотра.
Разметка OpenGraph
Кол-во: 3
Мета-теги для красивых превью в соцсетях
?
OpenGraph (og:title, og:description, og:image) управляет тем, как страница выглядит при репосте в социальных сетях и мессенджерах. Отсутствие OG-тегов — невзрачный превью при шеринге.
Разметка OpenGraph задана. Страница оптимизирована под социальные сети.
Показать полный список og мета-тегов
| Тип | Значение |
|---|---|
| og:title | Visual Studio Code for the Web |
| og:description | Build with Visual Studio Code, anywhere, anytime, entirely in your browser. |
| og:image | /static/stable/social.png |
Все мета-теги
Кол-во: 12
Полный список мета-тегов страницы
?
Таблица всех meta-тегов, включая нестандартные. Позволяет найти опечатки, дубли и лишние теги.
Найдены мета-теги 12шт. Мета-теги не видимы для человека и предназначены для обмена информацией между веб-страницей и поисковыми системами, браузерами и другими веб-службами. С ними роботы 🤖 и устройства ведут себя более ожидаемо.
Показать полный список мета-тегов
| Тип | Название | Значение |
|---|---|---|
| name | mobile-web-app-capable | yes |
| name | apple-mobile-web-app-capable | yes |
| name | apple-mobile-web-app-title | Code |
| name | twitter:card | summary_large_image |
| name | twitter:site | @code |
| name | viewport | width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no |
| name | vscode:versionInfo | stable;1.134.0;110a328ea54b42367b803ec53ee0bf52ef26b419 |
| name | vscode:baseURL | https://main.vscode-cdn.net/stable/110a328ea54b42367b803ec53ee0bf52ef26b419 |
| name | vscode:additionalBuiltinExtensions | {"github.vscode-pull-request-github":"https://GitHub.vscode-unpkg.net/GitHub/vscode-pull-request-github/0.162.0/extension","github.remotehub":"https://GitHub.vscode-unpkg.net/GitHub/remotehub/0.64.0/extension","ms-vscode.remote-server":"https://ms-vscode.vscode-unpkg.net/ms-vscode/remote-server/1.5.3/extension","github.codespaces":"https://GitHub.vscode-unpkg.net/GitHub/codespaces/1.18.16/extension","ms-vscode.azure-repos":"https://ms-vscode.vscode-unpkg.net/ms-vscode/azure-repos/0.40.0/extension","ms-vscode.anycode":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode/0.0.75/extension","ms-vscode.anycode-kotlin":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-kotlin/0.0.8/extension","ms-vscode.remote-explorer":"https://ms-vscode.vscode-unpkg.net/ms-vscode/remote-explorer/0.5.0/extension","ms-vscode.remote-repositories":"https://ms-vscode.vscode-unpkg.net/ms-vscode/remote-repositories/0.42.0/extension","ms-vscode.anycode-rust":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-rust/0.0.8/extension","ms-vscode.anycode-c-sharp":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-c-sharp/0.0.8/extension","ms-vscode.anycode-python":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-python/0.0.7/extension","ms-vscode.anycode-java":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-java/0.0.8/extension","ms-vscode.anycode-go":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-go/0.0.8/extension","ms-vscode.anycode-cpp":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-cpp/0.0.7/extension","ms-vscode.anycode-typescript":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-typescript/0.0.7/extension","ms-vscode.anycode-php":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-php/0.0.8/extension"} |
| property | og:title | Visual Studio Code for the Web |
| property | og:description | Build with Visual Studio Code, anywhere, anytime, entirely in your browser. |
| property | og:image | /static/stable/social.png |
Оптимизация Готовность: 0%
Структура
Ошибок нет
Семантические HTML-элементы страницы
?
Проверяет наличие основных структурных элементов: nav, header, footer, main. Корректная семантическая структура помогает поисковику понять архитектуру страницы.
Структура документа корректна (теги <html> и <body> присутствуют по одному на документ).
Контент
Есть ошибки
Объём и качество текстового содержимого
?
Анализирует объём полезного текста на странице. Слишком мало — страница может считаться малополезной. Слишком много — ухудшается читаемость и восприятие.
Слова из title 0 встречаются в тексте редко. Добавьте в контент страницы слова из тега <title>!
Абзацев с текстом 0 слишком мало. Добавьте больше абзацев с текстом (тег <p>)!
Среднее число слов в абзаце 0 слишком мало. Сделайте контент более читаемым!
Кол-во знаков контента 0 слишком мало. Добавьте больше текста!
Кол-во слов 0 слишком мало. Добавьте больше текста (минимум 400 слов)!
Заголовки
Есть ошибки
Иерархия заголовков H1–H6
?
H1 должен быть один и содержать ключевой запрос. H2–H6 описывают подразделы. Пропуск уровней (H1 → H3) и несколько H1 — типичные ошибки, снижающие понятность страницы для поисковика.
Не обнаружено заголовков на странице. Добавьте заголовки (<h1>, <h2> или <h3>)
Тошнота
Не удалось произвести расчет
Насколько одно слово доминирует в тексте
?
Классическая тошнота = √(частота самого повторяющегося слова). Норма до 7–8: текст воспринимается естественно. Выше — поисковик может счесть страницу переспамленной.
Тошнота не рассчитана. Измените текст страницы!
Академич. тошнота
Нет данных для расчета
Насколько текст перенасыщен ключевыми словами
?
Академическая тошнота = (частота слова / общее количество слов) × 100%. Показывает долю конкретного слова в тексте. Норма 5–15%.
Академическая тошнота не рассчитана. Измените текст страницы!
Семантическое ядро
Не удалось собрать
Наиболее часто встречающиеся слова на странице
?
Топ слов по частоте использования. Показывает, какие слова доминируют в тексте с точки зрения поисковика.
Контент страницы не содержит осмысленного текста. Добавьте текст на страницу!
Индексация Готовность: 0%
Индексирование
Есть ошибки
Разрешено ли индексирование страницы
?
Проверяет, не закрыта ли страница от индексации через robots.txt, meta robots или X-Robots-Tag. Страница, закрытая от индексации, не появится в поисковой выдаче.
Анкоров на странице не обнаружено. Велика вероятность, что сайт - одностраничник, такой сайт продвинуть крайне затруднительно!
Robots.txt
Найден корректный robots.txt
Файл управления сканированием сайта роботами
?
Robots.txt указывает поисковым роботам, какие страницы сканировать, а какие — нет. Ошибки в файле могут случайно закрыть важные разделы от индексации.
Кол-во редиректов для файла robots.txt 3 слишком большое! Это может вызывать затруднение при индексации поисковыми роботами!
Проверяемая страница не запрещена в robots.txt.
Robots.txt доступен по постоянному адресу
Цепочка редиректов для файла robots.txt:
http://github.dev/robots.txt
308 PermanentRedirect
https://github.dev/robots.txt
302 Found
https://vscode.dev/github/robots.txt
200 OK
Показать содержимое robots.txt
<!doctype html><html><head><script>performance.mark('code/didStartRenderer');</script><meta charset="utf-8"/><link rel="stylesheet" href="https://main.vscode-cdn.net/stable/110a328ea54b42367b803ec53ee0bf52ef26b419/out/vs/workbench/workbench.web.main.internal.css"/><link rel="preconnect" href="https://main.vscode-cdn.net/" crossorigin><link rel="dns-prefetch" href="https://main.vscode-cdn.net/"><link rel="preconnect" href="https://main.vscode-cdn.net/" crossorigin><link rel="dns-prefetch" href="https://update.code.visualstudio.com/"><link rel="dns-prefetch" href="https://marketplace.visualstudio.com/"><meta http-equiv="Content-Security-Policy" content=" default-src 'none' ; img-src 'self' https: http://localhost:* https://*.vscode-cdn.net data: blob: vscode-remote-resource: ; media-src 'self' http://localhost:* https://*.vscode-cdn.net data: blob: vscode-remote-resource: ; child-src blob: ; frame-src 'self' https://*.vscode-cdn.net http://localhost:* https://login.microsoftonline.com/ ; script-src 'self' 'sha256-BxXgMQwb5J9MsigLiEeFZBc3YhBz64exB7NbsYtDC6E=' 'sha256-VtAn6Z9Xx4JelZwS9dZntiryb6MLjWOLXXsQbR4/qCU=' 'sha256-hMX6al4xUUoSlIZK9ccax1AKI9Y3muDTLXoucvZjvxA=' 'sha256-FcK8uaFNez65hevnZdGgewmrMwCUg2MbHRtJ3IV0tsw=' 'unsafe-eval' https://main.vscode-cdn.net https://www.vscode-unpkg.net/nls/ https://ms-vscode.vscode-unpkg.net https://ms-toolsai.vscode-unpkg.net https://ms-azuretools.vscode-unpkg.net https://quantum.vscode-unpkg.net https://SynapseVSCode.vscode-unpkg.net https://teamsdevapp.vscode-unpkg.net https://ms-windows-ai-studio.vscode-unpkg.net http://localhost:* ; worker-src 'self' blob: ; style-src 'self' https://*.vscode-cdn.net http://localhost:* 'unsafe-inline' ; connect-src 'self' https://main.vscode-cdn.net http://localhost:* https://localhost:* https://login.microsoftonline.com/ https://api.github.com/ https://update.code.visualstudio.com/api/ https://*.vscode-unpkg.net/ https://default.exp-tas.com/vscode/ab https://vscode-sync.trafficmanager.net/ https://vscode-sync-insiders.trafficmanager.net/ https://*.gallerycdn.vsassets.io https://vortex.data.microsoft.com/collect/v1 https://marketplace.visualstudio.com/_apis/public/gallery/ https://vslsdev.azureedge.net/webextension/ https://vscodedotdev.blob.core.windows.net/web-builds/ https://main.vscode-cdn.net/experiments/vscode-experiments.json https://vscodeexperiments.azureedge.net/experiments/vscode-experiments.json https://code.visualstudio.com/raw/ https://vscode-auth.github.com https://*.gallery.vsassets.io/_apis/public/gallery/ https://marketplace.visualstudio.com/items/ https://main.vscode-cdn.net/extensions/ https://main.vscode-cdn.net/profile-templates/ https://mobile.events.data.microsoft.com/ https://auth.vscode.dev https://auth.insiders.vscode.dev https://*.rel.tunnels.api.visualstudio.com wss://*.rel.tunnels.api.visualstudio.com https://vscodeedu.com https://ppe.vscodeedu.com https://management.azure.com https://*.instances.azureml.ms:* wss://*.instances.azureml.ms:* https://api-dogfood.resources.windows-int.net/ https://login.windows-ppe.net/ https://*.servicebus.windows.net/ https://limelight-token-issuer-wrapper.azurewebsites.net/ https://*.discovery.microsoft.com wss://falcon-caas.mai.microsoft.com ; font-src 'self' https://*.vscode-cdn.net https://*.vscode-unpkg.net http://localhost:* vscode-remote-resource: ; manifest-src 'self' ; require-trusted-types-for 'script' ; trusted-types amdLoader cellRendererEditorText collapsedCellPreview defaultWorkerFactory diffEditorWidget diffEditorWidget2 diffReview domLineBreaksComputer dompurify editorGhostText editorViewLayer htmlToMarkdown notebookRenderer stickyScrollViewLayer tokenizeToString notebookChatEditController richScreenReaderContent chatDebugTokenizer ; "/><meta name="mobile-web-app-capable" content="yes"/><meta name="apple-mobile-web-app-capable" content="yes"/><meta name="apple-mobile-web-app-title" content="Code"/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:site" content="@code"/><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/><meta property="og:title" content="Visual Studio Code for the Web"/><meta property="og:description" content="Build with Visual Studio Code, anywhere, anytime, entirely in your browser."/><meta property="og:image" content="/static/stable/social.png"/><meta http-equiv="origin-trial" content="AoebRfEHK6fnUfMMtC/7rRfIqSiBjL0nuYbf5qZcy8lMwmQsP7ayJm/kmRtR3MgvA313dluI8PXGBoYvo6LCEwUAAABpeyJvcmlnaW4iOiJodHRwczovL3ZzY29kZS5kZXY6NDQzIiwiZmVhdHVyZSI6IkZpbGVTeXN0ZW1PYnNlcnZlciIsImV4cGlyeSI6MTc0NzE4MDc5OSwiaXNTdWJkb21haW4iOnRydWV9"><meta name="vscode:versionInfo" content="stable;1.134.0;110a328ea54b42367b803ec53ee0bf52ef26b419"/><meta name="vscode:baseURL" content="https://main.vscode-cdn.net/stable/110a328ea54b42367b803ec53ee0bf52ef26b419"/><meta name="vscode:additionalBuiltinExtensions" content="{"github.vscode-pull-request-github":"https://GitHub.vscode-unpkg.net/GitHub/vscode-pull-request-github/0.162.0/extension","github.remotehub":"https://GitHub.vscode-unpkg.net/GitHub/remotehub/0.64.0/extension","ms-vscode.remote-server":"https://ms-vscode.vscode-unpkg.net/ms-vscode/remote-server/1.5.3/extension","github.codespaces":"https://GitHub.vscode-unpkg.net/GitHub/codespaces/1.18.16/extension","ms-vscode.azure-repos":"https://ms-vscode.vscode-unpkg.net/ms-vscode/azure-repos/0.40.0/extension","ms-vscode.anycode":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode/0.0.75/extension","ms-vscode.anycode-kotlin":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-kotlin/0.0.8/extension","ms-vscode.remote-explorer":"https://ms-vscode.vscode-unpkg.net/ms-vscode/remote-explorer/0.5.0/extension","ms-vscode.remote-repositories":"https://ms-vscode.vscode-unpkg.net/ms-vscode/remote-repositories/0.42.0/extension","ms-vscode.anycode-rust":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-rust/0.0.8/extension","ms-vscode.anycode-c-sharp":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-c-sharp/0.0.8/extension","ms-vscode.anycode-python":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-python/0.0.7/extension","ms-vscode.anycode-java":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-java/0.0.8/extension","ms-vscode.anycode-go":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-go/0.0.8/extension","ms-vscode.anycode-cpp":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-cpp/0.0.7/extension","ms-vscode.anycode-typescript":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-typescript/0.0.7/extension","ms-vscode.anycode-php":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-php/0.0.8/extension"}"/></head><body></body><script>(()=>{"use strict";!function(){const e=new URL(window.location.href),a=e.searchParams.get("vscode-lang"),s=localStorage.getItem("vscode.nls.locale")||navigator.language.toLowerCase()||"en";s.startsWith("en")&&!a||a!==s&&(s.startsWith("en")?e.searchParams.delete("vscode-lang"):e.searchParams.set("vscode-lang",s),window.location.href=e.href)}()})();</script><script>(()=>{"use strict";!function(){performance.mark("code/willShowPartsSplash");(()=>{const t=localStorage.getItem("monaco-parts-splash");if(!t)return!1;let M;try{M=JSON.parse(t)}catch{return!1}if(!M||"object"!=typeof M||!M.layoutInfo)return!1;const e=document.createElement("style");e.className="initialShellColors",document.head.appendChild(e),e.textContent=`\n\t\t\tbody {\n\t\t\t\tbackground-color: ${M.colorInfo.editorBackground};\n\t\t\t\tcolor: ${M.colorInfo.foreground}; margin: 0; padding: 0;\n\t\t\t}\n\t\t\t#monaco-parts-splash {\n\t\t\t\ttransition: opacity 0.35s ease-out;\n\t\t\t\topacity: 0;\n\t\t\t}\n\t\t\t#monaco-parts-splash.loading {\n\t\t\t\topacity: 1;\n\t\t\t}`;const{layoutInfo:i,colorInfo:o}=M,a=document.createElement("div");a.id="monaco-parts-splash",a.className=M.baseTheme??"",i.sideBarWidth=Math.min(i.sideBarWidth,window.innerWidth-(i.activityBarWidth+i.editorPartMinWidth));const s=document.createElement("div");if(s.style.position="absolute",s.style.width="100%",s.style.height=`${i.titleBarHeight}px`,s.style.left="0",s.style.top="0",s.style.backgroundColor=`${o.titleBarBackground}`,s.style["-webkit-app-region"]="drag",a.appendChild(s),o.titleBarBorder&&i.titleBarHeight>0){const t=document.createElement("div");t.style.position="absolute",t.style.width="100%",t.style.height="1px",t.style.left="0",t.style.bottom="0",t.style.borderBottom=`1px solid ${o.titleBarBorder}`,s.appendChild(t)}const l=document.createElement("div");if(l.style.position="absolute",l.style.width=`${i.activityBarWidth}px`,l.style.height=`calc(100% - ${i.titleBarHeight+i.statusBarHeight}px)`,l.style.top=`${i.titleBarHeight}px`,"left"===i.sideBarSide?l.style.left="0":l.style.right="0",l.style.backgroundColor=`${o.activityBarBackground}`,a.appendChild(l),o.activityBarBorder&&i.activityBarWidth>0){const t=document.createElement("div");t.style.position="absolute",t.style.width="1px",t.style.height="100%",t.style.top="0","left"===i.sideBarSide?(t.style.right="0",t.style.borderRight=`1px solid ${o.activityBarBorder}`):(t.style.left="0",t.style.borderLeft=`1px solid ${o.activityBarBorder}`),l.appendChild(t)}const d=document.createElement("div");if(d.style.position="absolute",d.style.width=`${i.sideBarWidth}px`,d.style.height=`calc(100% - ${i.titleBarHeight+i.statusBarHeight}px)`,d.style.top=`${i.titleBarHeight}px`,"left"===i.sideBarSide?d.style.left=`${i.activityBarWidth}px`:d.style.right=`${i.activityBarWidth}px`,d.style.backgroundColor=`${o.sideBarBackground}`,a.appendChild(d),o.sideBarBorder&&i.sideBarWidth>0){const t=document.createElement("div");t.style.position="absolute",t.style.width="1px",t.style.height="100%",t.style.top="0",t.style.right="0","left"===i.sideBarSide?t.style.borderRight=`1px solid ${o.sideBarBorder}`:(t.style.left="0",t.style.borderLeft=`1px solid ${o.sideBarBorder}`),d.appendChild(t)}const n=document.createElement("div");if(n.style.position="absolute",n.style.width="100%",n.style.height=`${i.statusBarHeight}px`,n.style.bottom="0",n.style.left="0",n.style.backgroundColor=`${o.statusBarBackground}`,a.appendChild(n),o.statusBarBorder&&i.statusBarHeight>0){const t=document.createElement("div");t.style.position="absolute",t.style.width="100%",t.style.height="1px",t.style.top="0",t.style.borderTop=`1px solid ${o.statusBarBorder}`,n.appendChild(t)}return document.body.appendChild(a),a.classList.add("loading"),!0})()||(()=>{const t=document.createElement("style");t.textContent="\n\t\t\thtml, body, #monaco-parts-splash {\n\t\t\t\tmargin: 0;\n\t\t\t\tpadding: 0;\n\t\t\t\twidth: 100%;\n\t\t\t\theight: 100%;\n\t\t\t}\n\t\t\t#monaco-parts-splash {\n\t\t\t\tposition: absolute;\n\t\t\t\ttop: 0;\n\t\t\t\tleft: 0;\n\t\t\t\ttransition: opacity 0.35s ease-out;\n\t\t\t\topacity: 0;\n\t\t\t\tbackground-color: #1E1E1E; // vscode.dev uses dark theme by default\n\t\t\t\tbackground-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MiIgaGVpZ2h0PSI0MCIgZmlsbD0ibm9uZSIgdmlld0JveD0iMCAwIDQyIDQwIj4KICAgIDxnIG9wYWNpdHk9IjAuMDUiPgogICAgICAgIDxwYXRoIGZpbGw9ImJsYWNrIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zMC4yMzU0IDM5Ljg4MzZDMjkuOTE5NSAzOS44ODYyIDI5LjYwNTcgMzkuODI4NyAyOS4zMTA5IDM5LjcxMzlDMjguOTg5NiAzOS41ODg1IDI4LjY5NzcgMzkuMzk3OSAyOC40NTM5IDM5LjE1MzlMMTIuNjk5OSAyNC43Nzk5TDkuMjM5MTcgMjcuNDAzN0w1LjgzNDM0IDI5Ljk4NkM1LjcwNDU0IDMwLjA4NDUgNS41NjIwMSAzMC4xNjI2IDUuNDExNjQgMzAuMjE4OUM1LjIwMjU5IDMwLjI5NzYgNC45NzgzIDMwLjMzMzkgNC43NTE5IDMwLjMyMzlDNC4zNjM2MSAzMC4zMDY4IDMuOTkzNTYgMzAuMTU0MyAzLjcwNTg4IDI5Ljg5MjlMMS41MDU4OCAyNy44OTI5QzEuMzM0NTIgMjcuNzM2OCAxLjE5NzYzIDI3LjU0NjYgMS4xMDM5NiAyNy4zMzQ2QzEuMDEwMjkgMjcuMTIyNSAwLjk2MTkxNCAyNi44OTMzIDAuOTYxOTE0IDI2LjY2MTRDMC45NjE5MTQgMjYuNDI5NiAxLjAxMDI5IDI2LjIwMDQgMS4xMDM5NiAyNS45ODgzQzEuMTk3NjMgMjUuNzc2MiAxLjMzNDUyIDI1LjU4NjEgMS41MDU4OCAyNS40Mjk5TDcuNDU3ODggMTkuOTk5OUw0LjY3MDcyIDE3LjQ1MzJMMS41MDczNCAxNC41Njg5QzEuMzM1ODQgMTQuNDEyOSAxLjE5ODgzIDE0LjIyMjcgMS4xMDUwNyAxNC4wMTA3QzEuMDExMzIgMTMuNzk4NiAwLjk2Mjg5MSAxMy41NjkzIDAuOTYyODkxIDEzLjMzNzRDMC45NjI4OTEgMTMuMTA1NiAxLjAxMTMyIDEyLjg3NjMgMS4xMDUwNyAxMi42NjQyQzEuMTk4ODMgMTIuNDUyMSAxLjMzNTg0IDEyLjI2MiAxLjUwNzM0IDEyLjEwNTlMMy43MDczNCAxMC4xMDU5QzMuNzI5MjYgMTAuMDg2IDMuNzUxNjUgMTAuMDY2NyAzLjc3NDUgMTAuMDQ4QzQuMDUyMTMgOS44MjAyNyA0LjM5NjY2IDkuNjg3ODkgNC43NTY5IDkuNjcxOTZDNS4xNDUxOSA5LjY1NDc5IDUuNTI3MjUgOS43NzQwMSA1LjgzNjg4IDEwLjAwODlMMTIuNjk5OSAxNS4yMTc5TDI4LjQ1MTkgMC44NDM5NDJDMjguNTQ1MiAwLjc1MTY4MiAyOC42NDU1IDAuNjY2NzYzIDI4Ljc1MTkgMC41ODk5NDJDMjkuMTE1MyAwLjMyNTYwMSAyOS41NDM2IDAuMTY0NjMzIDI5Ljk5MTEgMC4xMjQxMzdDMzAuMDkxOSAwLjExNTAyIDMwLjE5MjggMC4xMTIwODYgMzAuMjkzMyAwLjExNTIzNEMzMC42NDQ0IDAuMTIzNzQ4IDMwLjk5MTggMC4yMDY0NDMgMzEuMzExNyAwLjM2MDAyN0wzOS41NDc3IDQuMzIxMDNDMzkuOTcxNiA0LjUyNTIyIDQwLjMyOTIgNC44NDQ4NyA0MC41Nzk1IDUuMjQzMjVDNDAuNzc4NyA1LjU2MDIzIDQwLjkwMzUgNS45MTY4IDQwLjk0NjIgNi4yODYyOUM0MC45NTc0IDYuMzgxNDggNDAuOTYzMiA2LjQ3NzU0IDQwLjk2MzMgNi41NzQwMVY2LjY3Mjk1QzQwLjk2MzMgNi42NTc4MSA0MC45NjMxIDYuNjQyNjggNDAuOTYyNyA2LjYyNzU3VjMzLjM3MDRDNDAuOTYzMSAzMy4zNTUyIDQwLjk2MzMgMzMuMzQwMSA0MC45NjMzIDMzLjMyNDlWMzMuNDE5OUM0MC45NjMzIDMzLjUxNDYgNDAuOTU3OSAzMy42MDkgNDAuOTQ3MiAzMy43MDI1QzQwLjkwNTUgMzQuMDc1NCA0MC43ODAyIDM0LjQzNTUgNDAuNTc5MyAzNC43NTUyQzQwLjMyOSAzNS4xNTM0IDM5Ljk3MTQgMzUuNDcyOSAzOS41NDc3IDM1LjY3N0wzMS4zMTE3IDM5LjYzOEMzMS4wMTkxIDM5Ljc3ODUgMzAuNzAzNyAzOS44NTk2IDMwLjM4MzMgMzkuODc5QzMwLjMzNDEgMzkuODgyIDMwLjI4NDggMzkuODgzNSAzMC4yMzU0IDM5Ljg4MzZaTTMwLjk1MDkgMTAuOTM2OUwxOS4wMDI4IDE5Ljk5ODdMMzAuOTU0OSAyOS4wNjM5TDMwLjk1MDkgMTAuOTM2OVoiIGNsaXAtcnVsZT0iZXZlbm9kZCIvPgogICAgPC9nPgo8L3N2Zz4=);\n\t\t\t\tbackground-repeat: no-repeat;\n\t\t\t\tbackground-position: 50% 50%;\n\t\t\t\tbackground-size: 300px;\n\t\t\t\tz-index: 100000000000000;\n\t\t\t\tpointer-events: none;\n\t\t\t}\n\t\t\t@media (prefers-color-scheme: dark) {\n\t\t\t\tbody, #monaco-parts-splash { background-color: #2c2c32; }\n\t\t\t}\n\t\t\t#monaco-parts-splash.loading {\n\t\t\t\topacity: 1;\n\t\t\t}",document.head.appendChild(t);const M=document.createElement("div");M.id="monaco-parts-splash",document.body.appendChild(M),setTimeout(()=>M.classList.add("loading"),20)})(),performance.mark("code/didShowPartsSplash")}()})();</script><script>(()=>{"use strict";!function(){const t=document.querySelector('meta[name="vscode:versionInfo"]').content.split(";"),e=document.querySelector('meta[name="vscode:baseURL"]').content,r=t[0],o=t[2]||void 0;let s;const i=window.trustedTypes?.createPolicy("amdLoader",{createScriptURL(t){if(void 0!==e&&t.startsWith(e))return t;if(t.startsWith("/static/")||"/sw.js"===t)return t;if(s&&t.startsWith(s))return t;throw new Error(`Invalid script url: ${t}`)}});globalThis._VSCODE_WEB_BOOTSTRAP_={quality:r,commit:o,baseUrl:e,trustedTypesPolicy:i},globalThis._VSCODE_FILE_ROOT=e+"/out/",globalThis._VSCODE_WEB_PACKAGE_TTP=i,performance.mark("code/willLoadWorkbenchMain")}()})();</script><script src="https://main.vscode-cdn.net/nlsmetadata/110a328ea54b42367b803ec53ee0bf52ef26b419/nls.messages.js"></script><script src=""></script><script type="module">import{Emitter as e,LogLevel as t,Menu as r,URI as o,commands as n,create as i,env as s,logger as a,window as c}from"https://main.vscode-cdn.net/stable/110a328ea54b42367b803ec53ee0bf52ef26b419/out/vs/workbench/workbench.web.main.internal.js";var l={251(e){const t=function(){};t.prototype=Object.create(null);const r=/; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu,o=/\\([\v\u0020-\u00ff])/gu,n=/^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u,i={type:"",parameters:new t};function s(e){if("string"!=typeof e)throw new TypeError("argument header is required and must be a string");let i=e.indexOf(";");const s=-1!==i?e.slice(0,i).trim():e.trim();if(!1===n.test(s))throw new TypeError("invalid media type");const a={type:s.toLowerCase(),parameters:new t};if(-1===i)return a;let c,l,h;for(r.lastIndex=i;l=r.exec(e);){if(l.index!==i)throw new TypeError("invalid parameter format");i+=l[0].length,c=l[1].toLowerCase(),h=l[2],'"'===h[0]&&(h=h.slice(1,h.length-1),o.test(h)&&(h=h.replace(o,"$1"))),a.parameters[c]=h}if(i!==e.length)throw new TypeError("invalid parameter format");return a}function a(e){if("string"!=typeof e)return i;let s=e.indexOf(";");const a=-1!==s?e.slice(0,s).trim():e.trim();if(!1===n.test(a))return i;const c={type:a.toLowerCase(),parameters:new t};if(-1===s)return c;let l,h,d;for(r.lastIndex=s;h=r.exec(e);){if(h.index!==s)return i;s+=h[0].length,l=h[1].toLowerCase(),d=h[2],'"'===d[0]&&(d=d.slice(1,d.length-1),o.test(d)&&(d=d.replace(o,"$1"))),c.parameters[l]=d}return s!==e.length?i:c}Object.freeze(i.parameters),Object.freeze(i),e.exports.xL=a}},h={};function d(e){var t=h[e];if(void 0!==t)return t.exports;var r=h[e]={exports:{}};return l[e](r,r.exports,d),r.exports}d.d=(e,t)=>{for(var r in t)d.o(t,r)&&!d.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},d.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);class u{constructor(e,t){this.crypto=e,this.quality=t,this._storageKey=`${this.quality}.secrets.provider`,this._secretsPromise=this.load(),this.type="persisted"}async load(){const e=window.localStorage.getItem(this._storageKey);if(e)try{return JSON.parse(await this.crypto.decrypt(e))}catch(e){console.error("Failed to decrypt secrets from localStorage",e),window.localStorage.removeItem(this._storageKey)}return{}}async get(e){return(await this._secretsPromise)[e]}async set(e,t){const r=await this._secretsPromise;r[e]=t,this._secretsPromise=Promise.resolve(r),this.save()}async delete(e){const t=await this._secretsPromise;delete t[e],this._secretsPromise=Promise.resolve(t),this.save()}async keys(){const e=await this._secretsPromise;return Object.keys(e)||[]}async save(){try{const e=await this.crypto.encrypt(JSON.stringify(await this._secretsPromise));window.localStorage.setItem(this._storageKey,e)}catch(e){console.error(e)}}}const g="function"==typeof Buffer,p="function"==typeof TextDecoder?new TextDecoder:void 0,m="function"==typeof TextEncoder?new TextEncoder:void 0,f=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),y=(()=>{let e={};return f.forEach((t,r)=>e[t]=r),e})(),w=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,v=String.fromCharCode.bind(String),C="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):e=>new Uint8Array(Array.prototype.slice.call(e,0)),I=e=>e.replace(/=/g,"").replace(/[+\/]/g,e=>"+"==e?"-":"_"),b=e=>e.replace(/[^A-Za-z0-9\+\/]/g,""),k=e=>{let t,r,o,n,i="";const s=e.length%3;for(let s=0;s<e.length;){if((r=e.charCodeAt(s++))>255||(o=e.charCodeAt(s++))>255||(n=e.charCodeAt(s++))>255)throw new TypeError("invalid character found");t=r<<16|o<<8|n,i+=f[t>>18&63]+f[t>>12&63]+f[t>>6&63]+f[63&t]}return s?i.slice(0,s-3)+"===".substring(s):i},S="function"==typeof btoa?e=>btoa(e):g?e=>Buffer.from(e,"binary").toString("base64"):k,T=g?e=>Buffer.from(e).toString("base64"):e=>{let t=[];for(let r=0,o=e.length;r<o;r+=4096)t.push(v.apply(null,e.subarray(r,r+4096)));return S(t.join(""))},A=(e,t=!1)=>t?I(T(e)):T(e),_=e=>{if(e.length<2)return(t=e.charCodeAt(0))<128?e:t<2048?v(192|t>>>6)+v(128|63&t):v(224|t>>>12&15)+v(128|t>>>6&63)+v(128|63&t);var t=65536+1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320);return v(240|t>>>18&7)+v(128|t>>>12&63)+v(128|t>>>6&63)+v(128|63&t)},E=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,P=e=>e.replace(E,_),x=g?e=>Buffer.from(e,"utf8").toString("base64"):m?e=>T(m.encode(e)):e=>S(P(e)),O=(e,t=!1)=>t?I(x(e)):x(e),R=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,M=e=>{switch(e.length){case 4:var t=((7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3))-65536;return v((t>>>10)+55296)+v(56320+(1023&t));case 3:return v((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return v((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},q=e=>e.replace(R,M),$=e=>{if(e=e.replace(/\s+/g,""),!w.test(e))throw new TypeError("malformed base64.");let t,r,o;e+="==".slice(2-(3&e.length));let n=[];for(let i=0;i<e.length;)t=y[e.charAt(i++)]<<18|y[e.charAt(i++)]<<12|(r=y[e.charAt(i++)])<<6|(o=y[e.charAt(i++)]),64===r?n.push(v(t>>16&255)):64===o?n.push(v(t>>16&255,t>>8&255)):n.push(v(t>>16&255,t>>8&255,255&t));return n.join("")},U="function"==typeof atob?e=>atob(b(e)):g?e=>Buffer.from(e,"base64").toString("binary"):$,L=g?e=>C(Buffer.from(e,"base64")):e=>C(U(e).split("").map(e=>e.charCodeAt(0))),N=e=>L(H(e)),D=g?e=>Buffer.from(e,"base64").toString("utf8"):p?e=>p.decode(L(e)):e=>q(U(e)),H=e=>b(e.replace(/[-_]/g,e=>"-"==e?"+":"/")),F=e=>D(H(e)),z=O,j=F,B=A,K=N;class W{constructor(e){this.authEndpoint=function(e){return"vscode.dev"===e||"insiders.vscode.dev"===e?`https://auth.${e}`:"/_auth"}(e)}async encrypt(e){const t=window.crypto.getRandomValues(new Uint8Array(W.IV_LENGTH)),r=await window.crypto.subtle.generateKey({name:W.ALGORITHM,length:W.KEY_LENGTH},!0,["encrypt","decrypt"]),o=new Uint8Array(await window.crypto.subtle.exportKey("raw",r)),n=await this.getKey(o),i=z(e),s=K(i),a=await window.crypto.subtle.encrypt({name:W.ALGORITHM,iv:t},n,new Uint8Array(s)),c=new Uint8Array(function*(...e){for(const t of e)for(const e of t)yield e}(o,t,new Uint8Array(a)));return B(c)}async decrypt(e){const t=K(e);if(t.byteLength<60)throw Error("Invalid length for the value for credentials.crypto");const r=W.KEY_LENGTH/8,o=t.slice(0,r),n=t.slice(r,r+W.IV_LENGTH),i=t.slice(r+W.IV_LENGTH),s=await this.getKey(o),a=await window.crypto.subtle.decrypt({name:W.ALGORITHM,iv:n},s,i),c=B(new Uint8Array(a));return j(c)}async getKey(e){if(!e||e.byteLength!=W.KEY_LENGTH/8)throw Error("Invalid length for clientKey");const t=await this.getServerKeyPart(),r=new Uint8Array(W.KEY_LENGTH/8);for(let o=0;o<r.byteLength;o++)r[o]=e[o]^t[o];return window.crypto.subtle.importKey("raw",r,{name:W.ALGORITHM,length:W.KEY_LENGTH},!0,["encrypt","decrypt"])}async getServerKeyPart(){if(this._serverKey)return this._serverKey;let e,t=0;for(;t<=3;)try{const e=await fetch(this.authEndpoint,{credentials:"include",method:"POST"});if(!e.ok)throw new Error(e.statusText);const t=await e.text(),r=K(t);if(r.byteLength!=W.KEY_LENGTH/8)throw Error(`The key retrieved by the server is not ${W.KEY_LENGTH} bit long.`);return this._serverKey=r,r}catch(r){e=r,t++,await new Promise(e=>setTimeout(e,t*t*100))}throw e}}W.ALGORITHM="AES-GCM",W.KEY_LENGTH=256,W.IV_LENGTH=12;class J{constructor(t){this.crypto=t,this._onCallback=new e,this.onCallback=this._onCallback.event,this.pendingCallbacks=new Set,this.lastTimeChecked=Date.now(),this.checkCallbacksTimeout=void 0}create(e={}){const t=++J.REQUEST_ID,r=[`vscode-reqid=${t}`];for(const t of J.KEYS){const o=e[t];o&&r.push(`vscode-${t}=${encodeURIComponent(o)}`)}if("vscode.github-authentication"!==e.authority||"/dummy"!==e.path){const e=`vscode-dev.url-callbacks[${t}]`;window.localStorage.removeItem(e),this.pendingCallbacks.add(t),this.startListening()}return o.parse(window.location.href).with({path:"/callback",query:r.join("&")})}startListening(){if(this.onDidChangeLocalStorageDisposable)return;const e=()=>this.onDidChangeLocalStorage();window.addEventListener("storage",e),this.onDidChangeLocalStorageDisposable={dispose:()=>window.removeEventListener("storage",e)}}stopListening(){this.onDidChangeLocalStorageDisposable?.dispose(),this.onDidChangeLocalStorageDisposable=void 0}async onDidChangeLocalStorage(){const e=Date.now()-this.lastTimeChecked;e>1e3?this.checkCallbacks():void 0===this.checkCallbacksTimeout&&(this.checkCallbacksTimeout=setTimeout(()=>{this.checkCallbacksTimeout=void 0,this.checkCallbacks()},1e3-e))}async checkCallbacks(){let e;for(const t of this.pendingCallbacks){const r=`vscode-dev.url-callbacks[${t}]`,n=window.localStorage.getItem(r);if(null!==n){try{this._onCallback.fire(o.revive(JSON.parse(await this.crypto.decrypt(n))))}catch(e){console.error(e)}e=e??new Set(this.pendingCallbacks),e.delete(t),window.localStorage.removeItem(r)}}e&&(this.pendingCallbacks=e,0===this.pendingCallbacks.size&&this.stopListening()),this.lastTimeChecked=Date.now()}}J.REQUEST_ID=0,J.KEYS=["scheme","query","authority","path","fragment"];class V{constructor(){this.set=new Set}register(e){return this.set.add(e),{dispose:()=>this.set.delete(e)}}[Symbol.iterator](){return this.set.values()}}class G{constructor(){this.map=new Map}register(e,t){return this.map.set(e,t),{dispose:()=>this.map.delete(e)}}get(e){return this.map.get(e)}[Symbol.iterator](){return this.map.values()}}const Q=new V;function Y(e){return Q.register(e)}function X(e,t){const r=("string"==typeof t.path?t.path:t.path.prefix).replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g,"\\$&");return new RegExp("string"==typeof t.path?`^/${r}/`:`^/${r}`,"i").test(e.endsWith("/")?e:`${e}/`)}const Z=Symbol("EmptyWorkspace"),ee=new V;function te(e){return ee.register(e)}const re=new V;function oe(e){return re.register(e)}function ne(e){return!!e&&e.folderUri instanceof o}const ie=e=>function(e){return!!e&&e.workspaceUri instanceof o}(e)?e.workspaceUri:e.folderUri;function se(e){for(const t of re){const r=t.resolveWorkspace(e);if(r)return r}}const ae=["cs","de","en","es","fr","it","ja","ko","pl","pt","ru","tr","zh-Hans","zh-Hant"];const ce=/{(\d+)}/g;class le{constructor(e){this.strings=e}toString(...e){const t=function(e,t){for(;;){const r=ae.indexOf(e);if(r>-1)return t[r];let o=e.replace(/-[^-]*$/,"");o===e&&(o="en"),e=o}}(window.navigator.language,this.strings);return 0===e.length?t:function(e,...t){return 0===t.length?e:e.replace(ce,function(e,r){const o=parseInt(r,10);return isNaN(o)||o<0||o>=t.length?e:t[o]})}(t,...e)}}const he={Anywhere:new le(["Visual Studio Code (Preview). Kdekoli, kdykoli a výhradně v prohlížeči.","Visual Studio Code (Vorschau). Überall, jederzeit, vollständig in Ihrem Browser.","Visual Studio Code (Preview). Anywhere, anytime, entirely in your browser.","Visual Studio Code (Versión preliminar). En cualquier lugar, en cualquier momento y plenamente en el explorador.","Visual Studio Code (préversion). N’importe où, à tout moment, entièrement dans votre navigateur.","Visual Studio Code (anteprima). Ovunque, in qualsiasi momento, interamente nel browser.","Visual Studio Code (プレビュー)。いつでもどこでも、すべてをブラウザーで。","Visual Studio Code(미리 보기). 언제 어디서나 브라우저에서 사용할 수 있습니다.","Visual Studio Code (wersja zapoznawcza). W dowolnym miejscu i czasie, wyłącznie w przeglądarce.","Visual Studio Code (Pré-visualização). Em qualquer lugar, a qualquer momento, totalmente em seu navegador.","Visual Studio Code (предварительная версия). В любом месте, в любое время, полностью в вашем браузере.","Visual Studio Code (Önizleme). Her yerde, her zaman, tamamen tarayıcınızda.","Visual Studio Code(预览版)。随时随地,尽在浏览器中。","Visual Studio Code (預覽)。隨時隨地,完全在瀏覽器中。"]),LearnMore:new le(["Další informace","Weitere Informationen","Learn More","Más información","En savoir plus","Altre informazioni","詳細情報","더 알아보기","Dowiedz się więcej","Saiba Mais","Дополнительные сведения","Daha Fazla Bilgi","了解详细信息","深入了解"]),ReadDoc:new le(["Přečtěte si dokumentaci","Lesen Sie die Dokumentation","Read the Documentation","Leer la documentación","Lire la documentation","Leggere la documentazione","ドキュメントを読む","문서 읽기","Przeczytaj dokumentację","Leia a documentação","Прочитать документацию","Belgeleri okuyun","阅读文档","閱讀文檔"]),Privacy:new le(["Ochrana osobních údajů a soubory cookie","Datenschutz und Cookies","Privacy & Cookies","Privacidad y cookies","Confidentialité et cookies","Privacy e cookie","プライバシーと Cookie","개인정보처리방침 및 위치정보이용약관","Prywatność i pliki cookie","Privacidade e Cookies","Конфиденциальность и файлы cookie","Gizlilik ve Tanımlama Bilgileri","隐私和 Cookie","隱私權與 Cookie"]),TermsofUse:new le(["Podmínky použití","Nutzungsbedingungen","Terms of Use","Términos de uso","Conditions d'utilisation","Condizioni per l'utilizzo","利用規約","사용 약관","Warunki użytkowania","Termos de Uso","Условия использования","Kullanım Koşulları","使用条款","使用規定"]),DownloadVSCode:new le(["Stáhnout VS Code","VS Code herunterladen","Download VS Code","Descargar VS Code","Télécharger VS Code","Scaricare Visual Studio Code","VS Code をダウンロードする","VS Code 다운로드","Pobierz program VS Code","Baixar o Visual Studio Code","Загрузить VS Code","VS Code’u indirin","下载 VS 代码","下載 VS 代碼"]),MakeCodePrompt:new le(["Použijte MakeCode k vytvoření vlastních arkádových her.","Verwenden Sie MakeCode, um eigene Arcade-Spiele zu erstellen.","Use MakeCode to create arcade games of your own.","Utilice MakeCode para crear sus propios juegos de arcade.","Utilisez MakeCode pour créer vos propres jeux d’arcade.","Usa MakeCode per creare giochi arcade personalizzati.","MakeCode を使用して、独自のアーケード ゲームを作成します。","MakeCode를 사용하여 자신만의 아케이드 게임을 만들 수 있습니다.","Użyj MakeCode, aby tworzyć własne gry zręcznościowe.","Use o MakeCode para criar seus próprios jogos de arcade.","Используйте MakeCode для создания собственных аркадных игр.","Kendi arcade oyunlarınızı oluşturmak için MakeCode'u kullanın.","使用MakeCode创建自己的街机游戏。","使用MakeCode創建自己的街機遊戲。"]),auth:{SessionExpiringSoon:new le(["Sessie pro {0} brzy vyprší. Chcete obnovit svou relaci? (otevře se vyskakovací okno)","Die Sitzung für {0} läuft in Kürze ab. Möchten Sie Ihre Sitzung aktualisieren? (Ein Popup wird geöffnet)","The session for {0} is expiring soon. Would you like to refresh your session? (a popup will be launched)","La sesión de {0} está a punto de caducar. ¿Desea actualizar su sesión? (se abrirá una ventana emergente)","La session pour {0} expire bientôt. Souhaitez-vous actualiser votre session ? (une fenêtre contextuelle sera ouverte)","La sessione per {0} sta per scadere. Vuoi aggiornare la sessione? (verrà aperto un popup)","{0} のセッションがまもなく期限切れになります。セッションを更新しますか? (ポップアップが開きます)","{0} 세션이 곧 만료됩니다. 세션을 새로 고치시겠습니까? (팝업이 열립니다)","Sesja dla {0} wygasa wkrótce. Czy chcesz odświeżyć swoją sesję? (otworzy się okno)","A sessão para {0} está prestes a expirar. Deseja atualizar sua sessão? (uma janela pop-up será aberta)","Сессия для {0} скоро истечет. Хотите обновить сессию? (будет открыто всплывающее окно)","{0} oturumu yakında sona erecek. Oturumu yenilemek ister misiniz? (bir açılır pencere açılacak)","{0} 的会话即将过期。是否要刷新会话?(将弹出一个弹出窗口)","{0} 的會話即將到期。是否要重新整理您的會話?(將開啟彈出視窗)"]),Refresh:new le(["Obnovit","Aktualisieren","Refresh","Refrescar","Actualiser","Aggiorna","更新","새로 고침","Odśwież","Atualizar","Обновить","Yenile","刷新","重新整理"]),MoreInfo:new le(["Více informací","Weitere Informationen","More Info","Más información","Plus d’informations","Ulteriori informazioni","詳細情報","더 알아보기","Więcej informacji","Mais informações","Дополнительные сведения","Daha Fazla Bilgi","更多信息","更多資訊"])}},de=JSON.parse('["ms-vscode","ms-toolsai","ms-azuretools","quantum","SynapseVSCode","teamsdevapp","ms-windows-ai-studio"]');let ue=!1;const ge=[],pe=e=>{ge.push(e),ue||(console.warn("registerLoopbackResponder will soon stop working. VS Code proposed.resolvers.d.ts now work in the web, please use those instead."),ue=!0,navigator.serviceWorker.addEventListener("message",async e=>{if(e.origin!==window.location.origin||"loopback"!==e.data.type||!e.source)return;const t={uri:o.parse(e.data.uri),headers:e.data.headers,method:e.data.method},r=t=>e.source.postMessage({type:"loopback",id:e.data.id,status:t.status,body:t.body,headers:t.headers},{targetOrigin:e.origin,transfer:[t.body]});try{for(const e of ge){const o=await e(t);if(o)return r(o)}r({status:404,body:(new TextEncoder).encode("Not found").buffer})}catch(e){r({status:504,body:(new TextEncoder).encode(String(e)).buffer})}}))},me=()=>{if(ue)return;let e;return navigator.serviceWorker.addEventListener("message",async t=>{t.origin===window.location.origin&&"loopback"===t.data.type&&t.source&&e?.({uri:o.parse(t.data.uri),respondWith(e,r,o){const n=r.byteLength===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);t.source.postMessage({type:"loopback",id:t.data.id,status:e,body:n,headers:o},{targetOrigin:t.origin,transfer:[n]})}})}),{path:"/loopback",onDidReceiveRequest:t=>(e=t,{dispose:()=>{e=void 0}})}};let fe=!1;async function ye(e,t){if(!fe){fe=!0;const e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href="/static/progress.css",document.head.append(e)}const r=document.createElement("div");r.classList.add("vscode-dev-progress");const o=document.createElement("h2");let n;o.textContent=e.title,r.appendChild(o),document.body.appendChild(r);try{return await t({report:e=>{e.message&&(n||(n=document.createElement("p"),r.appendChild(n)),n.textContent=e.message)}})}finally{r.remove()}}const we=new Set(["ms-vscode","ms-toolsai","ms-azuretools","quantum","synapsevscode","teamsdevapp","ms-windows-ai-studio"]),ve=new Set(de.map(e=>e.toLowerCase())),Ce=new Set(["vscode-quality","vscode-version","vscode-lang"]),Ie=new Set(["localhost","127.0.0.1","[::1]"]),be=new Map([["ms-vscode.remote-server","tunnel"],["quantum.qsharp-lang-vscode","quantum"],["ms-azuretools.vscode-dev-azurecloudshell","azure"]]),ke=new Map([...be].map(([e,t])=>[t,e])),Se=/\.code-workspace$/i,Te=/^([a-z0-9][a-z0-9\-]*)\.([a-z0-9][a-z0-9\-]*)(?:@([0-9]+\.[0-9]+\.[0-9]+))?$/;const Ae=new class{constructor(e){this.maxSize=e}save(e,t){const r=this.getAuthorityKey(e),o=this.getValue();o.delete(r),o.set(r,t);for(const e of o.keys()){if(o.size<this.maxSize)break;o.delete(e)}localStorage.setItem("anything.cache",JSON.stringify([...o]))}getExtensionFor(e){return this.getValue().get(this.getAuthorityKey(e))}getAuthorityKey(e){let t=e.indexOf("+");return-1===t?e:e.slice(0,t)}getValue(){if(!this._value){const e=localStorage.getItem("anything.cache");this._value=new Map(e?JSON.parse(e):void 0),this._value.set("tunnel","ms-vscode.remote-server")}return this._value}}(100);class _e{async route({url:e,microsoftAuthentication:t,githubAuthentication:r,quality:i,commit:s,continueOnBody:l}){const h=function(e){let t=e.indexOf("/",1);-1===t&&(t=e.length);const r=e.slice(1,-1===t?void 0:t),o=ke.get(r);let n;if(o)n=o;else{if("+"!==e[1])return;n=r.slice(1)}return{extensionPathPart:r,extensionId:n,folderUri:t+1<e.length?e.slice(t+1):void 0}}(e.pathname);if(!h)return;const d="stable"!==i,u=await this.getExtensionUrl(d,h.extensionId);if(!u)return;const g=await this.readPackageJson(u.url),p=u.publisher||g.publisher||"unknown",m=u.name||g.name||"unnamed",f=g.contributes?.webOpener;if(!we.has(p.toLowerCase()))return;l?.authentication?.microsoft?.length&&await t.setInitialSessions(l.authentication.microsoft),e=await t.tryCompleteAuthExchange(),e=function(e,t){if("+"!==t[0])return e;const r=be.get(t.slice(1));if(!r)return e;const o=new URL(e);return o.pathname=o.pathname.replace(/^\/[^/]+/,`/${r}`),window.history.replaceState(void 0,document.title,o.toString()),o}(e=await r.tryCompleteAuthExchange(),h.extensionPathPart);const y=`${p}.${m}`;let w,v={workspaceUri:o.from({scheme:"tmp",path:"/default.code-workspace"})};if(f?.scheme&&h.folderUri){const t=h.folderUri.indexOf("/"),r=new URLSearchParams(document.location.search);for(const e of Ce)r.delete(e);w=o.from({scheme:f.scheme,authority:-1===t?h.folderUri:h.folderUri.slice(0,t),fragment:e.hash.slice(1),query:r.toString(),path:-1===t?void 0:this.sanitizePathForUri(h.folderUri.slice(t))}),v=Se.test(w.path)?{workspaceUri:w}:{folderUri:w}}const C=await this.collectExtensionDependencies(d,g),I={workspace:v,workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none"},additionalBuiltinExtensions:[o.parse(u.url),...C.map(e=>e.uri)],enabledExtensions:[y]},excludeAdditionalBuiltinExtensions:[y],onDidCreateWorkbench:{runCommands:this.processRunCommands(f?.runCommands)}},b={commands:{executeCommand:n.executeCommand},logger:{log:a.log},window:{withProgress:c.withProgress}};if(ve.has(p.toLowerCase())&&f?.import){const e=await import(`${u.url}/${f.import}`),o={version:{quality:i,commit:s},registerLoopbackResponder:pe,microsoftAuthentication:t,githubAuthentication:r,workbench:b,withProgress:ye,...this.makeExportsApi(d)};await e.default(I,o)}if("object"==typeof I.workspace){const e=ie(I.workspace);e?.authority&&(Ae.save(e.authority,y),e.path||(I.workspace=Z))}return _e.lastRouted={extensionPathPart:h.extensionPathPart,uri:w},I}sanitizePathForUri(e){return e.replace(/%20/g," ")}async readPackageJson(e){const t=await fetch(`${e}/package.json`);if(!t.ok)throw new Error(`Unexpected ${t.status} from ${e}/package.json`);return await t.json()}processRunCommands(e){return e?.map(e=>({...e,args:e.args.map(e=>"$url"===e?document.location.href:e)}))??[]}async getExtension(e,t){const r=await this.getExtensionUrl(e,t);if(!r)return;const n=await this.readPackageJson(r.url);return{id:t,extensionUri:o.parse(r.url),packageJSON:n,isActive:!1,activate:()=>r.publisher&&ve.has(r.publisher.toLowerCase())&&n.contributes.webOpener?.import?import(`${r.url}/${n.contributes.webOpener.import}`).then(async t=>await(t.exports?.(this.makeExportsApi(e)))):Promise.resolve(void 0)}}makeExportsApi(e){return{getExtension:t=>this.getExtension(e,t)}}async getExtensionUrl(e,t){const r=Te.exec(t);if(r){const[,o,n,i=await this.getLatestExtensionVersion(t,e)]=r;return{url:`https://${o}.vscode-unpkg.net/${o}/${n}/${i}/extension`,publisher:o,name:n}}try{const e=atob(t),r=new URL(e);if(Ie.has(r.hostname))return{url:r.toString(),publisher:void 0,name:void 0}}catch{}}async getLatestExtensionVersion(e,t){const r=await fetch("https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery",{method:"POST",headers:{"Content-Type":"application/json",accept:"application/json;api-version=3.0-preview.1","x-market-client-id":"vscode-dev"},body:JSON.stringify({filters:[{criteria:[{filterType:7,value:e}]}],pageNumber:1,flags:1|(t?512:16)})});if(!r.ok)throw new Error(`Unexpected ${r.status} from marketplace search: ${await r.text()}`);const o=await r.json();let n=o.results[0].extensions[0]?.versions;if(!n?.length)return;const i=n.filter(e=>"web"===e.targetPlatform);let s="";if(i.length&&(n=i,s="+web"),t)return n[0].version+s;const a=n.find(e=>!e.properties.some(e=>"Microsoft.VisualStudio.Code.PreRelease"===e.key&&"true"===e.value));return a?a.version+s:void 0}async collectExtensionDependencies(e,t){const r=[],n=[t],i=new Set;for(;n.length;){const t=n.pop(),s=[...t.extensionDependencies??[],...t.extensionPack??[]];s.length&&await Promise.all(s.map(async t=>{if(i.has(t))return;i.add(t);const s=await this.getExtensionUrl(e,t);if(!s)return;const a=await this.readPackageJson(s.url);r.push({uri:o.parse(s.url),packageJson:a,name:s.name,publisher:s.publisher}),n.push(a)}))}return r}}for(const e of ke.keys())te(new class extends _e{constructor(){super(...arguments),this.path=e,this.additionalBuiltinExtensions=[]}});te(new class extends _e{constructor(){super(...arguments),this.path={prefix:"+"},this.additionalBuiltinExtensions=[]}}),oe(new class{resolveWorkspace(e){if(void 0===e&&_e.lastRouted?.uri){const e=new URL(document.location.href);return e.pathname=`/${_e.lastRouted.extensionPathPart}/${_e.lastRouted.uri.authority}`,e.toString()}const t=e&&ie(e);if(!t||!t.authority)return;let r=t.authority.split("@");const o=r[r.length-1];o.includes("+")&&(r[r.length-1]=o.slice(o.indexOf("+")+1));const n=t&&Ae.getExtensionFor(o);if(!n)return;const i=be.get(n)||`+${n}`,s=new URL(document.location.href);s.search=t?.query?`?${t.query}`:"",s.hash=t?.fragment?`#${t?.fragment}`:"",s.pathname=`/${i}/${r.join("@")}${t?.path||""}`;const a=new URLSearchParams(document.location.search);for(const e of Ce)a.has(e)&&s.searchParams.set(e,a.get(e));return s.toString()}});class Ee{constructor(e,t){this.service=t,this.regexp=new RegExp(`^/(?:https?://)?${e.replace(/\./g,"\\.")}/(?<rest>.*)`,"i")}redirect(e){const t=this.regexp.exec(e.pathname);if(!t?.groups)return;const r=new URL(e.toString());return r.pathname=`/${this.service}/${t.groups.rest}`,r}}var Pe;Y(new class{redirect(e){const t=/^#(?<rest>https?:\/\/.*)/i.exec(e.hash);if(!t?.groups)return;const r=new URL(e.toString());return r.pathname=t.groups.rest,r.hash="",r}}),function(e){e[e.Branch=0]="Branch",e[e.Tag=1]="Tag",e[e.Commit=2]="Commit",e[e.PullRequest=3]="PullRequest",e[e.Tree=4]="Tree"}(Pe||(Pe={}));const xe=/^[0-9a-f]{40}$/i;function Oe(e){return void 0!==e&&xe.test(e)}function Re(e){const[t,r]=e.split("+");let o;if(r)try{o=JSON.parse(function(e){const t=e.match(/(\w{2})/g);if(null===t)return"";const r=new Uint8Array(t.map(e=>parseInt(e,16)));return Ue.decode(r)}(r))}catch{}return{scheme:t,metadata:o}}function Me(e,t){return`${e}${t?`+${function(e){const t=$e.encode(e),r=new Array(t.length);for(let e=0;e<t.length;++e)r[e]=qe[t[e]];return r.join("")}(JSON.stringify(t))}`:""}`}const qe=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],$e=new TextEncoder;const Ue=new TextDecoder;const Le=new G;function Ne(e,t){return Le.register(e,t)}oe(new class{resolveWorkspace(e){if(!ne(e))return;const t=e.folderUri;if("vscode-vfs"!==t.scheme||!t.authority)return;const{scheme:r,metadata:o}=Re(t.authority),n=Le.get(r);if(!n)throw new Error(`RemoteHub authority not supported: ${t.authority}`);return n.resolveRemoteHubWorkspace(t,o)}});const De=/^\/(?<service>azurerepos)(?<indexed>\+idx=?(?<idx>latest|[0-9a-fA-F]{40})?)?(?:\/defaultcollection)?\/(?<organization>[^/]+)(?:\/(?<project>[^_/][^/]*))?(?:\/_git)?\/(?<repo>[^/]+)(?:\/commit\/(?<commit>[0-9a-f]{40})|\/pullrequest\/(?<pull>\d+))?/i;function He(){return"object"==typeof navigator&&"userAgent"in navigator?navigator.userAgent:"object"==typeof process&&void 0!==process.version?`Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`:"<environment undetectable>"}function Fe(e,t,r,o){if("function"!=typeof r)throw new Error("method for before hook must be a function");return o||(o={}),Array.isArray(t)?t.reverse().reduce((t,r)=>Fe.bind(null,e,r,t,o),r)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((e,t)=>t.hook.bind(null,e,o),r)():r(o))}function ze(e,t,r,o){const n=o;e.registry[r]||(e.registry[r]=[]),"before"===t&&(o=(e,t)=>Promise.resolve().then(n.bind(null,t)).then(e.bind(null,t))),"after"===t&&(o=(e,t)=>{let r;return Promise.resolve().then(e.bind(null,t)).then(e=>(r=e,n(r,t))).then(()=>r)}),"error"===t&&(o=(e,t)=>Promise.resolve().then(e.bind(null,t)).catch(e=>n(e,t))),e.registry[r].push({hook:o,orig:n})}function je(e,t,r){if(!e.registry[t])return;const o=e.registry[t].map(e=>e.orig).indexOf(r);-1!==o&&e.registry[t].splice(o,1)}te(new class{constructor(){this.path="azurerepos",this.additionalBuiltinExtensions=["ms-vscode.azure-repos"]}async route({url:e,quality:t}){const r=De.exec(e.pathname);if(void 0===r?.groups)return;const{indexed:n,idx:i,organization:s,project:a,repo:c,commit:l,pull:h}=r.groups,d=/^GC(?<commit>[0-9a-f]{40})/i.exec(e.searchParams.get("version")??""),u=/^GB(?<branchName>.+)/i.exec(e.searchParams.get("version")??""),g=/^GT(?<tagName>.+)/i.exec(e.searchParams.get("version")??"");let p,m,f={};if(u&&u.groups){const{branchName:e}=u.groups;p={v:1,ref:{type:Pe.Branch,id:e}}}else if(g&&g.groups){const{tagName:e}=g.groups;p={v:1,ref:{type:Pe.Tag,id:e}}}else if(l)p={v:1,ref:{type:Pe.Commit,id:l}};else if(d&&d.groups){const{commit:e}=d.groups;p={v:1,ref:{type:Pe.Commit,id:e}}}else h?p={v:1,ref:{type:Pe.PullRequest,id:h}}:f={"workbench.startupEditor":"readme"};n&&(p||(p={v:1}),p.idx=i||"latest");const y=e.searchParams.get("path");if(y){let t;if(e.searchParams.get("line")){const r=Number(e.searchParams.get("line"));t={startColumn:Number(e.searchParams.get("lineStartColumn")??0),startLineNumber:r,endColumn:Number(e.searchParams.get("lineEndColumn")??0),endLineNumber:Number(e.searchParams.get("lineEnd")??r+1)}}m={force:!0,editors:[{uri:{scheme:"vscode-vfs",authority:Me("azurerepos",p),path:`/${s}/${a??c}/${c}${y.startsWith("/")?y:`/${y}`}`},options:{selection:t},openOnlyIfExists:!0}]}}const w=e.searchParams.get("editSessionId")??void 0;return e.searchParams.delete("editSessionId"),window.history.replaceState(void 0,document.title,e.toString()),{workspace:{folderUri:o.from({scheme:"vscode-vfs",authority:Me("azurerepos",p),path:`/${s}/${a??c}/${c}`})},workbenchOptions:{configurationDefaults:{"remoteHub.richNavigation.enabled":!0,"workbench.startupEditor":"none",...f},editSessionId:w,defaultLayout:m,commands:[{id:"_remotehub.getLfsProxyEndpoint",handler:()=>({"dev.azure.com":`https://${"stable"===t?"vscode.dev":"insiders.vscode.dev"}/indexes/lfs`})}]}}}}),Ne("azurerepos",new class{resolveRemoteHubWorkspace(e,t){const r=new URL(document.location.href),o=De.exec(`/azurerepos${e.path}`);if(void 0===o?.groups)throw new Error(`RemoteHub uri not supported: ${e.toString()}`);const{organization:n,project:i,repo:s}=o.groups,a=new URLSearchParams(e.query);let c=a.get("vscode-experience")??"azurerepos";void 0!==t&&("latest"===t.idx?c+="+idx":Oe(t.idx)&&(c+=`+idx=${t.idx}`));let l=`/${c}/${n}/${i}/${s}`;switch(t?.ref?.type){case Pe.Commit:a.set("version",`GC${t.ref.id}`);break;case Pe.Branch:a.set("version",`GB${t.ref.id}`);break;case Pe.Tag:a.set("version",`GT${t.ref.id}`);break;case Pe.PullRequest:l=`${l}/pullrequest/${t.ref.id}`}return r.pathname=l,r.search=a.toString(),r.toString()}}),Y(new Ee("dev.azure.com","azurerepos")),Y(new class{constructor(e,t){this.service=t,this.regexp=new RegExp(`^/(?:https?://)?(?<organization>[^.]+)${e.replace(/\./g,"\\.")}(?:/defaultcollection)?/(?<rest>.*)`,"i")}redirect(e){const t=this.regexp.exec(e.pathname);if(!t?.groups||!t.groups.organization)return;const r=new URL(e.toString());return r.pathname=`/${this.service}/${t.groups.organization}/${t.groups.rest}`,r}}(".visualstudio.com","azurerepos")),Y(new class{redirect(e){const t=De.exec(e.pathname);if(void 0===t?.groups)return;const{organization:r,project:o,repo:n,commit:i,pull:s}=t.groups,a=new URL(e.toString());return a.pathname=`/azurerepos/${r}/${o??n}/${n}${i?`/commit/${i}`:s?`/pullrequest/${s}`:""}`,a}});const Be=Function.bind,Ke=Be.bind(Be);function We(e,t,r){const o=Ke(je,null).apply(null,r?[t,r]:[t]);e.api={remove:o},e.remove=o,["before","error","after","wrap"].forEach(o=>{const n=r?[t,o,r]:[t,o];e[o]=e.api[o]=Ke(ze,null).apply(null,n)})}const Je={Singular:function(){const e=Symbol("Singular"),t={registry:{}},r=Fe.bind(null,t,e);return We(r,t,e),r},Collection:function(){const e={registry:{}},t=Fe.bind(null,e);return We(t,e),t}};var Ve=`octokit-endpoint.js/0.0.0-development ${He()}`;function Ge(e,t){const r=Object.assign({},e);return Object.keys(t).forEach(o=>{!function(e){if("object"!=typeof e||null===e)return!1;if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;const r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}(t[o])?Object.assign(r,{[o]:t[o]}):o in e?r[o]=Ge(e[o],t[o]):Object.assign(r,{[o]:t[o]})}),r}function Qe(e){for(const t in e)void 0===e[t]&&delete e[t];return e}function Ye(e,t,r){if("string"==typeof t){let[e,o]=t.split(" ");r=Object.assign(o?{method:e,url:o}:{url:e},r)}else r=Object.assign({},t);var o;r.headers=(o=r.headers)?Object.keys(o).reduce((e,t)=>(e[t.toLowerCase()]=o[t],e),{}):{},Qe(r),Qe(r.headers);const n=Ge(e||{},r);return"/graphql"===r.url&&(e&&e.mediaType.previews?.length&&(n.mediaType.previews=e.mediaType.previews.filter(e=>!n.mediaType.previews.includes(e)).concat(n.mediaType.previews)),n.mediaType.previews=(n.mediaType.previews||[]).map(e=>e.replace(/-preview/,""))),n}var Xe=/\{[^{}}]+\}/g;function Ze(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function et(e,t){const r={__proto__:null};for(const o of Object.keys(e))-1===t.indexOf(o)&&(r[o]=e[o]);return r}function tt(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(e){return/%[0-9A-Fa-f]/.test(e)||(e=encodeURI(e).replace(/%5B/g,"[").replace(/%5D/g,"]")),e}).join("")}function rt(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}function ot(e,t,r){return t="+"===e||"#"===e?tt(t):rt(t),r?rt(r)+"="+t:t}function nt(e){return null!=e}function it(e){return";"===e||"&"===e||"?"===e}function st(e,t){var r=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(e,o,n){if(o){let e="";const n=[];if(-1!==r.indexOf(o.charAt(0))&&(e=o.charAt(0),o=o.substr(1)),o.split(/,/g).forEach(function(r){var o=/([^:\*]*)(?::(\d+)|(\*))?/.exec(r);n.push(function(e,t,r,o){var n=e[r],i=[];if(nt(n)&&""!==n)if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)n=n.toString(),o&&"*"!==o&&(n=n.substring(0,parseInt(o,10))),i.push(ot(t,n,it(t)?r:""));else if("*"===o)Array.isArray(n)?n.filter(nt).forEach(function(e){i.push(ot(t,e,it(t)?r:""))}):Object.keys(n).forEach(function(e){nt(n[e])&&i.push(ot(t,n[e],e))});else{const e=[];Array.isArray(n)?n.filter(nt).forEach(function(r){e.push(ot(t,r))}):Object.keys(n).forEach(function(r){nt(n[r])&&(e.push(rt(r)),e.push(ot(t,n[r].toString())))}),it(t)?i.push(rt(r)+"="+e.join(",")):0!==e.length&&i.push(e.join(","))}else";"===t?nt(n)&&i.push(rt(r)):""!==n||"&"!==t&&"?"!==t?""===n&&i.push(""):i.push(rt(r)+"=");return i}(t,e,o[1],o[2]||o[3]))}),e&&"+"!==e){var i=",";return"?"===e?i="&":"#"!==e&&(i=e),(0!==n.length?e:"")+n.join(i)}return n.join(",")}return tt(n)}),"/"===e?e:e.replace(/\/$/,"")}function at(e){let t,r=e.method.toUpperCase(),o=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),n=Object.assign({},e.headers),i=et(e,["method","baseUrl","url","headers","request","mediaType"]);const s=function(e){const t=e.match(Xe);return t?t.map(Ze).reduce((e,t)=>e.concat(t),[]):[]}(o);var a;o=(a=o,{expand:st.bind(null,a)}).expand(i),/^http/.test(o)||(o=e.baseUrl+o);const c=et(i,Object.keys(e).filter(e=>s.includes(e)).concat("baseUrl"));if(!/application\/octet-stream/i.test(n.accept)&&(e.mediaType.format&&(n.accept=n.accept.split(/,/).map(t=>t.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(",")),o.endsWith("/graphql")&&e.mediaType.previews?.length)){const t=n.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[];n.accept=t.concat(e.mediaType.previews).map(t=>`application/vnd.github.${t}-preview${e.mediaType.format?`.${e.mediaType.format}`:"+json"}`).join(",")}return["GET","HEAD"].includes(r)?o=function(e,t){const r=/\?/.test(e)?"&":"?",o=Object.keys(t);return 0===o.length?e:e+r+o.map(e=>"q"===e?"q="+t.q.split("+").map(encodeURIComponent).join("+"):`${e}=${encodeURIComponent(t[e])}`).join("&")}(o,c):"data"in c?t=c.data:Object.keys(c).length&&(t=c),n["content-type"]||void 0===t||(n["content-type"]="application/json; charset=utf-8"),["PATCH","PUT"].includes(r)&&void 0===t&&(t=""),Object.assign({method:r,url:o,headers:n},void 0!==t?{body:t}:null,e.request?{request:e.request}:null)}function ct(e,t,r){return at(Ye(e,t,r))}var lt=function e(t,r){const o=Ye(t,r),n=ct.bind(null,o);return Object.assign(n,{DEFAULTS:o,defaults:e.bind(null,o),merge:Ye.bind(null,o),parse:at})}(null,{method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":Ve},mediaType:{format:""}}),ht=d(251);class dt extends Error{name;status;request;response;constructor(e,t,r){super(e),this.name="HttpError",this.status=Number.parseInt(t),Number.isNaN(this.status)&&(this.status=0),"response"in r&&(this.response=r.response);const o=Object.assign({},r.request);r.request.headers.authorization&&(o.headers=Object.assign({},r.request.headers,{authorization:r.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),o.url=o.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=o}}async function ut(e){const t=e.request?.fetch||globalThis.fetch;if(!t)throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");const r=e.request?.log||console,o=!1!==e.request?.parseSuccessResponseBody,n=function(e){if("object"!=typeof e||null===e)return!1;if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;const r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}(e.body)||Array.isArray(e.body)?JSON.stringify(e.body):e.body,i=Object.fromEntries(Object.entries(e.headers).map(([e,t])=>[e,String(t)]));let s;try{s=await t(e.url,{method:e.method,body:n,redirect:e.request?.redirect,headers:i,signal:e.request?.signal,...e.body&&{duplex:"half"}})}catch(t){let r="Unknown Error";if(t instanceof Error){if("AbortError"===t.name)throw t.status=500,t;r=t.message,"TypeError"===t.name&&"cause"in t&&(t.cause instanceof Error?r=t.cause.message:"string"==typeof t.cause&&(r=t.cause))}const o=new dt(r,500,{request:e});throw o.cause=t,o}const a=s.status,c=s.url,l={};for(const[e,t]of s.headers)l[e]=t;const h={url:c,status:a,headers:l,data:""};if("deprecation"in l){const t=l.link&&l.link.match(/<([^<>]+)>; rel="deprecation"/),o=t&&t.pop();r.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${l.sunset}${o?`. See ${o}`:""}`)}if(204===a||205===a)return h;if("HEAD"===e.method){if(a<400)return h;throw new dt(s.statusText,a,{response:h,request:e})}if(304===a)throw h.data=await gt(s),new dt("Not modified",a,{response:h,request:e});if(a>=400)throw h.data=await gt(s),new dt(function(e){if("string"==typeof e)return e;if(e instanceof ArrayBuffer)return"Unknown error";if("message"in e){const t="documentation_url"in e?` - ${e.documentation_url}`:"";return Array.isArray(e.errors)?`${e.message}: ${e.errors.map(e=>JSON.stringify(e)).join(", ")}${t}`:`${e.message}${t}`}return`Unknown error: ${JSON.stringify(e)}`}(h.data),a,{response:h,request:e});return h.data=o?await gt(s):s.body,h}async function gt(e){const t=e.headers.get("content-type");if(!t)return e.text().catch(()=>"");const r=(0,ht.xL)(t);if(!function(e){return"application/json"===e.type||"application/scim+json"===e.type}(r))return r.type.startsWith("text/")||"utf-8"===r.parameters.charset?.toLowerCase()?e.text().catch(()=>""):e.arrayBuffer().catch(()=>new ArrayBuffer(0));{let t="";try{return t=await e.text(),JSON.parse(t)}catch(e){return t}}}var pt=function e(t,r){const o=t.defaults(r);return Object.assign(function(t,r){const n=o.merge(t,r);if(!n.request||!n.request.hook)return ut(o.parse(n));const i=(e,t)=>ut(o.parse(o.merge(e,t)));return Object.assign(i,{endpoint:o,defaults:e.bind(null,o)}),n.request.hook(i,n)},{endpoint:o,defaults:e.bind(null,o)})}(lt,{headers:{"user-agent":`octokit-request.js/0.0.0-development ${He()}`}});var mt=class extends Error{constructor(e,t,r){super("Request failed due to following response errors:\n"+r.errors.map(e=>` - ${e.message}`).join("\n")),this.request=e,this.headers=t,this.response=r,this.errors=r.errors,this.data=r.data,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}name="GraphqlResponseError";errors;data},ft=["method","baseUrl","url","headers","request","query","mediaType","operationName"],yt=["query","method","url"],wt=/\/api\/v3\/?$/;function vt(e,t){const r=e.defaults(t);return Object.assign((e,t)=>function(e,t,r){if(r){if("string"==typeof t&&"query"in r)return Promise.reject(new Error('[@octokit/graphql] "query" cannot be used as variable name'));for(const e in r)if(yt.includes(e))return Promise.reject(new Error(`[@octokit/graphql] "${e}" cannot be used as variable name`))}const o="string"==typeof t?Object.assign({query:t},r):t,n=Object.keys(o).reduce((e,t)=>ft.includes(t)?(e[t]=o[t],e):(e.variables||(e.variables={}),e.variables[t]=o[t],e),{}),i=o.baseUrl||e.endpoint.DEFAULTS.baseUrl;return wt.test(i)&&(n.url=i.replace(wt,"/api/graphql")),e(n).then(e=>{if(e.data.errors){const t={};for(const r of Object.keys(e.headers))t[r]=e.headers[r];throw new mt(n,t,e.data)}return e.data.data})}(r,e,t),{defaults:vt.bind(null,r),endpoint:r.endpoint})}vt(pt,{headers:{"user-agent":`octokit-graphql.js/0.0.0-development ${He()}`},method:"POST",url:"/graphql"});var Ct="(?:[a-zA-Z0-9_-]+)",It=new RegExp(`^${Ct}\\.${Ct}\\.${Ct}$`),bt=It.test.bind(It);async function kt(e){const t=bt(e),r=e.startsWith("v1.")||e.startsWith("ghs_"),o=e.startsWith("ghu_");return{type:"token",token:e,tokenType:t?"app":r?"installation":o?"user-to-server":"oauth"}}async function St(e,t,r,o){const n=t.endpoint.merge(r,o);return n.headers.authorization=function(e){return 3===e.split(/\./).length?`bearer ${e}`:`token ${e}`}(e),t(n)}var Tt=function(e){if(!e)throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");if("string"!=typeof e)throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");return e=e.replace(/^(token|bearer) +/i,""),Object.assign(kt.bind(null,e),{hook:St.bind(null,e)})};const At="6.1.4",_t=()=>{},Et=console.warn.bind(console),Pt=console.error.bind(console),xt=`octokit-core.js/${At} ${He()}`;class Ot{static VERSION=At;static defaults(e){return class extends(this){constructor(...t){const r=t[0]||{};super("function"!=typeof e?Object.assign({},e,r,r.userAgent&&e.userAgent?{userAgent:`${r.userAgent} ${e.userAgent}`}:null):e(r))}}}static plugins=[];static plugin(...e){const t=this.plugins;return class extends(this){static plugins=t.concat(e.filter(e=>!t.includes(e)))}}constructor(e={}){const t=new Je.Collection,r={baseUrl:pt.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},e.request,{hook:t.bind(null,"request")}),mediaType:{previews:[],format:""}};var o;if(r.headers["user-agent"]=e.userAgent?`${e.userAgent} ${xt}`:xt,e.baseUrl&&(r.baseUrl=e.baseUrl),e.previews&&(r.mediaType.previews=e.previews),e.timeZone&&(r.headers["time-zone"]=e.timeZone),this.request=pt.defaults(r),this.graphql=(o=this.request,vt(o,{method:"POST",url:"/graphql"})).defaults(r),this.log=Object.assign({debug:_t,info:_t,warn:Et,error:Pt},e.log),this.hook=t,e.authStrategy){const{authStrategy:r,...o}=e,n=r(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:o},e.auth));t.wrap("request",n.hook),this.auth=n}else if(e.auth){const r=Tt(e.auth);t.wrap("request",r.hook),this.auth=r}else this.auth=async()=>({type:"unauthenticated"});const n=this.constructor;for(let t=0;t<n.plugins.length;++t)Object.assign(this,n.plugins[t](this,e))}request;graphql;log;hook;auth}const Rt=["repo","workflow","user:email","read:user"];class Mt{constructor(){this.path="github",this.additionalBuiltinExtensions=["GitHub.vscode-pull-request-github"]}async route({url:e,githubAuthentication:t,quality:r}){const n=Mt.RX.exec(e.pathname);if(void 0===n?.groups)return;let i,s,{service:a,indexed:c,idx:l,owner:h,repo:d,blob:u,commit:g,tree:p,pull:m}=n.groups,f={};const y=await async function(e,t,r,o){try{const e=new Ot;return await qt(e,t,r,o)}catch(e){if(!o||e instanceof dt&&404!==e.status)return{owner:t,repo:r}}const n=(await e.login(Rt)).accessToken;try{if(void 0!==n){const e=new Ot({auth:`token ${n}`});return await qt(e,t,r,o)}}catch(e){console.error(e)}return{owner:t,repo:r}}(t,h,d,p??u);if(void 0===y)return;let w,v;if(({owner:h,repo:d,ref:v,path:w}=y),p||u){if(!v&&!w){const t=new URL(e);t.pathname=`/${a}/${h}/${d}`,window.location.href=t.toString(),await new Promise(()=>{})}if(s={v:1,ref:v},w&&u){let t,r;if(e.hash){const o=/(L(?<start>\d+)(?:-L(?<end>\d+))?)|(C(?<cell>\d+)(\:L(?<cell_line_start>\d+)(?:-L(?<cell_line_end>\d+))?)?)/.exec(e.hash);if(o?.groups){const{cell:e,start:n,end:i,cell_line_start:s,cell_line_end:a}=o.groups;void 0!==n&&(t={startLineNumber:Number(n),startColumn:0,endLineNumber:Number(i??n)+1,endColumn:0}),void 0!==e&&(r={indexedCellOptions:{index:Math.max(0,Number(e)-1),selection:void 0===s?void 0:{startLineNumber:Number(s),startColumn:1,endLineNumber:Number(a??s)+1,endColumn:1}}})}}i={force:!0,editors:[{uri:{scheme:"vscode-vfs",authority:Me("github",s),path:`/${h}/${d}${w?.startsWith("/")?w:w?`/${w}`:""}`},options:{...r,selection:t},openOnlyIfExists:!0}]}}}else g?s={v:1,ref:{type:Pe.Commit,id:g}}:m?s={v:1,ref:{type:Pe.PullRequest,id:m}}:v?s={v:1,ref:v}:f={"workbench.startupEditor":"readme"};c&&(s||(s={v:1}),s.idx=l||"latest");const C=e.searchParams.get("editSessionId")??void 0;e.searchParams.delete("editSessionId"),window.history.replaceState(void 0,document.title,e.toString());let I={configurationDefaults:{"workbench.startupEditor":"none","remoteHub.richNavigation.enabled":!0,"extensions.experimental.affinity":{"ms-vscode.remote-repositories":1,"GitHub.remotehub":1,"GitHub.vscode-pull-request-github":1,"vscode.github-authentication":1,"vscode.typescript-language-features":1,"vscode.git-base":1,"ms-vscode.anycode":1,"ms-vscode.vscode-python-web-wasm":1,"ms-azuretools.vscode-azurestaticwebapps":1,"eamodio.gitlens-insiders":1,"eamodio.gitlens":1},...f},_tarballProxyEndpoints:{"github.com":`https://${"stable"===r?"vscode.dev":"insiders.vscode.dev"}/indexes/github2/{owner}/{repo}/{sha}`},editSessionId:C,defaultLayout:i,commands:[{id:"_remotehub.getTarballProxyEndpoints",handler:()=>({"github.com":`https://${"stable"===r?"vscode.dev":"insiders.vscode.dev"}/indexes/github2/{owner}/{repo}/{sha}`})}]},b={};return"codetour"===a&&(I={...I,configurationDefaults:{...I.configurationDefaults,"workbench.startupEditor":"none"},enabledExtensions:["vsls-contrib.codetour"]},b={...b,openUri:{authority:"vsls-contrib.codetour",path:"/startDefaultTour"}}),{workspace:{folderUri:o.from({scheme:"vscode-vfs",authority:Me("github",s),path:`/${h}/${d}`})},workbenchOptions:I,onDidCreateWorkbench:b}}}Mt.RX=/^\/(?<service>github|codetour)(?<indexed>\+idx=?(?<idx>latest|[0-9a-fA-F]{40})?)?\/(?<owner>[^/]+)\/(?<repo>[^/?#]+)(?:|\.git|\/tree\/(?<tree>.+)|\/blob\/(?<blob>.+)|\/commit\/(?<commit>[0-9a-f]{40})|\/pull\/(?<pull>[0-9]+))?/i;async function qt(e,t,r,o){const n=await e.request(`GET /repos/{owner}/{repo}/git/extract-ref/${o??"HEAD"}`,{owner:t,repo:r});return[t,r]=n.data.name_with_owner.split("/"),o?{owner:t,repo:r,ref:{type:Pe.Tree,id:n.data.ref},path:n.data.path}:{owner:t,repo:r}}te(new Mt),te(new class extends Mt{constructor(){super(...arguments),this.path="codetour",this.additionalBuiltinExtensions=["GitHub.vscode-pull-request-github","vsls-contrib.codetour"]}}),Ne("github",new class{resolveRemoteHubWorkspace(e,t){const r=new URL(document.location.href);let o=new URLSearchParams(e.query).get("vscode-experience")??"github";switch(void 0!==t&&("latest"===t.idx?o+="+idx":Oe(t.idx)&&(o+=`+idx=${t.idx}`)),r.pathname=`/${o}${e.path}`,t?.ref?.type){case Pe.PullRequest:r.pathname+=`/pull/${t.ref.id}`;break;case Pe.Tree:r.pathname+=`/tree/${t.ref.id}`;break;case Pe.Commit:r.pathname+=`/commit/${t.ref.id}`}return r.toString()}}),Y(new Ee("github.com","github")),Y(new class{redirect(e){const t=e.searchParams.get("from");if(null===t)return;const r=new URL(e.toString());return r.searchParams.delete("from"),"open"===t&&(r.pathname="/github"+r.pathname),r}});Y(new class{redirect(e){const t=e.searchParams.get("idx");if(null===t)return;const r=/\/(?<service>[^/]+)\/(?<rest>.*)/.exec(e.pathname);if(!r?.groups)return;const o=new URL(e.toString());return o.searchParams.delete("idx"),""===t||"latest"===t?o.pathname=`/${r.groups.service}+idx/${r.groups.rest}`:/^[0-9a-f]{40}$/i.exec(t)&&(o.pathname=`/${r.groups.service}+idx=${t}/${r.groups.rest}`),o}});class $t{constructor(){this.path="editor/liveshare",this.additionalBuiltinExtensions=["MS-vsliveshare.vsliveshare"]}async route({url:e}){const t=$t.RX.exec(e.pathname);if(!t?.groups?.sessionId)return;const r=new URLSearchParams(e.searchParams);return r.set("sessionId",t.groups.sessionId),{workspace:{workspaceUri:o.from({scheme:"vsls",authority:"",path:"/Live Share.code-workspace",query:r.toString()})},workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none"},enabledExtensions:this.additionalBuiltinExtensions},onWillDisposeWorkbench:{runCommands:[{command:"liveshare.workbench.dispose",args:[]}]}}}}$t.RX=/^\/editor\/liveshare\/(?<sessionId>[^/]+)/i;te(new $t),Y({redirect(e){if(!/^\/liveshare\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/editor${e.pathname}`,t}}),oe(new class{resolveWorkspace(e){if(!ne(e))return;const t=e.folderUri;if("vsls"===t.scheme&&""===t.authority&&"/"===t.path){const e=new URL(document.location.href);return e.pathname="/liveshare",e.toString()}if("vsls"!==t.scheme||""!==t.authority||"/Live Share.code-workspace"!==t.path)return;const r=new URLSearchParams(t.query).get("sessionId");if(!r)return;const o=new URL(document.location.href);return o.pathname=`/liveshare/${r}`,o.toString()}});const Ut="https://arcade.makecode.com";class Lt{constructor(){this.path="edu/makecode",this.additionalBuiltinExtensions=[{id:"ms-edu.pxt-vscode-web",preRelease:!0}]}async route({url:e}){const t=Lt.routeRegex.exec(e.pathname);if(!t)return;const r=[],n=t.groups?.projectId;return n&&(r.push({command:"makecodeActions.focus",args:[]}),r.push({command:"makecode.importUrl",args:[n]})),{workspace:{workspaceUri:o.from({scheme:"tmp",path:"/default.code-workspace"})},workbenchOptions:{enabledExtensions:this.additionalBuiltinExtensions[0]?[this.additionalBuiltinExtensions[0].id]:[],configurationDefaults:{"workbench.startupEditor":"none"},homeIndicator:{icon:"smiley",title:"Microsoft MakeCode Arcade",href:Ut},windowIndicator:{onDidChange:()=>({dispose:()=>{}}),label:"MakeCode Arcade",tooltip:he.MakeCodePrompt.toString()},additionalTrustedDomains:[Ut]},onDidCreateWorkbench:{runCommands:r}}}}Lt.routeRegex=/^\/edu\/makecode(\/(?<projectId>(S?\d{4}[\d\-]+|_[a-zA-Z0-9]{10,}))\/?)?$/i,te(new Lt),Y({redirect(e){if(!/^\/makecode\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/edu${e.pathname}`,t}});class Nt{constructor(){this.path="editor/marketplace",this.additionalBuiltinExtensions=["ms-vscode.vscode-marketplace-extension-browser"]}async route({url:e}){const t=Nt.RX.exec(e.pathname);if(t?.groups)return{workspace:{folderUri:o.from({scheme:"vscode-marketplace",authority:"",path:`/${t.groups.owner}/${t.groups.repo}/${t.groups.version}`})},workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none"},enabledExtensions:this.additionalBuiltinExtensions},onDidCreateWorkbench:{openUri:{authority:this.additionalBuiltinExtensions[0],path:"/open"}}}}}Nt.RX=/^\/editor\/marketplace\/(?<owner>[^/]+)\/(?<repo>[^/]+)\/(?<version>\d+\.\d+\.\d+(-.*)?)$/i,te(new Nt),Y({redirect(e){if(!/^\/marketplace\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/editor${e.pathname}`,t}});class Dt{constructor(){this.path="editor/theme",this.additionalBuiltinExtensions=["ms-vscode.theme-tester"]}async route({url:e}){if(Dt.RX.exec(e.pathname))return{workspace:{folderUri:o.from({scheme:"vscode-theme-tester",authority:"",path:"/"})},workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none"},enabledExtensions:this.additionalBuiltinExtensions},onDidCreateWorkbench:{openUri:{authority:this.additionalBuiltinExtensions[0],path:"/open"}}}}}Dt.RX=/^\/editor\/theme\//i,te(new Dt),Y({redirect(e){if(!/^\/theme\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/editor${e.pathname}`,t}});const Ht=new Uint8Array(16);const Ft=[];for(let e=0;e<256;++e)Ft.push((e+256).toString(16).slice(1));function zt(e,t=0){return(Ft[e[t+0]]+Ft[e[t+1]]+Ft[e[t+2]]+Ft[e[t+3]]+"-"+Ft[e[t+4]]+Ft[e[t+5]]+"-"+Ft[e[t+6]]+Ft[e[t+7]]+"-"+Ft[e[t+8]]+Ft[e[t+9]]+"-"+Ft[e[t+10]]+Ft[e[t+11]]+Ft[e[t+12]]+Ft[e[t+13]]+Ft[e[t+14]]+Ft[e[t+15]]).toLowerCase()}const jt=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){e=e||{};const o=e.random??e.rng?.()??crypto.getRandomValues(Ht);if(o.length<16)throw new Error("Random bytes length must be >= 16");if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t){if((r=r||0)<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=o[e];return t}return zt(o)}(e,t,r):crypto.randomUUID()};class Bt{constructor(){this.path="editor/profile",this.additionalBuiltinExtensions=[]}async route({url:e,quality:t}){const r=Bt.RX.exec(e.pathname),n=r?.groups?.path;if(!n)return;let i="code-oss";switch(t){case"stable":i="vscode";break;case"insider":i="vscode-insiders"}return{workspace:{workspaceUri:o.from({scheme:"tmp",path:`/${jt()}`})},workbenchOptions:{profileToPreview:o.from({scheme:i,authority:"profile",path:`/${n}`})}}}}Bt.RX=/^\/editor\/profile\/(?<path>.+)$/i,te(new Bt),Y({redirect(e){if(!/^\/profile\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/editor${e.pathname}`,t}});te(new class{constructor(){this.path="tsplay",this.additionalBuiltinExtensions=["Orta.tspl"],this.excludeDefaultExtensions=!0,this.scheme="playfs"}async route({url:e,quality:t}){if(e.href.includes("localhost")||"stable"!==t)return{workspace:{folderUri:o.from({scheme:this.scheme,authority:"",path:"/"})},workbenchOptions:{configurationDefaults:{"scm.alwaysShowProviders":!1,"workbench.experimental.sidePanel.enabled":!0},enabledExtensions:this.additionalBuiltinExtensions,defaultLayout:{views:[{id:"ts-playground"}]}},onDidCreateWorkbench:{openUri:{authority:this.additionalBuiltinExtensions[0],path:e.pathname,query:e.search,fragment:e.hash},runCommands:[{command:"workbench.action.focusAuxiliaryBar",args:[]}]},welcomeBanner:{message:"TypeScript Playground in Code (Preview)",actions:[{href:`https://www.typescriptlang.org/play/${e.search}${e.hash}`,label:"Go back to TypeScript Playground"},{href:"https://privacy.microsoft.com/en-us/privacystatement",label:he.Privacy.toString()},{href:"https://www.microsoft.com/en-us/legal/terms-of-use",label:he.TermsofUse.toString()}]}}}});class Kt{constructor(){this.path="power",this.additionalBuiltinExtensions=["microsoft-IsvExpTools.powerplatform-vscode"]}async route({url:e}){const t=Kt.RX1.exec(e.pathname),r=Kt.RX2.exec(e.pathname);if(void 0===t?.groups&&void 0===r?.groups)return;const n=t?.groups?.appName??r?.groups?.appName,i=t?.groups?.entity,s=t?.groups?.entityId;let a=e.search,c="";c=!n||"portal"!==n&&"pages"!==n?"PowerPlatform":"PowerPages";const l=new URLSearchParams(a),h=l.get("enableMultifile"),d=l.get("websiteId")?.replace(/\//g,""),u="true"===h?.toLowerCase()&&d;return{workspace:{workspaceUri:o.from({scheme:"powerplatform-vfs",authority:"",path:!u&&i&&s?`/${i}/${s}/${c}`:`/${d}/${c}`})},workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none","files.autoSave":"off"},enabledExtensions:this.additionalBuiltinExtensions},onDidCreateWorkbench:{runCommands:[{command:"microsoft-powerapps-portals.webExtension.init",args:i&&s?[{appName:n,entity:i,entityId:s,searchParams:a}]:[{appName:n,searchParams:a}]}]}}}}Kt.RX1=/^\/(?<path>power)\/(?<appName>[^/]+)\/?(?<entity>[^/]+)?\/?(?<entityId>[^/?]+)?([?])?(?<queryString>[^#]+)?/i,Kt.RX2=/^\/(?<path>power)\/(?<appName>[^/]+)(?:\/(?<queryString>[^#]+))?/i,te(new Kt),Y({redirect(e){if(!/^\/powerplatform\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=t.pathname.replace(/^\/powerplatform/,"/power"),t}});class Wt{constructor(){this.path="contentmentor",this.additionalBuiltinExtensions=[]}async route({url:e}){if(!Wt.RX.test(e.pathname))return;const t=Wt.ACTION_RX.exec(e.pathname),r=t?.[1],o=e.searchParams.get("url"),n=e.searchParams.get("action");let i;if(o){const e=[`url=${encodeURIComponent(o)}`];!r&&n&&e.push(`action=${encodeURIComponent(n)}`),i={authority:Wt.EXTENSION_ID,path:r?`/${r}`:"/",query:e.join("&")}}return{workspace:Z,workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none"},windowIndicator:{onDidChange:()=>({dispose:()=>{}}),label:"Content Mentor",tooltip:"Content Mentor"},additionalTrustedDomains:["https://*.sharepoint.com"],commands:[{id:Wt.BOOTSTRAP_COMMAND,handler:()=>Wt.bootstrap(i)}]},disableWelcomeBanner:!0,onDidCreateWorkbench:{runCommands:[{command:Wt.BOOTSTRAP_COMMAND,args:[]}]}}}static async bootstrap(e){try{await n.executeCommand("workbench.extensions.installExtension",Wt.EXTENSION_ID)}catch(e){return void console.error(`[contentmentor] failed to install ${Wt.EXTENSION_ID}`,e)}e?await s.openUri(o.from({...e,scheme:await s.getUriScheme(),query:e.query||window.location.href})):await n.executeCommand("workbench.view.extension.content-mentor")}}Wt.RX=/^\/contentmentor(\/|$)/i,Wt.ACTION_RX=/^\/contentmentor\/([^/?]+)/i,Wt.EXTENSION_ID="msft-content.content-mentor",Wt.BOOTSTRAP_COMMAND="_contentmentor.bootstrap",te(new Wt);const Jt={dispose(){}},Vt=()=>Jt;const Gt="ms-edu.vscode-learning",Qt={homepageBase:"https://vscodeedu.com",signInUrl:"https://vscodeedu.com/signin",apiBase:"https://vscodeedu.com"},Yt={homepageBase:"https://vscodeedu.com/beta",signInUrl:"https://vscodeedu.com/beta/signin",apiBase:"https://vscodeedu.com"},Xt={homepageBase:"https://ppe.vscodeedu.com",signInUrl:"https://ppe.vscodeedu.com/signin",apiBase:"https://ppe.vscodeedu.com"};function Zt(e){return"ppe"===e?Xt:"beta"===e?Yt:Qt}const er="requestId",tr="otac",rr="redirectUri",or="codeChallenge",nr="codeVerifier";const ir=e=>e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");function sr(e){return`treehouse.auth.state.${e}`}function ar(){return JSON.stringify({extensionId:"ms-edu.vscode-learning",key:"VSCE_SESSIONTOKEN"})}te(new class{constructor(){this.path="edu",this.additionalBuiltinExtensions=[{id:"ms-vscode.wasm-wasi-core"},{id:"ms-python.python",preRelease:!1},{id:"ms-vscode.remote-repositories",preRelease:!0}],this.excludeDefaultExtensions=!0}async route({url:e,secretStorageProvider:t,githubAuthentication:r}){if(!/^\/edu\/?$/i.test(e.pathname))return;const n=e.searchParams.get("env")?.match(/^(ppe|prod|beta)$/i)?.[0]?.toLowerCase()??"prod",i="ppe"===n,s=i?Xt.apiBase:Qt.apiBase;!!e.searchParams.get("sign-out")?.match(/^(true|1)$/i)?.[0]&&await t.delete(ar()),await this.redirectToHomePageIfNecessary(e,Zt(n).homepageBase);if(!e.searchParams.get("auth")?.match(/^(false|0)$/i)?.[0]){const r=e.searchParams.get(er),o=e.searchParams.get(tr),i=e.searchParams.get("region"),a=Zt(n).signInUrl;r&&o?await async function(e,t,r,o,n){try{if(await e.get(ar()))return;const i=sr(t),s=sessionStorage.getItem(i);if(!s)return void console.error("Invalid request ID for VSCode Edu sign-in flow");sessionStorage.removeItem(i);const a=new URL("api/auth/otac:exchange",n);a.searchParams.set(tr,r),a.searchParams.set(nr,encodeURIComponent(s));const c=await fetch(a.toString(),{method:"POST",mode:"cors",headers:null!==o?{"x-ms-affinity-region":o}:void 0});if(!c.ok)throw new Error(`Unexpected ${c.status} from ${a.toString()}`);const l=await c.text();await e.set(ar(),l)}catch(e){console.error("Error completing VSCode Edu sign-in flow"),console.error(e)}}(t,r,o,i,s):await async function(e,t,r){try{const o=ar();let n=await e.get(o);if(n){const t=function(e){e.startsWith("#")&&(e=e.substring(1));const t=e.split("&"),r={};for(const e of t)if(-1===e.indexOf("="))r[e]="true";else{const t=e.split("=");2==t.length&&(r[t[0]]=t[1])}return r}(r)["account-id"];if(!t)return;const i=function(e){try{var t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(r)}catch(e){return void console.error(e)}}(n);if(i&&i.oid===t)return;await e.delete(o),n=void 0}if(!n){const e=await async function(){const e=crypto.randomUUID(),t=await self.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=ir(btoa(String.fromCharCode(...new Uint8Array(t))));return{codeVerifier:e,codeChallenge:r}}(),r=crypto.randomUUID(),o=new URL(t);o.searchParams.set(rr,window.location.href),o.searchParams.set(er,r),o.searchParams.set(or,e.codeChallenge),sessionStorage.setItem(sr(r),e.codeVerifier),window.location.href=o.toString()}}catch(e){console.error("Error starting VSCode Edu sign-in flow"),console.error(e)}}(t,a,e.hash)}const a=await this.getConfig(s),c=e.searchParams.get("extension")?.match(/^([0-9a-z]{7})$/i)?.[0]?.toLowerCase()??a[`${n}.extension`],l=o.parse(`${s}/extension/${c}/extension`),h=e.searchParams.get("profile")??"default-dark",d=h.includes("/")?h:`${a[`${n}.profile`]??""}/${h}`,u=o.parse(`${s}/profile/${d}.code-profile`),g=await this.getProfileName(u,h);let p,m=e.searchParams.get("workspace-scheme")??"vscode-edu-workspace",f=e.searchParams.get("workspace-path")??"/";const y=e.searchParams.get("courseId"),w=e.searchParams.get("curriculumId"),v={};e.searchParams.forEach((e,t)=>{v[t]=e});const C=e.hash.slice(1),I=[{command:"vscode-learning.handleRouteOptions",args:[v,C]}];if((y||w)&&I.push({command:"workbench.view.extension.learningView",args:[]}),w&&!y){const t=e.searchParams.get("githubRepo");if("string"!=typeof t)throw new Error("Missing githubRepo parameter for curriculum authoring scenario.");await async function(e,t){const[r,o]=t.split("/");if(!r||!o)return console.error("Invalid format for githubRepo: "+t),!1;try{const t=(await e.login(["repo","read:user","user:email","workflow"])).accessToken;if(void 0!==t){const e=new Ot({auth:`token ${t}`}),n=await async function(e,t,r,o){const n=await e.request(`GET /repos/{owner}/{repo}/git/extract-ref/${o??"HEAD"}`,{owner:t,repo:r});return[t,r]=n.data.name_with_owner.split("/"),o?{owner:t,repo:r,ref:{type:Pe.Tree,id:n.data.ref},path:n.data.path}:{owner:t,repo:r}}(e,r,o);return void 0!==n}}catch(e){console.error(e)}return!1}(r,t),m="vscode-vfs",p="github",f=`/${t}`}return{workspace:m?{folderUri:o.from({scheme:m,authority:p,path:f})}:{workspaceUri:o.from({scheme:"tmp",path:`/${jt()}`})},workbenchOptions:{enableWorkspaceTrust:!1,additionalBuiltinExtensions:[l],additionalTrustedDomains:[s],enabledExtensions:[Gt,...this.additionalBuiltinExtensions.map(e=>e.id)],configurationDefaults:{"workbench.startupEditor":"none","vscode-learning.usePPEHost":i,"vscode-learning.env":n},windowIndicator:{onDidChange:Vt,label:"Education",tooltip:"Learn to code"},profile:{name:g,contents:u},commands:this.createCommands(),productConfiguration:{extensionEnabledApiProposals:{[Gt]:["codiconDecoration"]}}},onDidCreateWorkbench:{runCommands:I},onWillDisposeWorkbench:{runCommands:[{command:"vscode-learning.beforeUnload",args:[]}]},disableWelcomeBanner:!0}}createCommands(){return[{id:"vscode-edu.openUrlInSameTab",label:void 0,menu:void 0,handler:async e=>{const t=new URL(e);if(t.origin!==Xt.homepageBase&&t.origin!==Qt.homepageBase)throw new Error(`URL must be of origin ${Xt.homepageBase} or ${Qt.homepageBase}`);window.open(t.toString(),"_self")}}]}async redirectToHomePageIfNecessary(e,t){const r=e.searchParams.get("courseId"),o=e.searchParams.get("curriculumId"),n=e.searchParams.get("projectId"),i=e.searchParams.get("sharedLinkId"),s=n||i;let a=!1;s&&(e.searchParams.get("workspace-scheme")||e.searchParams.get("workspace-path")||(a=!0)),r||s||o||(a=!0),a&&(window.location.href=t,await new Promise(()=>{}))}async getProfileName(e,t){const r=await fetch(e.toString());if(!r.ok)throw new Error(`Unexpected ${r.status} from ${e.toString()}`);const o=(await r.json()).name;return o&&"string"==typeof o?o:t}async getConfig(e){const t=`${e}/api/config`,r=await fetch(t);return r.ok?r.json():{}}});te(new class{constructor(){this.path="editor/treesitter",this.additionalBuiltinExtensions=["jrieken.vscode-tree-sitter-query"],this.excludeDefaultExtensions=!0}async route({url:e,quality:t}){if(e.href.includes("localhost")||"stable"!==t)return{workspace:Z,workbenchOptions:{configurationDefaults:{"scm.alwaysShowProviders":!1},enabledExtensions:this.additionalBuiltinExtensions},onDidCreateWorkbench:{runCommands:[{command:"vscode-treesitter-notebook.new",args:[]}]},welcomeBanner:{message:"Tree-sitter Playground (Preview)",actions:[{href:"https://tree-sitter.github.io/tree-sitter/",label:"Learn more about Tree-sitter"},{href:"https://tree-sitter.github.io/tree-sitter/playground",label:"Go back to Tree-sitter Playground"},{href:"https://privacy.microsoft.com/en-us/privacystatement",label:he.Privacy.toString()},{href:"https://www.microsoft.com/en-us/legal/terms-of-use",label:he.TermsofUse.toString()}]}}}});const cr={homepageBase:"https://studio.discovery.microsoft.com",extensionVsixUri:"https://studio.discovery.microsoft.com/ext"},lr={homepageBase:"https://studio-dev.discovery.microsoft.com",extensionVsixUri:"https://studio-dev.discovery.microsoft.com/ext"},hr={homepageBase:"https://studio-dev2.discovery.microsoft.com",extensionVsixUri:"https://studio-dev2.discovery.microsoft.com/ext"},dr={homepageBase:"https://studio-dev3.discovery.microsoft.com",extensionVsixUri:"https://studio-dev3.discovery.microsoft.com/ext"},ur={homepageBase:"https://studio-staging.discovery.microsoft.com",extensionVsixUri:"https://studio-staging.discovery.microsoft.com/ext"},gr={homepageBase:"https://localhost:8080",extensionVsixUri:"https://localhost:8080/ext"};te(new class{constructor(){this.ExtensionId="ms-discovery.studio",this.path="discovery",this.additionalBuiltinExtensions=[],this.excludeDefaultExtensions=!0}async route({url:e,secretStorageProvider:t}){if(!/^\/discovery\/?$/i.test(e.pathname))return;const r=e.searchParams.get("env")?.match(/^(dev|dev2|dev3|staging|local)$/i)?.[0]?.toLowerCase()??"prod";let n=cr;switch(r){case"staging":n=ur;break;case"local":n=gr;break;case"dev":n=lr;break;case"dev2":n=hr;break;case"dev3":n=dr}const i=e.searchParams.get("workspaceName"),s=e.searchParams.get("projectName"),a=e.searchParams.get("tenantId"),c=e.searchParams.get("subscriptionId"),l=e.searchParams.get("resourceGroupName"),h=e.searchParams.get("apiVersion"),d=e.searchParams.get("featureFlags");if(t&&(i||s||a||c||l||h||d)){const e={workspaceName:i||void 0,projectName:s||void 0,tenantId:a||void 0,subscriptionId:c||void 0,resourceGroupName:l||void 0,apiVersion:h||void 0,featureFlags:d||void 0,environment:r},o=JSON.stringify({extensionId:"ms-discovery.studio",key:"DISCOVERY_STUDIO_CONTEXT"});await t.set(o,JSON.stringify(e))}const u=o.parse(`${n.extensionVsixUri}/resources/Discovery.code-profile`),g=o.parse(n.extensionVsixUri);return{workbenchOptions:{configurationDefaults:{"scm.alwaysShowProviders":!1,"workbench.colorTheme":"Light Modern","workbench.startupEditor":"none"},profile:{name:"Discovery",contents:u},enabledExtensions:[this.ExtensionId],additionalBuiltinExtensions:[g]},onDidCreateWorkbench:{runCommands:[{command:"workbench.action.focusAuxiliaryBar",args:[]}]},disableWelcomeBanner:!0}}});class pr{constructor(e,t){this.secretStorageProvider=e,this.url=t,this.GITHUB_AUTHORIZE_URL="https://github.com/login/oauth/authorize",this.GITHUB_AUTH_EXTENSION_ID="vscode.github-authentication",this.GITHUB_AUTH_SECRET_STORAGE_KEY="github.auth",this.SECRET_STORAGE_PROVIDER_KEY=JSON.stringify({extensionId:this.GITHUB_AUTH_EXTENSION_ID,key:this.GITHUB_AUTH_SECRET_STORAGE_KEY}),this.SESSION_STORAGE_KEY="github.auth"}async tryCompleteAuthExchange(){const e=this.url.searchParams.get("code"),t=sessionStorage.getItem(this.SESSION_STORAGE_KEY);if(!e||!t)return this.url;const r=JSON.parse(t),o=await this.exchangeCodeForAccessToken(e);return void 0!==o&&(await this.persistInSecretStorageProvider(o,r),this.url.searchParams.delete("code"),this.url.searchParams.delete("state"),sessionStorage.removeItem(this.SESSION_STORAGE_KEY),window.history.replaceState(void 0,document.title,this.url.toString())),this.url}async login(e){await this.tryCompleteAuthExchange();const t=await this.getAuthSessions(),r=this.findSessionWithRequestedScopes(t,e);if(void 0!==r)return r;const o=this.url,n=`${this.url.protocol}//${this.url.host}/redirect`,i=new URLSearchParams([["client_id","localhost"===this.url.hostname?"c8d3980f24ffff70fbd6":"01ab8ac9400c4e429b23"],["redirect_uri",n],["scope",e.join(" ")],["state",o.toString()]]);sessionStorage.setItem(this.SESSION_STORAGE_KEY,JSON.stringify(e));const s=new URL(this.GITHUB_AUTHORIZE_URL);return s.search=i.toString(),window.location.href=s.toString(),await new Promise(()=>{})}async persistInSecretStorageProvider(e,t){const r=await this.getAuthSessions(),o={id:jt(),accessToken:e,scopes:t};r.push(o),await this.secretStorageProvider.set(this.SECRET_STORAGE_PROVIDER_KEY,JSON.stringify(r))}findSessionWithRequestedScopes(e,t){function r(e,t){return e.reduce((e,r)=>e&&t.includes(r),!0)}for(const o of e)if(r(t,o.scopes))return o}async getAuthSessions(){let e=await this.secretStorageProvider.get(this.SECRET_STORAGE_PROVIDER_KEY);if(e)try{return JSON.parse(e)}catch(e){console.log(e)}return[]}async exchangeCodeForAccessToken(e){let t;try{const r=`code=${e}`,o=await fetch("/codeExchangeProxyEndpoints/github/login/oauth/access_token",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Content-Length":`${r.toString().length}`},body:r});if(o.ok){t=(await o.json()).access_token}}catch(e){console.error(e)}return t}}const mr="https://login.microsoftonline.com/common/",fr="common",yr=`${mr}discovery/instance?api-version=1.1&authorization_endpoint=`,wr=".ciamlogin.com",vr=".onmicrosoft.com",Cr="openid",Ir="profile",br="offline_access",kr="S256",Sr="N/A",Tr="Not Available",Ar="http://169.254.169.254/metadata/instance/compute",_r=["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"],Er="GET",Pr="POST",xr=[Cr,Ir,br],Or=[...xr,"email"],Rr="Content-Type",Mr="Content-Length",qr="Retry-After",$r="X-AnchorMailbox",Ur="x-ms-request-id",Lr="x-ms-httpver",Nr="active-account-filters",Dr="common",Hr="organizations",Fr="consumers",zr="access_token",jr="xms_cc",Br="id_token",Kr="signin_state",Wr="login_hint",Jr="login",Vr="select_account",Gr="consent",Qr="none",Yr="no_session",Xr="code",Zr="id_token token refresh_token",eo="query",to="fragment",ro="authorization_code",oo="refresh_token",no="Generic",io={ID_TOKEN:"IdToken",ACCESS_TOKEN:"AccessToken",ACCESS_TOKEN_WITH_AUTH_SCHEME:"AccessToken_With_AuthScheme",REFRESH_TOKEN:"RefreshToken"},so="appmetadata",ao="1",co="authority-metadata",lo="config",ho="cache",uo="network",go="hardcoded_values",po=5,mo="server-telemetry",fo=",",yo={BEARER:"Bearer",POP:"pop",SSH:"ssh-cert"},wo="throttling",vo="1",Co="3",Io="4",bo="2",ko="4",So="5",To="0",Ao="1",_o="2",Eo="3",Po="4",xo="pop",Oo="invalid_grant",Ro=483,Mo=600,qo="msal",$o="msal.js.browser",Uo="53ee284d-920a-4b59-9d30-a60315b26836",Lo="ppnbnpeolgkicgegkbkbjmhlideopiji",No="MATS",Do="MicrosoftEntra",Ho="DOM API",Fo="get-token-and-sign-out",zo="PlatformAuthDOMHandler",jo="PlatformAuthExtensionHandler",Bo="Handshake",Ko="HandshakeResponse",Wo="GetToken",Jo="Response",Vo="localStorage",Go="sessionStorage",Qo="memoryStorage",Yo="GET",Xo="POST",Zo="signin",en="signout",tn="request.origin",rn="urlHash",on="request.params",nn="code.verifier",sn="interaction.status",an="request.native",cn="wrapper.sku",ln="wrapper.version",hn=861,dn=862,un=863,gn=865,pn=866,mn=61,fn=961,yn=962,wn=963,vn={861:"acquireTokenRedirect",862:"acquireTokenPopup",863:"ssoSilent",864:"acquireTokenSilent_authCode",865:"handleRedirectPromise",866:"acquireTokenByCode",61:"acquireTokenSilent_silentFlow",961:"logout",962:"logoutPopup",963:"hydrateCache",964:"loadExternalTokens"};var Cn;!function(e){e.Redirect="redirect",e.Popup="popup",e.Silent="silent",e.None="none"}(Cn||(Cn={}));const In={scopes:xr},bn="msal.db",kn=`${bn}.keys`,Sn=0,Tn=1,An=2,_n=3,En=4,Pn=5,xn=[Sn,Pn,En];function On(e){return`See https://aka.ms/msal.js.errors#${e} for details`}class Rn extends Error{constructor(e,t,r,o){const n=r||(e?On(e):"");super(n?`${e}: ${n}`:e),Object.setPrototypeOf(this,Rn.prototype),this.errorCode=e||"",this.errorMessage=n||"",this.subError=o||"",this.correlationId=t,this.name="AuthError"}}function Mn(e,t,r){return new Rn(e,t,r||On(e))}const qn="no_tokens_found",$n="refresh_token_expired",Un="ui_not_allowed",Ln="bad_token",Nn=["interaction_required","consent_required","login_required",Ln,Un,"interrupted_user"],Dn=["message_only","additional_action","basic_action","user_password_expired","consent_required","bad_token","ui_not_allowed","interrupted_user"];class Hn extends Rn{constructor(e,t,r,o,n,i,s,a){super(e,t,r,o),Object.setPrototypeOf(this,Hn.prototype),this.timestamp=n||"",this.traceId=i||"",this.claims=s||"",this.name="InteractionRequiredAuthError",this.errorNo=a}}function Fn(e,t,r){const o=!!e&&Nn.indexOf(e)>-1,n=!!r&&Dn.indexOf(r)>-1,i=!!t&&Nn.some(e=>t.indexOf(e)>-1);return o||i||n}function zn(e,t,r){return new Hn(e,t,r)}const jn=["openid","email","profile","offline_access"];class Bn{constructor(e=[],t){this.originalScopes=e;const r=[...e];r.sort(),this.allScopes=r,this.scopeStr=r.join(" "),this.claims=t,this.scopesToSend=this.getScopesToSend(r),this.clientId=this.getClientId(this.allScopes),this.tenant=this.getTenantId(this.allScopes),this.tenantId=["common","organizations","consumers"].includes(this.tenant)?void 0:this.tenant}getClientId(e){return e.reduce((e,t)=>t.startsWith("VSCODE_CLIENT_ID:")?t.split("VSCODE_CLIENT_ID:")[1]:e,void 0)??"aebc6443-996d-45c2-90f0-388ff96faa56"}getTenantId(e){return e.reduce((e,t)=>t.startsWith("VSCODE_TENANT:")?t.split("VSCODE_TENANT:")[1]:e,void 0)??"organizations"}getScopesToSend(e){const t=e.filter(e=>!e.startsWith("VSCODE_")),r=new Set(t);for(const e of jn)r.delete(e);return r.size||t.push("User.Read"),t}}class Kn extends Rn{constructor(e,t,r){super(e,t,r),this.name="ClientAuthError",Object.setPrototypeOf(this,Kn.prototype)}}function Wn(e,t,r){return new Kn(e,t,r)}const Jn="client_info_decoding_error",Vn="token_parsing_error",Gn="null_or_empty_token",Qn="endpoints_resolution_error",Yn="network_error",Xn="invalid_state",Zn="state_not_found",ei="empty_input_scopeset",ti="no_account_in_silent_request",ri="invalid_cache_environment",oi="no_account_found",ni="no_crypto_object",ii="token_refresh_required",si="key_id_missing",ai="method_not_implemented";class ci extends Rn{constructor(e,t,r){super(e,t,r),this.name="JoseHeaderError",Object.setPrototypeOf(this,ci.prototype)}}function li(e,t){return new ci(e,t)}class hi{constructor(e){this.typ=e.typ,this.alg=e.alg,this.kid=e.kid}static getShrHeaderString(e){if(!e.kid)throw li("missing_kid_error","");if(!e.alg)throw li("missing_alg_error","");const t=new hi({typ:e.typ||xo,kid:e.kid,alg:e.alg});return JSON.stringify(t)}}const di="standardInteractionClientGetDiscoveredAuthority",ui="nativeInteractionClientAcquireToken",gi="acquireTokenBySilentIframe",pi="initializeBaseRequest",mi="silentIframeClientTokenHelper",fi="silentHandlerInitiateAuthRequest",yi="silentHandlerMonitorIframeForHash",wi="standardInteractionClientCreateAuthCodeClient",vi="standardInteractionClientGetClientConfiguration",Ci="standardInteractionClientInitializeAuthorizationRequest",Ii="handleResponseEar",bi="handleResponsePlatformBroker",ki="handleResponseCode",Si="deserializeResponse",Ti="removeHiddenIframe",Ai="generatePkceCodes",_i="generateHKDF",Ei="decrypt",Pi="generateEarKey";function xi(e){return encodeURIComponent(Ri(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"))}function Oi(e){return Mi(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ri(e){return Mi((new TextEncoder).encode(e))}function Mi(e){const t=Array.from(e,e=>String.fromCodePoint(e)).join("");return btoa(t)}function qi(e){return`See https://aka.ms/msal.js.errors#${e} for details`}class $i extends Rn{constructor(e,t,r){super(e,t,qi(e),r),Object.setPrototypeOf(this,$i.prototype),this.name="BrowserAuthError"}}function Ui(e,t,r){return new $i(e,t,r)}const Li="pkce_not_created",Ni="ear_jwk_empty",Di="crypto_nonexistent",Hi="empty_navigate_uri",Fi="no_state_in_hash",zi="unable_to_parse_state",ji="user_cancelled",Bi="silent_logout_unsupported",Ki="non_browser_environment",Wi="database_not_open",Ji="no_network_connectivity",Vi="failed_to_parse_response",Gi="crypto_key_not_found",Qi="database_unavailable",Yi="native_connection_not_established",Xi="uninitialized_public_client_application",Zi="failed_to_decrypt_ear_response",es="timed_out";function ts(e){return(new TextDecoder).decode(rs(e))}function rs(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw Ui("invalid_base64_string","")}const r=atob(t);return Uint8Array.from(r,e=>e.codePointAt(0)||0)}const os="AES-GCM",ns="HKDF",is="SHA-256",ss=new Uint8Array([1,0,1]),as="0123456789abcdef",cs=new Uint32Array(1),ls="raw",hs="encrypt",ds="decrypt",us={name:"RSASSA-PKCS1-v1_5",hash:is,modulusLength:2048,publicExponent:ss};async function gs(e){const t=(new TextEncoder).encode(e);return window.crypto.subtle.digest(is,t)}function ps(e){return window.crypto.getRandomValues(e)}function ms(){return window.crypto.getRandomValues(cs),cs[0]}function fs(){const e=Date.now(),t=1024*ms()+(1023&ms()),r=new Uint8Array(16),o=Math.trunc(t/2**30),n=t&2**30-1,i=ms();r[0]=e/2**40,r[1]=e/2**32,r[2]=e/2**24,r[3]=e/65536,r[4]=e/256,r[5]=e,r[6]=112|o>>>8,r[7]=o,r[8]=128|n>>>24,r[9]=n>>>16,r[10]=n>>>8,r[11]=n,r[12]=i>>>24,r[13]=i>>>16,r[14]=i>>>8,r[15]=i;let s="";for(let e=0;e<r.length;e++)s+=as.charAt(r[e]>>>4),s+=as.charAt(15&r[e]),3!==e&&5!==e&&7!==e&&9!==e||(s+="-");return s}async function ys(e){return window.crypto.subtle.exportKey("jwk",e)}async function ws(){const e=await Cs(),t={alg:"dir",kty:"oct",k:Oi(new Uint8Array(e))};return Ri(JSON.stringify(t))}async function vs(e,t){const r=t.split(".");if(5!==r.length)throw Ui(Zi,"","jwe_length");const o=await async function(e){const t=ts(e),r=rs(JSON.parse(t).k);return window.crypto.subtle.importKey(ls,r,os,!1,[ds])}(e).catch(()=>{throw Ui(Zi,"","import_key")});try{const e=(new TextEncoder).encode(r[0]),t=rs(r[2]),n=rs(r[3]),i=rs(r[4]),s=8*i.byteLength,a=new Uint8Array(n.length+i.length);a.set(n),a.set(i,n.length);const c=await window.crypto.subtle.decrypt({name:os,iv:t,tagLength:s,additionalData:e},o,a);return(new TextDecoder).decode(c)}catch(e){throw Ui(Zi,"","decrypt")}}async function Cs(){const e=await window.crypto.subtle.generateKey({name:os,length:256},!0,[hs,ds]);return window.crypto.subtle.exportKey(ls,e)}async function Is(e){return window.crypto.subtle.importKey(ls,e,ns,!1,["deriveKey"])}async function bs(e,t,r){return window.crypto.subtle.deriveKey({name:ns,salt:t,hash:is,info:(new TextEncoder).encode(r)},e,{name:os,length:256},!1,[hs,ds])}async function ks(e,t,r){const o=(new TextEncoder).encode(t),n=window.crypto.getRandomValues(new Uint8Array(16)),i=await bs(e,n,r),s=await window.crypto.subtle.encrypt({name:os,iv:new Uint8Array(12)},i,o);return{data:Oi(new Uint8Array(s)),nonce:Oi(n)}}async function Ss(e,t,r,o){const n=rs(o),i=await bs(e,rs(t),r),s=await window.crypto.subtle.decrypt({name:os,iv:new Uint8Array(12)},i,n);return(new TextDecoder).decode(s)}class Ts{constructor(){this.dbName=bn,this.version=1,this.tableName=kn,this.dbOpen=!1}async open(){return new Promise((e,t)=>{const r=window.indexedDB.open(this.dbName,this.version);r.addEventListener("upgradeneeded",e=>{e.target.result.createObjectStore(this.tableName)}),r.addEventListener("success",t=>{const r=t;this.db=r.target.result,this.dbOpen=!0,e()}),r.addEventListener("error",()=>t(Ui(Qi,"")))})}closeConnection(){const e=this.db;e&&this.dbOpen&&(e.close(),this.dbOpen=!1)}async validateDbIsOpen(){if(!this.dbOpen)return this.open()}async getItem(e){return await this.validateDbIsOpen(),new Promise((t,r)=>{if(!this.db)return r(Ui(Wi,""));const o=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).get(e);o.addEventListener("success",e=>{const r=e;this.closeConnection(),t(r.target.result)}),o.addEventListener("error",e=>{this.closeConnection(),r(e)})})}async setItem(e,t){return await this.validateDbIsOpen(),new Promise((r,o)=>{if(!this.db)return o(Ui(Wi,""));const n=this.db.transaction([this.tableName],"readwrite").objectStore(this.tableName).put(t,e);n.addEventListener("success",()=>{this.closeConnection(),r()}),n.addEventListener("error",e=>{this.closeConnection(),o(e)})})}async removeItem(e){return await this.validateDbIsOpen(),new Promise((t,r)=>{if(!this.db)return r(Ui(Wi,""));const o=this.db.transaction([this.tableName],"readwrite").objectStore(this.tableName).delete(e);o.addEventListener("success",()=>{this.closeConnection(),t()}),o.addEventListener("error",e=>{this.closeConnection(),r(e)})})}async getKeys(){return await this.validateDbIsOpen(),new Promise((e,t)=>{if(!this.db)return t(Ui(Wi,""));const r=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).getAllKeys();r.addEventListener("success",t=>{const r=t;this.closeConnection(),e(r.target.result)}),r.addEventListener("error",e=>{this.closeConnection(),t(e)})})}async containsKey(e){return await this.validateDbIsOpen(),new Promise((t,r)=>{if(!this.db)return r(Ui(Wi,""));const o=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).count(e);o.addEventListener("success",e=>{const r=e;this.closeConnection(),t(1===r.target.result)}),o.addEventListener("error",e=>{this.closeConnection(),r(e)})})}async deleteDatabase(){return this.db&&this.dbOpen&&this.closeConnection(),new Promise((e,t)=>{const r=window.indexedDB.deleteDatabase(bn),o=setTimeout(()=>t(!1),200);r.addEventListener("success",()=>(clearTimeout(o),e(!0))),r.addEventListener("blocked",()=>(clearTimeout(o),e(!0))),r.addEventListener("error",()=>(clearTimeout(o),t(!1)))})}}class As{constructor(){this.cache=new Map}async initialize(){}getItem(e){return this.cache.get(e)||null}getUserData(e){return this.getItem(e)}setItem(e,t){this.cache.set(e,t)}async setUserData(e,t){this.setItem(e,t)}removeItem(e){this.cache.delete(e)}getKeys(){const e=[];return this.cache.forEach((t,r)=>{e.push(r)}),e}containsKey(e){return this.cache.has(e)}clear(){this.cache.clear()}decryptData(){return Promise.resolve(null)}}class _s{constructor(e){this.inMemoryCache=new As,this.indexedDBCache=new Ts,this.logger=e}handleDatabaseAccessError(e,t){if(!(e instanceof $i&&e.errorCode===Qi))throw e;this.logger.error("1wx7zz",t)}async getItem(e,t){const r=this.inMemoryCache.getItem(e);if(!r)try{return this.logger.verbose("0naxpl",t),await this.indexedDBCache.getItem(e)}catch(e){this.handleDatabaseAccessError(e,t)}return r}async setItem(e,t,r){this.inMemoryCache.setItem(e,t);try{await this.indexedDBCache.setItem(e,t)}catch(e){this.handleDatabaseAccessError(e,r)}}async removeItem(e,t){this.inMemoryCache.removeItem(e);try{await this.indexedDBCache.removeItem(e)}catch(e){this.handleDatabaseAccessError(e,t)}}async getKeys(e){const t=this.inMemoryCache.getKeys();if(0===t.length)try{return this.logger.verbose("1iqrbq",e),await this.indexedDBCache.getKeys()}catch(t){this.handleDatabaseAccessError(t,e)}return t}async containsKey(e,t){const r=this.inMemoryCache.containsKey(e);if(!r)try{return this.logger.verbose("03zl2j",t),await this.indexedDBCache.containsKey(e)}catch(e){this.handleDatabaseAccessError(e,t)}return r}clearInMemory(e){this.logger.verbose("03r21p",e),this.inMemoryCache.clear(),this.logger.verbose("0uksk1",e)}async clearPersistent(e){try{this.logger.verbose("0rdqut",e);const t=await this.indexedDBCache.deleteDatabase();return t&&this.logger.verbose("149ouc",e),t}catch(t){return this.handleDatabaseAccessError(t,e),!1}}}class Es{constructor(e,t,r){this.logger=e,function(e){if(!window)throw Ui(Ki,"");if(!window.crypto)throw Ui(Di,"");if(!e&&!window.crypto.subtle)throw Ui(Di,"","crypto_subtle_undefined")}(r??!1),this.cache=new _s(this.logger),this.performanceClient=t}createNewGuid(){return fs()}base64Encode(e){return Ri(e)}base64Decode(e){return ts(e)}base64UrlEncode(e){return xi(e)}encodeKid(e){return this.base64UrlEncode(JSON.stringify({kid:e}))}async getPublicKeyThumbprint(e){const t=this.performanceClient?.startMeasurement("cryptoOptsGetPublicKeyThumbprint",e.correlationId),r=await async function(e,t){return window.crypto.subtle.generateKey(us,e,t)}(Es.EXTRACTABLE,Es.POP_KEY_USAGES),o=await ys(r.publicKey),n=Ps({e:o.e,kty:o.kty,n:o.n}),i=await this.hashString(n),s=await ys(r.privateKey),a=await async function(e,t,r){return window.crypto.subtle.importKey("jwk",e,us,t,r)}(s,!1,["sign"]);return await this.cache.setItem(i,{privateKey:a,publicKey:r.publicKey,requestMethod:e.resourceRequestMethod,requestUri:e.resourceRequestUri},e.correlationId),t&&t.end({success:!0}),i}async removeTokenBindingKey(e,t){await this.cache.removeItem(e,t);if(await this.cache.containsKey(e,t))throw Wn("binding_key_not_removed",t)}async clearKeystore(e){this.cache.clearInMemory(e);try{return await this.cache.clearPersistent(e),!0}catch(t){return t instanceof Error?this.logger.error(`1owpn8 ${t.message}`,e):this.logger.error("0yrmwo",e),!1}}async signJwt(e,t,r,o){const n=this.performanceClient?.startMeasurement("cryptoOptsSignJwt",o),i=await this.cache.getItem(t,o||"");if(!i)throw Ui(Gi,o||"");const s=await ys(i.publicKey),a=Ps(s),c=xi(JSON.stringify({kid:t})),l=xi(hi.getShrHeaderString({...r?.header,alg:s.alg,kid:c}));e.cnf={jwk:JSON.parse(a)};const h=`${l}.${xi(JSON.stringify(e))}`,d=(new TextEncoder).encode(h),u=await async function(e,t){return window.crypto.subtle.sign(us,e,t)}(i.privateKey,d),g=`${h}.${Oi(new Uint8Array(u))}`;return n&&n.end({success:!0}),g}async hashString(e){return async function(e){const t=await gs(e);return Oi(new Uint8Array(t))}(e)}}function Ps(e){return JSON.stringify(e,Object.keys(e).sort())}function xs(e,t){if(e){if(t.resource&&(Os(t.extraParameters)||Os(t.extraQueryParameters)))throw Wn("misplaced_resource_parameter",t.correlationId||"");if(!t.resource)throw Wn("resource_parameter_required",t.correlationId||"")}}function Os(e){return!!e&&Object.prototype.hasOwnProperty.call(e,"resource")}Es.POP_KEY_USAGES=["sign","verify"],Es.EXTRACTABLE=!0;const Rs={createNewGuid:()=>{throw Wn(ai,"")},base64Decode:()=>{throw Wn(ai,"")},base64Encode:()=>{throw Wn(ai,"")},base64UrlEncode:()=>{throw Wn(ai,"")},encodeKid:()=>{throw Wn(ai,"")},async getPublicKeyThumbprint(){throw Wn(ai,"")},async removeTokenBindingKey(){throw Wn(ai,"")},async clearKeystore(){throw Wn(ai,"")},async signJwt(){throw Wn(ai,"")},async hashString(){throw Wn(ai,"")}},Ms=0,qs=1,$s=2,Us=3;class Ls extends Rn{constructor(e,t){super(e,t),this.name="ClientConfigurationError",Object.setPrototypeOf(this,Ls.prototype)}}function Ns(e,t){return new Ls(e,t)}class Ds{static isEmptyObj(e){if(e)try{const t=JSON.parse(e);return 0===Object.keys(t).length}catch(e){}return!0}static startsWith(e,t){return 0===e.indexOf(t)}static endsWith(e,t){return e.length>=t.length&&e.lastIndexOf(t)===e.length-t.length}static queryStringToObject(e){const t={},r=e.split("&"),o=e=>decodeURIComponent(e.replace(/\+/g," "));return r.forEach(e=>{if(e.trim()){const[r,n]=e.split(/=(.+)/g,2);r&&n&&(t[o(r)]=o(n))}}),t}static trimArrayEntries(e){return e.map(e=>e.trim())}static removeEmptyStringsFromArray(e){return e.filter(e=>!!e)}static jsonParseHelper(e){try{return JSON.parse(e)}catch(e){return null}}}const Hs="url_parse_error",Fs="pkce_params_missing",zs="invalid_cloud_discovery_metadata",js="missing_ssh_jwk",Bs="issuer_validation_failed";class Ks{get urlString(){return this._urlString}constructor(e,t){if(this._urlString=e,this.correlationId=t,!this._urlString)throw Ns("empty_url_error",t);e.includes("#")||(this._urlString=Ks.canonicalizeUri(e))}static canonicalizeUri(e){if(e){let t=e.toLowerCase();return Ds.endsWith(t,"?")?t=t.slice(0,-1):Ds.endsWith(t,"?/")&&(t=t.slice(0,-2)),Ds.endsWith(t,"/")||(t+="/"),t}return e}validateAsUri(){let e;try{e=this.getUrlComponents()}catch(e){throw Ns(Hs,this.correlationId)}if(!e.HostNameAndPort||!e.PathSegments)throw Ns(Hs,this.correlationId);if(!e.Protocol||"https:"!==e.Protocol.toLowerCase())throw Ns("authority_uri_insecure",this.correlationId)}static appendQueryString(e,t){return t?e.indexOf("?")<0?`${e}?${t}`:`${e}&${t}`:e}static removeHashFromUrl(e){return Ks.canonicalizeUri(e.split("#")[0])}replaceTenantPath(e){const t=this.getUrlComponents(),r=t.PathSegments;return!e||0===r.length||r[0]!==Dr&&r[0]!==Hr||(r[0]=e),Ks.constructAuthorityUriFromObject(t,this.correlationId)}getUrlComponents(){const e=RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"),t=this.urlString.match(e);if(!t)throw Ns(Hs,this.correlationId);const r={Protocol:t[1],HostNameAndPort:t[4],AbsolutePath:t[5],QueryString:t[7]};let o=r.AbsolutePath.split("/");return o=o.filter(e=>e&&e.length>0),r.PathSegments=o,r.QueryString&&r.QueryString.endsWith("/")&&(r.QueryString=r.QueryString.substring(0,r.QueryString.length-1)),r}static getDomainFromUrl(e,t){const r=RegExp("^([^:/?#]+://)?([^/?#]*)"),o=e.match(r);if(!o)throw Ns(Hs,t);return o[2]}static getAbsoluteUrl(e,t,r){if("/"===e[0]){const o=new Ks(t,r).getUrlComponents();return o.Protocol+"//"+o.HostNameAndPort+e}return e}static constructAuthorityUriFromObject(e,t){return new Ks(e.Protocol+"//"+e.HostNameAndPort+"/"+e.PathSegments.join("/"),t)}}const Ws={endpointMetadata:[{host:"login.microsoftonline.com"},{host:"login.chinacloudapi.cn",issuerHost:"login.partner.microsoftonline.cn"},{host:"login.microsoftonline.us"},{host:"login.sovcloud-identity.fr"},{host:"login.sovcloud-identity.de"},{host:"login.sovcloud-identity.sg"}].reduce((e,{host:t,issuerHost:r})=>(e[t]=function(e,t){return{token_endpoint:`https://${e}/{tenantid}/oauth2/v2.0/token`,jwks_uri:`https://${e}/{tenantid}/discovery/v2.0/keys`,issuer:`https://${t}/{tenantid}/v2.0`,authorization_endpoint:`https://${e}/{tenantid}/oauth2/v2.0/authorize`,end_session_endpoint:`https://${e}/{tenantid}/oauth2/v2.0/logout`}}(t,r||t),e),{}),instanceDiscoveryMetadata:{metadata:[{preferred_network:"login.microsoftonline.com",preferred_cache:"login.windows.net",aliases:["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"]},{preferred_network:"login.partner.microsoftonline.cn",preferred_cache:"login.partner.microsoftonline.cn",aliases:["login.partner.microsoftonline.cn","login.chinacloudapi.cn"]},{preferred_network:"login.microsoftonline.de",preferred_cache:"login.microsoftonline.de",aliases:["login.microsoftonline.de"]},{preferred_network:"login.microsoftonline.us",preferred_cache:"login.microsoftonline.us",aliases:["login.microsoftonline.us","login.usgovcloudapi.net"]},{preferred_network:"login-us.microsoftonline.com",preferred_cache:"login-us.microsoftonline.com",aliases:["login-us.microsoftonline.com"]},{preferred_network:"login.sovcloud-identity.fr",preferred_cache:"login.sovcloud-identity.fr",aliases:["login.sovcloud-identity.fr"]},{preferred_network:"login.sovcloud-identity.de",preferred_cache:"login.sovcloud-identity.de",aliases:["login.sovcloud-identity.de"]},{preferred_network:"login.sovcloud-identity.sg",preferred_cache:"login.sovcloud-identity.sg",aliases:["login.sovcloud-identity.sg"]},{preferred_network:"login.windows-ppe.net",preferred_cache:"login.windows-ppe.net",aliases:["login.windows-ppe.net","sts.windows-ppe.net","login.microsoft-ppe.com"]}]}},Js=Ws.endpointMetadata,Vs=Ws.instanceDiscoveryMetadata,Gs=new Set;function Qs(e,t,r,o,n){if(e.trace(`1bmquz ${n}`,t),r&&o){const i=Ys(o,r);if(i)return e.trace(`1fotbt ${n}`,t),i.aliases;e.trace(`14avvj ${n}`,t)}return null}function Ys(e,t){for(let r=0;r<e.length;r++){const o=e[r];if(o.aliases.includes(t))return o}return null}Vs.metadata.forEach(e=>{e.aliases.forEach(e=>{Gs.add(e)})});const Xs="AAD",Zs="OIDC",ea="EAR",ta="none";const ra="networkClientSendPostRequestAsync",oa="refreshTokenClientAcquireTokenWithCachedRefreshToken",na="getAuthCodeUrl",ia="handleCodeResponseFromServer",sa="popTokenGenerateCnf",aa="handleServerTokenResponse",ca="authorityUpdateMetadataWithRegionalInformation",la="regionDiscoveryGetRegionFromIMDS",ha=(e,t,r,o,n)=>(...i)=>{r.trace(`1plfzx ${t}`,n);const s=o.startMeasurement(t,n);n&&o.incrementFields({[`ext.${t}CallCount`]:1},n);try{const o=e(...i);return s.end({success:!0}),r.trace(`1g8n6a ${t}`,n),o}catch(e){r.trace(`0cfd8i ${t}`,n);try{r.trace(JSON.stringify(e),n)}catch(e){r.trace("00dty7",n)}throw s.end({success:!1},e),e}},da=(e,t,r,o,n)=>(...i)=>{r.trace(`1plfzx ${t}`,n);const s=o.startMeasurement(t,n);return n&&o.incrementFields({[`ext.${t}CallCount`]:1},n),e(...i).then(e=>(r.trace(`1g8n6a ${t}`,n),s.end({success:!0}),e)).catch(e=>{r.trace(`0cfd8i ${t}`,n);try{r.trace(JSON.stringify(e),n)}catch(e){r.trace("00dty7",n)}throw s.end({success:!1},e),e})};class ua{constructor(e,t,r,o){this.networkInterface=e,this.logger=t,this.performanceClient=r,this.correlationId=o}async detectRegion(e,t){let r=e;if(r)t.region_source=Co;else{const e=ua.IMDS_OPTIONS;try{const o=await da(this.getRegionFromIMDS.bind(this),la,this.logger,this.performanceClient,this.correlationId)("2021-02-01",e);if(200===o.status&&(r=o.body?.location,r&&(t.region_source=Io)),400===o.status){const o=await da(this.getCurrentVersion.bind(this),"regionDiscoveryGetCurrentVersion",this.logger,this.performanceClient,this.correlationId)(e);if(!o)return t.region_source=vo,null;const n=await da(this.getRegionFromIMDS.bind(this),la,this.logger,this.performanceClient,this.correlationId)(o,e);200===n.status&&(r=n.body?.location,r&&(t.region_source=Io))}}catch(e){return t.region_source=vo,null}}return r||(t.region_source=vo),r||null}async getRegionFromIMDS(e,t){return this.networkInterface.sendGetRequestAsync(`${Ar}?api-version=${e}`,t,2e3)}async getCurrentVersion(e){try{const t=await this.networkInterface.sendGetRequestAsync(`${Ar}?format=json`,e);return 400===t.status&&t.body&&t.body["newest-versions"]&&t.body["newest-versions"].length>0?t.body["newest-versions"][0]:null}catch(e){return null}}}function ga(e,t,r){const o=function(e,t){if(!e)throw Wn(Gn,t);const r=/^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/.exec(e);if(!r||r.length<4)throw Wn(Vn,t);return r[2]}(e,r);try{const e=t(o);return JSON.parse(e)}catch(e){throw Wn(Vn,r)}}function pa(e){if(!e.signin_state)return!1;const t=["kmsi","dvc_dmjd"];return e.signin_state.some(e=>t.includes(e.trim().toLowerCase()))}function ma(){return Math.round((new Date).getTime()/1e3)}function fa(e){return e.getTime()/1e3}function ya(e){return e?new Date(1e3*Number(e)):new Date}function wa(e,t){const r=Number(e)||0;return ma()+t>r}function va(e,t){const r=Number(e)+24*t*60*60*1e3;return Date.now()>r}function Ca(e,t,r,o,n){return{credentialType:io.ID_TOKEN,homeAccountId:e,environment:t,clientId:o,secret:r,realm:n,lastUpdatedAt:Date.now().toString()}}function Ia(e,t,r,o,n,i,s,a,c,l,h,d,u,g,p){const m={homeAccountId:e,credentialType:io.ACCESS_TOKEN,secret:r,cachedAt:ma().toString(),expiresOn:s.toString(),extendedExpiresOn:a.toString(),environment:t,clientId:o,realm:n,target:i,tokenType:d||yo.BEARER,lastUpdatedAt:Date.now().toString()};if(u&&(m.userAssertionHash=u),h&&(m.refreshOn=h.toString()),m.tokenType?.toLowerCase()!==yo.BEARER.toLowerCase())switch(m.credentialType=io.ACCESS_TOKEN_WITH_AUTH_SCHEME,m.tokenType){case yo.POP:const e=ga(r,c,l);if(!e?.cnf?.kid)throw Wn("token_claims_cnf_required_for_signedjwt",l);m.keyId=e.cnf.kid;break;case yo.SSH:m.keyId=g}return p&&Object.keys(p).length>0&&(m.additionalCacheKeyComponents=p),m}function ba(e){return e.hasOwnProperty("homeAccountId")&&e.hasOwnProperty("environment")&&e.hasOwnProperty("credentialType")&&e.hasOwnProperty("clientId")&&e.hasOwnProperty("secret")}function ka(e){return!!e&&(ba(e)&&e.hasOwnProperty("realm")&&e.hasOwnProperty("target")&&(e.credentialType===io.ACCESS_TOKEN||e.credentialType===io.ACCESS_TOKEN_WITH_AUTH_SCHEME))}function Sa(e){return!!e&&(ba(e)&&e.credentialType===io.REFRESH_TOKEN)}function Ta(){return ma()+86400}function Aa(e,t,r){e.authorization_endpoint=t.authorization_endpoint,e.token_endpoint=t.token_endpoint,e.end_session_endpoint=t.end_session_endpoint,e.issuer=t.issuer,e.endpointsFromNetwork=r,e.jwks_uri=t.jwks_uri}function _a(e,t,r){e.aliases=t.aliases,e.preferred_cache=t.preferred_cache,e.preferred_network=t.preferred_network,e.aliasesFromNetwork=r}function Ea(e){return e.expiresAt<=ma()}ua.IMDS_OPTIONS={headers:{Metadata:"true"}};class Pa{constructor(e,t,r,o,n,i,s,a){this.canonicalAuthority=e,this._canonicalAuthority.validateAsUri(),this.networkInterface=t,this.cacheManager=r,this.authorityOptions=o,this.regionDiscoveryMetadata={region_used:void 0,region_source:void 0,region_outcome:void 0},this.logger=n,this.performanceClient=s,this.correlationId=i,this.managedIdentity=a||!1,this.regionDiscovery=new ua(t,this.logger,this.performanceClient,this.correlationId)}getAuthorityType(e){if(e.HostNameAndPort.endsWith(wr))return Us;const t=e.PathSegments;if(t.length)switch(t[0].toLowerCase()){case"adfs":return qs;case"dstsv2":return $s}return Ms}get authorityType(){return this.getAuthorityType(this.canonicalAuthorityUrlComponents)}get protocolMode(){return this.authorityOptions.protocolMode}get options(){return this.authorityOptions}get canonicalAuthority(){return this._canonicalAuthority.urlString}set canonicalAuthority(e){this._canonicalAuthority=new Ks(e,this.correlationId),this._canonicalAuthority.validateAsUri(),this._canonicalAuthorityUrlComponents=null}get canonicalAuthorityUrlComponents(){return this._canonicalAuthorityUrlComponents||(this._canonicalAuthorityUrlComponents=this._canonicalAuthority.getUrlComponents()),this._canonicalAuthorityUrlComponents}get hostnameAndPort(){return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase()}get tenant(){return this.canonicalAuthorityUrlComponents.PathSegments[0]}get authorizationEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.authorization_endpoint);throw Wn(Qn,this.correlationId)}get tokenEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint);throw Wn(Qn,this.correlationId)}get deviceCodeEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint.replace("/token","/devicecode"));throw Wn(Qn,this.correlationId)}get endSessionEndpoint(){if(this.discoveryComplete()){if(!this.metadata.end_session_endpoint)throw Wn("end_session_endpoint_not_supported",this.correlationId);return this.replacePath(this.metadata.end_session_endpoint)}throw Wn(Qn,this.correlationId)}get selfSignedJwtAudience(){if(this.discoveryComplete())return this.replacePath(this.metadata.issuer);throw Wn(Qn,this.correlationId)}get jwksUri(){if(this.discoveryComplete())return this.replacePath(this.metadata.jwks_uri);throw Wn(Qn,this.correlationId)}canReplaceTenant(e){return 1===e.PathSegments.length&&!Pa.reservedTenantDomains.has(e.PathSegments[0])&&this.getAuthorityType(e)===Ms&&this.protocolMode!==Zs}replaceTenant(e){return e.replace(/{tenant}|{tenantid}/g,this.tenant)}replacePath(e){let t=e;const r=new Ks(this.metadata.canonical_authority,this.correlationId).getUrlComponents(),o=r.PathSegments;return this.canonicalAuthorityUrlComponents.PathSegments.forEach((e,n)=>{let i=o[n];if(0===n&&this.canReplaceTenant(r)){const e=new Ks(this.metadata.authorization_endpoint,this.correlationId).getUrlComponents().PathSegments[0];i!==e&&(this.logger.verbose(`1q3g2x ${i} ${e}`,this.correlationId),i=e)}e!==i&&(t=t.replace(`/${i}/`,`/${e}/`))}),this.replaceTenant(t)}get defaultOpenIdConfigurationEndpoint(){const e=this.hostnameAndPort;return this.canonicalAuthority.endsWith("v2.0/")||this.authorityType===qs||this.protocolMode===Zs&&!this.isAliasOfKnownMicrosoftAuthority(e)?`${this.canonicalAuthority}.well-known/openid-configuration`:`${this.canonicalAuthority}v2.0/.well-known/openid-configuration`}discoveryComplete(){return!!this.metadata}async resolveEndpointsAsync(){const e=this.getCurrentMetadataEntity(),t=await da(this.updateCloudDiscoveryMetadata.bind(this),"authorityUpdateCloudDiscoveryMetadata",this.logger,this.performanceClient,this.correlationId)(e);this.canonicalAuthority=this.canonicalAuthority.replace(this.hostnameAndPort,e.preferred_network);const r=await da(this.updateEndpointMetadata.bind(this),"authorityUpdateEndpointMetadata",this.logger,this.performanceClient,this.correlationId)(e);this.updateCachedMetadata(e,t,{source:r}),this.performanceClient?.addFields({cloudDiscoverySource:t,authorityEndpointSource:r},this.correlationId)}getCurrentMetadataEntity(){let e=this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort,this.correlationId);return e||(e={aliases:[],preferred_cache:this.hostnameAndPort,preferred_network:this.hostnameAndPort,canonical_authority:this.canonicalAuthority,authorization_endpoint:"",token_endpoint:"",end_session_endpoint:"",issuer:"",aliasesFromNetwork:!1,endpointsFromNetwork:!1,expiresAt:Ta(),jwks_uri:""}),e}updateCachedMetadata(e,t,r){t!==ho&&r?.source!==ho&&(e.expiresAt=Ta(),e.canonical_authority=this.canonicalAuthority);const o=this.cacheManager.generateAuthorityMetadataCacheKey(e.preferred_cache,this.correlationId);this.cacheManager.setAuthorityMetadata(o,e,this.correlationId),this.metadata=e}async updateEndpointMetadata(e){const t=this.updateEndpointMetadataFromLocalSources(e);if(t){if(t.source===go&&this.authorityOptions.azureRegionConfiguration?.azureRegion&&t.metadata){Aa(e,await da(this.updateMetadataWithRegionalInformation.bind(this),ca,this.logger,this.performanceClient,this.correlationId)(t.metadata),!1),e.canonical_authority=this.canonicalAuthority}return t.source}let r=await da(this.getEndpointMetadataFromNetwork.bind(this),"authorityGetEndpointMetadataFromNetwork",this.logger,this.performanceClient,this.correlationId)();if(r)return this.validateIssuer(r.issuer),this.authorityOptions.azureRegionConfiguration?.azureRegion&&(r=await da(this.updateMetadataWithRegionalInformation.bind(this),ca,this.logger,this.performanceClient,this.correlationId)(r)),Aa(e,r,!0),uo;throw Wn("openid_config_error",this.defaultOpenIdConfigurationEndpoint,this.correlationId)}updateEndpointMetadataFromLocalSources(e){this.logger.verbose("1fi0kc",this.correlationId);const t=this.getEndpointMetadataFromConfig();if(t)return this.logger.verbose("06t0uj",this.correlationId),Aa(e,t,!1),{source:lo};this.logger.verbose("151k0p",this.correlationId);const r=this.getEndpointMetadataFromHardcodedValues();if(r)return Aa(e,r,!1),{source:go,metadata:r};this.logger.verbose("1imop5",this.correlationId);const o=Ea(e);return this.isAuthoritySameType(e)&&e.endpointsFromNetwork&&!o?(this.logger.verbose("16uq31",""),{source:ho}):(o&&this.logger.verbose("0uoibc",""),null)}isAuthoritySameType(e){return new Ks(e.canonical_authority,this.correlationId).getUrlComponents().PathSegments.length===this.canonicalAuthorityUrlComponents.PathSegments.length}getEndpointMetadataFromConfig(){if(this.authorityOptions.authorityMetadata)try{return JSON.parse(this.authorityOptions.authorityMetadata)}catch(e){throw Ns("invalid_authority_metadata",this.correlationId)}return null}async getEndpointMetadataFromNetwork(){const e={},t=this.defaultOpenIdConfigurationEndpoint;this.logger.verbose(`1y65x6 ${t}`,this.correlationId);try{const r=await this.networkInterface.sendGetRequestAsync(t,e),o=function(e){return e.hasOwnProperty("authorization_endpoint")&&e.hasOwnProperty("token_endpoint")&&e.hasOwnProperty("issuer")&&e.hasOwnProperty("jwks_uri")}(r.body);return o?r.body:(this.logger.verbose("1koyv8",this.correlationId),null)}catch(e){return this.logger.verbose(`0a9wik ${e}`,this.correlationId),null}}getEndpointMetadataFromHardcodedValues(){return this.hostnameAndPort in Js?Js[this.hostnameAndPort]:null}async updateMetadataWithRegionalInformation(e){const t=this.authorityOptions.azureRegionConfiguration?.azureRegion;if(t){if("TryAutoDetect"!==t)return this.regionDiscoveryMetadata.region_outcome=bo,this.regionDiscoveryMetadata.region_used=t,Pa.replaceWithRegionalInformation(e,t,this.correlationId);const r=await da(this.regionDiscovery.detectRegion.bind(this.regionDiscovery),"regionDiscoveryDetectRegion",this.logger,this.performanceClient,this.correlationId)(this.authorityOptions.azureRegionConfiguration?.environmentRegion,this.regionDiscoveryMetadata);if(r)return this.regionDiscoveryMetadata.region_outcome=ko,this.regionDiscoveryMetadata.region_used=r,Pa.replaceWithRegionalInformation(e,r,this.correlationId);this.regionDiscoveryMetadata.region_outcome=So}return e}async updateCloudDiscoveryMetadata(e){const t=this.updateCloudDiscoveryMetadataFromLocalSources(e);if(t)return t;const r=await da(this.getCloudDiscoveryMetadataFromNetwork.bind(this),"authorityGetCloudDiscoveryMetadataFromNetwork",this.logger,this.performanceClient,this.correlationId)();if(r)return _a(e,r,!0),uo;throw Ns("untrusted_authority",this.correlationId)}updateCloudDiscoveryMetadataFromLocalSources(e){this.logger.verbose("1tpqlr",this.correlationId),this.logger.verbosePii(`1fy7uz ${this.authorityOptions.knownAuthorities||Sr}`,this.correlationId),this.logger.verbosePii(`08zabj ${this.authorityOptions.authorityMetadata||Sr}`,this.correlationId),this.logger.verbosePii(`1o1kv3 ${e.canonical_authority||Sr}`,this.correlationId);const t=this.getCloudDiscoveryMetadataFromConfig();if(t)return this.logger.verbose("1nakio",this.correlationId),_a(e,t,!1),lo;this.logger.verbose("1x74aj",this.correlationId);const r=(o=this.hostnameAndPort,Ys(Vs.metadata,o));var o;if(r)return this.logger.verbose("0by47c",this.correlationId),_a(e,r,!1),go;this.logger.verbose("0r2fzy",this.correlationId);const n=Ea(e);return this.isAuthoritySameType(e)&&e.aliasesFromNetwork&&!n?(this.logger.verbose("1uffgh",""),ho):(n&&this.logger.verbose("0uoibc",""),null)}getCloudDiscoveryMetadataFromConfig(){if(this.authorityType===Us)return this.logger.verbose("04y84h",this.correlationId),Pa.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);if(this.authorityOptions.cloudDiscoveryMetadata){this.logger.verbose("0gszr3",this.correlationId);try{this.logger.verbose("1iifkx",this.correlationId);const e=Ys(JSON.parse(this.authorityOptions.cloudDiscoveryMetadata).metadata,this.hostnameAndPort);if(this.logger.verbose("0q67e3",""),e)return this.logger.verbose("0hzfao",this.correlationId),e;this.logger.verbose("1ajz3u",this.correlationId)}catch(e){throw this.logger.verbose("1wq5tu",this.correlationId),Ns(zs,this.correlationId)}}return this.isInKnownAuthorities(this.hostnameAndPort)?(this.logger.verbose("0mt9al",this.correlationId),Pa.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)):null}async getCloudDiscoveryMetadataFromNetwork(){const e=`${yr}${this.canonicalAuthority}oauth2/v2.0/authorize`,t={};let r=null;try{const o=await this.networkInterface.sendGetRequestAsync(e,t);let n,i;if(function(e){return e.hasOwnProperty("tenant_discovery_endpoint")&&e.hasOwnProperty("metadata")}(o.body))n=o.body,i=n.metadata,this.logger.verbosePii(`1vglyt ${n.tenant_discovery_endpoint}`,this.correlationId);else{if(!function(e){return e.hasOwnProperty("error")&&e.hasOwnProperty("error_description")}(o.body))return this.logger.error("0768g0",this.correlationId),null;if(this.logger.warning(`062uto ${o.status}`,this.correlationId),n=o.body,"invalid_instance"===n.error)return this.logger.error("1x90tm",this.correlationId),null;this.logger.warning(`0wchdm ${n.error}`,this.correlationId),this.logger.warning(`1s5mpv ${n.error_description}`,this.correlationId),this.logger.warning("1yhqpw",this.correlationId),i=[]}this.logger.verbose("1lrobr",this.correlationId),r=Ys(i,this.hostnameAndPort)}catch(e){if(e instanceof Rn)this.logger.error(`0vwhc7 ${e.errorCode} ${e.errorMessage}`,this.correlationId);else{const t=e;this.logger.error(`0s2z41 ${t.name} ${t.message}`,this.correlationId)}return null}return r||(this.logger.warning("0jp28q",this.correlationId),this.logger.verbose("130sd8",this.correlationId),r=Pa.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)),r}isInKnownAuthorities(e){const t=e.toLowerCase();return this.authorityOptions.knownAuthorities.filter(e=>e&&Ks.getDomainFromUrl(e,this.correlationId).toLowerCase()===t).length>0}static generateAuthority(e,t){let r;if(t&&t.azureCloudInstance!==ta){const e=t.tenant?t.tenant:fr;r=`${t.azureCloudInstance}/${e}/`}return r||e}static createCloudDiscoveryMetadataFromHost(e){return{preferred_network:e,preferred_cache:e,aliases:[e]}}getPreferredCache(){if(this.managedIdentity)return"login.microsoftonline.com";if(this.discoveryComplete())return this.metadata.preferred_cache;throw Wn(Qn,this.correlationId)}isAlias(e){return this.metadata.aliases.indexOf(e)>-1}isAliasOfKnownMicrosoftAuthority(e){return Gs.has(e)}validateIssuer(e){if(!e)throw Ns(Bs,this.correlationId);let t;try{t=new URL(e)}catch{throw Ns(Bs,this.correlationId)}const r=t.protocol,o=t.host,n=(this.canonicalAuthorityUrlComponents.Protocol||"").toLowerCase(),i=(this.canonicalAuthorityUrlComponents.HostNameAndPort||"").toLowerCase(),s=this.matchesAuthorityOrigin(r,o,n,i),a="https:"===r&&this.isAliasOfKnownMicrosoftAuthority(o),c="https:"===r&&this.matchesRegionalMicrosoftHost(o),l=this.matchesCiamTenantPattern(t,i,this.canonicalAuthorityUrlComponents.PathSegments),h="https:"===r&&this.isInKnownAuthorities(o);if(!(s||a||c||l||h))throw Ns(Bs,this.correlationId)}matchesAuthorityOrigin(e,t,r,o){return e===r&&t===o}matchesRegionalMicrosoftHost(e){const t=e.indexOf(".");if(t>0&&t<e.length-1){const r=e.substring(t+1);return this.isAliasOfKnownMicrosoftAuthority(r)}return!1}matchesCiamTenantPattern(e,t,r){const o=r[0],n=o?o.endsWith(vr)?o.slice(0,-16):o:t.split(".")[0];if(!n)return!1;const i=`https://${n}${wr}`,s=[i,`${i}/${n}`,`${i}/${n}/v2.0`,`${i}/${n}${vr}`,`${i}/${n}${vr}/v2.0`],a=e.pathname.replace(/\/+$/,""),c=`${e.protocol}//${e.host}${a}`;return s.some(e=>e===c)}static isPublicCloudAuthority(e){return _r.indexOf(e)>=0}static buildRegionalAuthorityString(e,t,r,o){const n=new Ks(e,r);n.validateAsUri();const i=n.getUrlComponents();let s=`${t}.${i.HostNameAndPort}`;this.isPublicCloudAuthority(i.HostNameAndPort)&&(s=`${t}.login.microsoft.com`);const a=Ks.constructAuthorityUriFromObject({...n.getUrlComponents(),HostNameAndPort:s},r).urlString;return o?`${a}?${o}`:a}static replaceWithRegionalInformation(e,t,r){const o={...e};return o.authorization_endpoint=Pa.buildRegionalAuthorityString(o.authorization_endpoint,t,r),o.token_endpoint=Pa.buildRegionalAuthorityString(o.token_endpoint,t,r),o.end_session_endpoint&&(o.end_session_endpoint=Pa.buildRegionalAuthorityString(o.end_session_endpoint,t,r)),o}static transformCIAMAuthority(e,t){let r=e;const o=new Ks(e,t).getUrlComponents();if(0===o.PathSegments.length&&o.HostNameAndPort.endsWith(wr)){r=`${r}${o.HostNameAndPort.split(".")[0]}${vr}`}return r}}function xa(e){return e.endsWith("/")?e:`${e}/`}function Oa(e,t){if(!e)throw Wn("client_info_empty_error","");try{const r=t(e);return JSON.parse(r)}catch(e){throw Wn(Jn,"")}}function Ra(e){if(!e)throw Wn(Jn,"");const t=e.split(".",2);return{uid:t[0],utid:t.length<2?"":t[1]}}function Ma(e,t){return!!e&&!!t&&e===t.split(".")[1]}function qa(e,t,r,o,n){if(n){const{oid:t,sub:r,tid:i,name:s,tfp:a,acr:c,preferred_username:l,upn:h,login_hint:d}=n,u=i||a||c||"";return{tenantId:u,localAccountId:t||r||"",name:s,username:l||h||"",loginHint:d,isHomeTenant:Ma(u,e),upn:h,...o&&{nativeAccountId:o}}}return{tenantId:r,localAccountId:t,username:"",isHomeTenant:Ma(r,e),...o&&{nativeAccountId:o}}}function $a(e,t,r,o){let n=e;if(t){const{isHomeTenant:r,...o}=t;n={...e,...o}}if(r){const{isHomeTenant:t,...i}=qa(e.homeAccountId,e.localAccountId,e.tenantId,n.nativeAccountId,r);return n={...n,...i,idTokenClaims:r,idToken:o,kmsi:pa(r)},n}return n}function Ua(e){if(e){return e.tid||e.tfp||e.acr||null}return null}function La(e){const t=e.tenantProfiles||[];0===t.length&&e.realm&&e.localAccountId&&t.push(qa(e.homeAccountId,e.localAccountId,e.realm,e.nativeAccountId));const r=t.find(t=>t.tenantId===e.realm),o=r?.nativeAccountId||e.nativeAccountId;return{homeAccountId:e.homeAccountId,environment:e.environment,tenantId:e.realm,username:e.username,localAccountId:e.localAccountId,loginHint:e.loginHint,name:e.name,nativeAccountId:o,authorityType:e.authorityType,tenantProfiles:new Map(t.map(e=>[e.tenantId,e])),dataBoundary:e.dataBoundary}}function Na(e,t,r,o,n,i){if(t!==qs&&t!==$s){if(e)try{const t=Oa(e,o.base64Decode);if(t.uid&&t.utid)return`${t.uid}.${t.utid}`}catch(e){}r.warning("1ub6wv",n)}return i?.sub||""}function Da(e,t,r){return{clientId:e,authority:t.authority,scopes:t.scopes,homeAccountIdentifier:r,claims:t.claims,authenticationScheme:t.authenticationScheme,resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,sshKid:t.sshKid,embeddedClientId:t.embeddedClientId||t.extraParameters?.clientId,resource:t.resource}}Pa.reservedTenantDomains=new Set(["{tenant}","{tenantid}",Dr,Fr,Hr]);const Ha="acquireTokenRedirect",Fa="cache_quota_exceeded";class za extends Error{constructor(e,t){const r=t||On(e);super(r),Object.setPrototypeOf(this,za.prototype),this.name="CacheError",this.errorCode=e,this.errorMessage=r}}function ja(e){return e instanceof Error?"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name||e.message.includes("exceeded the quota")?new za(Fa):new za(e.name,e.message):new za("cache_error_unknown")}const Ba="@azure/msal-common",Ka="16.11.0";class Wa{constructor(e,t){this.correlationId=t;const r=e?Ds.trimArrayEntries([...e]):[],o=r?Ds.removeEmptyStringsFromArray(r):[];if(!o||!o.length)throw Ns("empty_input_scopes_error",t);this.scopes=new Set,o.forEach(e=>this.scopes.add(e))}static fromString(e,t){const r=(e||"").split(" ");return new Wa(r,t)}static createSearchScopes(e,t){const r=e&&e.length>0?e:[...xr],o=new Wa(r,t);return o.containsOnlyOIDCScopes()?o.removeScope(br):o.removeOIDCScopes(),o}containsScope(e){const t=this.printScopesLowerCase().split(" "),r=new Wa(t,this.correlationId);return!!e&&r.scopes.has(e.toLowerCase())}containsScopeSet(e){return!(!e||e.scopes.size<=0)&&(this.scopes.size>=e.scopes.size&&e.asArray().every(e=>this.containsScope(e)))}containsOnlyOIDCScopes(){let e=0;return Or.forEach(t=>{this.containsScope(t)&&(e+=1)}),this.scopes.size===e}appendScope(e){e&&this.scopes.add(e.trim())}appendScopes(e){try{e.forEach(e=>this.appendScope(e))}catch(e){throw Wn("cannot_append_scopeset",this.correlationId)}}removeScope(e){if(!e)throw Wn("cannot_remove_empty_scope",this.correlationId);this.scopes.delete(e.trim())}removeOIDCScopes(){Or.forEach(e=>{this.scopes.delete(e)})}unionScopeSets(e){if(!e)throw Wn(ei,this.correlationId);const t=new Set;return e.scopes.forEach(e=>t.add(e.toLowerCase())),this.scopes.forEach(e=>t.add(e.toLowerCase())),t}intersectingScopeSets(e){if(!e)throw Wn(ei,this.correlationId);e.containsOnlyOIDCScopes()||e.removeOIDCScopes();const t=this.unionScopeSets(e),r=e.getScopeCount(),o=this.getScopeCount();return t.size<o+r}getScopeCount(){return this.scopes.size}asArray(){const e=[];return this.scopes.forEach(t=>e.push(t)),e}printScopes(){if(this.scopes){return this.asArray().join(" ")}return""}printScopesLowerCase(){return this.printScopes().toLowerCase()}}class Ja{constructor(e,t,r,o,n){this.clientId=e,this.cryptoImpl=t,this.commonLogger=r.clone(Ba,Ka),this.staticAuthorityOptions=n,this.performanceClient=o}getAllAccounts(e={},t){return this.buildTenantProfiles(this.getAccountsFilteredBy(e,t),t,e)}getAccountInfoFilteredBy(e,t){if(0===Object.keys(e).length||Object.values(e).every(e=>null==e||""===e))return this.commonLogger.warning("1skb02",t),null;const r=this.getAllAccounts(e,t);if(r.length>1){return r.sort((e,t)=>{const r=e.idTokenClaims?1:0;return(t.idTokenClaims?1:0)-r})[0]}return 1===r.length?r[0]:null}getBaseAccountInfo(e,t){const r=this.getAccountsFilteredBy(e,t);return r.length>0?La(r[0]):null}buildTenantProfiles(e,t,r){return e.flatMap(e=>this.getTenantProfilesFromAccountEntity(e,t,r?.tenantId,r))}getTenantedAccountInfoByFilter(e,t,r,o,n){let i,s=null;if(n&&!this.tenantProfileMatchesFilter(r,n))return null;const a=this.getIdToken(e,o,t,r.tenantId);return a&&(i=ga(a.secret,this.cryptoImpl.base64Decode,o),!this.idTokenClaimsMatchTenantProfileFilter(i,n))?null:(s=$a(e,r,i,a?.secret),s)}getTenantProfilesFromAccountEntity(e,t,r,o){const n=La(e);let i=n.tenantProfiles||new Map;const s=this.getTokenKeys();if(r){const e=i.get(r);if(!e)return[];i=new Map([[r,e]])}const a=[];return i.forEach(e=>{const r=this.getTenantedAccountInfoByFilter(n,s,e,t,o);r&&a.push(r)}),a}tenantProfileMatchesFilter(e,t){return!(t.localAccountId&&!this.matchLocalAccountIdFromTenantProfile(e,t.localAccountId))&&((!t.name||e.name===t.name)&&((void 0===t.isHomeTenant||e.isHomeTenant===t.isHomeTenant)&&(!(t.username&&!this.matchUsername(e.username,t.username)&&!this.matchUsername(e.upn,t.username))&&(!(t.loginHint&&!this.matchLoginHintWithTenantProfile(e,t.loginHint))&&((!t.upn||e.upn===t.upn)&&(!t.nativeAccountId||e.nativeAccountId===t.nativeAccountId))))))}idTokenClaimsMatchTenantProfileFilter(e,t){if(t){if(t.localAccountId&&!this.matchLocalAccountIdFromTokenClaims(e,t.localAccountId))return!1;if(t.loginHint&&!this.matchLoginHintFromTokenClaims(e,t.loginHint))return!1;if(t.username&&!this.matchUsername(e.preferred_username,t.username)&&!this.matchUsername(e.upn,t.username))return!1;if(t.name&&!this.matchName(e,t.name))return!1;if(t.sid&&!this.matchSid(e,t.sid))return!1}return!0}async saveCacheRecord(e,t,r,o,n){if(!e)throw Wn("invalid_cache_record",t);try{e.account&&await this.setAccount(e.account,t,r,o),e.idToken&&!1!==n?.idToken&&await this.setIdTokenCredential(e.idToken,t,r),e.accessToken&&!1!==n?.accessToken&&await this.saveAccessToken(e.accessToken,t,r),e.refreshToken&&!1!==n?.refreshToken&&await this.setRefreshTokenCredential(e.refreshToken,t,r),e.appMetadata&&this.setAppMetadata(e.appMetadata,t)}catch(e){throw this.commonLogger?.error("0j476p",t),e instanceof Rn?e:ja(e)}}async saveAccessToken(e,t,r){const o={clientId:e.clientId,credentialType:e.credentialType,environment:e.environment,homeAccountId:e.homeAccountId,realm:e.realm,tokenType:e.tokenType},n=this.getTokenKeys(),i=Wa.fromString(e.target,t);n.accessToken.forEach(e=>{if(!this.accessTokenKeyMatchesFilter(e,o,!1))return;const r=this.getAccessTokenCredential(e,t);if(r&&this.credentialMatchesFilter(r,o,t)){Wa.fromString(r.target,t).intersectingScopeSets(i)&&this.removeAccessToken(e,t)}}),await this.setAccessTokenCredential(e,t,r)}getAccountsFilteredBy(e,t){const r=this.getAccountKeys(),o=[];return r.forEach(r=>{const n=this.getAccount(r,t);if(!n)return;if(e.homeAccountId&&!this.matchHomeAccountId(n,e.homeAccountId))return;if(e.environment&&!this.matchEnvironment(n,e.environment,t))return;if(e.realm&&!this.matchRealm(n,e.realm))return;if(e.authorityType&&!this.matchAuthorityType(n,e.authorityType))return;const i={localAccountId:e?.localAccountId,name:e?.name,username:e?.username,loginHint:e?.loginHint,upn:e?.upn,nativeAccountId:e?.nativeAccountId},s=n.tenantProfiles?.filter(e=>this.tenantProfileMatchesFilter(e,i));s&&0===s.length||o.push(n)}),o}credentialMatchesFilter(e,t,r){if(t.clientId&&!this.matchClientId(e,t.clientId))return!1;if(t.userAssertionHash&&!this.matchUserAssertionHash(e,t.userAssertionHash))return!1;if("string"==typeof t.homeAccountId&&!this.matchHomeAccountId(e,t.homeAccountId))return!1;if(t.environment&&!this.matchEnvironment(e,t.environment,r))return!1;if(t.realm&&!this.matchRealm(e,t.realm))return!1;if(t.credentialType&&!this.matchCredentialType(e,t.credentialType))return!1;if(t.familyId&&!this.matchFamilyId(e,t.familyId))return!1;if(t.target&&!this.matchTarget(e,t.target,r))return!1;if(e.credentialType===io.ACCESS_TOKEN_WITH_AUTH_SCHEME){if(t.tokenType&&!this.matchTokenType(e,t.tokenType))return!1;if(t.tokenType===yo.SSH&&t.keyId&&!this.matchKeyId(e,t.keyId))return!1}const o=e.additionalCacheKeyComponents,n=t.additionalCacheKeyComponents,i=!!o&&Object.keys(o).length>0,s=!!n&&Object.keys(n).length>0;if(i!==s)return!1;if(i&&s){const e=Object.keys(o).sort(),t=Object.keys(n).sort();if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r]||o[e[r]]!==n[t[r]])return!1}return!0}getAppMetadataFilteredBy(e,t){const r=this.getKeys(),o={};return r.forEach(r=>{if(!this.isAppMetadata(r))return;const n=this.getAppMetadata(r,t);n&&(e.environment&&!this.matchEnvironment(n,e.environment,t)||e.clientId&&!this.matchClientId(n,e.clientId)||(o[r]=n))}),o}getAuthorityMetadataByAlias(e,t){const r=this.getAuthorityMetadataKeys();let o=null;return r.forEach(r=>{if(!this.isAuthorityMetadata(r)||-1===r.indexOf(this.clientId))return;const n=this.getAuthorityMetadata(r,t);n&&-1!==n.aliases.indexOf(e)&&(o=n)}),o}removeAllAccounts(e){this.getAllAccounts({},e).forEach(t=>{this.removeAccount(t,e)})}removeAccount(e,t){this.removeAccountContext(e,t);this.getAccountKeys().filter(t=>t.includes(e.homeAccountId)&&t.includes(e.environment)).forEach(e=>{this.removeItem(e,t),this.performanceClient.incrementFields({accountsRemoved:1},t)})}removeAccountContext(e,t){const r=this.getTokenKeys(),o=t=>t.includes(e.homeAccountId)&&t.includes(e.environment);r.idToken.filter(o).forEach(e=>{this.removeIdToken(e,t)}),r.accessToken.filter(o).forEach(e=>{this.removeAccessToken(e,t)}),r.refreshToken.filter(o).forEach(e=>{this.removeRefreshToken(e,t)})}removeAccessToken(e,t){const r=this.getAccessTokenCredential(e,t);if(r&&(this.removeItem(e,t),this.performanceClient.incrementFields({accessTokensRemoved:1},t),r.credentialType.toLowerCase()===io.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()&&r.tokenType===yo.POP)){const e=r.keyId;e&&this.cryptoImpl.removeTokenBindingKey(e,t).catch(()=>{this.commonLogger.error(`0cx291 ${e}`,t),this.performanceClient?.incrementFields({removeTokenBindingKeyFailure:1},t)})}}removeAppMetadata(e){return this.getKeys().forEach(t=>{this.isAppMetadata(t)&&this.removeItem(t,e)}),!0}getIdToken(e,t,r,o){this.commonLogger.trace("1drz22",t);const n={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:io.ID_TOKEN,clientId:this.clientId,realm:o},i=this.getIdTokensByFilter(n,t,r),s=i.size;if(s<1)return this.commonLogger.info("1atvtd",t),null;if(s>1){let r=i;if(!o){const o=new Map;i.forEach((t,r)=>{t.realm===e.tenantId&&o.set(r,t)});const n=o.size;if(n<1)return this.commonLogger.info("0ooalx",t),i.values().next().value??null;if(1===n)return this.commonLogger.info("1eq2vc",t),o.values().next().value??null;r=o}return this.commonLogger.info("1ws328",t),r.forEach((e,r)=>{this.removeIdToken(r,t)}),this.performanceClient.addFields({multiMatchedID:i.size},t),null}return this.commonLogger.info("1sm769",t),i.values().next().value??null}getIdTokensByFilter(e,t,r){const o=r&&r.idToken||this.getTokenKeys().idToken,n=new Map;return o.forEach(r=>{if(!this.idTokenKeyMatchesFilter(r,{clientId:this.clientId,...e}))return;const o=this.getIdTokenCredential(r,t);o&&this.credentialMatchesFilter(o,e,t)&&n.set(r,o)}),n}idTokenKeyMatchesFilter(e,t){const r=e.toLowerCase();return(!t.clientId||-1!==r.indexOf(t.clientId.toLowerCase()))&&(!t.homeAccountId||-1!==r.indexOf(t.homeAccountId.toLowerCase()))}removeIdToken(e,t){this.removeItem(e,t)}removeRefreshToken(e,t){this.removeItem(e,t)}getAccessToken(e,t,r,o){const n=t.correlationId;this.commonLogger.trace("1t7hz1",n);const i=Wa.createSearchScopes(t.scopes,n),s=t.authenticationScheme||yo.BEARER,a=s&&s.toLowerCase()!==yo.BEARER.toLowerCase()?io.ACCESS_TOKEN_WITH_AUTH_SCHEME:io.ACCESS_TOKEN,c={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:a,clientId:this.clientId,realm:o||e.tenantId,target:i,tokenType:s,keyId:t.sshKid},l=r&&r.accessToken||this.getTokenKeys().accessToken,h=[];l.forEach(e=>{if(this.accessTokenKeyMatchesFilter(e,c,!0)){const t=this.getAccessTokenCredential(e,n);t&&this.credentialMatchesFilter(t,c,n)&&h.push(t)}});const d=h.length;return d<1?(this.commonLogger.info("1nckna",n),null):d>1?(this.commonLogger.info("1wkfwp",n),h.forEach(e=>{this.removeAccessToken(this.generateCredentialKey(e),n)}),this.performanceClient.addFields({multiMatchedAT:h.length},n),null):(this.commonLogger.info("06yt98",n),h[0])}accessTokenKeyMatchesFilter(e,t,r){const o=e.toLowerCase();if(t.clientId&&-1===o.indexOf(t.clientId.toLowerCase()))return!1;if(t.homeAccountId&&-1===o.indexOf(t.homeAccountId.toLowerCase()))return!1;if(t.realm&&-1===o.indexOf(t.realm.toLowerCase()))return!1;if(t.target){const e=t.target.asArray();for(let t=0;t<e.length;t++){if(r&&!o.includes(e[t].toLowerCase()))return!1;if(!r&&o.includes(e[t].toLowerCase()))return!0}}return!0}getAccessTokensByFilter(e,t){const r=this.getTokenKeys(),o=[];return r.accessToken.forEach(r=>{if(!this.accessTokenKeyMatchesFilter(r,e,!0))return;const n=this.getAccessTokenCredential(r,t);n&&this.credentialMatchesFilter(n,e,t)&&o.push(n)}),o}getRefreshToken(e,t,r,o){this.commonLogger.trace("0x53vi",r);const n=t?ao:void 0,i={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:io.REFRESH_TOKEN,clientId:this.clientId,familyId:n},s=o&&o.refreshToken||this.getTokenKeys().refreshToken,a=[];s.forEach(e=>{if(this.refreshTokenKeyMatchesFilter(e,i)){const t=this.getRefreshTokenCredential(e,r);t&&this.credentialMatchesFilter(t,i,r)&&a.push(t)}});const c=a.length;return c<1?(this.commonLogger.info("0dlw11",r),null):(c>1&&this.performanceClient.addFields({multiMatchedRT:c},r),this.commonLogger.info("0wcnep",r),a[0])}refreshTokenKeyMatchesFilter(e,t){const r=e.toLowerCase();return(!t.familyId||-1!==r.indexOf(t.familyId.toLowerCase()))&&(!(!t.familyId&&t.clientId&&-1===r.indexOf(t.clientId.toLowerCase()))&&(!t.homeAccountId||-1!==r.indexOf(t.homeAccountId.toLowerCase())))}readAppMetadataFromCache(e,t){const r={environment:e,clientId:this.clientId},o=this.getAppMetadataFilteredBy(r,t),n=Object.keys(o).map(e=>o[e]),i=n.length;if(i<1)return null;if(i>1)throw Wn("multiple_matching_appMetadata",t);return n[0]}isAppMetadataFOCI(e,t){const r=this.readAppMetadataFromCache(e,t);return!(!r||r.familyId!==ao)}matchHomeAccountId(e,t){return!("string"!=typeof e.homeAccountId||t!==e.homeAccountId)}matchLocalAccountIdFromTokenClaims(e,t){return t===(e.oid||e.sub)}matchLocalAccountIdFromTenantProfile(e,t){return e.localAccountId===t}matchName(e,t){return!(t.toLowerCase()!==e.name?.toLowerCase())}matchUsername(e,t){return!(!e||"string"!=typeof e||t?.toLowerCase()!==e.toLowerCase())}matchLoginHintWithTenantProfile(e,t){return e.loginHint===t||e.username===t||e.upn===t}matchUserAssertionHash(e,t){return!(!e.userAssertionHash||t!==e.userAssertionHash)}matchEnvironment(e,t,r){if(this.staticAuthorityOptions){const o=function(e,t,r){let o;const n=e.canonicalAuthority;if(n){const i=new Ks(n,r).getUrlComponents().HostNameAndPort;o=Qs(t,r,i,e.cloudDiscoveryMetadata?.metadata,lo)||Qs(t,r,i,Vs.metadata,go)||e.knownAuthorities}return o||[]}(this.staticAuthorityOptions,this.commonLogger,r);if(o.includes(t)&&o.includes(e.environment))return!0}const o=this.getAuthorityMetadataByAlias(t,r);return!!(o&&o.aliases.indexOf(e.environment)>-1)}matchCredentialType(e,t){return e.credentialType&&t.toLowerCase()===e.credentialType.toLowerCase()}matchClientId(e,t){return!(!e.clientId||t!==e.clientId)}matchFamilyId(e,t){return!(!e.familyId||t!==e.familyId)}matchRealm(e,t){return!(e.realm?.toLowerCase()!==t.toLowerCase())}matchLoginHintFromTokenClaims(e,t){return e.login_hint===t||(e.preferred_username===t||(e.upn===t||!(!e.emails||!e.emails.includes(t))))}matchSid(e,t){return e.sid===t}matchAuthorityType(e,t){return!(!e.authorityType||t.toLowerCase()!==e.authorityType.toLowerCase())}matchTarget(e,t,r){if(e.credentialType!==io.ACCESS_TOKEN&&e.credentialType!==io.ACCESS_TOKEN_WITH_AUTH_SCHEME||!e.target)return!1;return Wa.fromString(e.target,r).containsScopeSet(t)}matchTokenType(e,t){return!(!e.tokenType||e.tokenType!==t)}matchKeyId(e,t){return!(!e.keyId||e.keyId!==t)}isAppMetadata(e){return-1!==e.indexOf(so)}isAuthorityMetadata(e){return-1!==e.indexOf(co)}generateAuthorityMetadataCacheKey(e){return`${co}-${this.clientId}-${e}`}static toObject(e,t){for(const r in t)e[r]=t[r];return e}}class Va extends Ja{async setAccount(){throw Wn(ai,"")}getAccount(){throw Wn(ai,"")}async setIdTokenCredential(){throw Wn(ai,"")}getIdTokenCredential(){throw Wn(ai,"")}async setAccessTokenCredential(){throw Wn(ai,"")}getAccessTokenCredential(){throw Wn(ai,"")}async setRefreshTokenCredential(){throw Wn(ai,"")}getRefreshTokenCredential(){throw Wn(ai,"")}setAppMetadata(){throw Wn(ai,"")}getAppMetadata(){throw Wn(ai,"")}setServerTelemetry(){throw Wn(ai,"")}getServerTelemetry(){throw Wn(ai,"")}setAuthorityMetadata(){throw Wn(ai,"")}getAuthorityMetadata(){throw Wn(ai,"")}getAuthorityMetadataKeys(){throw Wn(ai,"")}setThrottlingCache(){throw Wn(ai,"")}getThrottlingCache(){throw Wn(ai,"")}removeItem(){throw Wn(ai,"")}getKeys(){throw Wn(ai,"")}getAccountKeys(){throw Wn(ai,"")}getTokenKeys(){throw Wn(ai,"")}generateCredentialKey(){throw Wn(ai,"")}generateAccountKey(){throw Wn(ai,"")}}const Ga="msal",Qa="browser",Ya=`${Ga}.${Qa}.log.level`,Xa=`${Ga}.${Qa}.log.pii`,Za=`${Ga}.version`,ec="account.keys",tc="token.keys",rc=`${Ga}.${Qa}.sso.capable`;function oc(e=3){return e<1?`${Ga}.${ec}`:`${Ga}.${e}.${ec}`}function nc(e,t=3){return t<1?`${Ga}.${tc}.${e}`:`${Ga}.${t}.${tc}.${e}`}class ic extends Rn{constructor(e,t,r){super(e,t,r),this.name="BrowserConfigurationAuthError",Object.setPrototypeOf(this,ic.prototype)}}function sc(e,t){return new ic(e,t,qi(e))}const ac=864e5,cc="Lax",lc="None";class hc{initialize(){return Promise.resolve()}getItem(e){const t=encodeURIComponent(e),r=document.cookie.split(";");for(let e=0;e<r.length;e++){const o=r[e].trim(),n=o.indexOf("=");if((-1===n?o:o.substring(0,n))===t){const e=-1===n?"":o.substring(n+1);try{return decodeURIComponent(e)}catch{return e}}}return""}getUserData(){throw Wn(ai,"")}setItem(e,t,r,o=!0,n=cc){let i=`${encodeURIComponent(e)}=${encodeURIComponent(t)};path=/;SameSite=${n};`;if(r){const e=function(e){const t=new Date,r=new Date(t.getTime()+e*ac);return r.toUTCString()}(r);i+=`expires=${e};`}(o||n===lc)&&(i+="Secure;"),document.cookie=i}async setUserData(e,t,r){return Promise.reject(Wn(ai,r))}removeItem(e){this.setItem(e,"",-1)}getKeys(){const e=document.cookie.split(";"),t=[];return e.forEach(e=>{const r=e.trim(),o=r.indexOf("="),n=-1===o?r:r.substring(0,o);try{t.push(decodeURIComponent(n))}catch{}}),t}containsKey(e){return this.getKeys().includes(e)}decryptData(){return Promise.resolve(null)}}function dc(e,t){const r=e.getItem(oc(t));return r?JSON.parse(r):[]}function uc(e,t,r){const o=t.getItem(nc(e,r));if(o){const e=JSON.parse(o);if(e&&e.hasOwnProperty("idToken")&&e.hasOwnProperty("accessToken")&&e.hasOwnProperty("refreshToken"))return e}return{idToken:[],accessToken:[],refreshToken:[]}}function gc(e){return e.hasOwnProperty("id")&&e.hasOwnProperty("nonce")&&e.hasOwnProperty("data")}const pc="storage_not_supported",mc="msal.cache.encryption";class fc{constructor(e,t,r){if(!window.localStorage)throw sc(pc,"");this.memoryStorage=new As,this.initialized=!1,this.clientId=e,this.logger=t,this.performanceClient=r,this.broadcast=new BroadcastChannel("msal.broadcast.cache")}async initialize(e){const t=new hc,r=t.getItem(mc);let o={key:"",id:""};if(r)try{o=JSON.parse(r)}catch(e){}if(o.key&&o.id){const t=ha(rs,"base64Decode",this.logger,this.performanceClient,e)(o.key);this.encryptionCookie={id:o.id,key:await da(Is,_i,this.logger,this.performanceClient,e)(t)}}else{const r=fs(),o=await da(Cs,"generateBaseKey",this.logger,this.performanceClient,e)(),n=ha(Oi,"urlEncodeArr",this.logger,this.performanceClient,e)(new Uint8Array(o));this.encryptionCookie={id:r,key:await da(Is,_i,this.logger,this.performanceClient,e)(o)};const i={id:r,key:n};t.setItem(mc,JSON.stringify(i),0,!0,lc)}await da(this.importExistingCache.bind(this),"importExistingCache",this.logger,this.performanceClient,e)(e),this.broadcast.addEventListener("message",t=>{this.updateCache(t,e)}),this.initialized=!0}getItem(e){return window.localStorage.getItem(e)}getUserData(e){if(!this.initialized)throw Ui(Xi,"");return this.memoryStorage.getItem(e)}async decryptData(e,t,r){if(!this.initialized||!this.encryptionCookie)throw Ui(Xi,"");if(t.id!==this.encryptionCookie.id)return this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},r),null;const o=await da(Ss,Ei,this.logger,this.performanceClient,r)(this.encryptionCookie.key,t.nonce,this.getContext(e),t.data);if(!o)return null;try{return{...JSON.parse(o),lastUpdatedAt:t.lastUpdatedAt}}catch(e){return this.performanceClient.incrementFields({encryptedCacheCorruptionCount:1},r),null}}setItem(e,t){window.localStorage.setItem(e,t)}async setUserData(e,t,r,o,n){if(!this.initialized||!this.encryptionCookie)throw Ui(Xi,"");if(n)this.setItem(e,t);else{const{data:n,nonce:i}=await da(ks,"encrypt",this.logger,this.performanceClient,r)(this.encryptionCookie.key,t,this.getContext(e)),s={id:this.encryptionCookie.id,nonce:i,data:n,lastUpdatedAt:o};this.setItem(e,JSON.stringify(s))}this.memoryStorage.setItem(e,t),this.broadcast.postMessage({key:e,value:t,context:this.getContext(e)})}removeItem(e){this.memoryStorage.containsKey(e)&&(this.memoryStorage.removeItem(e),this.broadcast.postMessage({key:e,value:null,context:this.getContext(e)})),window.localStorage.removeItem(e)}getKeys(){return Object.keys(window.localStorage)}containsKey(e){return window.localStorage.hasOwnProperty(e)}clear(){this.memoryStorage.clear();dc(this).forEach(e=>this.removeItem(e));const e=uc(this.clientId,this);e.idToken.forEach(e=>this.removeItem(e)),e.accessToken.forEach(e=>this.removeItem(e)),e.refreshToken.forEach(e=>this.removeItem(e)),this.getKeys().forEach(e=>{(e.startsWith(Ga)||-1!==e.indexOf(this.clientId))&&this.removeItem(e)})}async importExistingCache(e){if(!this.encryptionCookie)return;let t=dc(this);t=await this.importArray(t,e),t.length?this.setItem(oc(),JSON.stringify(t)):this.removeItem(oc());const r=uc(this.clientId,this);r.idToken=await this.importArray(r.idToken,e),r.accessToken=await this.importArray(r.accessToken,e),r.refreshToken=await this.importArray(r.refreshToken,e),r.idToken.length||r.accessToken.length||r.refreshToken.length?this.setItem(nc(this.clientId),JSON.stringify(r)):this.removeItem(nc(this.clientId))}async getItemFromEncryptedCache(e,t){if(!this.encryptionCookie)return null;const r=this.getItem(e);if(!r)return null;let o;try{o=JSON.parse(r)}catch(e){return null}return gc(o)?o.id!==this.encryptionCookie.id?(this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},t),null):(this.performanceClient.incrementFields({encryptedCacheCount:1},t),da(Ss,Ei,this.logger,this.performanceClient,t)(this.encryptionCookie.key,o.nonce,this.getContext(e),o.data)):(this.performanceClient.incrementFields({unencryptedCacheCount:1},t),r)}async importArray(e,t){const r=[],o=[];return e.forEach(e=>{const n=this.getItemFromEncryptedCache(e,t).then(t=>{t?(this.memoryStorage.setItem(e,t),r.push(e)):this.removeItem(e)});o.push(n)}),await Promise.all(o),r}getContext(e){let t="";return e.includes(this.clientId)&&(t=this.clientId),t}updateCache(e,t){this.logger.trace("17cxcm",t);const r=this.performanceClient.startMeasurement("localStorageUpdated");r.add({isBackground:!0});const{key:o,value:n,context:i}=e.data;return o?i&&i!==this.clientId?(this.logger.trace(`04rtdy ${i}`,t),void r.end({success:!1,errorCode:"contextMismatch"})):(n?(this.memoryStorage.setItem(o,n),this.logger.verbose("1vzsgt",t)):(this.memoryStorage.removeItem(o),this.logger.verbose("04ypih",t)),void r.end({success:!0})):(this.logger.error("0e10qr",t),void r.end({success:!1,errorCode:"noKey"}))}}class yc{constructor(){if(!window.sessionStorage)throw sc(pc,"")}async initialize(){}getItem(e){return window.sessionStorage.getItem(e)}getUserData(e){return this.getItem(e)}setItem(e,t){window.sessionStorage.setItem(e,t)}async setUserData(e,t){this.setItem(e,t)}removeItem(e){window.sessionStorage.removeItem(e)}getKeys(){return Object.keys(window.sessionStorage)}containsKey(e){return window.sessionStorage.hasOwnProperty(e)}decryptData(){return Promise.resolve(null)}}const wc="msal:initializeStart",vc="msal:initializeEnd",Cc="msal:activeAccountChanged",Ic="msal:loginSuccess",bc="msal:acquireTokenStart",kc="msal:acquireTokenSuccess",Sc="msal:acquireTokenFailure",Tc="msal:acquireTokenFromNetworkStart",Ac="msal:handleRedirectStart",_c="msal:handleRedirectEnd",Ec="msal:popupOpened",Pc="msal:logoutStart",xc="msal:logoutSuccess",Oc="msal:logoutFailure",Rc="msal:logoutEnd",Mc="msal:restoreFromBFCache";function qc(e,t,r,o){const n=function(e,t,r){if(!e)throw Wn(ni,t);const o={id:e.createNewGuid()};r&&(o.meta=r);const n=JSON.stringify(o);return e.base64Encode(n)}(e,o,r);return t?`${n}|${t}`:n}function $c(e,t,r){if(!e)throw Wn(ni,r);if(!t)throw Wn(Xn,r);try{const r=t.split("|"),o=r[0],n=r.length>1?r.slice(1).join("|"):"",i=e(o);return{userRequestState:n||"",libraryState:JSON.parse(i)}}catch(e){throw Wn(Xn,r)}}function Uc(e){return e.startsWith("#/")?e.substring(2):e.startsWith("#")||e.startsWith("?")?e.substring(1):e}function Lc(e){if(!e||e.indexOf("=")<0)return null;try{const t=Uc(e),r=Object.fromEntries(new URLSearchParams(t));if(r.code||r.ear_jwe||r.error||r.error_description||r.state)return r}catch(e){throw Wn("hash_not_deserialized","")}return null}function Nc(e){const t=new Array;return e.forEach((e,r)=>{t.push(`${r}=${encodeURIComponent(e)}`)}),t.join("&")}function Dc(e,t,r){if(!e)return e;const o=e.split("#")[0];if(!o)return o;try{const e=new URL(o);let t;e.search||(e.search="");try{t=decodeURIComponent(e.pathname)}catch(r){t=e.pathname}return t.endsWith("/")||(t+="/"),e.pathname=t,e.href}catch(e){throw t?.error(`15apdm ${e}`,r||""),Ns(Hs,r||"")}}const Hc="client_id",Fc="redirect_uri",zc="token_type",jc="req_cnf",Bc="return_spa_code",Kc="x-client-xtra-sku",Wc="brk_client_id",Jc="brk_redirect_uri",Vc="instance_aware";function Gc(e,t,r){if(!t)return;const o=e.get(Hc);o&&e.has(Wc)&&r?.addFields({embeddedClientId:o,embeddedRedirectUri:e.get(Fc)},t)}function Qc(e,t){e.set("response_type",t)}function Yc(e,t,r,o=!0,n=xr){!o||n.includes("openid")||t.includes("openid")||n.push("openid");const i=o?[...t||[],...n]:t||[],s=new Wa(i,r);e.set("scope",s.printScopes())}function Xc(e,t){e.set(Hc,t)}function Zc(e,t){e.set(Fc,t)}function el(e,t){e.set("login_hint",t)}function tl(e,t){e.set($r,`UPN:${t}`)}function rl(e,t){e.set($r,`Oid:${t.uid}@${t.utid}`)}function ol(e,t){e.set("sid",t)}function nl(e,t,r,o,n){const i=wl(r,n&&e.has(Wc)?void 0:o,t);e.set("claims",i)}function il(e,t){e.set("client-request-id",t)}function sl(e,t){e.set("x-client-SKU",t.sku),e.set("x-client-VER",t.version),t.os&&e.set("x-client-OS",t.os),t.cpu&&e.set("x-client-CPU",t.cpu)}function al(e,t){t?.appName&&e.set("x-app-name",t.appName),t?.appVersion&&e.set("x-app-ver",t.appVersion)}function cl(e,t){t&&e.set("state",t)}function ll(e,t,r){if(!t||!r)throw Ns(Fs,"");e.set("code_challenge",t),e.set("code_challenge_method",r)}function hl(e,t){e.set("client_secret",t)}function dl(e,t){t&&e.set("client_assertion",t)}function ul(e,t){t&&e.set("client_assertion_type",t)}function gl(e,t){e.set("grant_type",t)}function pl(e){e.set("client_info","1")}function ml(e){e.has(Vc)||e.set(Vc,"true")}function fl(e,t){Object.entries(t).forEach(([t,r])=>{!e.has(t)&&r&&e.set(t,r)})}const yl={[Kr]:{essential:!1},[Wr]:{essential:!1}};function wl(e,t,r=""){let o;if(e)try{const t=JSON.parse(e);if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("Claims must be a JSON object");o=t}catch(e){throw Ns("invalid_claims",r)}else o={};Object.prototype.hasOwnProperty.call(o,Br)||(o[Br]={});const n=o[Br];for(const[e,t]of Object.entries(yl))e in n||(n[e]=t);return t&&t.length>0&&(Object.prototype.hasOwnProperty.call(o,zr)||(o[zr]={}),o[zr][jr]={values:t}),JSON.stringify(o)}function vl(e,t){t&&(e.set(zc,yo.POP),e.set(jc,t))}function Cl(e,t){t&&(e.set(zc,yo.SSH),e.set(jc,t))}function Il(e,t){e.set("x-client-current-telemetry",t.generateCurrentRequestHeaderValue()),e.set("x-client-last-telemetry",t.generateLastRequestHeaderValue())}function bl(e){e.set("x-ms-lib-capability","retry-after, h429")}function kl(e,t,r){e.has(Wc)||e.set(Wc,t),e.has(Jc)||e.set(Jc,r)}function Sl(e,t){t&&e.set("resource",t)}function Tl(e){e.location.hash="","function"==typeof e.history.replaceState&&e.history.replaceState(null,"",`${e.location.origin}${e.location.pathname}${e.location.search}`)}function Al(){return window.parent!==window}function _l(){if(Al())return!1;try{const{libraryState:e}=function(){const e=window.location.hash,t=window.location.search;let r,o=!1,n=!1,i="";if(e&&e.length>1){const t="#"===e.charAt(0)?e.substring(1):e,n=new URLSearchParams(t);n.has("state")&&(o=!0,i=t,r=n)}if(t&&t.length>1){const e="?"===t.charAt(0)?t.substring(1):t,o=new URLSearchParams(e);o.has("state")&&(n=!0,i=e,r=o)}o&&n&&(i=`${"?"===t.charAt(0)?t.substring(1):t}${"#"===e.charAt(0)?e.substring(1):e}`,r=new URLSearchParams(i));if(!i||!r)throw Ui("empty_response","");const s=r.get("state");if(!s)throw Ui(Fi,"");const{libraryState:a}=$c(ts,s,""),{id:c,meta:l}=a;if(!c||!l)throw Ui(zi,"","missing_library_state");return{params:r,payload:i,urlHash:e,urlQuery:t,hasResponseInHash:o,hasResponseInQuery:n,libraryState:{id:c,meta:l}}}(),{meta:t}=e;return t.interactionType===Cn.Popup}catch(e){return!1}}let El=null;async function Pl(e,t,r,o,n){return new Promise((i,s)=>{t.verbose("1rf6em",r.correlationId);const a=r.correlationId;o.addFields({redirectBridgeTimeoutMs:e,lateResponseExperimentEnabled:n?.iframeTimeoutTelemetry||!1},a);const{libraryState:c}=$c(ts,r.state||"",r.correlationId),l=new BroadcastChannel(c.id);let h,d,u,g=!1;const p=window.setTimeout(()=>{El=null,n?.iframeTimeoutTelemetry?(u=o.startMeasurement("waitForBridgeLateResponse",a),g=!0,d=window.setTimeout(()=>{u?.end({success:!1}),clearTimeout(d),l.close()},6e4)):l.close(),s(Ui(es,"","redirect_bridge_timeout"))},e);El={timeoutId:p,channel:l,reject:s},l.onmessage=e=>{h=e.data.payload;const t=e?.data&&"number"==typeof e.data.v?e.data.v:void 0;if(g)return u?.end({success:!!h}),clearTimeout(d),void l.close();o.addFields({redirectBridgeMessageVersion:t},a),El=null,clearTimeout(p),l.close(),h?i(h):s(Ui("redirect_bridge_empty_response",a))}})}function xl(){return"undefined"!=typeof window&&window.location?window.location.href.split("?")[0].split("#")[0]:""}function Ol(){if("undefined"==typeof window)throw Ui(Ki,"")}function Rl(e){if(!e)throw Ui(Xi,"")}function Ml(e){Ol(),function(){if(Lc(window.location.hash)&&Al())throw Ui("block_iframe_reload","")}(),function(){if(_l())throw Ui("block_nested_popups","")}(),Rl(e)}function ql(e,t){if(Ml(e),function(e){if(Al()&&!e)throw Ui("redirect_in_iframe","")}(t.system.allowRedirectInIframe),t.cache.cacheLocation===Qo)throw sc("in_mem_redirect_unavailable","")}function $l(e){const t=document.createElement("link");t.rel="preconnect",t.href=new URL(e).origin,t.crossOrigin="anonymous",document.head.appendChild(t),window.setTimeout(()=>{try{document.head.removeChild(t)}catch{}},1e4)}function Ul(){return fs()}const Ll="@azure/msal-browser",Nl="5.16.0";function Dl(e,t){const r=e.indexOf(t);r>-1&&e.splice(r,1)}const Hl="invalid",Fl="ttlExpired",zl="decryptFailed",jl="expired";class Bl extends Ja{constructor(e,t,r,o,n,i,s){super(e,r,o,n,s),this.cacheConfig=t,this.logger=o,this.internalStorage=new As,this.browserStorage=Kl(e,t.cacheLocation,o,n),this.temporaryCacheStorage=Kl(e,Go,o,n),this.cookieStorage=new hc,this.eventHandler=i}async initialize(e){this.performanceClient.addFields({cacheLocation:this.cacheConfig.cacheLocation,cacheRetentionDays:this.cacheConfig.cacheRetentionDays},e),await this.browserStorage.initialize(e),await this.migrateExistingCache(e),this.trackVersionChanges(e)}async migrateExistingCache(e){let t=dc(this.browserStorage),r=uc(this.clientId,this.browserStorage);this.performanceClient.addFields({preMigrateAcntCount:t.length,preMigrateATCount:r.accessToken.length,preMigrateITCount:r.idToken.length,preMigrateRTCount:r.refreshToken.length},e);for(let t=0;t<3;t++){const r=t;await this.removeStaleAccounts(t,r,e)}for(let t=0;t<3;t++){const r=t;await this.migrateIdTokens(t,r,e)}const o=this.getKMSIValues();for(let t=0;t<3;t++)await this.migrateAccessTokens(t,o,e),await this.migrateRefreshTokens(t,o,e);t=dc(this.browserStorage),r=uc(this.clientId,this.browserStorage),this.performanceClient.addFields({postMigrateAcntCount:t.length,postMigrateATCount:r.accessToken.length,postMigrateITCount:r.idToken.length,postMigrateRTCount:r.refreshToken.length},e)}async updateOldEntry(e,t){const r=this.browserStorage.getItem(e),o=this.validateAndParseJson(r||"");if(!o)return this.browserStorage.removeItem(e),{entry:null,removalReason:Hl};if(o.lastUpdatedAt){if(va(o.lastUpdatedAt,this.cacheConfig.cacheRetentionDays))return this.browserStorage.removeItem(e),{entry:null,removalReason:Fl}}else o.lastUpdatedAt=Date.now().toString(),this.setItem(e,JSON.stringify(o),t);const n=gc(o),i=n?await this.browserStorage.decryptData(e,o,t):o;return i?ba(i)?(ka(i)||Sa(i))&&i.expiresOn&&wa(i.expiresOn,300)?(this.browserStorage.removeItem(e),{entry:null,removalReason:jl}):{entry:i}:(this.browserStorage.removeItem(e),{entry:null,removalReason:Hl}):(this.browserStorage.removeItem(e),{entry:null,removalReason:n?zl:Hl})}async removeStaleAccounts(e,t,r){const o=dc(this.browserStorage,e);if(0!==o.length){for(const e of[...o]){this.performanceClient.incrementFields({oldAcntCount:1},r);const n=this.browserStorage.getItem(e),i=this.validateAndParseJson(n||"");if(i)if(i.lastUpdatedAt){if(va(i.lastUpdatedAt,this.cacheConfig.cacheRetentionDays))await this.removeAccountOldSchema(e,i,t,r),this.performanceClient.incrementFields({ttlExpiredAcntCount:1},r),Dl(o,e);else if(gc(i)){await this.browserStorage.decryptData(e,i,r)||(this.browserStorage.removeItem(e),this.performanceClient.incrementFields({decryptFailedAcntCount:1},r),Dl(o,e))}}else i.lastUpdatedAt=Date.now().toString(),this.setItem(e,JSON.stringify(i),r);else this.browserStorage.removeItem(e),this.performanceClient.incrementFields({invalidAcntCount:1},r),Dl(o,e)}this.setAccountKeys(o,r,e)}}async removeAccountOldSchema(e,t,r,o){const n=gc(t)?await this.browserStorage.decryptData(e,t,o):t,i=n?.homeAccountId;if(i){const e=this.getTokenKeys(r);[...e.idToken].filter(e=>e.includes(i)).forEach(t=>{this.browserStorage.removeItem(t),Dl(e.idToken,t)}),[...e.accessToken].filter(e=>e.includes(i)).forEach(t=>{this.browserStorage.removeItem(t),Dl(e.accessToken,t)}),[...e.refreshToken].filter(e=>e.includes(i)).forEach(t=>{this.browserStorage.removeItem(t),Dl(e.refreshToken,t)}),this.setTokenKeys(e,o,r)}this.browserStorage.removeItem(e)}getKMSIValues(){const e={},t=this.getTokenKeys().idToken;for(const r of t){const t=this.browserStorage.getUserData(r);if(t){const r=JSON.parse(t),o=ga(r.secret,ts,"");o&&(e[r.homeAccountId]=pa(o))}}return e}async migrateIdTokens(e,t,r){const o=uc(this.clientId,this.browserStorage,e);if(0===o.idToken.length)return;const n=uc(this.clientId,this.browserStorage,3),i=dc(this.browserStorage),s=dc(this.browserStorage,t);for(const e of[...o.idToken]){this.performanceClient.incrementFields({oldITCount:1},r);const t=await this.updateOldEntry(e,r),a=t.entry;if(!a){switch(t.removalReason){case Fl:this.performanceClient.incrementFields({ttlExpiredITCount:1},r);break;case zl:this.performanceClient.incrementFields({decryptFailedITCount:1},r);break;case Hl:this.performanceClient.incrementFields({invalidITCount:1},r)}Dl(o.idToken,e);continue}const c=i.find(e=>e.includes(a.homeAccountId)),l=s.find(e=>e.includes(a.homeAccountId));let h=null;if(c)h=this.getAccount(c,r);else if(l){const e=this.browserStorage.getItem(l),t=this.validateAndParseJson(e||"");h=t&&gc(t)?await this.browserStorage.decryptData(l,t,r):t}if(!h){this.performanceClient.incrementFields({skipITMigrateCount:1},r);continue}const d=ga(a.secret,ts,r),u=this.generateCredentialKey(a),g=this.getIdTokenCredential(u,r),p=Object.keys(d).includes("signin_state"),m=g&&Object.keys(ga(g.secret,ts,r)||{}).includes("signin_state");if(!g||a.lastUpdatedAt>g.lastUpdatedAt&&(p||!m)){const e=h.tenantProfiles||[],t=Ua(d)||h.realm;if(t&&!e.find(e=>e.tenantId===t)){const r=qa(h.homeAccountId,h.localAccountId,t,h.nativeAccountId,d);e.push(r)}h.tenantProfiles=e;const o=this.generateAccountKey(La(h)),s=pa(d);await this.setUserData(o,JSON.stringify(h),r,h.lastUpdatedAt,s),i.includes(o)||i.push(o),await this.setUserData(u,JSON.stringify(a),r,a.lastUpdatedAt,s),this.performanceClient.incrementFields({migratedITCount:1},r),n.idToken.includes(u)||n.idToken.push(u)}}this.setTokenKeys(o,r,e),this.setTokenKeys(n,r),this.setAccountKeys(i,r)}async migrateAccessTokens(e,t,r){const o=uc(this.clientId,this.browserStorage,e);if(0===o.accessToken.length)return;const n=uc(this.clientId,this.browserStorage,3);for(const e of[...o.accessToken]){this.performanceClient.incrementFields({oldATCount:1},r);const i=await this.updateOldEntry(e,r),s=i.entry;if(!s){switch(i.removalReason){case Fl:this.performanceClient.incrementFields({ttlExpiredATCount:1},r);break;case zl:this.performanceClient.incrementFields({decryptFailedATCount:1},r);break;case jl:this.performanceClient.incrementFields({expiredATCount:1},r);break;case Hl:this.performanceClient.incrementFields({invalidATCount:1},r)}Dl(o.accessToken,e);continue}if(!(s.homeAccountId in t)){this.performanceClient.incrementFields({skipATMigrateCount:1},r);continue}const a=this.generateCredentialKey(s),c=t[s.homeAccountId];if(n.accessToken.includes(a)){const e=this.getAccessTokenCredential(a,r);(!e||s.lastUpdatedAt>e.lastUpdatedAt)&&(await this.setUserData(a,JSON.stringify(s),r,s.lastUpdatedAt,c),this.performanceClient.incrementFields({migratedATCount:1},r))}else await this.setUserData(a,JSON.stringify(s),r,s.lastUpdatedAt,c),this.performanceClient.incrementFields({migratedATCount:1},r),n.accessToken.push(a)}this.setTokenKeys(o,r,e),this.setTokenKeys(n,r)}async migrateRefreshTokens(e,t,r){const o=uc(this.clientId,this.browserStorage,e);if(0===o.refreshToken.length)return;const n=uc(this.clientId,this.browserStorage,3);for(const e of[...o.refreshToken]){this.performanceClient.incrementFields({oldRTCount:1},r);const i=await this.updateOldEntry(e,r),s=i.entry;if(!s){switch(i.removalReason){case Fl:this.performanceClient.incrementFields({ttlExpiredRTCount:1},r);break;case zl:this.performanceClient.incrementFields({decryptFailedRTCount:1},r);break;case jl:this.performanceClient.incrementFields({expiredRTCount:1},r);break;case Hl:this.performanceClient.incrementFields({invalidRTCount:1},r)}Dl(o.refreshToken,e);continue}if(!(s.homeAccountId in t)){this.performanceClient.incrementFields({skipRTMigrateCount:1},r);continue}const a=this.generateCredentialKey(s),c=t[s.homeAccountId];if(n.refreshToken.includes(a)){const e=this.getRefreshTokenCredential(a,r);(!e||s.lastUpdatedAt>e.lastUpdatedAt)&&(await this.setUserData(a,JSON.stringify(s),r,s.lastUpdatedAt,c),this.performanceClient.incrementFields({migratedRTCount:1},r))}else await this.setUserData(a,JSON.stringify(s),r,s.lastUpdatedAt,c),this.performanceClient.incrementFields({migratedRTCount:1},r),n.refreshToken.push(a)}this.setTokenKeys(o,r,e),this.setTokenKeys(n,r)}trackVersionChanges(e){const t=this.browserStorage.getItem(Za);t&&(this.logger.info(`1wuc87 ${t}`,e),this.performanceClient.addGlobalFields({previousLibraryVersion:t})),t!==Nl&&this.setItem(Za,Nl,e)}validateAndParseJson(e){if(!e)return null;try{const t=JSON.parse(e);return t&&"object"==typeof t?t:null}catch(e){return null}}setItem(e,t,r){const o=new Array(4).fill(0),n=[];for(let i=0;i<=20;i++)try{if(this.browserStorage.setItem(e,t),i>0)for(let e=0;e<=3;e++){const t=o.slice(0,e).reduce((e,t)=>e+t,0);if(t>=i)break;const s=i>t+o[e]?t+o[e]:i;i>t&&o[e]>0&&this.removeAccessTokenKeys(n.slice(t,s),r,e)}break}catch(s){const a=ja(s);if(!(a.errorCode===Fa&&i<20))throw a;if(!n.length)for(let r=0;r<=3;r++)if(e===nc(this.clientId,r)){const e=JSON.parse(t).accessToken;n.push(...e),o[r]=e.length}else{const e=this.getTokenKeys(r).accessToken;n.push(...e),o[r]=e.length}if(n.length<=i)throw a;this.removeAccessToken(n[i],r,!1)}}async setUserData(e,t,r,o,n){const i=new Array(4).fill(0),s=[];for(let a=0;a<=20;a++)try{if(await da(this.browserStorage.setUserData.bind(this.browserStorage),"setUserData",this.logger,this.performanceClient,r)(e,t,r,o,n),a>0)for(let e=0;e<=3;e++){const t=i.slice(0,e).reduce((e,t)=>e+t,0);if(t>=a)break;const o=a>t+i[e]?t+i[e]:a;a>t&&i[e]>0&&this.removeAccessTokenKeys(s.slice(t,o),r,e)}break}catch(e){const t=ja(e);if(!(t.errorCode===Fa&&a<20))throw t;if(!s.length)for(let e=0;e<=3;e++){const t=this.getTokenKeys(e).accessToken;s.push(...t),i[e]=t.length}if(s.length<=a)throw t;this.removeAccessToken(s[a],r,!1)}}getAccount(e,t){this.logger.trace("1lfvm6",t);const r=this.browserStorage.getUserData(e);if(!r)return this.removeAccountKeyFromMap(e,t),null;const o=this.validateAndParseJson(r);if(!(o&&(n=o,n&&n.hasOwnProperty("homeAccountId")&&n.hasOwnProperty("environment")&&n.hasOwnProperty("realm")&&n.hasOwnProperty("localAccountId")&&n.hasOwnProperty("username")&&n.hasOwnProperty("authorityType"))))return null;var n;const i=Ja.toObject({},o);var s;return this.performanceClient.addFields({accountCachedBy:(s=i.cachedByApiId,"number"==typeof s&&s in vn?vn[s]:"unknown")},t),i}async setAccount(e,t,r,o){this.logger.trace("1bz3wr",t);const n=this.generateAccountKey(La(e)),i=Date.now().toString();e.lastUpdatedAt=i,e.cachedByApiId=o,await this.setUserData(n,JSON.stringify(e),t,i,r),this.addAccountKeyToMap(n,t),this.performanceClient.addFields({kmsi:r},t)}setAccountKeys(e,t,r=3){0===e.length?this.removeItem(oc(r)):this.setItem(oc(r),JSON.stringify(e),t)}getAccountKeys(){return dc(this.browserStorage)}addAccountKeyToMap(e,t){this.logger.trace("0rb85k",t),this.logger.tracePii(`1l9bdo ${e}`,t);const r=this.getAccountKeys();return-1===r.indexOf(e)?(r.push(e),this.setItem(oc(),JSON.stringify(r),t),this.logger.verbose("0xia39",t),!0):(this.logger.verbose("0161kk",t),!1)}removeAccountKeyFromMap(e,t){this.logger.trace("1jpigu",t),this.logger.tracePii(`1xzspl ${e}`,t);const r=this.getAccountKeys(),o=r.indexOf(e);o>-1?(r.splice(o,1),this.setAccountKeys(r,t)):this.logger.trace("1dytu2",t)}removeAccount(e,t){const r=this.getActiveAccount(t);r?.homeAccountId===e.homeAccountId&&r?.environment===e.environment&&this.setActiveAccount(null,t),super.removeAccount(e,t),this.removeAccountKeyFromMap(this.generateAccountKey(e),t),this.browserStorage.getKeys().forEach(t=>{t.includes(e.homeAccountId)&&t.includes(e.environment)&&this.browserStorage.removeItem(t)})}removeIdToken(e,t){super.removeIdToken(e,t);const r=this.getTokenKeys(),o=r.idToken.indexOf(e);o>-1&&(this.logger.info("05udv9",t),r.idToken.splice(o,1),this.setTokenKeys(r,t))}removeAccessToken(e,t,r=!0){super.removeAccessToken(e,t),r&&this.removeAccessTokenKeys([e],t)}removeAccessTokenKeys(e,t,r=3){this.logger.trace("17o18n",t);const o=this.getTokenKeys(r);let n=0;if(e.forEach(e=>{const t=o.accessToken.indexOf(e);t>-1&&(o.accessToken.splice(t,1),n++)}),n>0)return this.logger.info(`15i5d5 ${n}`,t),void this.setTokenKeys(o,t,r)}removeRefreshToken(e,t){super.removeRefreshToken(e,t);const r=this.getTokenKeys(),o=r.refreshToken.indexOf(e);o>-1&&(this.logger.info("1f4fq3",t),r.refreshToken.splice(o,1),this.setTokenKeys(r,t))}getTokenKeys(e=3){return uc(this.clientId,this.browserStorage,e)}setTokenKeys(e,t,r=3){0!==e.idToken.length||0!==e.accessToken.length||0!==e.refreshToken.length?this.setItem(nc(this.clientId,r),JSON.stringify(e),t):this.removeItem(nc(this.clientId,r))}getIdTokenCredential(e,t){const r=this.browserStorage.getUserData(e);if(!r)return this.logger.trace("1jukz6",t),this.removeIdToken(e,t),null;const o=this.validateAndParseJson(r);return o&&((n=o)&&ba(n)&&n.hasOwnProperty("realm")&&n.credentialType===io.ID_TOKEN)?(this.logger.trace("01ju66",t),o):(this.logger.trace("1jukz6",t),null);var n}async setIdTokenCredential(e,t,r){this.logger.trace("13hjll",t);const o=this.generateCredentialKey(e),n=Date.now().toString();e.lastUpdatedAt=n,await this.setUserData(o,JSON.stringify(e),t,n,r);const i=this.getTokenKeys();-1===i.idToken.indexOf(o)&&(this.logger.info("07jy92",t),i.idToken.push(o),this.setTokenKeys(i,t))}getAccessTokenCredential(e,t){const r=this.browserStorage.getUserData(e);if(!r)return this.logger.trace("0bqvx8",t),this.removeAccessTokenKeys([e],t),null;const o=this.validateAndParseJson(r);return o&&ka(o)?(this.logger.trace("1o81rl",t),o):(this.logger.trace("0bqvx8",t),null)}async setAccessTokenCredential(e,t,r){this.logger.trace("1pondb",t);const o=this.generateCredentialKey(e),n=Date.now().toString();e.lastUpdatedAt=n,await this.setUserData(o,JSON.stringify(e),t,n,r);const i=this.getTokenKeys(),s=i.accessToken.indexOf(o);-1!==s&&i.accessToken.splice(s,1),this.logger.trace("1onhey "+(-1===s?"added to":"updated in"),t),i.accessToken.push(o),this.setTokenKeys(i,t)}getRefreshTokenCredential(e,t){const r=this.browserStorage.getUserData(e);if(!r)return this.logger.trace("0jlizt",t),this.removeRefreshToken(e,t),null;const o=this.validateAndParseJson(r);return o&&Sa(o)?(this.logger.trace("0nokxi",t),o):(this.logger.trace("0jlizt",t),null)}async setRefreshTokenCredential(e,t,r){this.logger.trace("0tcg8d",t);const o=this.generateCredentialKey(e),n=Date.now().toString();e.lastUpdatedAt=n,await this.setUserData(o,JSON.stringify(e),t,n,r);const i=this.getTokenKeys();-1===i.refreshToken.indexOf(o)&&(this.logger.info("0eckjs",t),i.refreshToken.push(o),this.setTokenKeys(i,t))}getAppMetadata(e,t){const r=this.browserStorage.getItem(e);if(!r)return this.logger.trace("1q101h",t),null;const o=this.validateAndParseJson(r);return o&&(n=e,(i=o)&&0===n.indexOf(so)&&i.hasOwnProperty("clientId")&&i.hasOwnProperty("environment"))?(this.logger.trace("19pvg2",t),o):(this.logger.trace("1q101h",t),null);var n,i}setAppMetadata(e,t){this.logger.trace("0cyma6",t);const r=function({environment:e,clientId:t}){return[so,e,t].join("-").toLowerCase()}(e);this.setItem(r,JSON.stringify(e),t)}getServerTelemetry(e,t){const r=this.browserStorage.getItem(e);if(!r)return this.logger.trace("0jk19c",t),null;const o=this.validateAndParseJson(r);return o&&function(e,t){const r=0===e.indexOf(mo);let o=!0;return t&&(o=t.hasOwnProperty("failedRequests")&&t.hasOwnProperty("errors")&&t.hasOwnProperty("cacheHits")),r&&o}(e,o)?(this.logger.trace("12jguk",t),o):(this.logger.trace("0jk19c",t),null)}setServerTelemetry(e,t,r){this.logger.trace("1poh61",r),this.setItem(e,JSON.stringify(t),r)}getAuthorityMetadata(e,t){const r=this.internalStorage.getItem(e);if(!r)return this.logger.trace("1r39oe",t),null;const o=this.validateAndParseJson(r);return o&&function(e,t){return!!t&&0===e.indexOf(co)&&t.hasOwnProperty("aliases")&&t.hasOwnProperty("preferred_cache")&&t.hasOwnProperty("preferred_network")&&t.hasOwnProperty("canonical_authority")&&t.hasOwnProperty("authorization_endpoint")&&t.hasOwnProperty("token_endpoint")&&t.hasOwnProperty("issuer")&&t.hasOwnProperty("aliasesFromNetwork")&&t.hasOwnProperty("endpointsFromNetwork")&&t.hasOwnProperty("expiresAt")&&t.hasOwnProperty("jwks_uri")}(e,o)?(this.logger.trace("1ohvk3",t),o):null}getAuthorityMetadataKeys(){return this.internalStorage.getKeys().filter(e=>this.isAuthorityMetadata(e))}setWrapperMetadata(e,t){this.internalStorage.setItem(cn,e),this.internalStorage.setItem(ln,t)}getWrapperMetadata(){return[this.internalStorage.getItem(cn)||"",this.internalStorage.getItem(ln)||""]}setAuthorityMetadata(e,t,r){this.logger.trace("07w8n2",r),this.internalStorage.setItem(e,JSON.stringify(t))}getActiveAccount(e){const t=this.generateCacheKey(Nr),r=this.browserStorage.getItem(t);if(!r)return this.logger.trace("08gw0e",e),null;const o=this.validateAndParseJson(r);return o?(this.logger.trace("1t3ch7",e),this.getAccountInfoFilteredBy({homeAccountId:o.homeAccountId,localAccountId:o.localAccountId,tenantId:o.tenantId},e)):(this.logger.trace("0me1up",e),null)}setActiveAccount(e,t){const r=this.generateCacheKey(Nr);if(e){this.logger.verbose("0rsj80",t);const o={homeAccountId:e.homeAccountId,localAccountId:e.localAccountId,tenantId:e.tenantId};this.setItem(r,JSON.stringify(o),t)}else this.logger.verbose("1bp5z5",t),this.browserStorage.removeItem(r);this.eventHandler.emitEvent(Cc,t)}getThrottlingCache(e,t){const r=this.browserStorage.getItem(e);if(!r)return this.logger.trace("1h4wa6",t),null;const o=this.validateAndParseJson(r);return o&&function(e,t){let r=!1;e&&(r=0===e.indexOf(wo));let o=!0;return t&&(o=t.hasOwnProperty("throttleTime")),r&&o}(e,o)?(this.logger.trace("0of6n8",t),o):(this.logger.trace("1h4wa6",t),null)}setThrottlingCache(e,t,r){this.logger.trace("0wfgh6",r),this.setItem(e,JSON.stringify(t),r)}getTemporaryCache(e,t,r){this.logger.trace("1ordf8",t);const o=r?this.generateCacheKey(e):e;return this.temporaryCacheStorage.getItem(o)}setTemporaryCache(e,t,r){const o=r?this.generateCacheKey(e):e;this.temporaryCacheStorage.setItem(o,t)}removeItem(e){this.browserStorage.removeItem(e)}removeTemporaryItem(e){this.temporaryCacheStorage.removeItem(e)}getKeys(){return this.browserStorage.getKeys()}clear(e){this.removeAllAccounts(e),this.removeAppMetadata(e),this.temporaryCacheStorage.getKeys().forEach(e=>{-1===e.indexOf(Ga)&&-1===e.indexOf(this.clientId)||this.removeTemporaryItem(e)}),this.browserStorage.getKeys().forEach(e=>{-1===e.indexOf(Ga)&&-1===e.indexOf(this.clientId)||this.browserStorage.removeItem(e)}),this.internalStorage.clear()}generateCacheKey(e){return Ds.startsWith(e,Ga)?e:`${Ga}.${this.clientId}.${e}`}generateCredentialKey(e){const t=e.credentialType===io.REFRESH_TOKEN&&e.familyId||e.clientId,r=e.tokenType&&e.tokenType.toLowerCase()!==yo.BEARER.toLowerCase()?e.tokenType.toLowerCase():"";return[`${Ga}.3`,e.homeAccountId,e.environment,e.credentialType,t,e.realm||"",e.target||"",r].join("|").toLowerCase()}generateAccountKey(e){const t=e.homeAccountId.split(".")[1];return[`${Ga}.3`,e.homeAccountId,e.environment,t||e.tenantId||""].join("|").toLowerCase()}resetRequestCache(e){this.logger.trace("0h0ynu",e),this.removeTemporaryItem(this.generateCacheKey(on)),this.removeTemporaryItem(this.generateCacheKey(nn)),this.removeTemporaryItem(this.generateCacheKey(tn)),this.removeTemporaryItem(this.generateCacheKey(rn)),this.removeTemporaryItem(this.generateCacheKey(an)),this.setInteractionInProgress(!1,void 0)}cacheAuthorizeRequest(e,t,r){this.logger.trace("1tzef5",t);const o=Ri(JSON.stringify(e));if(this.setTemporaryCache(on,o,!0),r){const e=Ri(r);this.setTemporaryCache(nn,e,!0)}}getCachedRequest(e){this.logger.trace("0uen20",e);const t=this.getTemporaryCache(on,e,!0);if(!t)throw Ui("no_token_request_cache_error","");const r=this.getTemporaryCache(nn,e,!0);let o,n="";try{o=JSON.parse(ts(t)),r&&(n=ts(r))}catch(r){throw this.logger.errorPii(`0ewsey ${t}`,e),this.logger.error(`0tvdic ${r}`,e),Ui("unable_to_parse_token_request_cache_error","")}return[o,n]}getCachedNativeRequest(){this.logger.trace("1yxcdm","");const e=this.getTemporaryCache(an,"",!0);if(!e)return this.logger.trace("0mnxd4",""),null;const t=this.validateAndParseJson(e);return t||(this.logger.error("0rrkip",""),null)}isInteractionInProgress(e){const t=this.getInteractionInProgress()?.clientId;return e?t===this.clientId:!!t}getInteractionInProgress(){const e=`${Ga}.${sn}`,t=this.getTemporaryCache(e,"",!1);try{return t?JSON.parse(t):null}catch(t){return this.logger.error("0jjyys",""),this.removeTemporaryItem(e),this.resetRequestCache(""),Tl(window),null}}setInteractionInProgress(e,t=Zo,r=!1,o=""){const n=`${Ga}.${sn}`;if(e){const e=this.getInteractionInProgress();if(e){if(!r)throw Ui("interaction_in_progress","");this.logger.warning(`1pmscr ${e.clientId} ${e.type}`,o),function(e,t){El&&(e.verbose("18y01k",t),clearTimeout(El.timeoutId),El.channel.close(),El.reject(Ui("interaction_in_progress_cancelled","")),El=null)}(this.logger,o),this.removeTemporaryItem(n)}this.setTemporaryCache(n,JSON.stringify({clientId:this.clientId,type:t}),!1)}else e||this.getInteractionInProgress()?.clientId!==this.clientId||this.removeTemporaryItem(n)}async hydrateCache(e,t){const r=Ca(e.account.homeAccountId,e.account.environment,e.idToken,this.clientId,e.tenantId),o=Ia(e.account.homeAccountId,e.account.environment,e.accessToken,this.clientId,e.tenantId,e.scopes.join(" "),e.expiresOn?fa(e.expiresOn):0,e.extExpiresOn?fa(e.extExpiresOn):0,ts,t.correlationId||"",void 0,e.tokenType,void 0,t.sshKid);t.resource&&(o.resource=t.resource);const n={idToken:r,accessToken:o};return this.saveCacheRecord(n,e.correlationId,pa(ga(e.idToken,ts,e.correlationId)),wn)}async saveCacheRecord(e,t,r,o,n){try{await super.saveCacheRecord(e,t,r,o,n)}catch(e){if(e instanceof za&&this.performanceClient&&t)try{const e=this.getTokenKeys();this.performanceClient.addFields({cacheRtCount:e.refreshToken.length,cacheIdCount:e.idToken.length,cacheAtCount:e.accessToken.length},t)}catch(e){}throw e}}}function Kl(e,t,r,o){try{switch(t){case Vo:return new fc(e,r,o);case Go:return new yc}}catch(e){r.error(e,"")}return new As}var Wl;!function(e){e[e.Error=0]="Error",e[e.Warning=1]="Warning",e[e.Info=2]="Info",e[e.Verbose=3]="Verbose",e[e.Trace=4]="Trace"}(Wl||(Wl={}));const Jl=new Map;function Vl(e,t){const r=Date.now();let o=Jl.get(e);if(o)!function(e,t){Jl.delete(e),Jl.set(e,t)}(e,o);else if(o={logs:[],firstEventTime:r},Jl.set(e,o),Jl.size>50){const e=Jl.keys().next().value;void 0!==e&&Jl.delete(e)}o.logs.push({...t,milliseconds:r-o.firstEventTime}),o.logs.length>500&&o.logs.shift()}class Gl{constructor(e,t,r){this.level=Wl.Info;const o=e||Gl.createDefaultLoggerOptions();this.localCallback=o.loggerCallback||(()=>{}),this.piiLoggingEnabled=o.piiLoggingEnabled||!1,this.level="number"==typeof o.logLevel?o.logLevel:Wl.Info,this.packageName=t||"",this.packageVersion=r||""}static createDefaultLoggerOptions(){return{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:Wl.Info}}clone(e,t){return new Gl({loggerCallback:this.localCallback,piiLoggingEnabled:this.piiLoggingEnabled,logLevel:this.level},e,t)}logMessage(e,t){const r=t.correlationId,o=function(e){if(e.length<6)return null;if(e.length>6&&" "!==e[6])return null;for(let t=0;t<6;t++){const r=e[t];if(!(r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"))return null}return e.substring(0,6)}(e);if(o){Vl(r,{hash:o,level:t.logLevel,containsPii:t.containsPii||!1,milliseconds:0})}if(t.logLevel>this.level||!this.piiLoggingEnabled&&t.containsPii)return;const n=`${`[${(new Date).toUTCString()}] : [${r}]`} : ${this.packageName}@${this.packageVersion} : ${Wl[t.logLevel]} - ${e}`;this.executeCallback(t.logLevel,n,t.containsPii||!1)}executeCallback(e,t,r){this.localCallback&&this.localCallback(e,t,r)}error(e,t){this.logMessage(e,{logLevel:Wl.Error,containsPii:!1,correlationId:t})}errorPii(e,t){this.logMessage(e,{logLevel:Wl.Error,containsPii:!0,correlationId:t})}warning(e,t){this.logMessage(e,{logLevel:Wl.Warning,containsPii:!1,correlationId:t})}warningPii(e,t){this.logMessage(e,{logLevel:Wl.Warning,containsPii:!0,correlationId:t})}info(e,t){this.logMessage(e,{logLevel:Wl.Info,containsPii:!1,correlationId:t})}infoPii(e,t){this.logMessage(e,{logLevel:Wl.Info,containsPii:!0,correlationId:t})}verbose(e,t){this.logMessage(e,{logLevel:Wl.Verbose,containsPii:!1,correlationId:t})}verbosePii(e,t){this.logMessage(e,{logLevel:Wl.Verbose,containsPii:!0,correlationId:t})}trace(e,t){this.logMessage(e,{logLevel:Wl.Trace,containsPii:!1,correlationId:t})}tracePii(e,t){this.logMessage(e,{logLevel:Wl.Trace,containsPii:!0,correlationId:t})}isPiiLoggingEnabled(){return this.piiLoggingEnabled||!1}}class Ql{constructor(e){this.eventCallbacks=new Map,this.logger=e||new Gl({},Ll,Nl),"undefined"!=typeof BroadcastChannel&&(this.broadcastChannel=new BroadcastChannel("msal.broadcast.event")),this.invokeCrossTabCallbacks=this.invokeCrossTabCallbacks.bind(this)}addEventCallback(e,t,r){if("undefined"!=typeof window){const o=r||Ul();return this.eventCallbacks.has(o)?(this.logger.error(`1578i0 ${o}`,""),null):(this.eventCallbacks.set(o,[e,t||[]]),this.logger.verbose(`1cnec4 ${o}`,""),o)}return null}removeEventCallback(e){this.eventCallbacks.delete(e),this.logger.verbose(`12zotd ${e}`,"")}emitEvent(e,t,r,o,n){const i={eventType:e,interactionType:r||null,payload:o||null,error:n||null,correlationId:t,timestamp:Date.now()};switch(e){case Ic:case xc:case Cc:this.broadcastChannel?.postMessage(i)}this.invokeCallbacks(i)}invokeCallbacks(e){this.eventCallbacks.forEach(([t,r],o)=>{(0===r.length||r.includes(e.eventType))&&(this.logger.verbose(`15jpwk ${o} ${e.eventType}`,""),t.apply(null,[e]))})}invokeCrossTabCallbacks(e){const t=e.data;this.invokeCallbacks(t)}subscribeCrossTab(){this.broadcastChannel?.addEventListener("message",this.invokeCrossTabCallbacks)}unsubscribeCrossTab(){this.broadcastChannel?.removeEventListener("message",this.invokeCrossTabCallbacks)}}const Yl=1;new Set(["accessTokenSize","durationMs","idTokenSize","matsSilentStatus","matsHttpStatus","refreshTokenSize","startTimeMs","status","multiMatchedAT","multiMatchedID","multiMatchedRT","unencryptedCacheCount","encryptedCacheExpiredCount","oldAccountCount","oldAccessCount","oldIdCount","oldRefreshCount","currAccountCount","currAccessCount","currIdCount","currRefreshCount","ttlExpiredAcntCount","ttlExpiredITCount","ttlExpiredATCount","ttlExpiredRTCount","decryptFailedAcntCount","decryptFailedITCount","decryptFailedATCount","decryptFailedRTCount","invalidAcntCount","invalidITCount","invalidATCount","invalidRTCount","expiredATCount","expiredRTCount","upgradedCacheCount","cacheMatchedAccounts","networkRtt","redirectBridgeTimeoutMs","redirectBridgeMessageVersion"]);class Xl{generateId(){return"callback-id"}startMeasurement(e,t){return{end:()=>null,discard:()=>{},add:()=>{},increment:()=>{},event:{eventId:this.generateId(),status:Yl,authority:"",libraryName:"",libraryVersion:"",clientId:"",name:e,startTimeMs:Date.now(),correlationId:t||""}}}endMeasurement(){return null}discardMeasurements(){}removePerformanceCallback(){return!0}addPerformanceCallback(){return""}emitEvents(){}addFields(){}addGlobalFields(){}incrementFields(){}cacheEventByCorrelationId(){}}const Zl={tokenRenewalOffsetSeconds:300,preventCorsPreflight:!1},eh={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:Wl.Info,correlationId:""},th={async sendGetRequestAsync(){throw Wn(ai,"")},async sendPostRequestAsync(){throw Wn(ai,"")}},rh={sku:"msal.js.common",version:Ka,cpu:"",os:""},oh={clientSecret:"",clientAssertion:void 0},nh={azureCloudInstance:ta,tenant:`${fr}`},ih={application:{appName:"",appVersion:""}};function sh({authOptions:e,systemOptions:t,loggerOptions:r,storageInterface:o,networkInterface:n,cryptoInterface:i,clientCredentials:s,libraryInfo:a,telemetry:c,serverTelemetryManager:l,persistencePlugin:h,serializableCache:d}){const u={...eh,...r};return{authOptions:(g=e,{clientCapabilities:[],azureCloudOptions:nh,instanceAware:!1,isMcp:!1,...g}),systemOptions:{...Zl,...t},loggerOptions:u,storageInterface:o||new Va(e.clientId,Rs,new Gl(u,Ba,Ka),new Xl),networkInterface:n||th,cryptoInterface:i||Rs,clientCredentials:s||oh,libraryInfo:{...rh,...a},telemetry:{...ih,...c},serverTelemetryManager:l||null,persistencePlugin:h||null,serializableCache:d||null};var g}function ah(e){return e.authOptions.authority.options.protocolMode===Zs}class ch{constructor(e,t){this.cache=e,this.hasChanged=t}get cacheHasChanged(){return this.hasChanged}get tokenCache(){return this.cache}}const lh="sw";class hh{constructor(e,t){this.cryptoUtils=e,this.performanceClient=t}async generateCnf(e,t){const r=await da(this.generateKid.bind(this),sa,t,this.performanceClient,e.correlationId)(e),o=this.cryptoUtils.base64UrlEncode(JSON.stringify(r));return{kid:r.kid,reqCnfString:o}}async generateKid(e){return{kid:await this.cryptoUtils.getPublicKeyThumbprint(e),xms_ksl:lh}}async signPopToken(e,t,r){return this.signPayload(e,t,r)}async signPayload(e,t,r,o){const{resourceRequestMethod:n,resourceRequestUri:i,shrClaims:s,shrNonce:a,shrOptions:c}=r,l=i?new Ks(i,r.correlationId):void 0,h=l?.getUrlComponents();return this.cryptoUtils.signJwt({at:e,ts:ma(),m:n?.toUpperCase(),u:h?.HostNameAndPort,nonce:a||this.cryptoUtils.createNewGuid(),p:h?.AbsolutePath,q:h?.QueryString?[[],h.QueryString]:void 0,client_claims:s||void 0,...o},t,c,r.correlationId)}}class dh extends Rn{constructor(e,t,r,o,n,i){super(e,t,r,o),this.name="ServerError",this.errorNo=n,this.status=i,Object.setPrototypeOf(this,dh.prototype)}}class uh{constructor(e,t,r,o,n,i,s){this.clientId=e,this.cacheStorage=t,this.cryptoObj=r,this.logger=o,this.performanceClient=n,this.serializableCache=i,this.persistencePlugin=s}validateTokenResponse(e,t,r){if(e.error||e.error_description||e.suberror){const o=`Error(s): ${e.error_codes||Tr} - Timestamp: ${e.timestamp||Tr} - Description: ${e.error_description||Tr} - Correlation ID: ${e.correlation_id||Tr} - Trace ID: ${e.trace_id||Tr}`,n=e.error_codes?.length?e.error_codes[0]:void 0,i=new dh(e.error||"",e.correlation_id||"",o,e.suberror,n,e.status);if(r&&e.status&&e.status>=500&&e.status<=599)return void this.logger.warning(`16ks7j ${i}`,t);if(r&&e.status&&e.status>=400&&e.status<=499)return void this.logger.warning(`0g61x3 ${i}`,t);if(Fn(e.error,e.error_description,e.suberror))throw new Hn(e.error||"",e.correlation_id||"",e.error_description,e.suberror,e.timestamp||"",e.trace_id||"",e.claims||"",n);throw i}}async handleServerTokenResponse(e,t,r,o,n,i,s,a,c,l,h){let d,u;if(e.id_token&&(d=ga(e.id_token||"",this.cryptoObj.base64Decode,o.correlationId),i&&i.nonce&&d.nonce!==i.nonce))throw Wn("nonce_mismatch",o.correlationId);this.homeAccountIdentifier=Na(e.client_info||"",t.authorityType,this.logger,this.cryptoObj,o.correlationId,d),i&&i.state&&(u=$c(this.cryptoObj.base64Decode,i.state,o.correlationId)),e.key_id=e.key_id||o.sshKid||void 0;const g=this.generateCacheRecord(e,t,r,o,d,s,i,h);let p;try{if(this.persistencePlugin&&this.serializableCache&&(this.logger.verbose("0jbz5k",o.correlationId),p=new ch(this.serializableCache,!0),await this.persistencePlugin.beforeCacheAccess(p)),a&&!c&&g.account){if(this.cacheStorage.getAllAccounts({homeAccountId:g.account.homeAccountId,environment:g.account.environment},o.correlationId).length<1)return this.logger.warning("1gmt66",o.correlationId),this.performanceClient?.addFields({acntLoggedOut:!0},o.correlationId),await uh.generateAuthenticationResult(this.cryptoObj,t,g,!1,o,this.performanceClient,d,u,void 0,l)}await this.cacheStorage.saveCacheRecord(g,o.correlationId,pa(d||{}),n,o.storeInCache)}finally{this.persistencePlugin&&this.serializableCache&&p&&(this.logger.verbose("1bh17u",o.correlationId),await this.persistencePlugin.afterCacheAccess(p))}return uh.generateAuthenticationResult(this.cryptoObj,t,g,!1,o,this.performanceClient,d,u,e,l)}generateCacheRecord(e,t,r,o,n,i,s,a){const c=t.getPreferredCache();if(!c)throw Wn(ri,o.correlationId);const l=Ua(n);let h,d;e.id_token&&n&&(h=Ca(this.homeAccountIdentifier,c,e.id_token,this.clientId,l||""),d=gh(this.cacheStorage,t,this.homeAccountIdentifier,this.cryptoObj.base64Decode,o.correlationId,n,e.client_info,c,l,s,void 0,this.logger,this.performanceClient));let u=null;if(e.access_token){const n=e.scope?Wa.fromString(e.scope,o.correlationId):new Wa(o.scopes||[],o.correlationId),s=("string"==typeof e.expires_in?parseInt(e.expires_in,10):e.expires_in)||0,h=("string"==typeof e.ext_expires_in?parseInt(e.ext_expires_in,10):e.ext_expires_in)||0,d=("string"==typeof e.refresh_in?parseInt(e.refresh_in,10):e.refresh_in)||void 0,g=r+s,p=g+h,m=d&&d>0?r+d:void 0;u=Ia(this.homeAccountIdentifier,c,e.access_token,this.clientId,l||t.tenant||"",n.printScopes(),g,p,this.cryptoObj.base64Decode,o.correlationId,m,e.token_type,i,e.key_id,a);const f=o.resource||null;f&&(u.resource=f)}let g=null;if(e.refresh_token){let t;if(e.refresh_token_expires_in){t=r+("string"==typeof e.refresh_token_expires_in?parseInt(e.refresh_token_expires_in,10):e.refresh_token_expires_in),this.performanceClient?.addFields({ntwkRtExpiresOnSeconds:t},o.correlationId)}g=function(e,t,r,o,n,i,s){const a={credentialType:io.REFRESH_TOKEN,homeAccountId:e,environment:t,clientId:o,secret:r,lastUpdatedAt:Date.now().toString()};return i&&(a.userAssertionHash=i),n&&(a.familyId=n),s&&(a.expiresOn=s.toString()),a}(this.homeAccountIdentifier,c,e.refresh_token,this.clientId,e.foci,i,t)}let p=null;return e.foci&&(p={clientId:this.clientId,environment:c,familyId:e.foci}),{account:d,idToken:h,accessToken:u,refreshToken:g,appMetadata:p}}static async generateAuthenticationResult(e,t,r,o,n,i,s,a,c,l){let h,d,u="",g=[],p=null,m="";if(r.accessToken){if(r.accessToken.tokenType!==yo.POP||n.popKid)u=r.accessToken.secret;else{const t=new hh(e,i),{secret:o,keyId:s}=r.accessToken;if(!s)throw Wn(si,n.correlationId);u=await t.signPopToken(o,s,n)}g=Wa.fromString(r.accessToken.target,n.correlationId).asArray(),p=ya(r.accessToken.expiresOn),h=ya(r.accessToken.extendedExpiresOn),r.accessToken.refreshOn&&(d=ya(r.accessToken.refreshOn))}r.appMetadata&&(m=r.appMetadata.familyId===ao?ao:"");const f=s?.oid||s?.sub||"",y=s?.tid||"";if(c?.spa_accountid&&r.account){r.account.nativeAccountId=c?.spa_accountid;const e=y||r.account.realm;if(r.account.tenantProfiles){const t=r.account.tenantProfiles.find(t=>t.tenantId===e);t&&(t.nativeAccountId=c.spa_accountid)}}const w=r.account?$a(La(r.account),void 0,s,r.idToken?.secret):null;return{authority:t.canonicalAuthority,uniqueId:f,tenantId:y,scopes:g,account:w,idToken:r?.idToken?.secret||"",idTokenClaims:s||{},accessToken:u,fromCache:o,expiresOn:p,extExpiresOn:h,refreshOn:d,correlationId:n.correlationId,requestId:l||"",familyId:m,tokenType:r.accessToken?.tokenType||"",state:a?a.userRequestState:"",cloudGraphHostName:r.account?.cloudGraphHostName||"",msGraphHost:r.account?.msGraphHost||"",code:c?.spa_code,fromPlatformBroker:!1}}}function gh(e,t,r,o,n,i,s,a,c,l,h,d,u){d?.verbose("09jz0t",n);const g=a||t.getPreferredCache(),p=e.getAccountsFilteredBy({homeAccountId:r,environment:g},n);u?.addFields({cacheMatchedAccounts:p.length},n),p.length>1&&d?.warning("0x7ad1",n);const m=(1===p.length?p[0]:null)||function(e,t,r,o){let n,i,s;n=t.authorityType===qs?"ADFS":t.protocolMode===Zs?no:"MSSTS",e.clientInfo&&o&&(i=Oa(e.clientInfo,o),i.xms_tdbr&&(s="EU"===i.xms_tdbr?"EU":"None"));const a=e.environment||t&&t.getPreferredCache();if(!a)throw Wn(ri,r);const c=e.idTokenClaims?.preferred_username||e.idTokenClaims?.upn,l=e.idTokenClaims?.emails?e.idTokenClaims.emails[0]:null,h=c||l||"",d=e.idTokenClaims?.login_hint,u=i?.utid||Ua(e.idTokenClaims)||"",g=i?.uid||e.idTokenClaims?.oid||e.idTokenClaims?.sub||"";let p;p=e.tenantProfiles?e.tenantProfiles:[qa(e.homeAccountId,g,u,e.nativeAccountId,e.idTokenClaims)];return{homeAccountId:e.homeAccountId,environment:a,realm:u,localAccountId:g,username:h,authorityType:n,loginHint:d,clientInfo:e.clientInfo,name:e.idTokenClaims?.name||"",lastModificationTime:void 0,lastModificationApp:void 0,cloudGraphHostName:e.cloudGraphHostName,msGraphHost:e.msGraphHost,nativeAccountId:e.nativeAccountId,tenantProfiles:p,dataBoundary:s}}({homeAccountId:r,idTokenClaims:i,clientInfo:s,environment:a,cloudGraphHostName:l?.cloud_graph_host_name,msGraphHost:l?.msgraph_host,nativeAccountId:h},t,n,o),f=m.tenantProfiles||[],y=c||m.realm;if(y&&!f.find(e=>e.tenantId===y)){const e=qa(r,m.localAccountId,y,h,i);f.push(e)}return m.tenantProfiles=f,m}const ph="home_account_id",mh="UPN";async function fh(e,t,r,o){if("string"==typeof e)return e;return e({clientId:t,tokenEndpoint:r,fmiPath:o})}class yh{static generateThrottlingStorageKey(e){return`${wo}.${JSON.stringify(e)}`}static preProcess(e,t,r){const o=yh.generateThrottlingStorageKey(t),n=e.getThrottlingCache(o,r);if(n){if(n.throttleTime<Date.now())return void e.removeItem(o,r);throw new dh(n.errorCodes?.join(" ")||"",r,n.errorMessage,n.subError)}}static postProcess(e,t,r,o){if(yh.checkResponseStatus(r)||yh.checkResponseForRetryAfter(r)){const n={throttleTime:yh.calculateThrottleTime(parseInt(r.headers[qr])),error:r.body.error,errorCodes:r.body.error_codes,errorMessage:r.body.error_description,subError:r.body.suberror};e.setThrottlingCache(yh.generateThrottlingStorageKey(t),n,o)}}static checkResponseStatus(e){return 429===e.status||e.status>=500&&e.status<600}static checkResponseForRetryAfter(e){return!!e.headers&&(e.headers.hasOwnProperty(qr)&&(e.status<200||e.status>=300))}static calculateThrottleTime(e){const t=e<=0?0:e,r=Date.now()/1e3;return Math.floor(1e3*Math.min(r+(t||60),r+3600))}static removeThrottle(e,t,r,o){const n=Da(t,r,o),i=this.generateThrottlingStorageKey(n);e.removeItem(i,r.correlationId)}}class wh extends Rn{constructor(e,t,r){super(e.errorCode,e.correlationId,e.errorMessage,e.subError),Object.setPrototypeOf(this,wh.prototype),this.name="NetworkError",this.error=e,this.httpStatus=t,this.responseHeaders=r}}function vh(e,t,r,o){return e.errorMessage=`${e.errorMessage}, additionalErrorInfo: error.name:${o?.name}, error.message:${o?.message}`,new wh(e,t,r)}function Ch(e,t,r){const o={};if(o[Rr]="application/x-www-form-urlencoded;charset=utf-8",!t&&r)switch(r.type){case ph:try{const e=Ra(r.credential);o[$r]=`Oid:${e.uid}@${e.utid}`}catch(t){e.verbose(`1qhtee ${t}`,"")}break;case mh:o[$r]=`UPN: ${r.credential}`}return o}function Ih(e,t,r,o){const n=new Map;return e.embeddedClientId&&kl(n,t,r),e.extraQueryParameters&&fl(n,e.extraQueryParameters),il(n,e.correlationId),Gc(n,e.correlationId,o),Nc(n)}async function bh(e,t,r,o,n,i,s,a,c,l){const h=await async function(e,t,r,o,n,i,s,a){let c;yh.preProcess(n,e,o);try{c=await da(i.sendPostRequestAsync.bind(i),ra,s,a,o)(t,r);const e=c.headers||{};a?.addFields({refreshTokenSize:c.body.refresh_token?.length||0,httpVerToken:e[Lr]||"",requestId:e[Ur]||""},o)}catch(e){if(e instanceof wh){const t=e.responseHeaders;throw t&&a?.addFields({httpVerToken:t[Lr]||"",requestId:t[Ur]||"",contentTypeHeader:t[Rr]||void 0,contentLengthHeader:t[Mr]||void 0,httpStatus:e.httpStatus},o),e.error}throw e instanceof Rn?e:Wn(Yn,o)}return yh.postProcess(n,e,c,o),c}(o,e,{body:t,headers:r},n,i,s,a,c);return l&&h.status<500&&429!==h.status&&l.clearTelemetryCache(),h}async function kh(e,t,r,o,n,i,s){const a=Pa.transformCIAMAuthority(xa(e),i),c=new Pa(a,t,r,o,n,i,s);try{return await da(c.resolveEndpointsAsync.bind(c),"authorityResolveEndpointsAsync",n,s,i)(),c}catch(e){throw Wn(Qn,i)}}class Sh{constructor(e,t){this.includeRedirectUri=!0,this.config=sh(e),this.logger=new Gl(this.config.loggerOptions,Ba,Ka),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t,this.oidcDefaultScopes=this.config.authOptions.authority.options.OIDCOptions?.defaultScopes}async acquireToken(e,t,r){if(!e.code)throw Wn("request_cannot_be_made",e.correlationId);r&&r.cloud_instance_host_name&&await da(this.updateTokenEndpointAuthority.bind(this),"updateTokenEndpointAuthority",this.logger,this.performanceClient,e.correlationId)(r.cloud_instance_host_name,e.correlationId);const o=ma(),n=await da(this.executeTokenRequest.bind(this),"authClientExecuteTokenRequest",this.logger,this.performanceClient,e.correlationId)(this.authority,e,this.serverTelemetryManager),i=n.headers?.[Ur],s=new uh(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.performanceClient,this.config.serializableCache,this.config.persistencePlugin);return s.validateTokenResponse(n.body,e.correlationId),da(s.handleServerTokenResponse.bind(s),aa,this.logger,this.performanceClient,e.correlationId)(n.body,this.authority,o,e,t,r,void 0,void 0,void 0,i)}getLogoutUri(e){if(!e)throw Ns("logout_request_empty","");const t=this.createLogoutUrlQueryString(e);return Ks.appendQueryString(this.authority.endSessionEndpoint,t)}async executeTokenRequest(e,t,r){const o=Ih(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri,this.performanceClient),n=Ks.appendQueryString(e.tokenEndpoint,o),i=await da(this.createTokenRequestBody.bind(this),"authClientCreateTokenRequestBody",this.logger,this.performanceClient,t.correlationId)(t);let s;if(t.clientInfo)try{const e=Oa(t.clientInfo,this.cryptoUtils.base64Decode);s={credential:`${e.uid}.${e.utid}`,type:ph}}catch(e){this.logger.verbose(`0wznt3 ${e}`,t.correlationId)}const a=Ch(this.logger,this.config.systemOptions.preventCorsPreflight,s||t.ccsCredential),c=Da(this.config.authOptions.clientId,t);return da(bh,"authorizationCodeClientExecutePostToTokenEndpoint",this.logger,this.performanceClient,t.correlationId)(n,i,a,c,t.correlationId,this.cacheManager,this.networkClient,this.logger,this.performanceClient,r)}async createTokenRequestBody(e){const t=new Map;if(Xc(t,e.embeddedClientId||e.extraParameters?.[Hc]||this.config.authOptions.clientId),this.includeRedirectUri)Zc(t,e.redirectUri);else if(!e.redirectUri)throw Ns("redirect_uri_empty",e.correlationId);if(Yc(t,e.scopes,e.correlationId,!0,this.oidcDefaultScopes),Sl(t,e.resource),function(e,t){e.set("code",t)}(t,e.code),sl(t,this.config.libraryInfo),al(t,this.config.telemetry.application),bl(t),this.serverTelemetryManager&&!ah(this.config)&&Il(t,this.serverTelemetryManager),e.codeVerifier&&function(e,t){e.set("code_verifier",t)}(t,e.codeVerifier),this.config.clientCredentials.clientSecret&&hl(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const r=this.config.clientCredentials.clientAssertion;dl(t,await fh(r.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),ul(t,r.assertionType)}if(gl(t,ro),pl(t),e.authenticationScheme===yo.POP){const r=new hh(this.cryptoUtils,this.performanceClient);let o;if(e.popKid)o=this.cryptoUtils.encodeKid(e.popKid);else{o=(await da(r.generateCnf.bind(r),sa,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}vl(t,o)}else if(e.authenticationScheme===yo.SSH){if(!e.sshJwk)throw Ns(js,e.correlationId);Cl(t,e.sshJwk)}let r;if(e.clientInfo)try{const t=Oa(e.clientInfo,this.cryptoUtils.base64Decode);r={credential:`${t.uid}.${t.utid}`,type:ph}}catch(t){this.logger.verbose(`0wznt3 ${t}`,e.correlationId)}else r=e.ccsCredential;if(this.config.systemOptions.preventCorsPreflight&&r)switch(r.type){case ph:try{rl(t,Ra(r.credential))}catch(t){this.logger.verbose(`1qhtee ${t}`,e.correlationId)}break;case mh:tl(t,r.credential)}return e.embeddedClientId&&kl(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.extraParameters&&fl(t,e.extraParameters),!e.enableSpaAuthorizationCode||e.extraParameters&&e.extraParameters[Bc]||fl(t,{[Bc]:"1"}),Gc(t,e.correlationId,this.performanceClient),nl(t,e.correlationId,e.claims,this.config.authOptions.clientCapabilities,e.skipBrokerClaims),Nc(t)}createLogoutUrlQueryString(e){const t=new Map;return e.postLogoutRedirectUri&&function(e,t){e.set("post_logout_redirect_uri",t)}(t,e.postLogoutRedirectUri),e.correlationId&&il(t,e.correlationId),e.idTokenHint&&function(e,t){e.set("id_token_hint",t)}(t,e.idTokenHint),e.state&&cl(t,e.state),e.logoutHint&&function(e,t){e.set("logout_hint",t)}(t,e.logoutHint),e.extraQueryParameters&&fl(t,e.extraQueryParameters),this.config.authOptions.instanceAware&&ml(t),Nc(t)}async updateTokenEndpointAuthority(e,t){const r=`https://${e}/${this.authority.tenant}/`,o=await kh(r,this.networkClient,this.cacheManager,this.authority.options,this.logger,t,this.performanceClient);this.authority=o}}function Th(e){const{skus:t,libraryName:r,libraryVersion:o,extensionName:n,extensionVersion:i}=e,s=new Map([[0,[r,o]],[2,[n,i]]]);let a=[];if(t?.length){if(a=t.split(","),a.length<4)return t}else a=Array.from({length:4},()=>"|");return s.forEach((e,t)=>{2===e.length&&e[0]?.length&&e[1]?.length&&function(e){const{skuArr:t,index:r,skuName:o,skuVersion:n}=e;if(r>=t.length)return;t[r]=[o,n].join("|")}({skuArr:a,index:t,skuName:e[0],skuVersion:e[1]})}),a.join(",")}class Ah{constructor(e,t){this.cacheOutcome=To,this.cacheManager=t,this.apiId=e.apiId,this.correlationId=e.correlationId,this.wrapperSKU=e.wrapperSKU||"",this.wrapperVer=e.wrapperVer||"",this.telemetryCacheKey=mo+"-"+e.clientId}generateCurrentRequestHeaderValue(){const e=`${this.apiId}${fo}${this.cacheOutcome}`,t=[this.wrapperSKU,this.wrapperVer],r=this.getNativeBrokerErrorCode();r?.length&&t.push(`broker_error=${r}`);const o=t.join(fo),n=[e,this.getRegionDiscoveryFields()].join(fo);return[po,n,o].join("|")}generateLastRequestHeaderValue(){const e=this.getLastRequests(),t=Ah.maxErrorsToSend(e),r=e.failedRequests.slice(0,2*t).join(fo),o=e.errors.slice(0,t).join(fo),n=e.errors.length,i=[n,t<n?"1":"0"].join(fo);return[po,e.cacheHits,r,o,i].join("|")}cacheFailedRequest(e){try{const t=this.getLastRequests();t.errors.length>=50&&(t.failedRequests.shift(),t.failedRequests.shift(),t.errors.shift()),t.failedRequests.push(this.apiId,this.correlationId),e instanceof Error&&e&&e.toString()?e instanceof Rn?e.subError?t.errors.push(e.subError):e.errorCode?t.errors.push(e.errorCode):t.errors.push(e.toString()):t.errors.push(e.toString()):t.errors.push("unknown_error"),this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t,this.correlationId)}catch{}}incrementCacheHits(){const e=this.getLastRequests();return e.cacheHits+=1,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e,this.correlationId),e.cacheHits}getLastRequests(){return this.cacheManager.getServerTelemetry(this.telemetryCacheKey,this.correlationId)||{failedRequests:[],errors:[],cacheHits:0}}clearTelemetryCache(){const e=this.getLastRequests(),t=Ah.maxErrorsToSend(e);if(t===e.errors.length)this.cacheManager.removeItem(this.telemetryCacheKey,this.correlationId);else{const r={failedRequests:e.failedRequests.slice(2*t),errors:e.errors.slice(t),cacheHits:0};this.cacheManager.setServerTelemetry(this.telemetryCacheKey,r,this.correlationId)}}static maxErrorsToSend(e){let t,r=0,o=0;const n=e.errors.length;for(t=0;t<n;t++){const n=e.failedRequests[2*t]||"",i=e.failedRequests[2*t+1]||"",s=e.errors[t]||"";if(o+=n.toString().length+i.toString().length+s.length+3,!(o<330))break;r+=1}return r}getRegionDiscoveryFields(){const e=[];return e.push(this.regionUsed||""),e.push(this.regionSource||""),e.push(this.regionOutcome||""),e.join(",")}updateRegionDiscoveryMetadata(e){this.regionUsed=e.region_used,this.regionSource=e.region_source,this.regionOutcome=e.region_outcome}setCacheOutcome(e){this.cacheOutcome=e}setNativeBrokerErrorCode(e){const t=this.getLastRequests();t.nativeBrokerErrorCode=e,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t,this.correlationId)}getNativeBrokerErrorCode(){return this.getLastRequests().nativeBrokerErrorCode}clearNativeBrokerErrorCode(){const e=this.getLastRequests();delete e.nativeBrokerErrorCode,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e,this.correlationId)}static makeExtraSkuString(e){return Th(e)}}class _h extends Ah{constructor(){super({clientId:"",apiId:0,correlationId:"",forceRefresh:!1},{})}generateCurrentRequestHeaderValue(){return""}generateLastRequestHeaderValue(){return""}cacheFailedRequest(){}incrementCacheHits(){return 0}clearTelemetryCache(){}getRegionDiscoveryFields(){return""}updateRegionDiscoveryMetadata(){}setCacheOutcome(){}setNativeBrokerErrorCode(){}getNativeBrokerErrorCode(){}clearNativeBrokerErrorCode(){}}class Eh{constructor(e,t,r,o,n,i,s,a,c){this.config=e,this.browserStorage=t,this.browserCrypto=r,this.networkClient=this.config.system.networkClient,this.eventHandler=n,this.navigationClient=i,this.platformAuthProvider=c,this.correlationId=a,this.logger=o.clone(Ll,Nl),this.performanceClient=s}}function Ph(e,t,r,o){r.verbose("0bd1la",o);const n=e||t||"";return Ks.getAbsoluteUrl(n,xl(),o)}function xh(e,t,r,o,n,i,s=!0){if(n.verbose("1p12tq",r),!s)return n.verbose("0tajnr",r),new _h;const a={clientId:t,correlationId:r,apiId:e,forceRefresh:i||!1,wrapperSKU:o.getWrapperMetadata()[0],wrapperVer:o.getWrapperMetadata()[1]};return new Ah(a,o)}async function Oh(e,t,r,o,n,i,s,a,c){const l=a&&a.hasOwnProperty("instance_aware")?a.instance_aware:void 0,h={protocolMode:e.system.protocolMode,OIDCOptions:e.auth.OIDCOptions,knownAuthorities:e.auth.knownAuthorities,cloudDiscoveryMetadata:e.auth.cloudDiscoveryMetadata,authorityMetadata:e.auth.authorityMetadata},d=i||e.auth.authority,u=l?.length?"true"===l:e.auth.instanceAware,g=c&&u?e.auth.authority.replace(Ks.getDomainFromUrl(d,t),c.environment):d,p=Pa.generateAuthority(g,s||e.auth.azureCloudOptions),m=await da(kh,"authorityFactoryCreateDiscoveredInstance",n,r,t)(p,e.system.networkClient,o,h,n,t,r);if(c&&!m.isAlias(c.environment))throw Ns("authority_mismatch",t);return m}async function Rh(e,t,r,o,n){if(n)try{e.removeAccount(n,o),r.verbose("0s4z6h",o)}catch(e){r.error("0mgg1d",o)}else try{r.verbose("0zj631",o),e.clear(o),await t.clearKeystore(o)}catch(e){r.error("12ih0c",o)}}async function Mh(e,t,r,o,n){const i=e.authority||t.auth.authority,s=[...e&&e.scopes||[]],a={...e,correlationId:e.correlationId,authority:i,scopes:s};if(a.authenticationScheme){if(a.authenticationScheme===yo.SSH){if(!e.sshJwk)throw Ns(js,"");if(!e.sshKid)throw Ns("missing_ssh_kid","")}o.verbose(`1ecmns ${a.authenticationScheme}`,n)}else a.authenticationScheme=yo.BEARER,o.verbose("1l4fwv",n);return a}async function qh(e,t,r,o,n){const i=await da(Mh,pi,n,o,e.correlationId)(e,r,o,n,e.correlationId);return{...e,...i,account:t,forceRefresh:e.forceRefresh||!1}}function $h(e,t){let r;const o=e.httpMethod;if(t===ea){if(o&&o!==Pr)throw Ns("invalid_request_method_for_EAR","");r=Pr}else r=o||Er;return r}class Uh extends Eh{initializeLogoutRequest(e){this.logger.verbose("0546u4",this.correlationId);const t={correlationId:this.correlationId,...e};if(e)if(e.logoutHint)this.logger.verbose("12k4l4",this.correlationId);else if(e.account){const r=e.account.loginHint||this.getLogoutHintFromIdTokenClaims(e.account);r&&(this.logger.verbose("0d7s8p",this.correlationId),t.logoutHint=r)}else this.logger.verbose("0pdtc3",this.correlationId);else this.logger.verbose("07ndze",this.correlationId);return e&&null===e.postLogoutRedirectUri?this.logger.verbose("0ljv63",t.correlationId):e&&e.postLogoutRedirectUri?(this.logger.verbose("1vamm6",t.correlationId),t.postLogoutRedirectUri=Ks.getAbsoluteUrl(e.postLogoutRedirectUri,xl(),t.correlationId)):null===this.config.auth.postLogoutRedirectUri?this.logger.verbose("15m5g7",t.correlationId):this.config.auth.postLogoutRedirectUri?(this.logger.verbose("1f4xlz",t.correlationId),t.postLogoutRedirectUri=Ks.getAbsoluteUrl(this.config.auth.postLogoutRedirectUri,xl(),t.correlationId)):(this.logger.verbose("17s5rf",t.correlationId),t.postLogoutRedirectUri=Ks.getAbsoluteUrl(xl(),xl(),t.correlationId)),t}getLogoutHintFromIdTokenClaims(e){const t=e.idTokenClaims;if(t){if(t.login_hint)return this.logger.verbose("0u5bmc",this.correlationId),t.login_hint;this.logger.verbose("0mvp54",this.correlationId)}else this.logger.verbose("1e7bdp",this.correlationId);return null}async createAuthCodeClient(e){const t=await da(this.getClientConfiguration.bind(this),vi,this.logger,this.performanceClient,this.correlationId)(e);return new Sh(t,this.performanceClient)}async getClientConfiguration(e){const{serverTelemetryManager:t,requestAuthority:r,requestAzureCloudOptions:o,requestExtraQueryParameters:n,account:i}=e,s=e.authority||await da(Oh,di,this.logger,this.performanceClient,this.correlationId)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,r,o,n,i),a=this.config.system.loggerOptions;return{authOptions:{clientId:this.config.auth.clientId,authority:s,clientCapabilities:this.config.auth.clientCapabilities,redirectUri:this.config.auth.redirectUri,isMcp:this.config.auth.isMcp},systemOptions:{tokenRenewalOffsetSeconds:this.config.system.tokenRenewalOffsetSeconds,preventCorsPreflight:!0},loggerOptions:{loggerCallback:a.loggerCallback,piiLoggingEnabled:a.piiLoggingEnabled,logLevel:a.logLevel,correlationId:this.correlationId},cryptoInterface:this.browserCrypto,networkInterface:this.networkClient,storageInterface:this.browserStorage,serverTelemetryManager:t,libraryInfo:{sku:$o,version:Nl,cpu:"",os:""},telemetry:this.config.telemetry}}}async function Lh(e,t,r,o,n,i,s,a){const c=Ph(e.redirectUri,r.auth.redirectUri,i,a);new URL(c).origin!==new URL(window.location.href).origin&&(i.warning("08qbvw",a),s.addFields({isRedirectUriCrossOrigin:!0},a));const l={interactionType:t},h=qc(o,e&&e.state||"",l,a),d={...await da(Mh,pi,i,s,a)({...e,correlationId:a},r,s,i,a),redirectUri:c,state:h,nonce:e.nonce||fs(),responseMode:r.auth.OIDCOptions.responseMode},u={...d,httpMethod:$h(d,r.system.protocolMode)};if(e.loginHint||e.sid)return u;const g=e.account||n.getActiveAccount(a);return g&&(i.verbose("1eqlb3",a),i.verbosePii(`0tf99t ${g.homeAccountId}`,a),u.account=g),u}function Nh(e,t,r,o){const n=Lc(e);if(!n)throw Uc(e)?(r.error(`13pl0s ${t} ${t}`,o),r.errorPii(`1097vx ${t} ${e}`,o),Ui("hash_does_not_contain_known_properties",o)):(r.error(`18h0l1 ${t} ${t}`,o),Ui("hash_empty_error",o));return n}function Dh(e,t,r,o){if(!e.state)throw Ui(Fi,o);const n=function(e,t,r){if(!t)return null;try{return $c(e.base64Decode,t,r).libraryState.meta}catch(e){throw Wn(Xn,r)}}(t,e.state,o);if(!n)throw Ui(zi,o);if(n.interactionType!==r)throw Ui("state_interaction_type_mismatch",o)}function Hh(e,t,r,o){const n=t.correlationId,i=new Map;Xc(i,t.embeddedClientId||t.extraQueryParameters?.[Hc]||e.clientId);if(Yc(i,[...t.scopes||[],...t.extraScopesToConsent||[]],t.correlationId,!0,e.authority.options.OIDCOptions?.defaultScopes),Sl(i,t.resource),Zc(i,t.redirectUri),il(i,n),function(e,t){e.set("response_mode",t||eo)}(i,t.responseMode),pl(i),function(e){e.set("clidata","1")}(i),t.prompt&&(!function(e,t){e.set("prompt",t)}(i,t.prompt),o?.addFields({prompt:t.prompt},n)),t.domainHint&&(!function(e,t){e.set("domain_hint",t)}(i,t.domainHint),o?.addFields({domainHintFromRequest:!0},n)),t.prompt!==Vr)if(t.sid&&t.prompt===Qr)r.verbose("1tvqyx",t.correlationId),ol(i,t.sid),o?.addFields({sidFromRequest:!0},n);else if(t.account){const e=(s=t.account,s.idTokenClaims?.sid||null);let a=function(e){return e.loginHint||e.idTokenClaims?.login_hint||null}(t.account);if(a&&t.domainHint&&(r.warning("0wkg3v",t.correlationId),a=null),a){r.verbose("1eyfsw",t.correlationId),el(i,a),o?.addFields({loginHintFromClaim:!0},n);try{rl(i,Ra(t.account.homeAccountId))}catch(e){r.verbose("12ugck",t.correlationId)}}else if(e&&t.prompt===Qr){r.verbose("1rmd8s",t.correlationId),ol(i,e),o?.addFields({sidFromClaim:!0},n);try{rl(i,Ra(t.account.homeAccountId))}catch(e){r.verbose("12ugck",t.correlationId)}}else if(t.loginHint)r.verbose("0y3007",t.correlationId),el(i,t.loginHint),tl(i,t.loginHint),o?.addFields({loginHintFromRequest:!0},n);else if(t.account.username){r.verbose("02f507",t.correlationId),el(i,t.account.username),o?.addFields({loginHintFromUpn:!0},n);try{rl(i,Ra(t.account.homeAccountId))}catch(e){r.verbose("12ugck",t.correlationId)}}}else t.loginHint&&(r.verbose("0g01ey",t.correlationId),el(i,t.loginHint),tl(i,t.loginHint),o?.addFields({loginHintFromRequest:!0},n));else r.verbose("169k9v",t.correlationId);var s;return t.nonce&&function(e,t){e.set("nonce",t)}(i,t.nonce),t.state&&cl(i,t.state),t.embeddedClientId&&kl(i,e.clientId,e.redirectUri),nl(i,t.correlationId,t.claims,e.clientCapabilities,t.skipBrokerClaims),!e.instanceAware||t.extraQueryParameters&&Object.keys(t.extraQueryParameters).includes(Vc)||ml(i),i}function Fh(e,t){const r=Nc(t);return Ks.appendQueryString(e.authorizationEndpoint,r)}function zh(e,t,r){if(!e.state||!t)throw e.state?Wn(Zn,r,"Cached State"):Wn(Zn,r,"Server State");let o,n;try{o=decodeURIComponent(e.state)}catch(t){throw Wn(Xn,r,e.state)}try{n=decodeURIComponent(t)}catch(t){throw Wn(Xn,r,e.state)}if(o!==n)throw Wn("state_mismatch",r);if(e.error||e.error_description||e.suberror){const t=function(e){const t="code=",r=e.error_uri?.lastIndexOf(t);return r&&r>=0?e.error_uri?.substring(r+t.length):void 0}(e);if(Fn(e.error,e.error_description,e.suberror))throw new Hn(e.error||"",e.correlation_id||r,e.error_description,e.suberror,e.timestamp||"",e.trace_id||"",e.claims||"",t);throw new dh(e.error||"",e.correlation_id||r,e.error_description,e.suberror,t)}}class jh{constructor(e,t,r,o,n){this.authModule=e,this.browserStorage=t,this.authCodeRequest=r,this.logger=o,this.performanceClient=n}async handleCodeResponse(e,t,r){let o;try{o=function(e,t,r){if(zh(e,t,r),!e.code)throw Wn("authorization_code_missing_from_server_response",r);return e}(e,t.state,t.correlationId)}catch(e){throw e instanceof dh&&e.subError===ji?Ui(ji,t.correlationId):e}return da(this.handleCodeResponseFromServer.bind(this),ia,this.logger,this.performanceClient,t.correlationId)(o,t,r)}async handleCodeResponseFromServer(e,t,r,o=!0){if(this.logger.trace("0mf2hb",t.correlationId),this.authCodeRequest.code=e.code,o&&(e.nonce=t.nonce||void 0),e.state=t.state,e.client_info)this.authCodeRequest.clientInfo=e.client_info;else{const e=this.createCcsCredentials(t);e&&(this.authCodeRequest.ccsCredential=e)}return await da(this.authModule.acquireToken.bind(this.authModule),"authClientAcquireToken",this.logger,this.performanceClient,t.correlationId)(this.authCodeRequest,r,e)}createCcsCredentials(e){return e.account?{credential:e.account.homeAccountId,type:ph}:e.loginHint?{credential:e.loginHint,type:mh}:null}}class Bh extends Rn{constructor(e,t,r,o){super(e,t,r||qi(e)),Object.setPrototypeOf(this,Bh.prototype),this.name="NativeAuthError",this.ext=o}}function Kh(e){if(e.ext&&e.ext.status&&"DISABLED"===e.ext.status)return!0;if(e.ext&&e.ext.error&&-2147186943===e.ext.error)return!0;switch(e.errorCode){case"ContentError":case"PageException":return!0;default:return!1}}function Wh(e,t,r,o){let n;if(o&&o.status){switch(o.status){case"ACCOUNT_UNAVAILABLE":n=zn("native_account_unavailable",t,qi(e));break;case"USER_INTERACTION_REQUIRED":n=new Hn(e,t,r);break;case"USER_CANCEL":n=Ui(ji,t);break;case"NO_NETWORK":n=Ui(Ji,t);break;case"UI_NOT_ALLOWED":n=zn(Un,t);break;default:n=new Bh(e,t,r,o)}return n}return n=new Bh(e,t,r,o),n}class Jh{constructor(e,t){this.config=sh(e),this.logger=new Gl(this.config.loggerOptions,Ba,Ka),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t}async acquireCachedToken(e){let t=To;if(e.forceRefresh||!Ds.isEmptyObj(e.claims))throw this.setCacheOutcome(Ao,e.correlationId),Wn(ii,e.correlationId);if(!e.account)throw Wn(ti,e.correlationId);const r=e.account.tenantId||function(e,t){const r=new Ks(e,t).getUrlComponents(),o=r.PathSegments.slice(-1)[0]?.toLowerCase();switch(o){case Dr:case Hr:case Fr:return;default:return o}}(e.authority,e.correlationId),o=this.cacheManager.getTokenKeys(),n=this.cacheManager.getAccessToken(e.account,e,o,r);if(!n)throw this.setCacheOutcome(_o,e.correlationId),Wn(ii,e.correlationId);if(i=n.cachedAt,Number(i)>ma()||wa(n.expiresOn,this.config.systemOptions.tokenRenewalOffsetSeconds))throw this.setCacheOutcome(Eo,e.correlationId),Wn(ii,e.correlationId);if(e.resource){if(n.resource!==e.resource)throw this.setCacheOutcome(_o,e.correlationId),Wn(ii,e.correlationId)}else n.refreshOn&&wa(n.refreshOn,0)&&(t=Po);var i;const s=e.authority||this.authority.getPreferredCache(),a={account:this.cacheManager.getAccount(this.cacheManager.generateAccountKey(e.account),e.correlationId),accessToken:n,idToken:this.cacheManager.getIdToken(e.account,e.correlationId,o,r),refreshToken:null,appMetadata:this.cacheManager.readAppMetadataFromCache(s,e.correlationId)};return this.setCacheOutcome(t,e.correlationId),this.config.serverTelemetryManager&&this.config.serverTelemetryManager.incrementCacheHits(),[await da(this.generateResultFromCacheRecord.bind(this),"silentFlowClientGenerateResultFromCacheRecord",this.logger,this.performanceClient,e.correlationId)(a,e),t]}setCacheOutcome(e,t){this.serverTelemetryManager?.setCacheOutcome(e),this.performanceClient?.addFields({cacheOutcome:e},t),e!==To&&this.logger.info(`09ingz ${e}`,t)}async generateResultFromCacheRecord(e,t){let r;return e.idToken&&(r=ga(e.idToken.secret,this.config.cryptoInterface.base64Decode,t.correlationId)),uh.generateAuthenticationResult(this.cryptoUtils,this.authority,e,!0,t,this.performanceClient,r)}}class Vh extends Uh{async acquireToken(e){const t=xh(mn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),r=await da(this.getClientConfiguration.bind(this),vi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:t,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,account:e.account}),o=new Jh(r,this.performanceClient);this.logger.verbose("0wa871",this.correlationId);try{const t=(await da(o.acquireCachedToken.bind(o),"silentFlowClientAcquireCachedToken",this.logger,this.performanceClient,e.correlationId)(e))[0];return this.performanceClient.addFields({fromCache:!0},e.correlationId),t}catch(e){throw e instanceof $i&&e.errorCode===Gi&&this.logger.verbose("06wena",this.correlationId),e}}logout(e){this.logger.verbose("1rkurh",this.correlationId);const t=this.initializeLogoutRequest(e);return Rh(this.browserStorage,this.browserCrypto,this.logger,this.correlationId,t.account)}}class Gh extends Eh{constructor(e,t,r,o,n,i,s,a,c,l,h,d){super(e,t,r,o,n,i,a,d,c),this.apiId=s,this.accountId=l,this.platformAuthProvider=c,this.nativeStorageManager=h,this.silentCacheClient=new Vh(e,this.nativeStorageManager,r,o,n,i,a,d,c);const u=this.platformAuthProvider.getExtensionName();this.skus=Ah.makeExtraSkuString({libraryName:$o,libraryVersion:Nl,extensionName:u,extensionVersion:this.platformAuthProvider.getExtensionVersion()})}addRequestSKUs(e){e.extraParameters={...e.extraParameters,[Kc]:this.skus}}async acquireToken(e,t){this.logger.trace("03qeos",this.correlationId);const r=this.performanceClient.startMeasurement(ui,this.correlationId),o=ma(),n=xh(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled);try{const i=await this.initializePlatformRequest(e);try{const e=await this.acquireTokensFromCache(this.accountId,i);return r.end({success:!0,isNativeBroker:!1,fromCache:!0}),e}catch(e){if(t===Tn)throw this.logger.info("0eitbc",this.correlationId),r.end({success:!1,brokerErrorCode:"cache_request_failed"}),e;this.logger.info("0957j1",this.correlationId)}const s=await this.platformAuthProvider.sendMessage(i);return await this.handleNativeResponse(s,i,o).then(e=>(r.end({success:!0,isNativeBroker:!0,requestId:e.requestId}),n.clearNativeBrokerErrorCode(),e)).catch(e=>{throw r.end({success:!1,errorCode:e.errorCode,subErrorCode:e.subError}),e})}catch(e){throw e instanceof Bh&&n.setNativeBrokerErrorCode(e.errorCode),r.end({success:!1}),e}}createSilentCacheRequest(e,t){return{authority:e.authority,correlationId:this.correlationId,scopes:Wa.fromString(e.scope,this.correlationId).asArray(),account:t,forceRefresh:!1}}async acquireTokensFromCache(e,t){if(!e)throw this.logger.warning("1ndf3e",this.correlationId),Wn(oi,this.correlationId);const r=this.browserStorage.getBaseAccountInfo({nativeAccountId:e},this.correlationId);if(!r)throw Wn(oi,this.correlationId);try{const e=this.createSilentCacheRequest(t,r),o=await this.silentCacheClient.acquireToken(e),n=this.browserStorage.getIdToken(r,this.correlationId,this.browserStorage.getTokenKeys(),r.tenantId),i=ga(n?.secret||"",ts,this.correlationId),s=$a(r,void 0,i,n?.secret);return{...o,idToken:n?.secret||"",idTokenClaims:i,account:s}}catch(e){throw e}}async acquireTokenRedirect(e,t,r){this.logger.trace("0luikq",this.correlationId);const o=await this.initializePlatformRequest(e),n=r?.navigateToLoginRequestUrl??!0;try{await this.platformAuthProvider.sendMessage(o)}catch(e){if(e instanceof Bh){if(xh(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled).setNativeBrokerErrorCode(e.errorCode),Kh(e))throw e}}this.browserStorage.setTemporaryCache(an,JSON.stringify(o),!0);const i={apiId:hn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},s=n?Ks.getAbsoluteUrl(e.redirectStartPage||window.location.href,xl(),this.correlationId):Ph(e.redirectUri,this.config.auth.redirectUri,this.logger,this.correlationId);t.end({success:!0}),await this.navigationClient.navigateExternal(s,i)}async handleRedirectPromise(){if(this.logger.trace("1c5lhw",this.correlationId),!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("0le6uv",this.correlationId),null;const e=this.browserStorage.getCachedNativeRequest();if(!e)return this.logger.verbose("0a6zjb",this.correlationId),this.performanceClient?.addFields({errorCode:"no_cached_request"},this.correlationId),null;const{prompt:t,...r}=e;t&&this.logger.verbose("0ac34v",this.correlationId),this.browserStorage.removeItem(this.browserStorage.generateCacheKey(an));const o=ma();try{this.logger.verbose("003x5a",this.correlationId);const e=await this.platformAuthProvider.sendMessage(r),t=await this.handleNativeResponse(e,r,o);return xh(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled).clearNativeBrokerErrorCode(),this.performanceClient?.addFields({isNativeBroker:!0},this.correlationId),t}catch(e){throw e}}logout(){return this.logger.trace("0u2sjm",this.correlationId),Promise.reject("Logout not implemented yet")}async handleNativeResponse(e,t,r){this.logger.trace("1bojln",this.correlationId);const o=ga(e.id_token,ts,this.correlationId),n=this.createHomeAccountIdentifier(e,o),i=this.browserStorage.getAccountInfoFilteredBy({nativeAccountId:t.accountId},this.correlationId)?.homeAccountId;if(t.extraParameters?.child_client_id&&e.account.id!==t.accountId)this.logger.info("1ub1in",this.correlationId);else if(n!==i&&e.account.id!==t.accountId)throw Wh("user_switch",this.correlationId);const s=await Oh(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,t.authority),a=gh(this.browserStorage,s,n,ts,this.correlationId,o,e.client_info,s.getPreferredCache(),o.tid,void 0,e.account.id,this.logger,this.performanceClient);e.expires_in=Number(e.expires_in);const c=await this.generateAuthenticationResult(e,t,o,a,s.canonicalAuthority,r);return await this.cacheAccount(a,pa(o)),await this.cacheNativeTokens(e,t,n,o,c.tenantId,r,s.getPreferredCache()),c}createHomeAccountIdentifier(e,t){return Na(e.client_info||"",Ms,this.logger,this.browserCrypto,this.correlationId,t)}generateScopes(e,t){return t?Wa.fromString(t,this.correlationId):Wa.fromString(e,this.correlationId)}async generatePopAccessToken(e,t){if(t.tokenType===yo.POP&&t.signPopToken){if(e.shr)return this.logger.trace("0coqhu",this.correlationId),e.shr;const r=new hh(this.browserCrypto,this.performanceClient),o={resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,shrNonce:t.shrNonce,correlationId:this.correlationId};if(!t.keyId)throw Wn(si,this.correlationId);return r.signPopToken(e.access_token,t.keyId,o)}return e.access_token}async generateAuthenticationResult(e,t,r,o,n,i){const s=this.addTelemetryFromNativeResponse(e.properties.MATS),a=this.generateScopes(t.scope,e.scope),c=e.account.properties||{},l=c.UID||r.oid||r.sub||"",h=c.TenantId||r.tid||"",d=$a(La(o),void 0,r,e.id_token);if(d.nativeAccountId!==e.account.id){d.nativeAccountId=e.account.id;const t=h||d.tenantId,r=d.tenantProfiles?.get(t);r&&(r.nativeAccountId=e.account.id)}const u=await this.generatePopAccessToken(e,t),g=t.tokenType===yo.POP?yo.POP:yo.BEARER;return{authority:n,uniqueId:l,tenantId:h,scopes:a.asArray(),account:d,idToken:e.id_token,idTokenClaims:r,accessToken:u,fromCache:!!s&&this.isResponseFromCache(s),expiresOn:ya(i+e.expires_in),tokenType:g,correlationId:this.correlationId,state:e.state,fromPlatformBroker:!0,...t.resource&&{resource:t.resource}}}async cacheAccount(e,t){await this.browserStorage.setAccount(e,this.correlationId,t,this.apiId),this.browserStorage.removeAccountContext(La(e),this.correlationId)}async cacheNativeTokens(e,t,r,o,n,i,s){const a=Ca(r,s,e.id_token||"",t.clientId,o.tid||""),c=i+(t.tokenType===yo.POP?240:("string"==typeof e.expires_in?parseInt(e.expires_in,10):e.expires_in)||0),l=this.generateScopes(e.scope,t.scope),h=Ia(r,s,e.access_token,t.clientId,o.tid||n,l.printScopes(),c,0,ts,t.correlationId,void 0,t.tokenType,void 0,t.keyId);a&&!1!==t.storeInCache?.idToken&&await this.browserStorage.setIdTokenCredential(a,this.correlationId,pa(o));const d={accessToken:h};return this.nativeStorageManager.saveCacheRecord(d,this.correlationId,pa(o),this.apiId,t.storeInCache)}getExpiresInValue(e,t){return e===yo.POP?240:("string"==typeof t?parseInt(t,10):t)||0}addTelemetryFromNativeResponse(e){const t=this.getMATSFromResponse(e);return t?(this.performanceClient.addFields({extensionId:this.platformAuthProvider.getExtensionId(),extensionVersion:this.platformAuthProvider.getExtensionVersion(),matsBrokerVersion:t.broker_version,matsAccountJoinOnStart:t.account_join_on_start,matsAccountJoinOnEnd:t.account_join_on_end,matsDeviceJoin:t.device_join,matsPromptBehavior:t.prompt_behavior,matsApiErrorCode:t.api_error_code,matsUiVisible:t.ui_visible,matsSilentCode:t.silent_code,matsSilentBiSubCode:t.silent_bi_sub_code,matsSilentMessage:t.silent_message,matsSilentStatus:t.silent_status,matsHttpStatus:t.http_status,matsHttpEventCount:t.http_event_count},this.correlationId),t):null}getMATSFromResponse(e){if(e)try{return JSON.parse(e)}catch(e){this.logger.error("0b3l57",this.correlationId)}return null}isResponseFromCache(e){return void 0===e.is_cached?(this.logger.verbose("1okqev",this.correlationId),!1):!!e.is_cached}async initializePlatformRequest(e){this.logger.trace("1xdm2a",this.correlationId);const t=await this.getCanonicalAuthority(e),r=e.skipBrokerClaims&&e.embeddedClientId?void 0:this.config.auth.clientCapabilities,{scopes:o,claims:n,...i}=e,s=new Wa(o||[],this.correlationId);s.appendScopes(xr);const a={...i,claims:wl(n,r?.length?r:void 0),accountId:this.accountId,clientId:this.config.auth.clientId,authority:t.urlString,scope:s.printScopes(),redirectUri:Ph(e.redirectUri,this.config.auth.redirectUri,this.logger,this.correlationId),prompt:this.getPrompt(e.prompt),correlationId:this.correlationId,tokenType:e.authenticationScheme,windowTitleSubstring:document.title,extraParameters:{...e.extraParameters},extendedExpiryToken:!1,keyId:e.popKid};if(a.signPopToken&&e.popKid)throw Ui("invalid_pop_token_request",this.correlationId);if(this.handleExtraBrokerParams(a),a.extraParameters=a.extraParameters||{},a.extraParameters.telemetry=No,e.authenticationScheme===yo.POP){const t={resourceRequestUri:e.resourceRequestUri,resourceRequestMethod:e.resourceRequestMethod,shrClaims:e.shrClaims,shrNonce:e.shrNonce,correlationId:this.correlationId},r=new hh(this.browserCrypto,this.performanceClient);let o;if(a.keyId)o=this.browserCrypto.base64UrlEncode(JSON.stringify({kid:a.keyId})),a.signPopToken=!1;else{const e=await da(r.generateCnf.bind(r),sa,this.logger,this.performanceClient,this.correlationId)(t,this.logger);o=e.reqCnfString,a.keyId=e.kid,a.signPopToken=!0}a.reqCnf=o}return this.addRequestSKUs(a),a}async getCanonicalAuthority(e){const t=e.authority||this.config.auth.authority,{azureCloudOptions:r,account:o}=e;o&&await Oh(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,t,r,void 0,o);const n=new Ks(t,this.correlationId);return n.validateAsUri(),n}getPrompt(e){switch(this.apiId){case un:case mn:return this.logger.trace("12n1y2",this.correlationId),Qr}if(e)switch(e){case Qr:case Gr:case Jr:return this.logger.trace("0i0hco",this.correlationId),e;default:throw this.logger.trace(`0w3tpw ${e}`,this.correlationId),Ui("native_prompt_not_supported",this.correlationId)}else this.logger.trace("0uid1p",this.correlationId)}handleExtraBrokerParams(e){const t=e.extraParameters&&e.extraParameters.hasOwnProperty(Wc)&&e.extraParameters.hasOwnProperty(Jc)&&e.extraParameters.hasOwnProperty(Hc);if(!e.embeddedClientId&&!t)return;let r="";const o=e.redirectUri;e.embeddedClientId?(e.redirectUri=this.config.auth.redirectUri,r=e.embeddedClientId):e.extraParameters&&(e.redirectUri=e.extraParameters[Jc],r=e.extraParameters[Hc]),e.extraParameters={child_client_id:r,child_redirect_uri:o},this.performanceClient?.addFields({embeddedClientId:r,embeddedRedirectUri:o},this.correlationId)}}const Qh=new Map([["e","AAD"],["m","MSA"]]);function Yh(e,t,r){const o=function(e){if(!e)return null;try{const t=(/%(?:[0-9A-Fa-f]{2})/.test(e)?decodeURIComponent(e):e).split("|");return t.length<5?null:{accountType:Qh.get(t[0]?.trim()||"")||"",error:t[1]?.trim()||"",subError:t[2]?.trim()||"",cloudInstance:t[3]?.trim()||"",callerDataBoundary:t[4]?.trim()||""}}catch{return null}}(e.clientdata);o?.accountType&&r.addFields({accountType:o.accountType},t),o?.error&&r.addFields({serverErrorNo:o.error},t),o?.subError&&r.addFields({serverSubErrorNo:o.subError},t)}async function Xh(e,t,r,o,n){const i=Hh({...e.auth,authority:t},r,o,n);if(sl(i,{sku:$o,version:Nl,os:"",cpu:""}),e.system.protocolMode!==Zs&&al(i,e.telemetry.application),r.platformBroker&&(function(e){e.set("nativebroker","1")}(i),n.addFields({isPlatformAuthorizeRequest:!0},r.correlationId),r.authenticationScheme===yo.POP)){const e=new Es(o,n),t=new hh(e,n);let s;if(r.popKid)s=e.encodeKid(r.popKid);else{s=(await da(t.generateCnf.bind(t),sa,o,n,r.correlationId)(r,o)).reqCnfString}vl(i,s)}return Gc(i,r.correlationId,n),i}async function Zh(e,t,r,o,n){if(!r.codeChallenge)throw Ns(Fs,r.correlationId);const i=await da(Xh,"getStandardParams",o,n,r.correlationId)(e,t,r,o,n);return Qc(i,Xr),ll(i,r.codeChallenge,kr),fl(i,{...r.extraQueryParameters,...r.extraParameters}),Fh(t,i)}async function ed(e,t,r,o,n,i){if(!o.earJwk)throw Ui(Ni,o.correlationId);const s=await Xh(t,r,o,n,i);Qc(s,Zr),function(e,t){e.set("ear_jwk",encodeURIComponent(t)),e.set("ear_jwe_crypto","eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0")}(s,o.earJwk),ll(s,o.codeChallenge,kr),fl(s,{...o.extraParameters});const a=new Map;fl(a,o.extraQueryParameters||{}),il(a,o.correlationId);return rd(e,Fh(r,a),s)}async function td(e,t,r,o,n,i){const s=await Xh(t,r,o,n,i);Qc(s,Xr),ll(s,o.codeChallenge,o.codeChallengeMethod||kr),fl(s,{...o.extraParameters});const a=new Map;fl(a,o.extraQueryParameters||{}),il(a,o.correlationId);return rd(e,Fh(r,a),s)}function rd(e,t,r){const o=e.createElement("form");return o.method="post",o.action=t,r.forEach((t,r)=>{const n=e.createElement("input");n.hidden=!0,n.name=r,n.value=t,o.appendChild(n)}),e.body.appendChild(o),o}async function od(e,t,r,o,n,i,s,a,c,l){if(a.verbose("11qcow",e.correlationId),!l)throw Ui(Yi,e.correlationId);const h=new Es(a,c),d=new Gh(o,n,h,a,s,o.system.navigationClient,r,c,l,t,i,e.correlationId),{userRequestState:u}=$c(h.base64Decode,e.state,e.correlationId);return da(d.acquireToken.bind(d),ui,a,c,e.correlationId)({...e,state:u,prompt:void 0})}async function nd(e,t,r,o,n,i,s,a,c,l,h,d){if(yh.removeThrottle(s,n.auth.clientId,e),Yh(t,e.correlationId,h),t.accountId)return da(od,bi,l,h,e.correlationId)(e,t.accountId,o,n,s,a,c,l,h,d);const u={...e,code:t.code||"",codeVerifier:r},g=new jh(i,s,u,l,h);return await da(g.handleCodeResponse.bind(g),"handleCodeResponse",l,h,e.correlationId)(t,e,o)}async function id(e,t,r,o,n,i,s,a,c,l,h){if(yh.removeThrottle(i,o.auth.clientId,e),Yh(t,e.correlationId,l),zh(t,e.state,e.correlationId),!t.ear_jwe)throw Ui("ear_jwe_empty",e.correlationId);if(!e.earJwk)throw Ui(Ni,e.correlationId);const d=JSON.parse(await da(vs,"decryptEarResponse",c,l,e.correlationId)(e.earJwk,t.ear_jwe));if(d.accountId)return da(od,bi,c,l,e.correlationId)(e,d.accountId,r,o,i,s,a,c,l,h);const u=new uh(o.auth.clientId,i,new Es(c,l),c,l,null,null);u.validateTokenResponse(d,e.correlationId);const g={code:"",state:e.state,nonce:e.nonce,client_info:d.client_info,cloud_graph_host_name:d.cloud_graph_host_name,cloud_instance_host_name:d.cloud_instance_host_name,cloud_instance_name:d.cloud_instance_name,msgraph_host:d.msgraph_host};return await da(u.handleServerTokenResponse.bind(u),aa,c,l,e.correlationId)(d,n,ma(),e,r,g,void 0,void 0,void 0,void 0)}async function sd(e,t,r){const o=ha(ad,"generateCodeVerifier",t,e,r)(e,t,r);return{verifier:o,challenge:await da(cd,"generateCodeChallengeFromVerifier",t,e,r)(o,e,t,r)}}function ad(e,t,r){try{const o=new Uint8Array(32);ha(ps,"getRandomValues",t,e,r)(o);return Oi(o)}catch(e){throw Ui(Li,r)}}async function cd(e,t,r,o){try{const n=await da(gs,"sha256Digest",r,t,o)(e);return Oi(new Uint8Array(n))}catch(e){throw Ui(Li,o)}}const ld={sendGetRequestAsync:()=>Promise.reject(Wn(ai,"")),sendPostRequestAsync:()=>Promise.reject(Wn(ai,""))};class hd{navigateInternal(e,t){return hd.defaultNavigateWindow(e,t)}navigateExternal(e,t){return hd.defaultNavigateWindow(e,t)}static defaultNavigateWindow(e,t){return t.noHistory?window.location.replace(e):window.location.assign(e),new Promise((e,r)=>{setTimeout(()=>{r(Ui(es,"","failed_to_redirect"))},t.timeout)})}}class dd{async sendGetRequestAsync(e,t){let r,o={},n=0;const i=ud(t);try{r=await fetch(e,{method:Yo,headers:i})}catch(e){throw vh(Ui(window.navigator.onLine?"get_request_failed":Ji,""),void 0,void 0,e)}o=gd(r.headers);try{return n=r.status,{headers:o,body:await r.json(),status:n}}catch(e){throw vh(Ui(Vi,""),n,o,e)}}async sendPostRequestAsync(e,t){const r=t&&t.body||"",o=ud(t);let n,i=0,s={};try{n=await fetch(e,{method:Xo,headers:o,body:r})}catch(e){throw vh(Ui(window.navigator.onLine?"post_request_failed":Ji,""),void 0,void 0,e)}s=gd(n.headers);try{return i=n.status,{headers:s,body:await n.json(),status:i}}catch(e){throw vh(Ui(Vi,""),i,s,e)}}}function ud(e){try{const t=new Headers;if(!e||!e.headers)return t;const r=e.headers;return Object.entries(r).forEach(([e,r])=>{t.append(e,r)}),t}catch(e){throw vh(Ui("failed_to_build_headers",""),void 0,void 0,e)}}function gd(e){try{const t={};return e.forEach((e,r)=>{t[r]=e}),t}catch(e){throw Ui("failed_to_parse_headers","")}}const pd="unexpected_error";class md{constructor(e,t,r,o){this.logger=e,this.handshakeTimeoutMs=t,this.extensionId=o,this.resolvers=new Map,this.handshakeResolvers=new Map,this.messageChannel=new MessageChannel,this.windowListener=this.onWindowMessage.bind(this),this.performanceClient=r,this.handshakeEvent=this.performanceClient.startMeasurement("nativeMessageHandlerHandshake"),this.platformAuthType=jo}async sendMessage(e){this.logger.trace(`0on4p2 ${this.platformAuthType}`,e.correlationId);const t={method:Wo,request:e},r={channel:Uo,extensionId:this.extensionId,responseId:fs(),body:t};this.logger.trace(`1qadfi ${this.platformAuthType}`,e.correlationId),this.logger.tracePii(`1xm533 ${this.platformAuthType} ${JSON.stringify(r)}`,e.correlationId),this.messageChannel.port1.postMessage(r);const o=await new Promise((e,t)=>{this.resolvers.set(r.responseId,{resolve:e,reject:t})});return this.validatePlatformBrokerResponse(o)}static async createProvider(e,t,r,o){e.trace("15zfnw",o);try{const n=new md(e,t,r,Lo);return await n.sendHandshakeRequest(o),n}catch(n){const i=new md(e,t,r);return await i.sendHandshakeRequest(o),i}}async sendHandshakeRequest(e){this.logger.trace(`1dpg9o ${this.platformAuthType}`,e),window.addEventListener("message",this.windowListener,!1);const t={channel:Uo,extensionId:this.extensionId,responseId:fs(),body:{method:Bo}};return this.handshakeEvent.add({extensionId:this.extensionId,extensionHandshakeTimeoutMs:this.handshakeTimeoutMs}),this.messageChannel.port1.onmessage=e=>{this.onChannelMessage(e)},window.postMessage(t,window.origin,[this.messageChannel.port2]),new Promise((e,r)=>{this.handshakeResolvers.set(t.responseId,{resolve:e,reject:r}),this.timeoutId=window.setTimeout(()=>{window.removeEventListener("message",this.windowListener,!1),this.messageChannel.port1.close(),this.messageChannel.port2.close(),this.handshakeEvent.end({extensionHandshakeTimedOut:!0,success:!1}),r(Ui("native_handshake_timeout","")),this.handshakeResolvers.delete(t.responseId)},this.handshakeTimeoutMs)})}onWindowMessage(e){const t=Ul();if(this.logger.trace(`0jpn5u ${this.platformAuthType}`,t),e.source!==window)return;const r=e.data;if(r.channel&&r.channel===Uo&&(!r.extensionId||r.extensionId===this.extensionId)&&r.body.method===Bo){const e=this.handshakeResolvers.get(r.responseId);if(!e)return void this.logger.trace(`07buhm ${this.platformAuthType} ${r.responseId}`,t);this.logger.verbose(r.extensionId?`0xrkug ${r.extensionId}`:"No extension installed",t),clearTimeout(this.timeoutId),this.messageChannel.port1.close(),this.messageChannel.port2.close(),window.removeEventListener("message",this.windowListener,!1),this.handshakeEvent.end({success:!1,extensionInstalled:!1}),e.reject(Ui("native_extension_not_installed",""))}}onChannelMessage(e){const t=Ul();this.logger.trace(`1py8yf ${this.platformAuthType}`,t);const r=e.data,o=this.resolvers.get(r.responseId),n=this.handshakeResolvers.get(r.responseId);try{const e=r.body.method;if(e===Jo){if(!o)return;const e=r.body.response;if(this.logger.trace(`19hpgm ${this.platformAuthType}`,t),this.logger.tracePii(`179a24 ${this.platformAuthType} ${JSON.stringify(e)}`,t),"Success"!==e.status)o.reject(Wh(e.code,t,e.description,e.ext));else{if(!e.result)throw Mn(pd,t,"Event does not contain result.");e.result.code&&e.result.description?o.reject(Wh(e.result.code,t,e.result.description,e.result.ext)):o.resolve(e.result)}this.resolvers.delete(r.responseId)}else if(e===Ko){if(!n)return void this.logger.trace(`082qnt ${this.platformAuthType} ${r.responseId}`,t);clearTimeout(this.timeoutId),window.removeEventListener("message",this.windowListener,!1),this.extensionId=r.extensionId,this.extensionVersion=r.body.version,this.logger.verbose(`0yf5ib ${this.platformAuthType} ${this.extensionId}`,t),this.handshakeEvent.end({extensionInstalled:!0,success:!0}),n.resolve(),this.handshakeResolvers.delete(r.responseId)}}catch(r){this.logger.error("0xf978",t),this.logger.errorPii(`04i99o ${r}`,t),this.logger.errorPii(`0xdvsy ${e}`,t),o?o.reject(r):n&&n.reject(r)}}validatePlatformBrokerResponse(e){if(e.hasOwnProperty("access_token")&&e.hasOwnProperty("id_token")&&e.hasOwnProperty("client_info")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scope")&&e.hasOwnProperty("expires_in"))return e;throw Mn(pd,"","Response missing expected properties.")}getExtensionId(){return this.extensionId}getExtensionVersion(){return this.extensionVersion}getExtensionName(){return this.getExtensionId()===Lo?"chrome":this.getExtensionId()?.length?"unknown":void 0}}class fd{constructor(e,t,r){this.logger=e,this.performanceClient=t,this.correlationId=r,this.platformAuthType=zo}static async createProvider(e,t,r){if(e.trace("12mj4a",r),window.navigator?.platformAuthentication){const o=await window.navigator.platformAuthentication.getSupportedContracts(Do);if(o?.includes(Fo))return e.trace("1h5q1r",r),new fd(e,t,r)}}getExtensionId(){return Do}getExtensionVersion(){return""}getExtensionName(){return Ho}async sendMessage(e){this.logger.trace(`02bcil ${this.platformAuthType}`,e.correlationId);try{const t=this.initializePlatformDOMRequest(e),r=await window.navigator.platformAuthentication.executeGetToken(t);return this.validatePlatformBrokerResponse(r,e.correlationId)}catch(t){throw this.logger.error(`11im7g ${this.platformAuthType}`,e.correlationId),t}}initializePlatformDOMRequest(e){this.logger.trace(`15d6yv ${this.platformAuthType}`,e.correlationId);const{accountId:t,clientId:r,authority:o,scope:n,redirectUri:i,correlationId:s,state:a,storeInCache:c,embeddedClientId:l,extraParameters:h,...d}=e,u=this.getDOMExtraParams(d,s);return{accountId:t,brokerId:this.getExtensionId(),authority:o,clientId:r,correlationId:s||this.correlationId,extraParameters:{...h,...u},isSecurityTokenService:!1,redirectUri:i,scope:n,state:a,storeInCache:c,embeddedClientId:l}}validatePlatformBrokerResponse(e,t){if(e.hasOwnProperty("isSuccess")){if(e.hasOwnProperty("accessToken")&&e.hasOwnProperty("idToken")&&e.hasOwnProperty("clientInfo")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scopes")&&e.hasOwnProperty("expiresIn"))return this.logger.trace(`0h4vei ${this.platformAuthType}`,t),this.convertToPlatformBrokerResponse(e,t);if(e.hasOwnProperty("error")){const r=e;if(!1===r.isSuccess&&r.error&&r.error.code)throw this.logger.trace(`0g92vm ${this.platformAuthType}`,t),Wh(r.error.code,t,r.error.description,{error:parseInt(r.error.errorCode),protocol_error:r.error.protocolError,status:r.error.status,properties:r.error.properties})}}throw Mn(pd,t,"Response missing expected properties.")}convertToPlatformBrokerResponse(e,t){this.logger.trace(`14913t ${this.platformAuthType}`,t);return{access_token:e.accessToken,id_token:e.idToken,client_info:e.clientInfo,account:e.account,expires_in:e.expiresIn,scope:e.scopes,state:e.state||"",properties:e.properties||{},extendedLifetimeToken:e.extendedLifetimeToken??!1,shr:e.proofOfPossessionPayload}}getDOMExtraParams(e,t){try{const t={};for(const[r,o]of Object.entries(e))o&&(t[r]="object"==typeof o?JSON.stringify(o):String(o));return t}catch(e){return this.logger.error(`0eu9o3 ${this.platformAuthType}`,t),this.logger.errorPii(`17rpl5 ${this.platformAuthType} ${e}`,t),{}}}}async function yd(e,t,r,o,n){let i;e.trace("134j0v",r),e.trace(`04c81g ${n}`,r);try{n&&(i=await fd.createProvider(e,t,r)),i||(e.trace("0l3na8",r),i=await md.createProvider(e,o||2e3,t,r))}catch(t){e.trace("0icbd7",t)}return i}function wd(e,t,r,o,n){if(t.trace("0uko3r",r),!e.system.allowPlatformBroker&&e.experimental.allowPlatformBrokerWithDOM)throw Ns("invalid_platform_broker_configuration","");if(!e.system.allowPlatformBroker)return t.trace("04hozs",r),!1;if(!o)return t.trace("0kvv1r",r),!1;if(n)switch(n){case yo.BEARER:case yo.POP:return t.trace("18tev1",r),!0;default:return t.trace("1dd2nh",r),!1}return!0}class vd extends Uh{constructor(e,t,r,o,n,i,s,a,c,l,h){super(e,t,r,o,n,i,s,c,l),this.nativeStorage=a,this.eventHandler=n,this.waitForPopupResponseHook=h}acquireToken(e,t){let r;try{if(r={popupName:this.generatePopupName(e.scopes||xr,e.authority||this.config.auth.authority),popupWindowAttributes:e.popupWindowAttributes||{},popupWindowParent:e.popupWindowParent??window},this.performanceClient.addFields({isAsyncPopup:!this.config.system.navigatePopups},this.correlationId),this.config.system.navigatePopups){const o={...e,httpMethod:$h(e,this.config.system.protocolMode)};return this.logger.verbose("1f9ok3",this.correlationId),r.popup=this.openSizedPopup("about:blank",r),this.acquireTokenPopupAsync(o,r,t)}return this.logger.verbose("162h4u",this.correlationId),this.acquireTokenPopupAsync(e,r,t)}catch(e){return Promise.reject(e)}}logout(e){try{this.logger.verbose("068rup",this.correlationId);const t=this.initializeLogoutRequest(e),r={popupName:this.generateLogoutPopupName(t),popupWindowAttributes:e?.popupWindowAttributes||{},popupWindowParent:e?.popupWindowParent??window},o=e&&e.authority,n=e&&e.mainWindowRedirectUri;return this.config.system.navigatePopups?(this.logger.verbose("1a28da",this.correlationId),r.popup=this.openSizedPopup("about:blank",r),this.logoutPopupAsync(t,r,o,n)):(this.logger.verbose("1phd8u",this.correlationId),this.logoutPopupAsync(t,r,o,n))}catch(e){return Promise.reject(e)}}async acquireTokenPopupAsync(e,t,r){this.logger.verbose("1g77pg",this.correlationId);const o=await da(Lh,Ci,this.logger,this.performanceClient,this.correlationId)(e,Cn.Popup,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId);t.popup&&$l(o.authority);const n=wd(this.config,this.logger,this.correlationId,this.platformAuthProvider,e.authenticationScheme);return o.platformBroker=n,this.config.system.protocolMode===ea?this.executeEarFlow(o,t,r):this.executeCodeFlow(o,t,r)}async executeCodeFlow(e,t,r){const o=e.correlationId,n=xh(dn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),i=r||await da(sd,Ai,this.logger,this.performanceClient,o)(this.performanceClient,this.logger,o),s={...e,codeChallenge:i.challenge};try{const r=await da(this.createAuthCodeClient.bind(this),wi,this.logger,this.performanceClient,o)({serverTelemetryManager:n,requestAuthority:s.authority,requestAzureCloudOptions:s.azureCloudOptions,requestExtraQueryParameters:s.extraQueryParameters,account:s.account});if(s.httpMethod===Pr)return await this.executeCodeFlowWithPost(s,t,r,i.verifier);{const n=await da(Zh,na,this.logger,this.performanceClient,o)(this.config,r.authority,s,this.logger,this.performanceClient),a=this.initiateAuthRequest(n,t);this.eventHandler.emitEvent(Ec,o,Cn.Popup,{popupWindow:a},null);const c=await this.waitForPopupResponse(e,a,t.popupWindowParent),l=ha(Nh,Si,this.logger,this.performanceClient,this.correlationId)(c,this.config.auth.OIDCOptions.responseMode,this.logger,this.correlationId);return await da(nd,ki,this.logger,this.performanceClient,o)(e,l,i.verifier,dn,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}}catch(e){throw t.popup?.close(),e instanceof Rn&&(e.correlationId=this.correlationId,n.cacheFailedRequest(e)),e}}async executeEarFlow(e,t,r){const{correlationId:o,authority:n,azureCloudOptions:i,extraQueryParameters:s,account:a}=e,c=await da(Oh,di,this.logger,this.performanceClient,o)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,n,i,s,a),l=await da(ws,Pi,this.logger,this.performanceClient,o)(),h=r||await da(sd,Ai,this.logger,this.performanceClient,o)(this.performanceClient,this.logger,o),d={...e,earJwk:l,codeChallenge:h.challenge},u=t.popup||this.openPopup("about:blank",t);(await ed(u.document,this.config,c,d,this.logger,this.performanceClient)).submit();const g=await da(this.waitForPopupResponse.bind(this),yi,this.logger,this.performanceClient,o)(d,u,t.popupWindowParent),p=ha(Nh,Si,this.logger,this.performanceClient,this.correlationId)(g,this.config.auth.OIDCOptions.responseMode,this.logger,this.correlationId);if(!p.ear_jwe&&p.code){const t=await da(this.createAuthCodeClient.bind(this),wi,this.logger,this.performanceClient,o)({serverTelemetryManager:xh(dn,this.config.auth.clientId,o,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account,authority:c});return da(nd,ki,this.logger,this.performanceClient,o)(d,p,h.verifier,dn,this.config,t,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}return da(id,Ii,this.logger,this.performanceClient,o)(d,p,dn,this.config,c,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async executeCodeFlowWithPost(e,t,r,o){const n=e.correlationId,i=await da(Oh,di,this.logger,this.performanceClient,n)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger),s=t.popup||this.openPopup("about:blank",t);(await td(s.document,this.config,i,e,this.logger,this.performanceClient)).submit();const a=await da(this.waitForPopupResponse.bind(this),yi,this.logger,this.performanceClient,n)(e,s,t.popupWindowParent),c=ha(Nh,Si,this.logger,this.performanceClient,this.correlationId)(a,this.config.auth.OIDCOptions.responseMode,this.logger,this.correlationId);return da(nd,ki,this.logger,this.performanceClient,n)(e,c,o,dn,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async logoutPopupAsync(e,t,r,o){this.logger.verbose("0b7yrk",this.correlationId),this.eventHandler.emitEvent(Pc,this.correlationId,Cn.Popup,e);const n=xh(yn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled);try{await Rh(this.browserStorage,this.browserCrypto,this.logger,this.correlationId,e.account);const i=await da(this.createAuthCodeClient.bind(this),wi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:n,requestAuthority:r,account:e.account||void 0});try{i.authority.endSessionEndpoint}catch{if(e.account?.homeAccountId&&e.postLogoutRedirectUri&&i.authority.protocolMode===Zs){if(this.eventHandler.emitEvent(xc,e.correlationId,Cn.Popup,e),o){const e={apiId:yn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},t=Ks.getAbsoluteUrl(o,xl(),this.correlationId);await this.navigationClient.navigateInternal(t,e)}return void t.popup?.close()}}e.state=qc(this.browserCrypto,e.state||"",{interactionType:Cn.Popup},e.correlationId);const s=i.getLogoutUri(e);this.eventHandler.emitEvent(xc,e.correlationId,Cn.Popup,e);const a=this.openPopup(s,t);if(this.eventHandler.emitEvent(Ec,e.correlationId,Cn.Popup,{popupWindow:a},null),await this.waitForPopupResponse(e,a,t.popupWindowParent).catch(()=>{}),o){const e={apiId:yn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},t=Ks.getAbsoluteUrl(o,xl(),this.correlationId);this.logger.verbose("0qcur2",this.correlationId),this.logger.verbosePii(`0oj7lk ${t}`,this.correlationId),await this.navigationClient.navigateInternal(t,e)}else this.logger.verbose("03zgcf",this.correlationId)}catch(e){throw t.popup?.close(),e instanceof Rn&&(e.correlationId=this.correlationId,n.cacheFailedRequest(e)),this.eventHandler.emitEvent(Oc,this.correlationId,Cn.Popup,null,e),this.eventHandler.emitEvent(Rc,this.correlationId,Cn.Popup),e}this.eventHandler.emitEvent(Rc,this.correlationId,Cn.Popup)}initiateAuthRequest(e,t){if(e)return this.logger.infoPii(`1kcr9k ${e}`,this.correlationId),this.openPopup(e,t);throw this.logger.error("1l7hyp",this.correlationId),Ui(Hi,this.correlationId)}openPopup(e,t){try{let r;if(t.popup?(r=t.popup,this.logger.verbosePii(`0cgeo7 ${e}`,this.correlationId),r.location.assign(e)):void 0===t.popup&&(this.logger.verbosePii(`0c2awd ${e}`,this.correlationId),r=this.openSizedPopup(e,t)),!r)throw Ui("empty_window_error",this.correlationId);try{r.document.title="Microsoft Authentication"}catch(e){"undefined"!=typeof DOMException&&e instanceof DOMException&&"SecurityError"===e.name||this.logger.verbose("1s1yfs",this.correlationId)}return r.focus&&r.focus(),this.currentWindow=r,r}catch(e){throw this.logger.error(`0dxfb9 ${e.message}`,this.correlationId),Ui("popup_window_error",this.correlationId)}}openSizedPopup(e,{popupName:t,popupWindowAttributes:r,popupWindowParent:o}){const n=o.screenLeft?o.screenLeft:o.screenX,i=o.screenTop?o.screenTop:o.screenY,s=o.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,a=o.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;let c=r.popupSize?.width,l=r.popupSize?.height,h=r.popupPosition?.top,d=r.popupPosition?.left;return(!c||c<0||c>s)&&(this.logger.verbose("08vfmo",this.correlationId),c=Ro),(!l||l<0||l>a)&&(this.logger.verbose("09cxa0",this.correlationId),l=Mo),(!h||h<0||h>a)&&(this.logger.verbose("1qh4wo",this.correlationId),h=Math.max(0,a/2-Mo/2+i)),(!d||d<0||d>s)&&(this.logger.verbose("1sz3en",this.correlationId),d=Math.max(0,s/2-Ro/2+n)),o.open(e,t,`width=${c}, height=${l}, top=${h}, left=${d}, scrollbars=yes`)}generatePopupName(e,t){return`${qo}.${this.config.auth.clientId}.${e.join("-")}.${t}.${this.correlationId}`}generateLogoutPopupName(e){const t=e.account&&e.account.homeAccountId;return`${qo}.${this.config.auth.clientId}.${t}.${this.correlationId}`}async waitForPopupResponse(e,t,r){return this.waitForPopupResponseHook?this.waitForPopupResponseHook(e,t,r):Pl(this.config.system.popupBridgeTimeout,this.logger,e,this.performanceClient)}}class Cd extends Uh{constructor(e,t,r,o,n,i,s,a,c,l){super(e,t,r,o,n,i,s,c,l),this.nativeStorage=a}async acquireToken(e){const t=await da(Lh,Ci,this.logger,this.performanceClient,this.correlationId)(e,Cn.Redirect,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId);t.platformBroker=wd(this.config,this.logger,this.correlationId,this.platformAuthProvider,e.authenticationScheme);const r=e=>{e.persisted&&(this.logger.verbose("0udvtt",this.correlationId),this.browserStorage.resetRequestCache(this.correlationId),this.eventHandler.emitEvent(Mc,this.correlationId,Cn.Redirect))},o=this.getRedirectStartPage(e.redirectStartPage);this.logger.verbosePii(`0zao0a ${o}`,this.correlationId),this.browserStorage.setTemporaryCache(tn,o,!0),window.addEventListener("pageshow",r);try{this.config.system.protocolMode===ea?await this.executeEarFlow(t):await this.executeCodeFlow(t)}catch(e){throw e instanceof Rn&&(e.correlationId=this.correlationId),window.removeEventListener("pageshow",r),e}}async executeCodeFlow(e){const t=e.correlationId,r=xh(hn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),o=await da(sd,Ai,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),n={...e,codeChallenge:o.challenge};this.browserStorage.cacheAuthorizeRequest(n,this.correlationId,o.verifier);try{if(n.httpMethod===Pr)return await this.executeCodeFlowWithPost(n);{const t=await da(this.createAuthCodeClient.bind(this),wi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:r,requestAuthority:n.authority,requestAzureCloudOptions:n.azureCloudOptions,requestExtraQueryParameters:n.extraQueryParameters,account:n.account}),o=await da(Zh,na,this.logger,this.performanceClient,e.correlationId)(this.config,t.authority,n,this.logger,this.performanceClient);return await this.initiateAuthRequest(o)}}catch(e){throw e instanceof Rn&&(e.correlationId=this.correlationId,r.cacheFailedRequest(e)),e}}async executeEarFlow(e){const{correlationId:t,authority:r,azureCloudOptions:o,extraQueryParameters:n,account:i}=e,s=await da(Oh,di,this.logger,this.performanceClient,t)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,r,o,n,i),a=await da(ws,Pi,this.logger,this.performanceClient,t)(),c=await da(sd,Ai,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),l={...e,earJwk:a,codeChallenge:c.challenge};this.browserStorage.cacheAuthorizeRequest(l,this.correlationId,c.verifier);return(await ed(document,this.config,s,l,this.logger,this.performanceClient)).submit(),new Promise((e,t)=>{setTimeout(()=>{t(Ui(es,"","failed_to_redirect"))},this.config.system.redirectNavigationTimeout)})}async executeCodeFlowWithPost(e){const t=e.correlationId,r=await da(Oh,di,this.logger,this.performanceClient,t)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger);this.browserStorage.cacheAuthorizeRequest(e,this.correlationId);return(await td(document,this.config,r,e,this.logger,this.performanceClient)).submit(),new Promise((e,t)=>{setTimeout(()=>{t(Ui(es,"","failed_to_redirect"))},this.config.system.redirectNavigationTimeout)})}async handleRedirectPromise(e,t,r,o){const n=document.title;document.title="Microsoft Authentication";const i=xh(gn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),s=o?.navigateToLoginRequestUrl??!0;try{const[n,a]=this.getRedirectResponse(o?.hash||"");if(!n)return this.logger.info("1qmv0q",this.correlationId),this.browserStorage.resetRequestCache(this.correlationId),"back_forward"!==function(){if("undefined"==typeof window||void 0===window.performance||"function"!=typeof window.performance.getEntriesByType)return;const e=window.performance.getEntriesByType("navigation"),t=e.length?e[0]:void 0;return t?.type}()?r.event.errorCode="no_server_response":this.logger.verbose("1eqegq",this.correlationId),null;const c=this.browserStorage.getTemporaryCache(tn,this.correlationId,!0)||"",l=Dc(c,this.logger,this.correlationId);if(l===Dc(window.location.href,this.logger,this.correlationId)&&s){this.logger.verbose("11yred",this.correlationId),c.indexOf("#")>-1&&function(e){const t=e.split("#");t.shift(),window.location.hash=t.length>0?t.join("#"):""}(c);return await this.handleResponse(n,e,t,i)}if(!s)return this.logger.verbose("0v4sdv",this.correlationId),await this.handleResponse(n,e,t,i);if(!Al()||this.config.system.allowRedirectInIframe){this.browserStorage.setTemporaryCache(rn,a,!0);const r={apiId:gn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!0};let o=!0;if(c)this.logger.verbose(`08jpy1 ${c}`,this.correlationId),o=await this.navigationClient.navigateInternal(c,r);else{const e=function(e){const t=new Ks(window.location.href,e||"").getUrlComponents();return`${t.Protocol}//${t.HostNameAndPort}/`}(this.correlationId);this.browserStorage.setTemporaryCache(tn,e,!0),this.logger.warning("1dutq1",this.correlationId),o=await this.navigationClient.navigateInternal(e,r)}if(!o)return await this.handleResponse(n,e,t,i)}return null}catch(e){throw e instanceof Rn&&(e.correlationId=this.correlationId,i.cacheFailedRequest(e)),e}finally{document.title=n}}getRedirectResponse(e){this.logger.verbose("1c5i8m",this.correlationId);let t=e;t||(t=this.config.auth.OIDCOptions.responseMode===eo?window.location.search:window.location.hash);let r=Lc(t);if(r){try{Dh(r,this.browserCrypto,Cn.Redirect,this.correlationId)}catch(e){return e instanceof Rn&&this.logger.error(`0bkq6p ${e.errorCode} ${e.errorMessage}`,this.correlationId),[null,""]}return Tl(window),this.logger.verbose("00uvho",this.correlationId),[r,t]}const o=this.browserStorage.getTemporaryCache(rn,this.correlationId,!0);return this.browserStorage.removeItem(this.browserStorage.generateCacheKey(rn)),o&&(r=Lc(o),r)?(this.logger.verbose("001671",this.correlationId),[r,o]):[null,""]}async handleResponse(e,t,r,o){if(!e.state)throw Ui(Fi,t.correlationId);const{authority:n,azureCloudOptions:i,extraQueryParameters:s,account:a}=t;if(e.ear_jwe){const r=await da(Oh,di,this.logger,this.performanceClient,t.correlationId)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,n,i,s,a);return da(id,Ii,this.logger,this.performanceClient,t.correlationId)(t,e,hn,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}const c=await da(this.createAuthCodeClient.bind(this),wi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:o,requestAuthority:t.authority});return da(nd,ki,this.logger,this.performanceClient,t.correlationId)(t,e,r,hn,this.config,c,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async initiateAuthRequest(e){if(this.logger.verbose("0yaw2e",this.correlationId),e){this.logger.infoPii(`1luf83 ${e}`,this.correlationId);const t={apiId:hn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},r=this.config.auth.onRedirectNavigate;if("function"==typeof r){this.logger.verbose("1nehvl",this.correlationId);return!1!==r(e)?(this.logger.verbose("1a0jxh",this.correlationId),void await this.navigationClient.navigateExternal(e,t)):void this.logger.verbose("09k5h5",this.correlationId)}return this.logger.verbose("0klwf7",this.correlationId),void await this.navigationClient.navigateExternal(e,t)}throw this.logger.info("0rlh4e",this.correlationId),Ui(Hi,this.correlationId)}async logout(e){this.logger.verbose("1rkurh",this.correlationId);const t=this.initializeLogoutRequest(e),r=xh(fn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled);try{this.eventHandler.emitEvent(Pc,this.correlationId,Cn.Redirect,e),await Rh(this.browserStorage,this.browserCrypto,this.logger,this.correlationId,t.account);const o={apiId:fn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},n=await da(this.createAuthCodeClient.bind(this),wi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:r,requestAuthority:e&&e.authority,requestExtraQueryParameters:e?.extraQueryParameters,account:e&&e.account||void 0});if(n.authority.protocolMode===Zs)try{n.authority.endSessionEndpoint}catch{if(t.account?.homeAccountId)return void this.eventHandler.emitEvent(xc,this.correlationId,Cn.Redirect,t)}t.state=qc(this.browserCrypto,t.state||"",{interactionType:Cn.Redirect},t.correlationId);const i=n.getLogoutUri(t);t.account?.homeAccountId&&this.eventHandler.emitEvent(xc,this.correlationId,Cn.Redirect,t);const s=this.config.auth.onRedirectNavigate;if("function"!=typeof s)return this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0,en),void await this.navigationClient.navigateExternal(i,o);if(!1!==s(i))return this.logger.verbose("06v57e",this.correlationId),this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0,en),void await this.navigationClient.navigateExternal(i,o);this.browserStorage.setInteractionInProgress(!1),this.logger.verbose("0xqes1",this.correlationId)}catch(e){throw e instanceof Rn&&(e.correlationId=this.correlationId,r.cacheFailedRequest(e)),this.eventHandler.emitEvent(Oc,this.correlationId,Cn.Redirect,null,e),this.eventHandler.emitEvent(Rc,this.correlationId,Cn.Redirect),e}this.eventHandler.emitEvent(Rc,this.correlationId,Cn.Redirect)}getRedirectStartPage(e){const t=e||window.location.href,r=Ks.getAbsoluteUrl(t,xl(),this.correlationId);return function(e,t,r){try{new URL(e)}catch(e){throw t?.error(`1lrjz7 ${e}`,r||""),Ns(Hs,r||"")}}(r,this.logger,this.correlationId),r}}async function Id(e,t,r,o){if(!t)throw r.info("1l7hyp",o),Ui(Hi,o);return e.src=t,e}async function bd(e,t,r,o,n,i){if(!e.contentDocument)throw"No document associated with iframe!";return(await td(e.contentDocument,t,r,o,n,i)).submit(),e}async function kd(e,t,r,o,n,i){if(!e.contentDocument)throw"No document associated with iframe!";return(await ed(e.contentDocument,t,r,o,n,i)).submit(),e}function Sd(){const e=document.createElement("iframe");return e.className="msalSilentIframe",e.title="Microsoft Authentication",e.style.visibility="hidden",e.style.position="absolute",e.style.width=e.style.height="0",e.style.border="0",e.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),e.setAttribute("allow","local-network-access *"),document.body.appendChild(e),e}function Td(e){document.body===e.parentNode&&document.body.removeChild(e)}class Ad extends Uh{constructor(e,t,r,o,n,i,s,a,c,l,h,d){super(e,t,r,o,n,i,a,l,h),this.apiId=s,this.nativeStorage=c,this.waitForIframeResponseHook=d}async acquireToken(e){e.loginHint||e.sid||e.account&&e.account.username||this.logger.warning("1kl318",this.correlationId);const t={...e};t.prompt?t.prompt!==Qr&&t.prompt!==Yr&&(this.logger.warning(`0bmctg ${t.prompt} ${Qr}`,this.correlationId),t.prompt=Qr):t.prompt=Qr;const r=await da(Lh,Ci,this.logger,this.performanceClient,this.correlationId)(t,Cn.Silent,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId);return r.platformBroker=wd(this.config,this.logger,this.correlationId,this.platformAuthProvider,r.authenticationScheme),$l(r.authority),this.config.system.protocolMode===ea?this.executeEarFlow(r):this.executeCodeFlow(r)}async executeCodeFlow(e){let t;const r=xh(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled);try{return t=await da(this.createAuthCodeClient.bind(this),wi,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:r,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),await da(this.silentTokenHelper.bind(this),mi,this.logger,this.performanceClient,e.correlationId)(t,e)}catch(o){if(o instanceof Rn&&(o.correlationId=this.correlationId,r.cacheFailedRequest(o)),!(t&&o instanceof Rn&&o.errorCode===Oo))throw o;return this.performanceClient.addFields({retryError:o.errorCode},this.correlationId),await da(this.silentTokenHelper.bind(this),mi,this.logger,this.performanceClient,this.correlationId)(t,e)}}async executeEarFlow(e){const{correlationId:t,authority:r,azureCloudOptions:o,extraQueryParameters:n,account:i}=e,s=await da(Oh,di,this.logger,this.performanceClient,t)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,r,o,n,i),a=await da(ws,Pi,this.logger,this.performanceClient,t)(),c=await da(sd,Ai,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),l={...e,earJwk:a,codeChallenge:c.challenge},h=Sd(),d=this.config.auth.OIDCOptions.responseMode;let u;try{const r=da(this.waitForIframeResponse.bind(this),yi,this.logger,this.performanceClient,t)(h,e);r.catch(()=>{}),await da(kd,fi,this.logger,this.performanceClient,t)(h,this.config,s,l,this.logger,this.performanceClient),u=await r}finally{ha(Td,Ti,this.logger,this.performanceClient,t)(h)}const g=ha(Nh,Si,this.logger,this.performanceClient,t)(u,d,this.logger,this.correlationId);if(!g.ear_jwe&&g.code){const r=await da(this.createAuthCodeClient.bind(this),wi,this.logger,this.performanceClient,t)({serverTelemetryManager:xh(this.apiId,this.config.auth.clientId,t,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account,authority:s});return da(nd,ki,this.logger,this.performanceClient,t)(l,g,c.verifier,this.apiId,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}return da(id,Ii,this.logger,this.performanceClient,t)(l,g,this.apiId,this.config,s,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async verifySso(e){const t={...e};t.prompt||(t.prompt=Qr);const r=await da(Lh,Ci,this.logger,this.performanceClient,this.correlationId)(t,Cn.Silent,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId),o=await da(this.createAuthCodeClient.bind(this),wi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:xh(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),requestAuthority:r.authority,requestAzureCloudOptions:r.azureCloudOptions,requestExtraQueryParameters:r.extraQueryParameters,account:r.account}),{serverParams:n}=await this.silentAuthorizeHelper(o,r),i=r.correlationId;return zh(n,r.state,i),n.code?(this.logger.verbose("0kkkcj",i),!0):(this.logger.warning("0y34ti",i),!1)}logout(){return Promise.reject(Ui(Bi,""))}async silentTokenHelper(e,t){const{serverParams:r,pkceCodes:o}=await this.silentAuthorizeHelper(e,t);return da(nd,ki,this.logger,this.performanceClient,t.correlationId)(t,r,o.verifier,this.apiId,this.config,e,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async silentAuthorizeHelper(e,t){const r=t.correlationId,o=await da(sd,Ai,this.logger,this.performanceClient,r)(this.performanceClient,this.logger,r),n={...t,codeChallenge:o.challenge},i=Sd(),s=this.config.auth.OIDCOptions.responseMode;let a;try{const o=da(this.waitForIframeResponse.bind(this),yi,this.logger,this.performanceClient,r)(i,t);if(o.catch(()=>{}),t.httpMethod===Pr)await da(bd,fi,this.logger,this.performanceClient,r)(i,this.config,e.authority,n,this.logger,this.performanceClient);else{const t=await da(Zh,na,this.logger,this.performanceClient,r)(this.config,e.authority,n,this.logger,this.performanceClient);await da(Id,fi,this.logger,this.performanceClient,r)(i,t,this.logger,r)}a=await o}finally{ha(Td,Ti,this.logger,this.performanceClient,r)(i)}return{serverParams:ha(Nh,Si,this.logger,this.performanceClient,r)(a,s,this.logger,this.correlationId),pkceCodes:o,silentRequest:n}}async waitForIframeResponse(e,t){return this.waitForIframeResponseHook?this.waitForIframeResponseHook(e,t):Pl(this.config.system.iframeBridgeTimeout,this.logger,t,this.performanceClient,this.config.experimental)}}class _d{constructor(e,t){this.config=sh(e),this.logger=new Gl(this.config.loggerOptions,Ba,Ka),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t}async acquireToken(e,t){const r=ma(),o=await da(this.executeTokenRequest.bind(this),"refreshTokenClientExecuteTokenRequest",this.logger,this.performanceClient,e.correlationId)(e,this.authority),n=o.headers?.[Ur],i=new uh(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.performanceClient,this.config.serializableCache,this.config.persistencePlugin);return i.validateTokenResponse(o.body,e.correlationId),da(i.handleServerTokenResponse.bind(i),aa,this.logger,this.performanceClient,e.correlationId)(o.body,this.authority,r,e,t,void 0,void 0,!0,e.forceCache,n)}async acquireTokenByRefreshToken(e,t){if(!e)throw Ns("token_request_empty","");if(!e.account)throw Wn(ti,e.correlationId);if(this.cacheManager.isAppMetadataFOCI(e.account.environment,e.correlationId))try{return await da(this.acquireTokenWithCachedRefreshToken.bind(this),oa,this.logger,this.performanceClient,e.correlationId)(e,!0,t)}catch(r){const o=r instanceof Hn&&r.errorCode===qn,n=r instanceof dh&&"invalid_grant"===r.errorCode&&"client_mismatch"===r.subError;if(o||n)return da(this.acquireTokenWithCachedRefreshToken.bind(this),oa,this.logger,this.performanceClient,e.correlationId)(e,!1,t);throw r}return da(this.acquireTokenWithCachedRefreshToken.bind(this),oa,this.logger,this.performanceClient,e.correlationId)(e,!1,t)}async acquireTokenWithCachedRefreshToken(e,t,r){const o=ha(this.cacheManager.getRefreshToken.bind(this.cacheManager),"cacheManagerGetRefreshToken",this.logger,this.performanceClient,e.correlationId)(e.account,t,e.correlationId,void 0);if(!o)throw zn(qn,e.correlationId);if(o.expiresOn){const t=e.refreshTokenExpirationOffsetSeconds||300;if(this.performanceClient?.addFields({cacheRtExpiresOnSeconds:Number(o.expiresOn),rtOffsetSeconds:t},e.correlationId),wa(o.expiresOn,t))throw zn($n,e.correlationId)}const n={...e,refreshToken:o.secret,authenticationScheme:e.authenticationScheme||yo.BEARER,ccsCredential:{credential:e.account.homeAccountId,type:ph}};try{return await da(this.acquireToken.bind(this),"refreshTokenClientAcquireToken",this.logger,this.performanceClient,e.correlationId)(n,r)}catch(t){if(t instanceof Hn&&t.subError===Ln){this.logger.verbose("1pg3ap",e.correlationId);const t=this.cacheManager.generateCredentialKey(o);this.cacheManager.removeRefreshToken(t,e.correlationId)}throw t}}async executeTokenRequest(e,t){const r=Ih(e,this.config.authOptions.clientId,this.config.authOptions.redirectUri,this.performanceClient),o=Ks.appendQueryString(t.tokenEndpoint,r),n=await da(this.createTokenRequestBody.bind(this),"refreshTokenClientCreateTokenRequestBody",this.logger,this.performanceClient,e.correlationId)(e),i=Ch(this.logger,this.config.systemOptions.preventCorsPreflight,e.ccsCredential),s=Da(this.config.authOptions.clientId,e);return da(bh,"refreshTokenClientExecutePostToTokenEndpoint",this.logger,this.performanceClient,e.correlationId)(o,n,i,s,e.correlationId,this.cacheManager,this.networkClient,this.logger,this.performanceClient,this.serverTelemetryManager)}async createTokenRequestBody(e){const t=new Map;if(Xc(t,e.embeddedClientId||e.extraParameters?.[Hc]||this.config.authOptions.clientId),e.redirectUri&&Zc(t,e.redirectUri),Yc(t,e.scopes,e.correlationId,!0,this.config.authOptions.authority.options.OIDCOptions?.defaultScopes),gl(t,oo),pl(t),sl(t,this.config.libraryInfo),al(t,this.config.telemetry.application),bl(t),this.serverTelemetryManager&&!ah(this.config)&&Il(t,this.serverTelemetryManager),function(e,t){e.set("refresh_token",t)}(t,e.refreshToken),this.config.clientCredentials.clientSecret&&hl(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const r=this.config.clientCredentials.clientAssertion;dl(t,await fh(r.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),ul(t,r.assertionType)}if(e.authenticationScheme===yo.POP){const r=new hh(this.cryptoUtils,this.performanceClient);let o;if(e.popKid)o=this.cryptoUtils.encodeKid(e.popKid);else{o=(await da(r.generateCnf.bind(r),sa,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}vl(t,o)}else if(e.authenticationScheme===yo.SSH){if(!e.sshJwk)throw Ns(js,e.correlationId);Cl(t,e.sshJwk)}if(this.config.systemOptions.preventCorsPreflight&&e.ccsCredential)switch(e.ccsCredential.type){case ph:try{rl(t,Ra(e.ccsCredential.credential))}catch(t){this.logger.verbose(`1qhtee ${t}`,e.correlationId)}break;case mh:tl(t,e.ccsCredential.credential)}return e.embeddedClientId&&kl(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.extraParameters&&fl(t,{...e.extraParameters}),Gc(t,e.correlationId,this.performanceClient),nl(t,e.correlationId,e.claims,this.config.authOptions.clientCapabilities,e.skipBrokerClaims),Nc(t)}}class Ed extends Uh{async acquireToken(e){const t=await da(Mh,pi,this.logger,this.performanceClient,e.correlationId)(e,this.config,this.performanceClient,this.logger,this.correlationId),r={...e,...t};e.redirectUri&&(r.redirectUri=Ph(e.redirectUri,this.config.auth.redirectUri,this.logger,this.correlationId));const o=xh(mn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),n=await this.createRefreshTokenClient({serverTelemetryManager:o,authorityUrl:r.authority,azureCloudOptions:r.azureCloudOptions,account:r.account});return da(n.acquireTokenByRefreshToken.bind(n),"refreshTokenClientAcquireTokenByRefreshToken",this.logger,this.performanceClient,e.correlationId)(r,mn).catch(e=>{throw e.correlationId=this.correlationId,o.cacheFailedRequest(e),e})}logout(){return Promise.reject(Ui(Bi,""))}async createRefreshTokenClient(e){const t=await da(this.getClientConfiguration.bind(this),vi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:e.serverTelemetryManager,requestAuthority:e.authorityUrl,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account});return new _d(t,this.performanceClient)}}class Pd extends Sh{constructor(e,t){super(e,t),this.includeRedirectUri=!1}}class xd extends Uh{constructor(e,t,r,o,n,i,s,a,c,l){super(e,t,r,o,n,i,a,c,l),this.apiId=s}async acquireToken(e){if(!e.code)throw Ui("auth_code_required",this.correlationId);const t=await da(Lh,Ci,this.logger,this.performanceClient,this.correlationId)(e,Cn.Silent,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId),r=xh(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled);try{const o={...t,code:e.code},n=await da(this.getClientConfiguration.bind(this),vi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:r,requestAuthority:t.authority,requestAzureCloudOptions:t.azureCloudOptions,requestExtraQueryParameters:t.extraQueryParameters,account:t.account}),i=new Pd(n,this.performanceClient);this.logger.verbose("1uic5e",this.correlationId);const s=new jh(i,this.browserStorage,o,this.logger,this.performanceClient);return await da(s.handleCodeResponseFromServer.bind(s),ia,this.logger,this.performanceClient,this.correlationId)({code:e.code,msgraph_host:e.msGraphHost,cloud_graph_host_name:e.cloudGraphHostName,cloud_instance_host_name:e.cloudInstanceHostName},t,this.apiId,!1)}catch(e){throw e instanceof Rn&&(e.correlationId=this.correlationId,r.cacheFailedRequest(e)),e}}logout(){return Promise.reject(Ui(Bi,""))}}function Od(e,t,r,o){try{Ml(e),xs(r.auth.isMcp,o)}catch(e){throw t.end({success:!1},e,o.account),e}}class Rd{constructor(e){var t,r,o,n;this.operatingContext=e,this.isBrowserEnvironment=this.operatingContext.isBrowserEnvironment(),this.config=e.getConfig(),this.initialized=!1,this.logger=this.operatingContext.getLogger(),this.networkClient=this.config.system.networkClient,this.navigationClient=this.config.system.navigationClient,this.redirectResponse=new Map,this.hybridAuthCodeResponses=new Map,this.performanceClient=this.config.telemetry.client,this.browserCrypto=this.isBrowserEnvironment?new Es(this.logger,this.performanceClient):Rs,this.eventHandler=new Ql(this.logger),this.browserStorage=this.isBrowserEnvironment?new Bl(this.config.auth.clientId,this.config.cache,this.browserCrypto,this.logger,this.performanceClient,this.eventHandler,function(e){const t=e.cloudDiscoveryMetadata;let r;if(t)try{r=JSON.parse(t)}catch(e){throw Ns(zs,"")}return{canonicalAuthority:e.authority?xa(e.authority):void 0,knownAuthorities:e.knownAuthorities,cloudDiscoveryMetadata:r}}(this.config.auth)):(t=this.config.auth.clientId,r=this.logger,o=this.performanceClient,n=this.eventHandler,new Bl(t,{cacheLocation:Qo,cacheRetentionDays:5},Rs,r,o,n));const i={cacheLocation:Qo,cacheRetentionDays:5};this.nativeInternalStorage=new Bl(this.config.auth.clientId,i,this.browserCrypto,this.logger,this.performanceClient,this.eventHandler),this.activeSilentTokenRequests=new Map,this.trackStateChange=this.trackStateChange.bind(this),this.trackStateChangeWithMeasurement=this.trackStateChangeWithMeasurement.bind(this)}static async createController(e,t){const r=new Rd(e);return await r.initialize(t),r}trackStateChange(e,t){e&&("visibilitychange"===t.type?(this.logger.info("16v6hv",e),this.performanceClient.incrementFields({visibilityChangeCount:1},e)):"online"===t.type?(this.logger.info("0zirfd",e),this.performanceClient.incrementFields({onlineStatusChangeCount:1},e)):"offline"===t.type&&(this.logger.info("1xk9ef",e),this.performanceClient.incrementFields({onlineStatusChangeCount:1},e)))}async initialize(e){const t=this.getRequestCorrelationId(e);if(this.logger.trace("1f7joy",t),this.initialized)return void this.logger.info("061m5x",t);if(!this.isBrowserEnvironment)return this.logger.info("19fvpi",t),this.initialized=!0,void this.eventHandler.emitEvent(vc,t);const r=this.config.system.allowPlatformBroker,o=this.performanceClient.startMeasurement("initializeClientApplication",t);if(this.eventHandler.emitEvent(wc,t),this.logMultipleInstances(o,t),o.add({isMcp:this.config.auth.isMcp}),await da(this.browserStorage.initialize.bind(this.browserStorage),"initializeCache",this.logger,this.performanceClient,t)(t),r)try{this.platformAuthProvider=await yd(this.logger,this.performanceClient,t,this.config.system.nativeBrokerHandshakeTimeout,this.config.experimental.allowPlatformBrokerWithDOM)}catch(e){this.logger.verbose(e,t)}this.config.cache.cacheLocation===Vo&&this.eventHandler.subscribeCrossTab(),!this.config.system.navigatePopups&&await this.preGeneratePkceCodes(t),this.initialized=!0,this.eventHandler.emitEvent(vc,t),o.end({allowPlatformBroker:r,success:!0})}async handleRedirectPromise(e){if(this.logger.verbose("02l8bm",""),Rl(this.initialized),this.isBrowserEnvironment){const t=e?.hash||"";let r=this.redirectResponse.get(t);return void 0===r?(r=this.handleRedirectPromiseInternal(e),this.redirectResponse.set(t,r),this.logger.verbose("1wn9kp","")):this.logger.verbose("0w0gm3",""),r}return this.logger.verbose("12xi63",""),null}async handleRedirectPromiseInternal(e){if(!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("0le6uv",""),null;const t=this.browserStorage.getInteractionInProgress()?.type;if(t===en)return this.logger.verbose("1ywcv2",""),this.browserStorage.setInteractionInProgress(!1),Promise.resolve(null);const r=this.getAllAccounts(),o=this.browserStorage.getCachedNativeRequest(),n=o&&!e?.hash;let i,s,a;try{if(n&&this.platformAuthProvider){const e=o?.correlationId||"";this.eventHandler.emitEvent(Ac,e,Cn.Redirect),i=this.performanceClient.startMeasurement(Ha,e),this.logger.trace("12v7is",e),i.add({isPlatformBrokerRequest:!0});const t=new Gh(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,gn,this.performanceClient,this.platformAuthProvider,o.accountId,this.nativeInternalStorage,o.correlationId);s=da(t.handleRedirectPromise.bind(t),"handleNativeRedirectPromise",this.logger,this.performanceClient,i.event.correlationId)()}else{const[t,r]=this.browserStorage.getCachedRequest("");a=t;const o=t.correlationId;this.eventHandler.emitEvent(Ac,o,Cn.Redirect),i=this.performanceClient.startMeasurement(Ha,o),this.logger.trace("0znzs5",o);const n=this.createRedirectClient(o);s=da(n.handleRedirectPromise.bind(n),"handleRedirectPromise",this.logger,this.performanceClient,i.event.correlationId)(t,r,i,e)}}catch(e){throw this.browserStorage.resetRequestCache(""),e}return s.then(e=>{if(e){this.browserStorage.resetRequestCache(e.correlationId),this.eventHandler.emitEvent(kc,e.correlationId,Cn.Redirect,e),this.logger.verbose("0ui8f5",e.correlationId);r.length<this.getAllAccounts().length&&(this.eventHandler.emitEvent(Ic,e.correlationId,Cn.Redirect,e.account),this.logger.verbose("16im3l",e.correlationId)),i.end({success:!0},void 0,e.account),this.verifySsoCapability(a,Cn.Redirect)}else i.event.errorCode?i.end({success:!1},void 0):i.discard();return this.eventHandler.emitEvent(_c,i.event.correlationId,Cn.Redirect),e}).catch(e=>{this.browserStorage.resetRequestCache(i.event.correlationId);const t=e;throw this.eventHandler.emitEvent(Sc,i.event.correlationId,Cn.Redirect,null,t),this.eventHandler.emitEvent(_c,i.event.correlationId,Cn.Redirect),i.end({success:!1},t),e})}async acquireTokenRedirect(e){const t=this.getRequestCorrelationId(e);this.logger.verbose("0os66p",t),ql(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0,Zo);const r=this.performanceClient.startMeasurement("acquireTokenPreRedirect",t);r.add({scenarioId:e.scenarioId});const o=this.config.auth.onRedirectNavigate;this.config.auth.onRedirectNavigate=t=>{const n="function"==typeof o?o(t):void 0;return r.add({navigateCallbackResult:!1!==n}),r.event=r.end({success:!0},void 0,e.account)||r.event,n};try{let o;if(xs(this.config.auth.isMcp,e),this.eventHandler.emitEvent(bc,t,Cn.Redirect,e),this.platformAuthProvider&&this.canUsePlatformBroker(e)){const n=new Gh(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,hn,this.performanceClient,this.platformAuthProvider,this.getNativeAccountId(e),this.nativeInternalStorage,t);o=da(n.acquireTokenRedirect.bind(n),"nativeInteractionClientAcquireToken",this.logger,this.performanceClient,t)(e,r).catch(o=>{if(r.add({brokerErrorName:o.name,brokerErrorCode:o.errorCode}),o instanceof Bh&&Kh(o)){this.platformAuthProvider=void 0;return this.createRedirectClient(t).acquireToken(e)}if(o instanceof Hn){this.logger.verbose("1ipyz4",t);return this.createRedirectClient(t).acquireToken(e)}throw o})}else{o=this.createRedirectClient(t).acquireToken(e)}return await o}catch(o){throw this.browserStorage.resetRequestCache(t),2===r.event.status?this.performanceClient.startMeasurement(Ha,t).end({success:!1},o,e.account):r.end({success:!1},o,e.account),this.eventHandler.emitEvent(Sc,t,Cn.Redirect,null,o),o}}acquireTokenPopup(e){const t=this.getRequestCorrelationId(e),r=this.performanceClient.startMeasurement("acquireTokenPopup",t);r.add({scenarioId:e.scenarioId});try{this.logger.verbose("0ch87b",t),Od(this.initialized,r,this.config,e),this.browserStorage.setInteractionInProgress(!0,Zo,e.overrideInteractionInProgress,t)}catch(e){return Promise.reject(e)}const o=this.getAllAccounts();let n;this.eventHandler.emitEvent(bc,t,Cn.Popup,e);const i=this.getPreGeneratedPkceCodes(t);if(this.canUsePlatformBroker(e))r.add({isPlatformBrokerRequest:!0}),n=this.acquireTokenNative({...e,correlationId:t},dn).then(e=>(r.end({success:!0,isNativeBroker:!0},void 0,e.account),e)).catch(o=>{if(r.add({brokerErrorName:o.name,brokerErrorCode:o.errorCode}),o instanceof Bh&&Kh(o)){this.platformAuthProvider=void 0;return this.createPopupClient(t).acquireToken(e,i)}if(o instanceof Hn){this.logger.verbose("0yy5fw",t);return this.createPopupClient(t).acquireToken(e,i)}throw o});else{n=this.createPopupClient(t).acquireToken(e,i)}return n.then(n=>{const i=o.length<this.getAllAccounts().length;return this.eventHandler.emitEvent(kc,t,Cn.Popup,n),i&&this.eventHandler.emitEvent(Ic,t,Cn.Popup,n.account),r.end({success:!0,accessTokenSize:n.accessToken.length,idTokenSize:n.idToken.length},void 0,n.account),this.verifySsoCapability(e,Cn.Popup),n}).catch(o=>(this.eventHandler.emitEvent(Sc,t,Cn.Popup,null,o),r.end({success:!1},o,e.account),Promise.reject(o))).finally(async()=>{this.browserStorage.setInteractionInProgress(!1),this.config.system.navigatePopups||await this.preGeneratePkceCodes(t)})}trackStateChangeWithMeasurement(e){const t=this.ssoSilentMeasurement||this.acquireTokenByCodeAsyncMeasurement;t&&("visibilitychange"===e.type?(this.logger.info(`0yzimq ${t.event.name}`,t.event.correlationId),t.increment({visibilityChangeCount:1})):"online"===e.type?(this.logger.info(`1caf53 ${t.event.name}`,t.event.correlationId),t.increment({onlineStatusChangeCount:1})):"offline"===e.type&&(this.logger.info(`0fdyk7 ${t.event.name}`,t.event.correlationId),t.increment({onlineStatusChangeCount:1})))}addStateChangeListeners(e){document.addEventListener("visibilitychange",e),window.addEventListener("online",e),window.addEventListener("offline",e)}removeStateChangeListeners(e){document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e),window.removeEventListener("offline",e)}getCachedSsoCapable(){try{const e=window.localStorage.getItem(rc);if(e){const t=JSON.parse(e);if(t&&"boolean"==typeof t.ssoCapable&&t.expiresOn&&Date.now()<t.expiresOn)return t.ssoCapable}}catch{}}verifySsoCapability(e,t){if(!this.config.auth.verifySSO)return;const r=rc;if(void 0!==this.getCachedSsoCapable())return void this.logger.verbose(`13poou ${t}`,"");const o=fs(),n=this.performanceClient.startMeasurement("ssoCapable",o);n.add({"ext.interactionType":t}),this.logger.verbose(`0pbr0i ${t}`,o),setTimeout(()=>{const i={...e,correlationId:o};this.createSilentIframeClient(o).verifySso(i).then(e=>{this.logger.verbose(`1gd1iv ${t} ${e}`,o);try{const t=JSON.stringify({ssoCapable:e,expiresOn:Date.now()+864e5});window.localStorage.setItem(r,t)}catch{this.logger.warning(`18lmoj ${t}`,o)}n.end({fromCache:!1,success:e},void 0)}).catch(e=>{this.logger.warning(`05g83w ${t} ${e.message}`,o);try{window.localStorage.removeItem(r)}catch{this.logger.warning(`0nlf9q ${t}`,o)}n.end({fromCache:!1,success:!1},e)})},0)}async ssoSilent(e){const t=this.getRequestCorrelationId(e),r={...e,correlationId:t};this.ssoSilentMeasurement=this.performanceClient.startMeasurement("ssoSilent",t),this.ssoSilentMeasurement?.add({scenarioId:e.scenarioId,ssoCapable:this.getCachedSsoCapable()}),Od(this.initialized,this.ssoSilentMeasurement,this.config,r),this.ssoSilentMeasurement?.increment({visibilityChangeCount:0,onlineStatusChangeCount:0}),this.addStateChangeListeners(this.trackStateChangeWithMeasurement);const o=this.getAllAccounts();let n;if(this.logger.verbose("0w1b45",t),this.eventHandler.emitEvent(bc,t,Cn.Silent,r),this.canUsePlatformBroker(r))this.ssoSilentMeasurement?.add({isPlatformBrokerRequest:!0}),n=this.acquireTokenNative(r,un).catch(e=>{if(this.ssoSilentMeasurement?.add({brokerErrorName:e.name,brokerErrorCode:e.errorCode}),e instanceof Bh&&Kh(e)){this.platformAuthProvider=void 0;return this.createSilentIframeClient(r.correlationId).acquireToken(r)}throw e});else{n=this.createSilentIframeClient(r.correlationId).acquireToken(r)}return n.then(e=>{const r=o.length<this.getAllAccounts().length;return this.eventHandler.emitEvent(kc,t,Cn.Silent,e),r&&this.eventHandler.emitEvent(Ic,t,Cn.Silent,e.account),this.ssoSilentMeasurement?.end({success:!0,isNativeBroker:e.fromPlatformBroker,accessTokenSize:e.accessToken.length,idTokenSize:e.idToken.length},void 0,e.account),e}).catch(r=>{throw this.eventHandler.emitEvent(Sc,t,Cn.Silent,null,r),this.ssoSilentMeasurement?.end({success:!1},r,e.account),r}).finally(()=>{this.removeStateChangeListeners(this.trackStateChangeWithMeasurement)})}async acquireTokenByCode(e){const t=this.getRequestCorrelationId(e);this.logger.trace("0ch6ga",t);const r=this.performanceClient.startMeasurement("acquireTokenByCode",t);Od(this.initialized,r,this.config,e),this.eventHandler.emitEvent(bc,t,Cn.Silent,e),r.add({scenarioId:e.scenarioId});try{if(e.code&&e.nativeAccountId)throw Ui("spa_code_and_nativeAccountId_present",t);if(e.code){const o=e.code;let n=this.hybridAuthCodeResponses.get(o);return n?(this.logger.verbose("0qgp28",t),r.discard()):(this.logger.verbose("06eh73",t),n=this.acquireTokenByCodeAsync({...e,correlationId:t}).then(e=>(this.eventHandler.emitEvent(kc,t,Cn.Silent,e),this.hybridAuthCodeResponses.delete(o),r.end({success:!0,accessTokenSize:e.accessToken.length,idTokenSize:e.idToken.length},void 0,e.account),e)).catch(e=>{throw this.hybridAuthCodeResponses.delete(o),this.eventHandler.emitEvent(Sc,t,Cn.Silent,null,e),r.end({success:!1},e),e}),this.hybridAuthCodeResponses.set(o,n)),await n}if(e.nativeAccountId){if(this.canUsePlatformBroker(e,e.nativeAccountId)){r.add({isPlatformBrokerRequest:!0});const o=await this.acquireTokenNative({...e,correlationId:t},pn,e.nativeAccountId).catch(e=>{throw r.add({brokerErrorName:e.name,brokerErrorCode:e.errorCode}),e instanceof Bh&&Kh(e)&&(this.platformAuthProvider=void 0),e});return r.end({success:!0},void 0,o.account),o}throw Ui("unable_to_acquire_token_from_native_platform",t)}throw Ui("auth_code_or_nativeAccountId_required",t)}catch(e){throw this.eventHandler.emitEvent(Sc,t,Cn.Silent,null,e),r.end({success:!1},e),e}}async acquireTokenByCodeAsync(e){const t=this.getRequestCorrelationId(e);this.logger.trace("10d9hy",t),this.acquireTokenByCodeAsyncMeasurement=this.performanceClient.startMeasurement("acquireTokenByCodeAsync",t),this.acquireTokenByCodeAsyncMeasurement?.increment({visibilityChangeCount:0,onlineStatusChangeCount:0}),this.addStateChangeListeners(this.trackStateChangeWithMeasurement);const r=this.createSilentAuthCodeClient(t);return await r.acquireToken(e).then(e=>(this.acquireTokenByCodeAsyncMeasurement?.end({success:!0,fromCache:e.fromCache}),e)).catch(e=>{throw this.acquireTokenByCodeAsyncMeasurement?.end({success:!1},e),e}).finally(()=>{this.removeStateChangeListeners(this.trackStateChangeWithMeasurement)})}async acquireTokenFromCache(e,t){switch(t){case Sn:case Tn:case An:const t=this.createSilentCacheClient(e.correlationId);return da(t.acquireToken.bind(t),"silentCacheClientAcquireToken",this.logger,this.performanceClient,e.correlationId)(e);default:throw Wn(ii,e.correlationId)}}async acquireTokenByRefreshToken(e,t){switch(t){case Sn:case An:case _n:case En:const t=this.createSilentRefreshClient(e.correlationId);return da(t.acquireToken.bind(t),"silentRefreshClientAcquireToken",this.logger,this.performanceClient,e.correlationId)(e);default:throw Wn(ii,e.correlationId)}}async acquireTokenBySilentIframe(e){const t=this.createSilentIframeClient(e.correlationId);return da(t.acquireToken.bind(t),"silentIframeClientAcquireToken",this.logger,this.performanceClient,e.correlationId)(e)}async logoutRedirect(e){const t=this.getRequestCorrelationId(e);ql(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0,en);return this.createRedirectClient(t).logout(e)}logoutPopup(e){try{const t=this.getRequestCorrelationId(e);Ml(this.initialized),this.browserStorage.setInteractionInProgress(!0,en);return this.createPopupClient(t).logout(e).finally(()=>{this.browserStorage.setInteractionInProgress(!1)})}catch(e){return Promise.reject(e)}}async clearCache(e){if(!this.isBrowserEnvironment)return;const t=this.getRequestCorrelationId(e);return this.createSilentCacheClient(t).logout(e)}getAllAccounts(e){return function(e,t,r,o,n){return e.verbose("1yd030",o),r?t.getAllAccounts(n,o):[]}(this.logger,this.browserStorage,this.isBrowserEnvironment,this.getRequestCorrelationId(),e)}getAccount(e){return function(e,t,r,o){t.trace("0u7b90",o);const n=r.getAccountInfoFilteredBy(e,o);return n?(t.verbose("0btgll",o),n):(t.verbose("0ltaj5",o),null)}(e,this.logger,this.browserStorage,this.getRequestCorrelationId())}setActiveAccount(e){!function(e,t,r){t.setActiveAccount(e,r)}(e,this.browserStorage,this.getRequestCorrelationId())}getActiveAccount(){return e=this.browserStorage,t=this.getRequestCorrelationId(),e.getActiveAccount(t);var e,t}async hydrateCache(e,t){this.logger.verbose("16jycr",e.correlationId);const r=function(e,t,r){const o=Array.from(e.tenantProfiles?.values()||[]);if(0===o.length&&e.tenantId&&e.localAccountId)o.push(qa(e.homeAccountId,e.localAccountId,e.tenantId,e.nativeAccountId,e.idTokenClaims));else if(e.nativeAccountId){const t=o.find(t=>t.tenantId===e.tenantId);t&&!t.nativeAccountId&&(t.nativeAccountId=e.nativeAccountId)}return{authorityType:e.authorityType||no,homeAccountId:e.homeAccountId,localAccountId:e.localAccountId,nativeAccountId:e.nativeAccountId,realm:e.tenantId,environment:e.environment,username:e.username,loginHint:e.loginHint,name:e.name,cloudGraphHostName:t,msGraphHost:r,tenantProfiles:o,dataBoundary:e.dataBoundary}}(e.account,e.cloudGraphHostName,e.msGraphHost);if(await this.browserStorage.setAccount(r,e.correlationId,pa(e.idTokenClaims),wn),!e.fromPlatformBroker)return this.browserStorage.hydrateCache(e,t);{this.logger.verbose("1i5atf",e.correlationId);const r=Ca(e.account.homeAccountId,e.account.environment,e.idToken,this.config.auth.clientId,e.tenantId),o=Ia(e.account.homeAccountId,e.account.environment,e.accessToken,this.config.auth.clientId,e.tenantId,e.scopes.join(" "),e.expiresOn?fa(e.expiresOn):0,e.extExpiresOn?fa(e.extExpiresOn):0,ts,t.correlationId||"",void 0,e.tokenType,void 0,t.sshKid);t.resource&&(o.resource=t.resource);const n=pa(e.idTokenClaims);await this.browserStorage.setIdTokenCredential(r,e.correlationId,n),await this.nativeInternalStorage.setAccessTokenCredential(o,e.correlationId,n)}}async acquireTokenNative(e,t,r,o){const n=this.getRequestCorrelationId(e);if(this.logger.trace("0b9y3p",n),!this.platformAuthProvider)throw Ui(Yi,n);const i=new Gh(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,t,this.performanceClient,this.platformAuthProvider,r||this.getNativeAccountId(e),this.nativeInternalStorage,n);return da(i.acquireToken.bind(i),ui,this.logger,this.performanceClient,n)(e,o)}canUsePlatformBroker(e,t){const r=this.getRequestCorrelationId(e);if(this.logger.trace("1n9lbl",r),!this.platformAuthProvider)return this.logger.trace("0vnu11",r),!1;if(!wd(this.config,this.logger,r,this.platformAuthProvider,e.authenticationScheme))return this.logger.trace("0yoy1g",r),!1;if(e.prompt)switch(e.prompt){case Qr:case Gr:case Jr:this.logger.trace("0vdv8e",r);break;default:return this.logger.trace(`0pdzw6 ${e.prompt}`,r),!1}return!(!t&&!this.getNativeAccountId(e))||(this.logger.trace("16lbtk",r),!1)}getNativeAccountId(e){const t=e.account||this.getAccount({loginHint:e.loginHint,sid:e.sid})||(e.loginHint||e.sid?null:this.getActiveAccount());return t&&t.nativeAccountId||""}createPopupClient(e){return new vd(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,e,this.platformAuthProvider,this.operatingContext.getResponseHandlers()?.waitForPopupResponse)}createRedirectClient(e){return new Cd(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,e,this.platformAuthProvider)}createSilentIframeClient(e){return new Ad(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,un,this.performanceClient,this.nativeInternalStorage,e,this.platformAuthProvider,this.operatingContext.getResponseHandlers()?.waitForIframeResponse)}createSilentCacheClient(e){return new Vh(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,e,this.platformAuthProvider)}createSilentRefreshClient(e){return new Ed(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,e,this.platformAuthProvider)}createSilentAuthCodeClient(e){return new xd(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,pn,this.performanceClient,e,this.platformAuthProvider)}addEventCallback(e,t){return this.eventHandler.addEventCallback(e,t)}removeEventCallback(e){this.eventHandler.removeEventCallback(e)}addPerformanceCallback(e){return Ol(),this.performanceClient.addPerformanceCallback(e)}removePerformanceCallback(e){return this.performanceClient.removePerformanceCallback(e)}getLogger(){return this.logger}setLogger(e){this.logger=e}initializeWrapperLibrary(e,t){this.browserStorage.setWrapperMetadata(e,t)}setNavigationClient(e){this.navigationClient=e}getConfiguration(){return this.config}getPerformanceClient(){return this.performanceClient}isBrowserEnv(){return this.isBrowserEnvironment}getRequestCorrelationId(e){return e?.correlationId?e.correlationId:this.isBrowserEnvironment?fs():""}async loginRedirect(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("0lz9hf",t),this.acquireTokenRedirect({correlationId:t,...e||In})}loginPopup(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("0qw7v5",t),this.acquireTokenPopup({correlationId:t,...e||In})}async acquireTokenSilent(e){const t=this.getRequestCorrelationId(e),r=this.performanceClient.startMeasurement("acquireTokenSilent",t);r.add({cacheLookupPolicy:e.cacheLookupPolicy,scenarioId:e.scenarioId,ssoCapable:this.getCachedSsoCapable()}),Od(this.initialized,r,this.config,e),this.logger.verbose("0x1c4s",t);const o=e.account||this.getActiveAccount();if(!o)throw Ui("no_account_error",t);return this.acquireTokenSilentDeduped(e,o,t).then(o=>(r.end({success:!0,fromCache:o.fromCache,accessTokenSize:o.accessToken.length,idTokenSize:o.idToken.length},void 0,o.account),{...o,state:e.state,correlationId:t})).catch(e=>{throw e instanceof Rn&&(e.correlationId=t),r.end({success:!1},e,o),e})}async acquireTokenSilentDeduped(e,t,r){const o=Da(this.config.auth.clientId,{...e,authority:e.authority||this.config.auth.authority,correlationId:r},t.homeAccountId),n=JSON.stringify(o),i=this.activeSilentTokenRequests.get(n);if(void 0===i){this.logger.verbose("0fcjbk",r),this.performanceClient.addFields({deduped:!1},r);const o=da(this.acquireTokenSilentAsync.bind(this),"acquireTokenSilentAsync",this.logger,this.performanceClient,r)({...e,correlationId:r},t);return this.activeSilentTokenRequests.set(n,o),o.finally(()=>{this.activeSilentTokenRequests.delete(n)})}return this.logger.verbose("1yq7nb",r),this.performanceClient.addFields({deduped:!0},r),i}async acquireTokenSilentAsync(e,t){const r=t=>this.trackStateChange(e.correlationId,t);this.eventHandler.emitEvent(bc,e.correlationId,Cn.Silent,e),e.correlationId&&this.performanceClient.incrementFields({visibilityChangeCount:0,onlineStatusChangeCount:0},e.correlationId),this.addStateChangeListeners(r);const o=await da(qh,"initializeSilentRequest",this.logger,this.performanceClient,e.correlationId)(e,t,this.config,this.performanceClient,this.logger),n=e.cacheLookupPolicy||Sn;return this.acquireTokenSilentNoIframe(o,n).catch(async t=>{const r=function(e,t){const r=!(e instanceof Hn&&e.subError!==Ln),o=e.errorCode===Oo||e.errorCode===ii,n=r&&o||e.errorCode===qn||e.errorCode===$n,i=xn.includes(t);return n&&i}(t,n);if(r){const r=`${t.errorCode}${t.subError?`|${t.subError}`:""}`;if(this.performanceClient.addFields({silentRefreshReason:r},e.correlationId),this.activeIframeRequest){if(n!==Pn){const[e,r]=this.activeIframeRequest;this.logger.verbose(`1w8fso ${r}`,o.correlationId);const i=this.performanceClient.startMeasurement("awaitConcurrentIframe",o.correlationId);i.add({awaitIframeCorrelationId:r});const s=await e;if(i.end({success:s}),s)return this.logger.verbose(`0ywzzi ${r}`,o.correlationId),this.acquireTokenSilentNoIframe(o,n);throw this.logger.info(`17y14q ${r}`,o.correlationId),t}return this.logger.warning("1bd4p8",o.correlationId),da(this.acquireTokenBySilentIframe.bind(this),gi,this.logger,this.performanceClient,o.correlationId)(o)}{let e;return this.activeIframeRequest=[new Promise(t=>{e=t}),o.correlationId],this.logger.verbose("0rh08z",o.correlationId),da(this.acquireTokenBySilentIframe.bind(this),gi,this.logger,this.performanceClient,o.correlationId)(o).then(t=>(e(!0),t)).catch(t=>{throw e(!1),t}).finally(()=>{this.activeIframeRequest=void 0})}}throw t}).then(t=>(this.eventHandler.emitEvent(kc,e.correlationId,Cn.Silent,t),e.correlationId&&this.performanceClient.addFields({fromCache:t.fromCache,isNativeBroker:t.fromPlatformBroker},e.correlationId),t)).catch(t=>{throw this.eventHandler.emitEvent(Sc,e.correlationId,Cn.Silent,null,t),t}).finally(()=>{this.removeStateChangeListeners(r)})}async acquireTokenSilentNoIframe(e,t){return wd(this.config,this.logger,e.correlationId,this.platformAuthProvider,e.authenticationScheme)&&e.account.nativeAccountId?(this.logger.verbose("0sczo4",e.correlationId),this.performanceClient.addFields({isPlatformBrokerRequest:!0},e.correlationId),this.acquireTokenNative(e,mn,e.account.nativeAccountId,t).catch(async t=>{if(this.performanceClient.addFields({brokerErrorName:t.name,brokerErrorCode:t.errorCode},e.correlationId),t instanceof Bh&&Kh(t))throw this.logger.verbose("07rkmb",e.correlationId),this.platformAuthProvider=void 0,Wn(ii,e.correlationId);throw t})):(this.logger.verbose("0ox81t",e.correlationId),t===Tn&&this.logger.verbose("0fvwxe",e.correlationId),da(this.acquireTokenFromCache.bind(this),"acquireTokenFromCache",this.logger,this.performanceClient,e.correlationId)(e,t).catch(r=>{if(t===Tn)throw r;return this.eventHandler.emitEvent(Tc,e.correlationId,Cn.Silent,e),da(this.acquireTokenByRefreshToken.bind(this),"acquireTokenByRefreshToken",this.logger,this.performanceClient,e.correlationId)(e,t)}))}async preGeneratePkceCodes(e){return this.logger.verbose("1x6uj6",e),this.pkceCode=await da(sd,Ai,this.logger,this.performanceClient,e)(this.performanceClient,this.logger,e),Promise.resolve()}getPreGeneratedPkceCodes(e){const t=this.pkceCode?{...this.pkceCode}:void 0;return this.pkceCode=void 0,t?this.logger.verbose("12js1o",e):this.logger.verbose("1oe9ci",e),this.performanceClient.addFields({usePreGeneratedPkce:!!t},e),t}logMultipleInstances(e,t){const r=this.config.auth.clientId;if(!window)return;window.msal=window.msal||{},window.msal.clientIds=window.msal.clientIds||[];window.msal.clientIds.length>0&&this.logger.verbose("1qtz3l",t),window.msal.clientIds.push(r),function(e,t,r,o){const n=window.msal?.clientIds||[],i=n.length,s=n.filter(t=>t===e).length;s>1&&r.warning("1e88vg",o),t.add({msalInstanceCount:i,sameClientIdInstanceCount:s})}(r,e,this.logger,t)}}class Md{static loggerCallback(e,t){switch(e){case Wl.Error:return void console.error(t);case Wl.Info:return void console.info(t);case Wl.Verbose:return void console.debug(t);case Wl.Warning:return void console.warn(t);default:return void console.log(t)}}constructor(e,t){let r;this.browserEnvironment="undefined"!=typeof window,this.config=function({auth:e,cache:t,system:r,experimental:o,telemetry:n},i){const s={clientId:"",authority:`${mr}`,knownAuthorities:[],cloudDiscoveryMetadata:"",authorityMetadata:"",redirectUri:"undefined"!=typeof window&&window.location?window.location.href.split("?")[0].split("#")[0]:"",postLogoutRedirectUri:"",clientCapabilities:[],OIDCOptions:{responseMode:to,defaultScopes:[Cr,Ir,br]},azureCloudOptions:{azureCloudInstance:ta,tenant:""},instanceAware:!1,isMcp:!1,verifySSO:!1},a={cacheLocation:Go,cacheRetentionDays:5},c={loggerCallback:()=>{},logLevel:Wl.Info,piiLoggingEnabled:!1},l={...{...Zl,loggerOptions:c,networkClient:i?new dd:ld,navigationClient:new hd,popupBridgeTimeout:r?.popupBridgeTimeout||6e4,iframeBridgeTimeout:r?.iframeBridgeTimeout||1e4,redirectNavigationTimeout:3e4,allowRedirectInIframe:!1,navigatePopups:!0,allowPlatformBroker:!1,nativeBrokerHandshakeTimeout:r?.nativeBrokerHandshakeTimeout||2e3,protocolMode:Xs,serverTelemetryEnabled:!1},...r,loggerOptions:r?.loggerOptions||c},h={application:{appName:"",appVersion:""},client:new Xl};r?.protocolMode!==Zs&&e?.OIDCOptions&&new Gl(l.loggerOptions,Ll,Nl).warning(JSON.stringify(Ns("cannot_set_OIDCOptions","")),"");if(r?.protocolMode&&r.protocolMode===Zs&&l?.allowPlatformBroker)throw Ns("cannot_allow_platform_broker","");return{auth:{...s,...e,OIDCOptions:{...s.OIDCOptions,...e?.OIDCOptions}},cache:{...a,...t},system:l,experimental:{iframeTimeoutTelemetry:!1,allowPlatformBrokerWithDOM:!1,...o},telemetry:{...h,...n}}}(e,this.browserEnvironment),this.responseHandlers=t;try{r=window[Go]}catch(e){}const o=r?.getItem(Ya),n=r?.getItem(Xa)?.toLowerCase(),i="true"===n||"false"!==n&&void 0,s={...this.config.system.loggerOptions},a=o&&Object.keys(Wl).includes(o)?Wl[o]:void 0;a&&(s.loggerCallback=Md.loggerCallback,s.logLevel=a),void 0!==i&&(s.piiLoggingEnabled=i),this.logger=new Gl(s,Ll,Nl),this.available=!1}getConfig(){return this.config}getResponseHandlers(){return this.responseHandlers}getLogger(){return this.logger}isAvailable(){return this.available}isBrowserEnvironment(){return this.browserEnvironment}}class qd extends Md{getModuleName(){return qd.MODULE_NAME}getId(){return qd.ID}async initialize(e){return this.available="undefined"!=typeof window,this.available}}qd.MODULE_NAME="",qd.ID="StandardOperatingContext";class $d{constructor(e,t){this.controller=t||new Rd(new qd(e,{waitForPopupResponse:this.waitForPopupResponse.bind(this),waitForIframeResponse:this.waitForIframeResponse.bind(this)}))}async waitForPopupResponse(e,t,r){const o=this.controller;return Pl(o.getConfiguration().system.popupBridgeTimeout,o.getLogger(),e,o.getPerformanceClient())}async waitForIframeResponse(e,t){const r=this.controller,o=r.getConfiguration();return Pl(o.system.iframeBridgeTimeout,r.getLogger(),t,r.getPerformanceClient(),o.experimental)}async initialize(e){return this.controller.initialize(e)}async acquireTokenPopup(e){return this.controller.acquireTokenPopup(e)}acquireTokenRedirect(e){return this.controller.acquireTokenRedirect(e)}acquireTokenSilent(e){return this.controller.acquireTokenSilent(e)}acquireTokenByCode(e){return this.controller.acquireTokenByCode(e)}addEventCallback(e,t){return this.controller.addEventCallback(e,t)}removeEventCallback(e){return this.controller.removeEventCallback(e)}addPerformanceCallback(e){return this.controller.addPerformanceCallback(e)}removePerformanceCallback(e){return this.controller.removePerformanceCallback(e)}getAccount(e){return this.controller.getAccount(e)}getAllAccounts(e){return this.controller.getAllAccounts(e)}handleRedirectPromise(e){return this.controller.handleRedirectPromise(e)}loginPopup(e){return this.controller.loginPopup(e)}loginRedirect(e){return this.controller.loginRedirect(e)}logoutRedirect(e){return this.controller.logoutRedirect(e)}logoutPopup(e){return this.controller.logoutPopup(e)}ssoSilent(e){return this.controller.ssoSilent(e)}getLogger(){return this.controller.getLogger()}setLogger(e){this.controller.setLogger(e)}setActiveAccount(e){this.controller.setActiveAccount(e)}getActiveAccount(){return this.controller.getActiveAccount()}initializeWrapperLibrary(e,t){return this.controller.initializeWrapperLibrary(e,t)}setNavigationClient(e){this.controller.setNavigationClient(e)}getConfiguration(){return this.controller.getConfiguration()}async hydrateCache(e,t){return this.controller.hydrateCache(e,t)}clearCache(e){return this.controller.clearCache(e)}}function Ud(e){return"[Auth] "+e.map(e=>e instanceof Error?e.message:String(e)).join(" ")}class Ld{static info(...e){const r=Ud(e);a.log(t.Info,r),console.info(r)}static warn(...e){const r=Ud(e);a.log(t.Warning,r),console.warn(r)}static error(...e){const r=Ud(e);a.log(t.Error,r),console.error(r)}static debug(...e){const r=Ud(e);a.log(t.Debug,r),console.debug(r)}static trace(...e){const r=Ud(e);a.log(t.Trace,r),console.debug(r)}}var Nd,Dd,Hd,Fd=function(e,t,r,o){if("a"===r&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?o:"a"===r?o.call(e):o?o.value:t.get(e)},zd=function(e,t,r,o,n){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?n.call(e,r):n?n.value=r:t.set(e,r),r};class jd{constructor(e){Nd.add(this),this._cloudName=e,Dd.set(this,void 0),this._key=`publicClients-${this._cloudName}`,Ld.trace(`Initializing PublicClientApplicationsStorage with key: ${this._key}`),this.get(),Ld.trace(`Initial value loaded: ${JSON.stringify(Fd(this,Dd,"f"))}`)}get(){if(Fd(this,Dd,"f"))return Fd(this,Dd,"f");const e=localStorage.getItem(this._key);if(!e)return;let t;try{if(t=JSON.parse(e),!Fd(this,Nd,"m",Hd).call(this,t))return}catch{return}return zd(this,Dd,t,"f"),t}store(e){localStorage.setItem(this._key,JSON.stringify(e)),zd(this,Dd,e,"f")}delete(){localStorage.removeItem(this._key),zd(this,Dd,void 0,"f")}}Dd=new WeakMap,Nd=new WeakSet,Hd=function(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)};class Bd{constructor(e){if(this._set=new Set,e)for(const t of e)this.add(t)}add(e){return this._set.add(e.toLowerCase()),this}clear(){this._set.clear()}delete(e){return this._set.delete(e.toLowerCase())}forEach(e,t){this._set.forEach(r=>{e.call(t,r,r,this)})}has(e){return this._set.has(e.toLowerCase())}get size(){return this._set.size}entries(){return this._set.entries()}keys(){return this._set.keys()}values(){return this._set.values()}[Symbol.iterator](){return this._set[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}class Kd{constructor(e){if(this._map=new Map,e)for(const[t,r]of e)this.set(t,r)}set(e,t){return this._map.set(e.toLowerCase(),t),this}get(e){return this._map.get(e.toLowerCase())}has(e){return this._map.has(e.toLowerCase())}delete(e){return this._map.delete(e.toLowerCase())}clear(){this._map.clear()}forEach(e,t){this._map.forEach((r,o)=>{e.call(t,r,o,this)})}get size(){return this._map.size}entries(){return this._map.entries()}keys(){return this._map.keys()}values(){return this._map.values()}[Symbol.iterator](){return this._map[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}}class Wd{constructor(e,t){this._token=-1,"function"==typeof e&&"number"==typeof t&&this.setIfNotSet(e,t)}dispose(){this.cancel()}cancel(){-1!==this._token&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){-1===this._token&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}}function Jd(e,t){return e?.toLowerCase()===t?.toLowerCase()}class Vd{constructor(t){this._pcas=new Kd,this._expireWarning=new Kd,this._disposables=[],this._onDidChangeSessionsEmitter=new e,this.onDidAccountsChange=this._onDidChangeSessionsEmitter.event,this._onWillExpireSoonEmitter=new e,this.onWillExpireSoon=this._onWillExpireSoonEmitter.event,this._storage=new jd(t)}async initialize(){const e=this._storage.get();if(!e)return void Ld.info("No existing PublicClientApplications to initialize.");const t=[],r=new Bd;for(const o of e){(await this.createMsalObj(o)).getAllAccounts().forEach(e=>{r.has(e.homeAccountId)||(r.add(e.homeAccountId),t.push(e))})}this._onDidChangeSessionsEmitter.fire({added:t,changed:[],deleted:[]})}getOrCreate(e){return this._pcas.has(e)?Promise.resolve(this._pcas.get(e)):this.createMsalObj(e)}getAll(){return Array.from(this._pcas.values())}async createMsalObj(e){const t=new $d({auth:{clientId:e,redirectUri:Vd.REDIRECT_ROUTE},cache:{cacheLocation:"localStorage"},system:{loggerOptions:{loggerCallback:(e,t,r)=>{if(!r)switch(e){case Wl.Error:return void Ld.error(t);case Wl.Info:return void Ld.info(t);case Wl.Verbose:return void Ld.trace(t);case Wl.Warning:return void Ld.warn(t)}},piiLoggingEnabled:!1}}});await t.initialize(),this._pcas.set(e,t),this._storage.store(Array.from(this._pcas.keys()));const r=t.addEventCallback(e=>{switch(e.eventType){case Ic:const t=e.payload;this._onDidChangeSessionsEmitter.fire({added:[t],changed:[],deleted:[]});break;case xc:const r=e.payload;r?.account&&this._onDidChangeSessionsEmitter.fire({added:[],changed:[],deleted:[r.account]});break;case kc:const o=e.payload;let n=this._expireWarning.get(o.account.homeAccountId);if(n||(n=new Wd,this._expireWarning.set(o.account.homeAccountId,n)),!o.fromCache&&o.refreshOn){Ld.info(`Token acquired for account ${o.account.username} via interaction.`);this.getAll().flatMap(e=>e.getAllAccounts()).find(e=>Jd(e.homeAccountId,o.account.homeAccountId)&&e!==o.account)||this._onDidChangeSessionsEmitter.fire({added:[o.account],changed:[],deleted:[]}),n.cancelAndSet(()=>this._onWillExpireSoonEmitter.fire(o),72e6)}break;default:return}});return this._disposables.push({dispose:()=>t.removeEventCallback(r)}),t}dispose(){this._onDidChangeSessionsEmitter.dispose(),this._disposables.forEach(e=>e.dispose())}}Vd.REDIRECT_ROUTE="/msal";async function Gd(e,t,r,o,n,i){const{clientId:s}=e.getConfiguration().auth,a=new URL(Vd.REDIRECT_ROUTE,window.location.origin);t.length&&a.searchParams.append("scopes",t.join(" ")),a.searchParams.append("clientId",s),a.searchParams.append("authority",o),n&&a.searchParams.append("loginHint",n),i&&a.searchParams.append("claims",i);if(!function(e){const t=Math.floor(window.screenLeft+window.innerWidth/2-390),r=Math.floor(window.screenTop+window.innerHeight/2-320);return window.open(e,"_blank",`width=780,height=640,top=${r},left=${t}`)??void 0}(a.toString()))throw new Error("Could not open popup");const c=function(e,t,r){return new BroadcastChannel(`microsoftAuthPopup#${JSON.stringify({clientId:e,authority:t,scopes:r})}`)}(s,o,t);return await new Promise((n,s)=>{c.onmessage=async a=>{if(a.data)if("message"in a.data)s(a.data);else{const c=5;let l=0;const h=[];for(;l<c;)try{const s=await e.acquireTokenSilent({scopes:t,account:a.data.account,authority:o,claims:i,cacheLookupPolicy:An,forceRefresh:!1,state:r});n(s);break}catch(e){h.push(e instanceof Error?e:new Error(String(e))),l++,l<c&&await new Promise(e=>setTimeout(e,50*Math.pow(2,l-1)))}h.length>0&&s(new AggregateError(h,`Failed to acquire token after ${c} attempts`))}else s("data is undefined");c.onmessage=null,c.postMessage({close:!0}),c.close()}})}function Qd(e){const t=[];for(const r of e)"bearer"===r.scheme.toLowerCase()&&r.params.scope&&t.push(...r.params.scope.split(" "));return t}function Yd(e){for(const t of e)if("bearer"===t.scheme.toLowerCase()&&t.params.claims)try{return JSON.parse(t.params.claims),t.params.claims}catch(e){try{const e=j(t.params.claims);return JSON.parse(e),e}catch(e){Ld.error(`[extractClaimsFromChallenges] failed to decode and parse claims: ${JSON.stringify(e)}`);continue}}}class Xd{constructor(){this.id="microsoft",this.label="Microsoft",this.supportsMultipleAccounts=!0,this._disposables=new Array,this._onDidChangeSessionsEmitter=new e,this.onDidChangeSessions=this._onDidChangeSessionsEmitter.event,this._eventBufferer=new tu;const t=new Vd("Public");this._disposables.push(t),this._disposables.push(this._onDidChangeSessionsEmitter),this._pcaManager=t,this._registerAccountsChangeHandler()}async initialize(){await this._pcaManager.initialize()}getMsalObj(e){return this._pcaManager.getOrCreate(e)}async getSessions(e,t){const r=void 0===e,o=new Bn(e??[]);if(Ld.info(`[getSessions] [${e?o.scopeStr:"all"}] starting`),r){const e=new Map;for(const t of this._pcaManager.getAll())for(const r of t.getAllAccounts())e.has(r.homeAccountId)||e.set(r.homeAccountId,Zd(r));const t=Array.from(e.values());return Ld.info(`[getSessions] [all] returned ${t.length} session(s)`),t}const n=await this._pcaManager.getOrCreate(o.clientId),i=await this.getAllSessionsForPca(n,o,t?.account);return Ld.info(`[getSessions] [${o.scopeStr}] returned ${i.length} session(s)`),i}async createSession(e,t){const r=new Bn(e);Ld.info(`[createSession] [${r.scopeStr}] starting`);const o=await this._pcaManager.getOrCreate(r.clientId),n=JSON.stringify({originalScopes:r.originalScopes}),i=new URL(r.tenant,Xd.DEFAULT_AAD_ENDPOINT).toString(),s=await Gd(o,r.scopesToSend,n,i,t.account?.label);o.setActiveAccount(s.account);const a=eu(s,r.originalScopes,t.account?.label);return Ld.info(`[createSession] [${r.scopeStr}] returned a session`),a}async getSessionsFromChallenges(e,t){Ld.info(`[getSessionsFromChallenges] starting with ${e.challenges.length} challenges`);const r=Qd(e.challenges)??e.scopes;if(!r||0===r.length)throw new Error("No scopes found in authentication challenges or fallback scopes");const o=Yd(e.challenges);if(!o)throw new Error("No claims found in authentication challenges");const n=new Bn(r,o);Ld.info(`[getSessions] [${r?n.scopeStr:"all"}] starting`);const i=await this._pcaManager.getOrCreate(n.clientId),s=await this.getAllSessionsForPca(i,n,t?.account);return Ld.info(`[getSessions] [${n.scopeStr}] returned ${s.length} session(s)`),s}async createSessionFromChallenges(e,t){const r=e.scopes?.length?[...e.scopes]:Qd(e.challenges),o=Yd(e.challenges),n=new Bn(r,o);Ld.info(`[createSession] [${n.scopeStr}] starting`);const i=await this._pcaManager.getOrCreate(n.clientId),s=JSON.stringify({originalScopes:n.originalScopes}),a=new URL(n.tenant,Xd.DEFAULT_AAD_ENDPOINT).toString(),c=await Gd(i,n.scopesToSend,s,a,t.account?.label,o);i.setActiveAccount(c.account);const l=eu(c,n.originalScopes,t.account?.label);return Ld.info(`[createSession] [${n.scopeStr}] returned a session`),l}async removeSession(e){Ld.info(`[removeSession] [${e}] starting`);const t=new Array;for(const r of this._pcaManager.getAll()){const o=r.getAllAccounts();for(const n of o)Jd(n.homeAccountId,e)&&(t.push((async()=>(await r.clearCache({account:n}),n))()),Ld.info(`[removeSession] [${e}] [${r.getConfiguration().auth.clientId}] removing session...`))}if(!t.length)return void Ld.info(`[removeSession] [${e}] session not found`);const r=await Promise.allSettled(t),o=new Array;for(const t of r)"rejected"===t.status?Ld.error(`[removeSession] [${e}] error removing session: ${t.reason}`):o.push(t.value);0!==o.length?(this._onDidChangeSessionsEmitter.fire({added:[],changed:[],removed:o.map(Zd)}),Ld.info(`[removeSession] [${e}] removed ${o.length} sessions`)):Ld.info(`[removeSession] [${e}] no sessions were removed`)}dispose(){this._disposables.forEach(e=>e.dispose())}_registerAccountsChangeHandler(){this._disposables.push(this._eventBufferer.wrapEvent(this._pcaManager.onDidAccountsChange,(e,t)=>{if(!e)return t;const r={added:[...e.added??[],...t.added??[]],deleted:[...e.deleted??[],...t.deleted??[]],changed:[...e.changed??[],...t.changed??[]]};return{added:Array.from(new Map(r.added.map(e=>[e.username,e])).values()),deleted:Array.from(new Map(r.deleted.map(e=>[e.username,e])).values()),changed:Array.from(new Map(r.changed.map(e=>[e.username,e])).values())}},{added:new Array,deleted:new Array,changed:new Array})(e=>this._handleAccountChange(e)))}_handleAccountChange({added:e,changed:t,deleted:r}){Ld.debug(`[_handleAccountChange] added: ${e.length}, changed: ${t.length}, deleted: ${r.length}`),this._onDidChangeSessionsEmitter.fire({added:e.map(Zd),changed:t.map(Zd),removed:r.map(Zd)})}async getAllSessionsForPca(e,t,r){let o=r?e.getAllAccounts().filter(e=>Jd(e.homeAccountId,r.id)):e.getAllAccounts();const n=new Map;for(const e of o){const t=n.get(e.homeAccountId)||[];t.push(e),n.set(e.homeAccountId,t)}o=Array.from(n.values()).map(e=>{if(1===e.length)return e[0];if(t.tenantId){const r=e.find(e=>Jd(e.tenantId,t.tenantId));if(r)return r}return e.find(e=>Jd(e.tenantId,e.idTokenClaims?.tid))||e[0]});const i=new URL(t.tenant,Xd.DEFAULT_AAD_ENDPOINT).toString(),s=[];return this._eventBufferer.bufferEventsAsync(async()=>{for(const r of o)try{let o,n;t.tenantId?Jd(r.tenantId,t.tenantId)||(o=!0):Jd(r.tenantId,r.idTokenClaims?.tid)||(o=!0),t.claims&&(o=!0,n=t.claims);try{const a=await e.acquireTokenSilent({account:r,refreshTokenExpirationOffsetSeconds:3600,authority:i,scopes:t.scopesToSend,claims:n,forceRefresh:o,cacheLookupPolicy:An});s.push(eu(a,t.originalScopes))}catch(a){const c=await e.acquireTokenSilent({account:r,authority:i,scopes:t.scopesToSend,claims:n,forceRefresh:o,cacheLookupPolicy:An});this.informUserOfExpiredSession(c),s.push(eu(c,t.originalScopes))}}catch(e){Ld.info(`[getAllSessionsForPca] [${t.scopeStr}] [${r.username}] failed to acquire token silently, skipping account ${JSON.stringify(e)}`);continue}return s})}async informUserOfExpiredSession(e){const t=he.auth.Refresh.toString(),r=he.auth.MoreInfo.toString(),o=await c.showInformationMessage(he.auth.SessionExpiringSoon.toString(e.account.username),t,r);if(o===t){const t=e.state?JSON.parse(e.state).originalScopes??e.scopes:e.scopes,r=e.idTokenClaims?.login_hint??e.account.idTokenClaims?.login_hint;await this.createSession(t,{account:eu(e,t,r).account})}else o===r&&(window.open("https://learn.microsoft.com/en-us/entra/identity-platform/refresh-tokens#token-lifetime","_blank"),await this.informUserOfExpiredSession(e))}}function Zd(e){return{accessToken:"1234",id:e.homeAccountId,scopes:[],account:{id:e.homeAccountId,label:e.username.toLowerCase()},idToken:e.idToken}}function eu(e,t,r){return{id:e.idToken,scopes:t??e.scopes,account:{label:r??e.account.username,id:e.account.homeAccountId},accessToken:e.accessToken,idToken:e.idToken}}Xd.DEFAULT_AAD_ENDPOINT="https://login.microsoftonline.com/";class tu{constructor(){this.data=[]}wrapEvent(e,t,r){return(o,n,i)=>e(e=>{const i=this.data[this.data.length-1];if(!t)return void(i?i.buffers.push(()=>o.call(n,e)):o.call(n,e));const s=i;s?(s.items??=[],s.items.push(e),0===s.buffers.length&&i.buffers.push(()=>{s.reducedResult??=r?s.items.reduce(t,r):s.items.reduce(t),o.call(n,s.reducedResult)})):o.call(n,t(r,e))},void 0,i)}bufferEvents(e){const t={buffers:new Array};this.data.push(t);const r=e();return this.data.pop(),t.buffers.forEach(e=>e()),r}async bufferEventsAsync(e){const t={buffers:new Array};this.data.push(t);try{return await e()}finally{this.data.pop(),t.buffers.forEach(e=>e())}}}class ru{constructor(e){this.url=e,this.authenticationProvider=new Xd,this._initialized=this.initialize()}async initialize(){await this.authenticationProvider.initialize();const e=window.sessionStorage.getItem("microsoftAuthRedirectData");if(!e)return;const{clientId:t}=JSON.parse(e),r=await this.authenticationProvider.getMsalObj(t);await r.handleRedirectPromise({navigateToLoginRequestUrl:!1}),window.sessionStorage.removeItem("microsoftAuthRedirectData")}async getSessions(e,t){if(t?.forceNewSession&&t?.silent)throw new Error("Invalid options: forceNewSession and silent cannot be used together.");await this._initialized,t?.clientId&&e.push(`VSCODE_CLIENT_ID:${t.clientId}`),t?.tenant&&e.push(`VSCODE_TENANT:${t.tenant}`);const r=new Bn(e);let o;const n=await this.authenticationProvider.getMsalObj(r.clientId),i=new URL(r.tenant,Xd.DEFAULT_AAD_ENDPOINT).toString();if(!t?.forceNewSession){for(const e of n.getAllAccounts()){if(r.tenantId&&!Jd(e.tenantId,r.tenantId))continue;const o={refreshTokenExpirationOffsetSeconds:79200,forceRefresh:!0,scopes:r.scopesToSend,cacheLookupPolicy:An,account:e,authority:i,state:JSON.stringify({originalScopes:r.originalScopes})};try{await n.acquireTokenSilent(o)}catch(e){if(t?.silent){console.error(e);continue}e instanceof Hn?(window.sessionStorage.setItem("microsoftAuthRedirectData",JSON.stringify({clientId:r.clientId,tenant:r.tenant,redirectUri:window.location.href})),await n.acquireTokenRedirect({...o,claims:e.claims})):console.error(e)}}o=await this.authenticationProvider.getSessions(r.originalScopes,{})}if(!o?.length){if(t?.silent)return[];throw window.sessionStorage.setItem("microsoftAuthRedirectData",JSON.stringify({clientId:r.clientId,tenant:r.tenant,redirectUri:window.location.href})),await n.loginRedirect({scopes:r.scopesToSend,authority:i,state:JSON.stringify({originalScopes:r.originalScopes})}),new Error("Redirecting to authenticate")}return o.map(e=>({...e,getAccessToken:()=>Promise.resolve(e.accessToken)}))}dispose(){this.authenticationProvider.dispose()}async setInitialSessions(e){}tryCompleteAuthExchange(){return Promise.resolve(this.url)}}const ou="stable";new Set(["stable","insider","exploration","dev"]);class nu{constructor(e){this.workspace=e,this.trusted=!0}get payload(){if(void 0===this._payload){let e=null;new URL(window.location.href).searchParams.forEach((t,r)=>{if(r===nu.QUERY_PARAM_PAYLOAD)try{e=JSON.parse(t)}catch(e){console.error(e)}}),this._payload=e}return this._payload??void 0}async open(e,t){let r=se(e);if(!r&&(void 0===e||ie(e).toString()===su.workspaceUri.toString())){const e=new URL(window.location.href);e.pathname="/",r=e.toString()}if(r){if(t?.payload){const e=new URL(r);e.searchParams.set(nu.QUERY_PARAM_PAYLOAD,JSON.stringify(t.payload)),r=e.toString()}if(t?.reuse)return window.location.href=r,!0;let e;return e=window.matchMedia&&window.matchMedia("(display-mode: standalone)").matches?window.open(r,"_blank","toolbar=no"):window.open(r),!!e}throw new Error("Not implemented")}}nu.QUERY_PARAM_PAYLOAD="payload";const iu=["https://github.com/login/oauth/authorize","https://app.vssps.visualstudio.com/oauth2/authorize","https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize","https://login.microsoftonline.com/common/oauth2/v2.0/authorize","https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize","https://vscodeedu.com/signin","https://vscodeedu.com/beta/signin","https://ppe.vscodeedu.com/signin"],su={workspaceUri:o.from({scheme:"tmp",path:"/default.code-workspace"})},au=[{href:"https://aka.ms/vscode-web-docs",label:he.ReadDoc.toString()},{href:"https://go.microsoft.com/fwlink/?LinkId=521839",label:he.Privacy.toString()},{href:"https://www.microsoft.com/en-us/legal/terms-of-use",label:he.TermsofUse.toString()},{href:"https://code.visualstudio.com/download",label:he.DownloadVSCode.toString()}];function cu(e,t){return r=>{/vscode\.dev$/.test(e.hostname)&&!e.searchParams.get("vscode-quality")?e.hostname="insider"===r?"insiders.vscode.dev":"vscode.dev":r===t?e.searchParams.delete("vscode-quality"):e.searchParams.set("vscode-quality",r),window.location.href=e.toString()}}function lu(e){switch(e.searchParams.get("vscode-log")?.toLowerCase()){case"trace":return t.Trace;case"debug":return t.Debug;case"warning":return t.Warning;case"error":return t.Error;case"critical":return t.Critical;case"off":return t.Off;default:return t.Info}}async function hu(e,t,a){let c=new URL(window.location.href);c=function(e){for(const t of Q)e=t.redirect(e)??e;return e}(c),window.history.replaceState(void 0,"",c.toString());const l=new W(c.host),h=new u(l,e);let d;const g=window.sessionStorage.getItem(`vscode-continueOn-${c.pathname}`);if(g)try{d=JSON.parse(g)}catch(e){console.error("Failed to parse continueOn body",e)}const p=new pr(h,c),m=new ru(c),f=await async function(e){for(const t of ee)if(X(e.url.pathname,t)){const r="string"==typeof t.path?t.path:t.path.prefix;performance.mark(`web/willRoute/${r}`);const o=await t.route(e);return performance.mark(`web/didRoute/${r}`),o&&t.additionalBuiltinExtensions.length&&(o.workbenchOptions={...o.workbenchOptions,additionalBuiltinExtensions:o.workbenchOptions?.additionalBuiltinExtensions?.concat(t.additionalBuiltinExtensions)??t.additionalBuiltinExtensions}),o}}({url:c,githubAuthentication:p,microsoftAuthentication:m,secretStorageProvider:h,quality:e,commit:t,continueOnBody:d});f||(c=new URL(window.location.href),c.pathname="/",window.history.replaceState(void 0,"",c.toString()));const y=function(e,t){const r=[],n=JSON.parse(document.querySelector('meta[name="vscode:additionalBuiltinExtensions"]').content),i=e.searchParams.get("vscode-remotehub-dev");i&&(delete n["github.remotehub"],r.push(o.parse(i)));const s=e.searchParams.get("vscode-azurerepos-dev");s&&(delete n["ms-vscode.azure-repos"],r.push(o.parse(s)));const a=t?.excludeAdditionalBuiltinExtensions?new Set(t?.excludeAdditionalBuiltinExtensions.map(e=>e.toLowerCase())):new Set;for(const[e,t]of Object.entries(n))a.has(e)||r.push("string"==typeof t?o.parse(t):{id:e,preRelease:t});const c=t?.workbenchOptions?.additionalBuiltinExtensions??[];for(const e of c){const t=du(e)?e:"string"==typeof e?{id:e}:void 0;t&&n[t.id.toLowerCase()]||r.push(e)}return r}(c,f),w=f?.workbenchOptions?.enabledExtensions??[];let v=w;f?.excludeAdditionalBuiltinExtensions||(v=[...w,"GitHub.remotehub","ms-vscode.azure-repos"]);const C=f?.workspace??su,I=new nu(C===Z?void 0:C),b=[{id:"vscode.dev:help",label:"Help: Visual Studio Code for the Web",handler:()=>n.executeCommand("vscode.open",o.parse("https://aka.ms/vscode-web-docs"))}];f?.hasOwnProperty("workspace")&&b.push({id:"vscode.dev:close",label:"Close Remote Workspace",menu:[r?.CommandPalette,r?.StatusBarWindowIndicatorMenu],handler:()=>I.open(su,{reuse:!0})});const k=["/+","/tunnel/"];b.push({id:"vscode.dev:openPath",handler:(e,t)=>{k.some(t=>e.startsWith(t))&&(t?.newTab?window.open(e,"_blank"):window.location.pathname=e)}});const S=function(e){const t={enableTelemetry:!0,embedderIdentifier:"vscode.dev",openToWelcomeMainPage:!0,documentationUrl:"https://aka.ms/vscode-web-docs",licenseUrl:"https://www.microsoft.com/en-us/legal/terms-of-use",keyboardShortcutsUrlMac:"https://aka.ms/vscode-dev-shortcuts-macos",keyboardShortcutsUrlLinux:"https://aka.ms/vscode-dev-shortcuts-linux",keyboardShortcutsUrlWin:"https://aka.ms/vscode-dev-shortcuts-win"};return"dev"!==e?t:{...t,extensionsGallery:{nlsBaseUrl:"https://www.vscode-unpkg.net/_lp/",serviceUrl:"https://marketplace.visualstudio.com/_apis/public/gallery",searchUrl:"https://marketplace.visualstudio.com/_apis/public/gallery/searchrelevancy/extensionquery",servicePPEUrl:"https://marketplace.vsallin.net/_apis/public/gallery",cacheUrl:"https://vscode.blob.core.windows.net/gallery/index",itemUrl:"https://marketplace.visualstudio.com/items",resourceUrlTemplate:"https://{publisher}.vscode-unpkg.net/{publisher}/{name}/{version}/{path}",controlUrl:"https://main.vscode-cdn.net/extensions/marketplace.json",publisherUrl:"https://marketplace.visualstudio.com/publishers"},trustedExtensionAuthAccess:["vscode.git","vscode.github","ms-vscode.remote-repositories","github.remotehub","ms-vscode.azure-repos","ms-vscode.remote-server","github.vscode-pull-request-github","github.codespaces","ms-vsliveshare.vsliveshare","github.copilot","github.copilot-chat"]}}(e),T={...f?.workbenchOptions??{},configurationDefaults:{"workbench.colorTheme":"Default Dark Modern",...f?.workbenchOptions?.configurationDefaults??{}},additionalBuiltinExtensions:y,enabledExtensions:v,urlCallbackProvider:new J(l),secretStorageProvider:h,remoteResourceProvider:f?.workbenchOptions?.remoteResourceProvider??(f?.workbenchOptions?.remoteAuthority?me():void 0),productConfiguration:{...S,...f?.workbenchOptions?.productConfiguration??{},extensionEnabledApiProposals:{...S?.extensionEnabledApiProposals??{},...f?.workbenchOptions?.productConfiguration?.extensionEnabledApiProposals??{}},npsSurveyUrl:void 0,cesSurveyUrl:void 0,surveys:void 0},enableWorkspaceTrust:f?.workbenchOptions?.enableWorkspaceTrust??!0,initialColorTheme:{themeType:"dark"},welcomeBanner:f?.disableWelcomeBanner?void 0:f?.welcomeBanner??{message:he.Anywhere.toString(),actions:au},codeExchangeProxyEndpoints:{microsoft:`${window.location.protocol}//${window.location.host}/codeExchangeProxyEndpoints/microsoft/`,github:`${window.location.protocol}//${window.location.host}/codeExchangeProxyEndpoints/github/`},authenticationProviders:[m.authenticationProvider],resolveExternalUri:async e=>{const t=se({folderUri:e});if(!t)throw new Error(`Scheme not supported: ${e.scheme}`);return o.parse(t)},commands:f?.workbenchOptions?.commands?.concat(b)??b,workspaceProvider:I,productQualityChangeHandler:cu(c,a),developmentOptions:{logLevel:lu(c)},openerAllowedExternalUrlPrefixes:iu,resolveCommonTelemetryProperties:()=>({"common.isPWAInstalled":String(navigator.standalone||window.matchMedia("(display-mode: standalone)").matches)})};if(i(document.body,T),f?.onDidCreateWorkbench?.openUri){const e=f.onDidCreateWorkbench.openUri;s.openUri(o.from({scheme:await s.getUriScheme(),query:window.location.href,...e}))}if(f?.onDidCreateWorkbench?.runCommands)for(const e of f.onDidCreateWorkbench.runCommands)n.executeCommand(e.command,...e.args);if(f?.onWillDisposeWorkbench?.runCommands){const e=f.onWillDisposeWorkbench.runCommands;window.addEventListener("beforeunload",()=>{for(const t of e)n.executeCommand(t.command,...t.args)})}}function du(e){const t=e;return"string"==typeof t?.id&&(void 0===t.preRelease||"boolean"==typeof t.preRelease)}/^de($|-)/i.test(window.navigator.language)&&au.push({href:"https://news.microsoft.com/de-ch/impressum/",label:"Impressum"}),/^it($|-)/i.test(window.navigator.language)&&au.push({href:"https://go.microsoft.com/fwlink/?linkid=2121429",label:"Accessibilità"}),async function(){const{quality:e,commit:t,baseUrl:r,trustedTypesPolicy:o}=globalThis._VSCODE_WEB_BOOTSTRAP_;if(function(e,t={}){const{favicon:r=!0,appleTouchIcon:o=!0,manifest:n=!0}=t;if(e="insider"===e?"insider":"stable",r){const t=document.createElement("link");t.rel="icon",t.href=`/static/${e}/favicon.ico`,t.type="image/x-icon",document.head.append(t)}if(o){const t=document.createElement("link");t.rel="apple-touch-icon",t.href=`/static/${e}/code-192-apple.png`,document.head.append(t)}if(n){const t=document.createElement("link");t.rel="manifest",t.href=`/static/${e}/code.webmanifest`,t.crossOrigin="use-credentials",document.head.append(t)}}(e),function(){const e=navigator.language.split("-")[0];e&&document.documentElement.setAttribute("lang",e)}(),"dev"===e)try{const e=await fetch(`${r}/_builtin`),t=await e.text(),o=document.createElement("meta");o.id="vscode-workbench-builtin-extensions",o.setAttribute("data-settings",t),document.head.append(o)}catch{throw new Error("Failed to load dev sources, make sure you're running 'yarn web'.")}const n=new URL(window.location.href),i=n.searchParams.get("vscode-version");if(i&&!window.confirm(`You are about to load an older version of the VS Code workbench (${i.substring(0,8)}), which might be vulnerable to security issues. Are you sure you want to continue?`))return n.searchParams.delete("vscode-version"),void(window.location.href=n.toString());try{performance.mark("web/willCallMain"),await hu(e,t,ou)}finally{performance.mark("web/didCallMain")}if(location.origin.includes("localhost"))navigator.serviceWorker.getRegistrations().then(e=>{for(const t of e)t.unregister()});else if("serviceWorker"in navigator){const t=o?.createScriptURL("/sw.js")??"/sw.js",r=navigator.serviceWorker.register(t);"dev"!==e&&r.then(async e=>{let t=e.active??e.waiting;t||(t=await new Promise(t=>{if(e.active)return t(e.active);if(!e.installing)throw new Error("Unnexpected service worker state");const r=e.installing,o=e=>{if("activated"===e.target.state)return r.removeEventListener("statechange",o),t(e.target)};r.addEventListener("statechange",o)}));const r={quality:globalThis._VSCODE_WEB_BOOTSTRAP_.quality,version:globalThis._VSCODE_WEB_BOOTSTRAP_.commit};setTimeout(()=>t?.postMessage({type:"preload",preload:r}),2e3)})}}().catch(function(e){console.error(JSON.stringify(e,void 0,2)),console.error(e),document.getElementById("monaco-parts-splash")?.remove();const t=document.createElement("link");t.rel="stylesheet",t.type="text/css",t.href="/static/base.css",document.head.append(t);const r=document.createElement("span");r.className="branding",r.textContent="Visual Studio Code";const o=document.createElement("div");o.className="message-container";const n=document.createElement("div");n.className="message",n.textContent="Fatal Error 🙈 Please check Developer Tools 🐱💻",document.body.appendChild(r),o.appendChild(n),document.body.appendChild(o)}).finally(()=>performance.mark("web/didBootstrap"));export{hu as main};</script></html>
Sitemap
Кол-во: 0
XML-карта сайта для поисковиков
?
Sitemap.xml помогает поисковику быстрее находить и индексировать страницы. Особенно важен для крупных сайтов и новых страниц, на которые ещё нет входящих ссылок.
Robots.txt не содержит ссылку на карту сайта. Рекомендуется добавить карту сайта и указать ссылку на нее в robots.txt.
Внутренние ссылки
Не найдено
Ссылки на другие страницы своего сайта
?
Внутренние ссылки распределяют ссылочный вес между страницами и помогают поисковику обходить сайт. Пустые анкоры и ссылки на запрещённые robots.txt страницы — типичные ошибки.
Внутренних ссылок на странице 0 оптимально.
Внешние ссылки
Не найдено
Ссылки на сторонние сайты
?
Исходящие внешние ссылки передают часть ссылочного веса на чужие сайты. Ссылки на авторитетные ресурсы безопасны; ссылки на мусорные сайты могут навредить репутации страницы.
Внешних ссылок на странице не найдено.
Конкуренты Готовность: 0%
Конкуренты в Яндексе
Кол-во: 0
Топ сайтов-конкурентов в Яндексе
?
Сайты, чаще всего появляющиеся в ТОПе Яндекса по запросам из семантического ядра этой страницы.
Мы не нашли у вас конкурентов в Яндексе. Сайт или очень молодой или плохо продвигается.
Конкурентов в ТОП-10 Яндекса не нашлось.
Конкуренты в Google
Кол-во: 0
Топ сайтов-конкурентов в Google
?
Сайты, чаще всего появляющиеся в ТОПе Google по запросам из семантического ядра этой страницы.
Конкуренты в Google тоже не найдены. Займитесь продвижением сайта!
Конкурентов в ТОП-10 Google не нашлось.
ЗоЗПП: права потребителей Готовность: 100%
Нарушения
Не выявлены
Признаков дистанционной продажи товаров (интернет-магазина) не обнаружено — требования ЗоЗПП о раскрытии информации продавца к сайту не применяются. Нарушений нет.
ФЗ-149: рекомендательные технологии Готовность: 100%
Нарушения
Не выявлены
Рекомендательные блоки («с этим покупают», «похожие товары» и т.п.) на сайте не обнаружены — требования ст. 10.7 ФЗ-149 к сайту не применяются. Нарушений нет.
ФЗ-38: реклама Готовность: 100%
Нарушения
Не выявлены
Рекламных тематик с обязательными оговорками (медицина, БАД, кредиты и займы, новостройки) на сайте не обнаружено. Нарушений нет.
ФЗ-436: защита детей Готовность: 100%
Нарушения
Не выявлены
Признаков информационной продукции (новости, видео, книги, игры, курсы) не обнаружено — обязательная возрастная маркировка по ФЗ-436 сайту не требуется. Нарушений нет.
Вердикт
Таким сайт github.dev видят поисковые системы. Процент оптимизации невысокий - 31%. Чтобы улучшить сайт и попасть в ТОП необходимо:
Исправьте ошибки в мета-тегах.
Исправьте ошибки оптимизации.
Исправьте ошибки индексации.
Поделитесь с друзьями: