@voxket-ai/voxket-live 1.0.59 → 1.0.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,14 +1,3 @@
1
-
2
- (function() {
3
- if (typeof document !== 'undefined' && !document.getElementById('voxket-widget-styles')) {
4
- const style = document.createElement('style');
5
- style.id = 'voxket-widget-styles';
6
- style.textContent = `/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@layer properties{@supports ((-webkit-hyphens:none) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-pan-x:initial;--tw-pan-y:initial;--tw-pinch-zoom:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-x-reverse:0;--tw-border-style:solid;--tw-divide-y-reverse:0;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial}.\@container{container-type:inline-size}.voxket-widget-root .pointer-events-auto{pointer-events:auto}.voxket-widget-root .pointer-events-none{pointer-events:none}.voxket-widget-root .collapse{visibility:collapse}.voxket-widget-root .invisible{visibility:hidden}.voxket-widget-root .visible{visibility:visible}.voxket-widget-root .sr-only{clip:rect(0,0,0,0);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.voxket-widget-root .not-sr-only{clip:auto;white-space:normal;width:auto;height:auto;margin:0;padding:0;position:static;overflow:visible}.voxket-widget-root .absolute{position:absolute}.voxket-widget-root .fixed{position:fixed}.voxket-widget-root .relative{position:relative}.voxket-widget-root .static{position:static}.voxket-widget-root .sticky{position:sticky}.voxket-widget-root .inset-0{inset:calc(var(--spacing)*0)}.voxket-widget-root .inset-4{inset:calc(var(--spacing)*4)}.voxket-widget-root .-top-2{top:calc(var(--spacing)*-2)}.voxket-widget-root .top-0{top:calc(var(--spacing)*0)}.voxket-widget-root .top-1{top:calc(var(--spacing)*1)}.voxket-widget-root .top-2{top:calc(var(--spacing)*2)}.voxket-widget-root .top-4{top:calc(var(--spacing)*4)}.voxket-widget-root .-right-2{right:calc(var(--spacing)*-2)}.voxket-widget-root .right-0{right:calc(var(--spacing)*0)}.voxket-widget-root .right-2{right:calc(var(--spacing)*2)}.voxket-widget-root .right-4{right:calc(var(--spacing)*4)}.voxket-widget-root .-bottom-2{bottom:calc(var(--spacing)*-2)}.voxket-widget-root .bottom-0{bottom:calc(var(--spacing)*0)}.voxket-widget-root .bottom-2{bottom:calc(var(--spacing)*2)}.voxket-widget-root .bottom-4{bottom:calc(var(--spacing)*4)}.voxket-widget-root .-left-2{left:calc(var(--spacing)*-2)}.voxket-widget-root .left-0{left:calc(var(--spacing)*0)}.voxket-widget-root .left-2{left:calc(var(--spacing)*2)}.voxket-widget-root .left-4{left:calc(var(--spacing)*4)}.voxket-widget-root .isolate{isolation:isolate}.voxket-widget-root .isolation-auto{isolation:auto}.voxket-widget-root .z-0{z-index:0}.voxket-widget-root .z-10{z-index:10}.voxket-widget-root .z-20{z-index:20}.voxket-widget-root .z-50{z-index:50}.voxket-widget-root .z-\[100\]{z-index:100}.voxket-widget-root .z-\[9999\]{z-index:9999}.voxket-widget-root .order-1{order:1}.voxket-widget-root .order-2{order:2}.voxket-widget-root .col-span-2{grid-column:span 2/span 2}.voxket-widget-root .col-start-1{grid-column-start:1}.voxket-widget-root .col-start-2{grid-column-start:2}.voxket-widget-root .row-span-3{grid-row:span 3/span 3}.voxket-widget-root .row-start-1{grid-row-start:1}.voxket-widget-root .row-start-3{grid-row-start:3}.voxket-widget-root .container{width:100%}@media (min-width:40rem){.container{max-width:40rem}@media (min-width:48rem){.container{max-width:48rem}@media (min-width:64rem){.container{max-width:64rem}@media (min-width:80rem){.container{max-width:80rem}@media (min-width:96rem){.container{max-width:96rem}.voxket-widget-root .m-4{margin:calc(var(--spacing)*4)}.voxket-widget-root .-mx-1{margin-inline:calc(var(--spacing)*-1)}.voxket-widget-root .mx-0{margin-inline:calc(var(--spacing)*0)}.voxket-widget-root .mx-0\.5{margin-inline:calc(var(--spacing)*.5)}.voxket-widget-root .mx-4{margin-inline:calc(var(--spacing)*4)}.voxket-widget-root .mx-5{margin-inline:calc(var(--spacing)*5)}.voxket-widget-root .mx-8{margin-inline:calc(var(--spacing)*8)}.voxket-widget-root .mx-auto{margin-inline:auto}.voxket-widget-root .my-1{margin-block:calc(var(--spacing)*1)}.voxket-widget-root .my-2{margin-block:calc(var(--spacing)*2)}.voxket-widget-root .my-auto{margin-block:auto}.voxket-widget-root .mt-0\.5{margin-top:calc(var(--spacing)*.5)}.voxket-widget-root .mt-1{margin-top:calc(var(--spacing)*1)}.voxket-widget-root .mt-2{margin-top:calc(var(--spacing)*2)}.voxket-widget-root .mt-4{margin-top:calc(var(--spacing)*4)}.voxket-widget-root .mt-6{margin-top:calc(var(--spacing)*6)}.voxket-widget-root .mt-8{margin-top:calc(var(--spacing)*8)}.voxket-widget-root .mr-1{margin-right:calc(var(--spacing)*1)}.voxket-widget-root .mr-2{margin-right:calc(var(--spacing)*2)}.voxket-widget-root .mr-3{margin-right:calc(var(--spacing)*3)}.voxket-widget-root .mb-1{margin-bottom:calc(var(--spacing)*1)}.voxket-widget-root .mb-2{margin-bottom:calc(var(--spacing)*2)}.voxket-widget-root .mb-3{margin-bottom:calc(var(--spacing)*3)}.voxket-widget-root .mb-4{margin-bottom:calc(var(--spacing)*4)}.voxket-widget-root .mb-6{margin-bottom:calc(var(--spacing)*6)}.voxket-widget-root .mb-8{margin-bottom:calc(var(--spacing)*8)}.voxket-widget-root .ml-1{margin-left:calc(var(--spacing)*1)}.voxket-widget-root .ml-2{margin-left:calc(var(--spacing)*2)}.voxket-widget-root .ml-auto{margin-left:auto}.voxket-widget-root .line-clamp-1{-webkit-line-clamp:1;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.voxket-widget-root .block{display:block}.voxket-widget-root .contents{display:contents}.voxket-widget-root .flex{display:flex}.voxket-widget-root .flow-root{display:flow-root}.voxket-widget-root .grid{display:grid}.voxket-widget-root .hidden{display:none}.voxket-widget-root .hidden\!{display:none!important}.voxket-widget-root .inline{display:inline}.voxket-widget-root .inline-block{display:inline-block}.voxket-widget-root .inline-flex{display:inline-flex}.voxket-widget-root .inline-grid{display:inline-grid}.voxket-widget-root .inline-table{display:inline-table}.voxket-widget-root .list-item{display:list-item}.voxket-widget-root .table{display:table}.voxket-widget-root .table-caption{display:table-caption}.voxket-widget-root .table-cell{display:table-cell}.voxket-widget-root .table-column{display:table-column}.voxket-widget-root .table-column-group{display:table-column-group}.voxket-widget-root .table-footer-group{display:table-footer-group}.voxket-widget-root .table-header-group{display:table-header-group}.voxket-widget-root .table-row{display:table-row}.voxket-widget-root .table-row-group{display:table-row-group}.voxket-widget-root .aspect-square{aspect-ratio:1}.voxket-widget-root .aspect-video{aspect-ratio:var(--aspect-video)}.voxket-widget-root .size-3\.5{width:calc(var(--spacing)*3.5);height:calc(var(--spacing)*3.5)}.voxket-widget-root .size-4{width:calc(var(--spacing)*4);height:calc(var(--spacing)*4)}.voxket-widget-root .size-9{width:calc(var(--spacing)*9);height:calc(var(--spacing)*9)}.voxket-widget-root .h-0{height:calc(var(--spacing)*0)}.voxket-widget-root .h-1{height:calc(var(--spacing)*1)}.voxket-widget-root .h-1\.5{height:calc(var(--spacing)*1.5)}.voxket-widget-root .h-2{height:calc(var(--spacing)*2)}.voxket-widget-root .h-3{height:calc(var(--spacing)*3)}.voxket-widget-root .h-4{height:calc(var(--spacing)*4)}.voxket-widget-root .h-5{height:calc(var(--spacing)*5)}.voxket-widget-root .h-6{height:calc(var(--spacing)*6)}.voxket-widget-root .h-8{height:calc(var(--spacing)*8)}.voxket-widget-root .h-9{height:calc(var(--spacing)*9)}.voxket-widget-root .h-10{height:calc(var(--spacing)*10)}.voxket-widget-root .h-12{height:calc(var(--spacing)*12)}.voxket-widget-root .h-16{height:calc(var(--spacing)*16)}.voxket-widget-root .h-20{height:calc(var(--spacing)*20)}.voxket-widget-root .h-24{height:calc(var(--spacing)*24)}.voxket-widget-root .h-28{height:calc(var(--spacing)*28)}.voxket-widget-root .h-32{height:calc(var(--spacing)*32)}.voxket-widget-root .h-96{height:calc(var(--spacing)*96)}.voxket-widget-root .h-\[25rem\]{height:25rem}.voxket-widget-root .h-\[30rem\]{height:30rem}.voxket-widget-root .h-\[60px\]{height:60px}.voxket-widget-root .h-\[64px\]{height:64px}.voxket-widget-root .h-\[70px\]{height:70px}.voxket-widget-root .h-\[90px\]{height:90px}.voxket-widget-root .h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.voxket-widget-root .h-auto{height:auto}.voxket-widget-root .h-fit{height:-moz-fit-content;height:fit-content}.voxket-widget-root .h-full{height:100%}.voxket-widget-root .h-px{height:1px}.voxket-widget-root .h-screen{height:100vh}.voxket-widget-root .max-h-\(--radix-select-content-available-height\){max-height:var(--radix-select-content-available-height)}.voxket-widget-root .max-h-20{max-height:calc(var(--spacing)*20)}.voxket-widget-root .max-h-48{max-height:calc(var(--spacing)*48)}.voxket-widget-root .max-h-\[80vh\]{max-height:80vh}.voxket-widget-root .max-h-\[85vh\]{max-height:85vh}.voxket-widget-root .max-h-\[90vh\]{max-height:90vh}.voxket-widget-root .min-h-0{min-height:calc(var(--spacing)*0)}.voxket-widget-root .min-h-2{min-height:calc(var(--spacing)*2)}.voxket-widget-root .min-h-4{min-height:calc(var(--spacing)*4)}.voxket-widget-root .min-h-\[3rem\]{min-height:3rem}.voxket-widget-root .min-h-\[32px\]{min-height:32px}.voxket-widget-root .min-h-\[180px\]{min-height:180px}.voxket-widget-root .min-h-fit{min-height:-moz-fit-content;min-height:fit-content}.voxket-widget-root .min-h-screen{min-height:100vh}.voxket-widget-root .\!w-full{width:100%!important}.voxket-widget-root .w-0\.5{width:calc(var(--spacing)*.5)}.voxket-widget-root .w-1\.5{width:calc(var(--spacing)*1.5)}.voxket-widget-root .w-2{width:calc(var(--spacing)*2)}.voxket-widget-root .w-3{width:calc(var(--spacing)*3)}.voxket-widget-root .w-4{width:calc(var(--spacing)*4)}.voxket-widget-root .w-5{width:calc(var(--spacing)*5)}.voxket-widget-root .w-6{width:calc(var(--spacing)*6)}.voxket-widget-root .w-8{width:calc(var(--spacing)*8)}.voxket-widget-root .w-10{width:calc(var(--spacing)*10)}.voxket-widget-root .w-12{width:calc(var(--spacing)*12)}.voxket-widget-root .w-16{width:calc(var(--spacing)*16)}.voxket-widget-root .w-20{width:calc(var(--spacing)*20)}.voxket-widget-root .w-24{width:calc(var(--spacing)*24)}.voxket-widget-root .w-28{width:calc(var(--spacing)*28)}.voxket-widget-root .w-32{width:calc(var(--spacing)*32)}.voxket-widget-root .w-40{width:calc(var(--spacing)*40)}.voxket-widget-root .w-80{width:calc(var(--spacing)*80)}.voxket-widget-root .w-96{width:calc(var(--spacing)*96)}.voxket-widget-root .w-\[180px\]{width:180px}.voxket-widget-root .w-auto{width:auto}.voxket-widget-root .w-fit{width:-moz-fit-content;width:fit-content}.voxket-widget-root .w-full{width:100%}.voxket-widget-root .w-screen{width:100vw}.voxket-widget-root .max-w-2xl{max-width:var(--container-2xl)}.voxket-widget-root .max-w-3xl{max-width:var(--container-3xl)}.voxket-widget-root .max-w-4xl{max-width:var(--container-4xl)}.voxket-widget-root .max-w-5xl{max-width:var(--container-5xl)}.voxket-widget-root .max-w-6xl{max-width:var(--container-6xl)}.voxket-widget-root .max-w-\[85\%\]{max-width:85%}.voxket-widget-root .max-w-full{max-width:100%}.voxket-widget-root .max-w-lg{max-width:var(--container-lg)}.voxket-widget-root .max-w-md{max-width:var(--container-md)}.voxket-widget-root .max-w-none{max-width:none}.voxket-widget-root .max-w-sm{max-width:var(--container-sm)}.voxket-widget-root .max-w-xs{max-width:var(--container-xs)}.voxket-widget-root .min-w-0{min-width:calc(var(--spacing)*0)}.voxket-widget-root .min-w-8{min-width:calc(var(--spacing)*8)}.voxket-widget-root .min-w-9{min-width:calc(var(--spacing)*9)}.voxket-widget-root .min-w-10{min-width:calc(var(--spacing)*10)}.voxket-widget-root .min-w-\[2\.5rem\]{min-width:2.5rem}.voxket-widget-root .min-w-\[8rem\]{min-width:8rem}.voxket-widget-root .min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.voxket-widget-root .flex-1{flex:1}.voxket-widget-root .flex-shrink-0{flex-shrink:0}.voxket-widget-root .shrink{flex-shrink:1}.voxket-widget-root .shrink-0{flex-shrink:0}.voxket-widget-root .grow{flex-grow:1}.voxket-widget-root .border-collapse{border-collapse:collapse}.voxket-widget-root .origin-\(--radix-select-content-transform-origin\){transform-origin:var(--radix-select-content-transform-origin)}.voxket-widget-root .origin-center{transform-origin:50%}.voxket-widget-root .translate-y-0{--tw-translate-y:calc(var(--spacing)*0);translate:var(--tw-translate-x)var(--tw-translate-y)}.voxket-widget-root .translate-y-10{--tw-translate-y:calc(var(--spacing)*10);translate:var(--tw-translate-x)var(--tw-translate-y)}.voxket-widget-root .translate-none{translate:none}.voxket-widget-root .scale-3d{scale:var(--tw-scale-x)var(--tw-scale-y)var(--tw-scale-z)}.voxket-widget-root .transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.voxket-widget-root .animate-pulse{animation:var(--animate-pulse)}.voxket-widget-root .animate-spin{animation:var(--animate-spin)}.voxket-widget-root .cursor-default{cursor:default}.voxket-widget-root .cursor-not-allowed{cursor:not-allowed}.voxket-widget-root .cursor-pointer{cursor:pointer}.voxket-widget-root .touch-pinch-zoom{--tw-pinch-zoom:pinch-zoom;touch-action:var(--tw-pan-x,)var(--tw-pan-y,)var(--tw-pinch-zoom,)}.voxket-widget-root .resize{resize:both}.voxket-widget-root .resize-none{resize:none}.voxket-widget-root .scroll-my-1{scroll-margin-block:calc(var(--spacing)*1)}.voxket-widget-root .list-inside{list-style-position:inside}.voxket-widget-root .list-decimal{list-style-type:decimal}.voxket-widget-root .list-disc{list-style-type:disc}.voxket-widget-root .grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.voxket-widget-root .grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.voxket-widget-root .grid-cols-\[0_1fr\]{grid-template-columns:0 1fr}.voxket-widget-root .grid-cols-\[1fr_1fr\]{grid-template-columns:1fr 1fr}.voxket-widget-root .grid-rows-\[90px_1fr_90px\]{grid-template-rows:90px 1fr 90px}.voxket-widget-root .flex-col{flex-direction:column}.voxket-widget-root .flex-row{flex-direction:row}.voxket-widget-root .flex-row-reverse{flex-direction:row-reverse}.voxket-widget-root .flex-wrap{flex-wrap:wrap}.voxket-widget-root .place-content-center{place-content:center}.voxket-widget-root .place-content-end{place-content:end}.voxket-widget-root .items-center{align-items:center}.voxket-widget-root .items-end{align-items:flex-end}.voxket-widget-root .items-start{align-items:flex-start}.voxket-widget-root .justify-between{justify-content:space-between}.voxket-widget-root .justify-center{justify-content:center}.voxket-widget-root .justify-end{justify-content:flex-end}.voxket-widget-root .justify-start{justify-content:flex-start}.voxket-widget-root .justify-items-start{justify-items:start}.voxket-widget-root .gap-1{gap:calc(var(--spacing)*1)}.voxket-widget-root .gap-1\.5{gap:calc(var(--spacing)*1.5)}.voxket-widget-root .gap-2{gap:calc(var(--spacing)*2)}.voxket-widget-root .gap-3{gap:calc(var(--spacing)*3)}.voxket-widget-root .gap-4{gap:calc(var(--spacing)*4)}.voxket-widget-root .gap-6{gap:calc(var(--spacing)*6)}.voxket-widget-root .gap-8{gap:calc(var(--spacing)*8)}.voxket-widget-root :where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*1)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*1)*calc(1 - var(--tw-space-y-reverse)))}.voxket-widget-root :where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*2)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*2)*calc(1 - var(--tw-space-y-reverse)))}.voxket-widget-root :where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*3)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*3)*calc(1 - var(--tw-space-y-reverse)))}.voxket-widget-root :where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*4)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*4)*calc(1 - var(--tw-space-y-reverse)))}.voxket-widget-root :where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*6)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*6)*calc(1 - var(--tw-space-y-reverse)))}.voxket-widget-root :where(.space-y-8>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*8)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*8)*calc(1 - var(--tw-space-y-reverse)))}.voxket-widget-root :where(.space-y-reverse>:not(:last-child)){--tw-space-y-reverse:1}.voxket-widget-root .gap-x-0\.5{-moz-column-gap:calc(var(--spacing)*.5);column-gap:calc(var(--spacing)*.5)}.voxket-widget-root .gap-x-2{-moz-column-gap:calc(var(--spacing)*2);column-gap:calc(var(--spacing)*2)}.voxket-widget-root :where(.space-x-1>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing)*1)*var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing)*1)*calc(1 - var(--tw-space-x-reverse)))}.voxket-widget-root :where(.space-x-2>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing)*2)*var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing)*2)*calc(1 - var(--tw-space-x-reverse)))}.voxket-widget-root :where(.space-x-3>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing)*3)*var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing)*3)*calc(1 - var(--tw-space-x-reverse)))}.voxket-widget-root :where(.space-x-4>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing)*4)*var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing)*4)*calc(1 - var(--tw-space-x-reverse)))}.voxket-widget-root :where(.space-x-reverse>:not(:last-child)){--tw-space-x-reverse:1}.voxket-widget-root .gap-y-0\.5{row-gap:calc(var(--spacing)*.5)}.voxket-widget-root .gap-y-2{row-gap:calc(var(--spacing)*2)}.voxket-widget-root :where(.divide-x>:not(:last-child)){--tw-divide-x-reverse:0;border-inline-style:var(--tw-border-style);border-inline-start-width:calc(1px*var(--tw-divide-x-reverse));border-inline-end-width:calc(1px*calc(1 - var(--tw-divide-x-reverse)))}.voxket-widget-root :where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}.voxket-widget-root :where(.divide-y-reverse>:not(:last-child)){--tw-divide-y-reverse:1}.voxket-widget-root .self-center{align-self:center}.voxket-widget-root .justify-self-end{justify-self:flex-end}.voxket-widget-root .justify-self-start{justify-self:flex-start}.voxket-widget-root .truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.voxket-widget-root .overflow-auto{overflow:auto}.voxket-widget-root .overflow-hidden{overflow:hidden}.voxket-widget-root .overflow-x-auto{overflow-x:auto}.voxket-widget-root .overflow-x-hidden{overflow-x:hidden}.voxket-widget-root .overflow-y-auto{overflow-y:auto}.voxket-widget-root .rounded{border-radius:.25rem}.voxket-widget-root .rounded-2xl{border-radius:var(--radius-2xl)}.voxket-widget-root .rounded-3xl{border-radius:var(--radius-3xl)}.voxket-widget-root .rounded-full{border-radius:3.40282e38px}.voxket-widget-root .rounded-lg{border-radius:var(--radius-lg)}.voxket-widget-root .rounded-md{border-radius:var(--radius-md)}.voxket-widget-root .rounded-none{border-radius:0}.voxket-widget-root .rounded-sm{border-radius:var(--radius-sm)}.voxket-widget-root .rounded-xl{border-radius:var(--radius-xl)}.voxket-widget-root .rounded-s{border-start-start-radius:.25rem;border-end-start-radius:.25rem}.voxket-widget-root .rounded-ss{border-start-start-radius:.25rem}.voxket-widget-root .rounded-e{border-start-end-radius:.25rem;border-end-end-radius:.25rem}.voxket-widget-root .rounded-se{border-start-end-radius:.25rem}.voxket-widget-root .rounded-ee{border-end-end-radius:.25rem}.voxket-widget-root .rounded-es{border-end-start-radius:.25rem}.voxket-widget-root .rounded-t{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.voxket-widget-root .rounded-t-4xl{border-top-left-radius:var(--radius-4xl);border-top-right-radius:var(--radius-4xl)}.voxket-widget-root .rounded-l{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem}.voxket-widget-root .rounded-tl{border-top-left-radius:.25rem}.voxket-widget-root .rounded-r{border-top-right-radius:.25rem;border-bottom-right-radius:.25rem}.voxket-widget-root .rounded-tr{border-top-right-radius:.25rem}.voxket-widget-root .rounded-b{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.voxket-widget-root .rounded-br{border-bottom-right-radius:.25rem}.voxket-widget-root .rounded-br-md{border-bottom-right-radius:var(--radius-md)}.voxket-widget-root .rounded-bl{border-bottom-left-radius:.25rem}.voxket-widget-root .rounded-bl-md{border-bottom-left-radius:var(--radius-md)}.voxket-widget-root .border{border-style:var(--tw-border-style);border-width:1px}.voxket-widget-root .border-0{border-style:var(--tw-border-style);border-width:0}.voxket-widget-root .border-2{border-style:var(--tw-border-style);border-width:2px}.voxket-widget-root .border-x{border-inline-style:var(--tw-border-style);border-inline-width:1px}.voxket-widget-root .border-y{border-block-style:var(--tw-border-style);border-block-width:1px}.voxket-widget-root .border-s{border-inline-start-style:var(--tw-border-style);border-inline-start-width:1px}.voxket-widget-root .border-e{border-inline-end-style:var(--tw-border-style);border-inline-end-width:1px}.voxket-widget-root .border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.voxket-widget-root .border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.voxket-widget-root .border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.voxket-widget-root .border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.voxket-widget-root .border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.voxket-widget-root .\!border-none{--tw-border-style:none!important;border-style:none!important}.voxket-widget-root .border-none{--tw-border-style:none;border-style:none}.voxket-widget-root .border-\[\#3B82F6\]\/40{border-color:#3b82f666}.voxket-widget-root .border-\[\#8B5CF6\]\/30{border-color:#8b5cf64d}.voxket-widget-root .border-\[\#813aa7\]\/30{border-color:#813aa74d}.voxket-widget-root .border-\[\#5078F2\]\/30{border-color:#5078f24d}.voxket-widget-root .border-\[\#23233a\]{border-color:#23233a}.voxket-widget-root .border-\[\#232336\]{border-color:#232336}.voxket-widget-root .border-\[\#EC4899\]\/20{border-color:#ec489933}.voxket-widget-root .border-blue-100{border-color:var(--color-blue-100)}.voxket-widget-root .border-blue-200{border-color:var(--color-blue-200)}.voxket-widget-root .border-blue-400{border-color:var(--color-blue-400)}.voxket-widget-root .border-blue-500{border-color:var(--color-blue-500)}.voxket-widget-root .border-blue-500\/20{border-color:#3080ff33}@supports (color:color-mix(in lab,red,red)){.border-blue-500\/20{border-color:color-mix(in oklab,var(--color-blue-500)20%,transparent)}.voxket-widget-root .border-blue-600{border-color:var(--color-blue-600)}.voxket-widget-root .border-current{border-color:currentColor}.voxket-widget-root .border-gray-200{border-color:var(--color-gray-200)}.voxket-widget-root .border-gray-300{border-color:var(--color-gray-300)}.voxket-widget-root .border-gray-400\/15{border-color:#99a1af26}@supports (color:color-mix(in lab,red,red)){.border-gray-400\/15{border-color:color-mix(in oklab,var(--color-gray-400)15%,transparent)}.voxket-widget-root .border-gray-500\/20{border-color:#6a728233}@supports (color:color-mix(in lab,red,red)){.border-gray-500\/20{border-color:color-mix(in oklab,var(--color-gray-500)20%,transparent)}.voxket-widget-root .border-gray-600{border-color:var(--color-gray-600)}.voxket-widget-root .border-gray-600\/30{border-color:#4a55654d}@supports (color:color-mix(in lab,red,red)){.border-gray-600\/30{border-color:color-mix(in oklab,var(--color-gray-600)30%,transparent)}.voxket-widget-root .border-gray-700{border-color:var(--color-gray-700)}.voxket-widget-root .border-gray-800{border-color:var(--color-gray-800)}.voxket-widget-root .border-gray-900{border-color:var(--color-gray-900)}.voxket-widget-root .border-green-200{border-color:var(--color-green-200)}.voxket-widget-root .border-pink-500\/10{border-color:#f6339a1a}@supports (color:color-mix(in lab,red,red)){.border-pink-500\/10{border-color:color-mix(in oklab,var(--color-pink-500)10%,transparent)}.voxket-widget-root .border-purple-500\/15{border-color:#ac4bff26}@supports (color:color-mix(in lab,red,red)){.border-purple-500\/15{border-color:color-mix(in oklab,var(--color-purple-500)15%,transparent)}.voxket-widget-root .border-red-200{border-color:var(--color-red-200)}.voxket-widget-root .border-red-800{border-color:var(--color-red-800)}.voxket-widget-root .border-white{border-color:var(--color-white)}.voxket-widget-root .border-white\/20{border-color:#fff3}@supports (color:color-mix(in lab,red,red)){.border-white\/20{border-color:color-mix(in oklab,var(--color-white)20%,transparent)}.voxket-widget-root .border-yellow-200{border-color:var(--color-yellow-200)}.voxket-widget-root .border-t-transparent{border-top-color:#0000}.voxket-widget-root .bg-\[\#1E1E2E\]{background-color:#1e1e2e}.voxket-widget-root .bg-\[\#1E1E2E\]\/80{background-color:#1e1e2ecc}.voxket-widget-root .bg-\[\#1E1E2E\]\/90{background-color:#1e1e2ee6}.voxket-widget-root .bg-\[\#3B82F6\]{background-color:#3b82f6}.voxket-widget-root .bg-\[\#10B981\]{background-color:#10b981}.voxket-widget-root .bg-\[\#221f3f\]{background-color:#221f3f}.voxket-widget-root .bg-\[\#813aa7\]{background-color:#813aa7}.voxket-widget-root .bg-\[\#5078F2\]{background-color:#5078f2}.voxket-widget-root .bg-\[\#6721a4\]{background-color:#6721a4}.voxket-widget-root .bg-\[\#18182a\]\/80{background-color:#18182acc}.voxket-widget-root .bg-\[\#18182a\]\/90{background-color:#18182ae6}.voxket-widget-root .bg-black{background-color:var(--color-black)}.voxket-widget-root .bg-black\/0{background-color:#0000}@supports (color:color-mix(in lab,red,red)){.bg-black\/0{background-color:color-mix(in oklab,var(--color-black)0%,transparent)}.voxket-widget-root .bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black)50%,transparent)}.voxket-widget-root .bg-black\/70{background-color:#000000b3}@supports (color:color-mix(in lab,red,red)){.bg-black\/70{background-color:color-mix(in oklab,var(--color-black)70%,transparent)}.voxket-widget-root .bg-black\/80{background-color:#000c}@supports (color:color-mix(in lab,red,red)){.bg-black\/80{background-color:color-mix(in oklab,var(--color-black)80%,transparent)}.voxket-widget-root .bg-blue-50{background-color:var(--color-blue-50)}.voxket-widget-root .bg-blue-100{background-color:var(--color-blue-100)}.voxket-widget-root .bg-blue-200{background-color:var(--color-blue-200)}.voxket-widget-root .bg-blue-400{background-color:var(--color-blue-400)}.voxket-widget-root .bg-blue-500{background-color:var(--color-blue-500)}.voxket-widget-root .bg-blue-600{background-color:var(--color-blue-600)}.voxket-widget-root .bg-blue-900\/50{background-color:#1c398e80}@supports (color:color-mix(in lab,red,red)){.bg-blue-900\/50{background-color:color-mix(in oklab,var(--color-blue-900)50%,transparent)}.voxket-widget-root .bg-current{background-color:currentColor}.voxket-widget-root .bg-gray-50{background-color:var(--color-gray-50)}.voxket-widget-root .bg-gray-100{background-color:var(--color-gray-100)}.voxket-widget-root .bg-gray-200{background-color:var(--color-gray-200)}.voxket-widget-root .bg-gray-400{background-color:var(--color-gray-400)}.voxket-widget-root .bg-gray-600{background-color:var(--color-gray-600)}.voxket-widget-root .bg-gray-600\/50{background-color:#4a556580}@supports (color:color-mix(in lab,red,red)){.bg-gray-600\/50{background-color:color-mix(in oklab,var(--color-gray-600)50%,transparent)}.voxket-widget-root .bg-gray-700{background-color:var(--color-gray-700)}.voxket-widget-root .bg-gray-700\/50{background-color:#36415380}@supports (color:color-mix(in lab,red,red)){.bg-gray-700\/50{background-color:color-mix(in oklab,var(--color-gray-700)50%,transparent)}.voxket-widget-root .bg-gray-800{background-color:var(--color-gray-800)}.voxket-widget-root .bg-gray-800\/50{background-color:#1e293980}@supports (color:color-mix(in lab,red,red)){.bg-gray-800\/50{background-color:color-mix(in oklab,var(--color-gray-800)50%,transparent)}.voxket-widget-root .bg-gray-900{background-color:var(--color-gray-900)}.voxket-widget-root .bg-gray-900\/50{background-color:#10182880}@supports (color:color-mix(in lab,red,red)){.bg-gray-900\/50{background-color:color-mix(in oklab,var(--color-gray-900)50%,transparent)}.voxket-widget-root .bg-gray-900\/80{background-color:#101828cc}@supports (color:color-mix(in lab,red,red)){.bg-gray-900\/80{background-color:color-mix(in oklab,var(--color-gray-900)80%,transparent)}.voxket-widget-root .bg-gray-900\/95{background-color:#101828f2}@supports (color:color-mix(in lab,red,red)){.bg-gray-900\/95{background-color:color-mix(in oklab,var(--color-gray-900)95%,transparent)}.voxket-widget-root .bg-green-50{background-color:var(--color-green-50)}.voxket-widget-root .bg-green-500{background-color:var(--color-green-500)}.voxket-widget-root .bg-green-600{background-color:var(--color-green-600)}.voxket-widget-root .bg-indigo-600{background-color:var(--color-indigo-600)}.voxket-widget-root .bg-orange-600{background-color:var(--color-orange-600)}.voxket-widget-root .bg-purple-500{background-color:var(--color-purple-500)}.voxket-widget-root .bg-purple-600{background-color:var(--color-purple-600)}.voxket-widget-root .bg-red-50{background-color:var(--color-red-50)}.voxket-widget-root .bg-red-500{background-color:var(--color-red-500)}.voxket-widget-root .bg-red-600{background-color:var(--color-red-600)}.voxket-widget-root .bg-red-600\/80{background-color:#e40014cc}@supports (color:color-mix(in lab,red,red)){.bg-red-600\/80{background-color:color-mix(in oklab,var(--color-red-600)80%,transparent)}.voxket-widget-root .bg-red-900\/20{background-color:#82181a33}@supports (color:color-mix(in lab,red,red)){.bg-red-900\/20{background-color:color-mix(in oklab,var(--color-red-900)20%,transparent)}.voxket-widget-root .bg-transparent{background-color:#0000}.voxket-widget-root .bg-white{background-color:var(--color-white)}.voxket-widget-root .bg-white\/10{background-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.bg-white\/10{background-color:color-mix(in oklab,var(--color-white)10%,transparent)}.voxket-widget-root .bg-white\/20{background-color:#fff3}@supports (color:color-mix(in lab,red,red)){.bg-white\/20{background-color:color-mix(in oklab,var(--color-white)20%,transparent)}.voxket-widget-root .bg-white\/80{background-color:#fffc}@supports (color:color-mix(in lab,red,red)){.bg-white\/80{background-color:color-mix(in oklab,var(--color-white)80%,transparent)}.voxket-widget-root .bg-white\/90{background-color:#ffffffe6}@supports (color:color-mix(in lab,red,red)){.bg-white\/90{background-color:color-mix(in oklab,var(--color-white)90%,transparent)}.voxket-widget-root .bg-white\/95{background-color:#fffffff2}@supports (color:color-mix(in lab,red,red)){.bg-white\/95{background-color:color-mix(in oklab,var(--color-white)95%,transparent)}.voxket-widget-root .bg-yellow-50{background-color:var(--color-yellow-50)}.voxket-widget-root .bg-gradient-to-b{--tw-gradient-position:to bottom in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.voxket-widget-root .bg-gradient-to-br{--tw-gradient-position:to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.voxket-widget-root .bg-gradient-to-r{--tw-gradient-position:to right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.voxket-widget-root .bg-gradient-to-tr{--tw-gradient-position:to top right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.voxket-widget-root .bg-\[radial-gradient\(ellipse_at_center\, .voxket-widget-root _var\(--tw-gradient-stops\)\)\]{background-image:radial-gradient(ellipse at center,var(--tw-gradient-stops))}.voxket-widget-root .from-\[\#3B82F6\]{--tw-gradient-from:#3b82f6;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-\[\#3B82F6\]\/15{--tw-gradient-from:oklab(62.3083% -.0332476 -.185052/.15);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-\[\#8B5CF6\]{--tw-gradient-from:#8b5cf6;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-\[\#8B5CF6\]\/25{--tw-gradient-from:oklab(60.5631% .0845415 -.201932/.25);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-\[\#10B981\]{--tw-gradient-from:#10b981;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-\[\#171727\]{--tw-gradient-from:#171727;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-\[\#171727\]\/90{--tw-gradient-from:oklab(21.3014% .00727232 -.0304822/.9);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-\[\#181825\]{--tw-gradient-from:#181825;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-\[\#EC4899\]{--tw-gradient-from:#ec4899;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-\[\#EC4899\]\/20{--tw-gradient-from:oklab(65.592% .210729 -.0210022/.2);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-black{--tw-gradient-from:var(--color-black);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-black\/90{--tw-gradient-from:#000000e6}@supports (color:color-mix(in lab,red,red)){.from-black\/90{--tw-gradient-from:color-mix(in oklab,var(--color-black)90%,transparent)}.voxket-widget-root .from-black\/90{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-blue-500{--tw-gradient-from:var(--color-blue-500);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-blue-500\/5{--tw-gradient-from:#3080ff0d}@supports (color:color-mix(in lab,red,red)){.from-blue-500\/5{--tw-gradient-from:color-mix(in oklab,var(--color-blue-500)5%,transparent)}.voxket-widget-root .from-blue-500\/5{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-blue-600{--tw-gradient-from:var(--color-blue-600);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-gray-400{--tw-gradient-from:var(--color-gray-400);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-gray-500{--tw-gradient-from:var(--color-gray-500);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-gray-500\/8{--tw-gradient-from:#6a728214}@supports (color:color-mix(in lab,red,red)){.from-gray-500\/8{--tw-gradient-from:color-mix(in oklab,var(--color-gray-500)8%,transparent)}.voxket-widget-root .from-gray-500\/8{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-gray-600{--tw-gradient-from:var(--color-gray-600);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-gray-600\/10{--tw-gradient-from:#4a55651a}@supports (color:color-mix(in lab,red,red)){.from-gray-600\/10{--tw-gradient-from:color-mix(in oklab,var(--color-gray-600)10%,transparent)}.voxket-widget-root .from-gray-600\/10{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-gray-800\/20{--tw-gradient-from:#1e293933}@supports (color:color-mix(in lab,red,red)){.from-gray-800\/20{--tw-gradient-from:color-mix(in oklab,var(--color-gray-800)20%,transparent)}.voxket-widget-root .from-gray-800\/20{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-pink-500{--tw-gradient-from:var(--color-pink-500);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-pink-500\/8{--tw-gradient-from:#f6339a14}@supports (color:color-mix(in lab,red,red)){.from-pink-500\/8{--tw-gradient-from:color-mix(in oklab,var(--color-pink-500)8%,transparent)}.voxket-widget-root .from-pink-500\/8{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-purple-500\/10{--tw-gradient-from:#ac4bff1a}@supports (color:color-mix(in lab,red,red)){.from-purple-500\/10{--tw-gradient-from:color-mix(in oklab,var(--color-purple-500)10%,transparent)}.voxket-widget-root .from-purple-500\/10{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-white{--tw-gradient-from:var(--color-white);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .from-white\/90{--tw-gradient-from:#ffffffe6}@supports (color:color-mix(in lab,red,red)){.from-white\/90{--tw-gradient-from:color-mix(in oklab,var(--color-white)90%,transparent)}.voxket-widget-root .from-white\/90{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .via-\[\#8B5CF6\]{--tw-gradient-via:#8b5cf6;--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-via)var(--tw-gradient-via-position),var(--tw-gradient-to)var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.voxket-widget-root .via-gray-200{--tw-gradient-via:var(--color-gray-200);--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-via)var(--tw-gradient-via-position),var(--tw-gradient-to)var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.voxket-widget-root .via-purple-600{--tw-gradient-via:var(--color-purple-600);--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-via)var(--tw-gradient-via-position),var(--tw-gradient-to)var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.voxket-widget-root .via-transparent{--tw-gradient-via:transparent;--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-via)var(--tw-gradient-via-position),var(--tw-gradient-to)var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.voxket-widget-root .to-\[\#8B5CF6\]{--tw-gradient-to:#8b5cf6;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-\[\#12121F\]{--tw-gradient-to:#12121f;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-\[\#059669\]{--tw-gradient-to:#059669;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-\[\#232336\]{--tw-gradient-to:#232336;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-\[\#EC4899\]{--tw-gradient-to:#ec4899;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-gray-50{--tw-gradient-to:var(--color-gray-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-gray-300{--tw-gradient-to:var(--color-gray-300);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-gray-500{--tw-gradient-to:var(--color-gray-500);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-gray-600{--tw-gradient-to:var(--color-gray-600);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-gray-700{--tw-gradient-to:var(--color-gray-700);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-gray-900{--tw-gradient-to:var(--color-gray-900);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-pink-600{--tw-gradient-to:var(--color-pink-600);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-purple-500{--tw-gradient-to:var(--color-purple-500);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-purple-600{--tw-gradient-to:var(--color-purple-600);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .to-transparent{--tw-gradient-to:transparent;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .bg-clip-text{-webkit-background-clip:text;background-clip:text}.voxket-widget-root .bg-repeat{background-repeat:repeat}.voxket-widget-root .mask-no-clip{-webkit-mask-clip:no-clip;mask-clip:no-clip}.voxket-widget-root .mask-repeat{-webkit-mask-repeat:repeat;mask-repeat:repeat}.voxket-widget-root .object-cover{-o-object-fit:cover;object-fit:cover}.voxket-widget-root .p-0{padding:calc(var(--spacing)*0)}.voxket-widget-root .p-1{padding:calc(var(--spacing)*1)}.voxket-widget-root .p-2{padding:calc(var(--spacing)*2)}.voxket-widget-root .p-3{padding:calc(var(--spacing)*3)}.voxket-widget-root .p-4{padding:calc(var(--spacing)*4)}.voxket-widget-root .p-6{padding:calc(var(--spacing)*6)}.voxket-widget-root .p-8{padding:calc(var(--spacing)*8)}.voxket-widget-root .px-0{padding-inline:calc(var(--spacing)*0)}.voxket-widget-root .px-1{padding-inline:calc(var(--spacing)*1)}.voxket-widget-root .px-1\.5{padding-inline:calc(var(--spacing)*1.5)}.voxket-widget-root .px-2{padding-inline:calc(var(--spacing)*2)}.voxket-widget-root .px-2\.5{padding-inline:calc(var(--spacing)*2.5)}.voxket-widget-root .px-3{padding-inline:calc(var(--spacing)*3)}.voxket-widget-root .px-4{padding-inline:calc(var(--spacing)*4)}.voxket-widget-root .px-5{padding-inline:calc(var(--spacing)*5)}.voxket-widget-root .px-6{padding-inline:calc(var(--spacing)*6)}.voxket-widget-root .px-8{padding-inline:calc(var(--spacing)*8)}.voxket-widget-root .px-10{padding-inline:calc(var(--spacing)*10)}.voxket-widget-root .py-1{padding-block:calc(var(--spacing)*1)}.voxket-widget-root .py-1\.5{padding-block:calc(var(--spacing)*1.5)}.voxket-widget-root .py-2{padding-block:calc(var(--spacing)*2)}.voxket-widget-root .py-3{padding-block:calc(var(--spacing)*3)}.voxket-widget-root .py-4{padding-block:calc(var(--spacing)*4)}.voxket-widget-root .py-8{padding-block:calc(var(--spacing)*8)}.voxket-widget-root .py-12{padding-block:calc(var(--spacing)*12)}.voxket-widget-root .pt-3{padding-top:calc(var(--spacing)*3)}.voxket-widget-root .pt-5{padding-top:calc(var(--spacing)*5)}.voxket-widget-root .pr-8{padding-right:calc(var(--spacing)*8)}.voxket-widget-root .pb-2{padding-bottom:calc(var(--spacing)*2)}.voxket-widget-root .pb-3{padding-bottom:calc(var(--spacing)*3)}.voxket-widget-root .pb-4{padding-bottom:calc(var(--spacing)*4)}.voxket-widget-root .pl-1{padding-left:calc(var(--spacing)*1)}.voxket-widget-root .pl-2{padding-left:calc(var(--spacing)*2)}.voxket-widget-root .text-center{text-align:center}.voxket-widget-root .text-end{text-align:end}.voxket-widget-root .text-left{text-align:left}.voxket-widget-root .text-right{text-align:right}.voxket-widget-root .font-mono{font-family:var(--font-mono)}.voxket-widget-root .text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.voxket-widget-root .text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.voxket-widget-root .text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.voxket-widget-root .text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.voxket-widget-root .text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.voxket-widget-root .text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.voxket-widget-root .text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.voxket-widget-root .leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.voxket-widget-root .leading-snug{--tw-leading:var(--leading-snug);line-height:var(--leading-snug)}.voxket-widget-root .leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.voxket-widget-root .font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.voxket-widget-root .font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.voxket-widget-root .font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.voxket-widget-root .tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.voxket-widget-root .tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.voxket-widget-root .text-wrap{text-wrap:wrap}.voxket-widget-root .break-words{overflow-wrap:break-word}.voxket-widget-root .text-clip{text-overflow:clip}.voxket-widget-root .text-ellipsis{text-overflow:ellipsis}.voxket-widget-root .whitespace-nowrap{white-space:nowrap}.voxket-widget-root .whitespace-pre-line{white-space:pre-line}.voxket-widget-root .whitespace-pre-wrap{white-space:pre-wrap}.voxket-widget-root .text-black{color:var(--color-black)}.voxket-widget-root .text-blue-300{color:var(--color-blue-300)}.voxket-widget-root .text-blue-400{color:var(--color-blue-400)}.voxket-widget-root .text-blue-500{color:var(--color-blue-500)}.voxket-widget-root .text-blue-600{color:var(--color-blue-600)}.voxket-widget-root .text-blue-700{color:var(--color-blue-700)}.voxket-widget-root .text-blue-800{color:var(--color-blue-800)}.voxket-widget-root .text-gray-200{color:var(--color-gray-200)}.voxket-widget-root .text-gray-300{color:var(--color-gray-300)}.voxket-widget-root .text-gray-400{color:var(--color-gray-400)}.voxket-widget-root .text-gray-500{color:var(--color-gray-500)}.voxket-widget-root .text-gray-600{color:var(--color-gray-600)}.voxket-widget-root .text-gray-700{color:var(--color-gray-700)}.voxket-widget-root .text-gray-800{color:var(--color-gray-800)}.voxket-widget-root .text-gray-900{color:var(--color-gray-900)}.voxket-widget-root .text-green-700{color:var(--color-green-700)}.voxket-widget-root .text-inherit{color:inherit}.voxket-widget-root .text-red-400{color:var(--color-red-400)}.voxket-widget-root .text-red-500{color:var(--color-red-500)}.voxket-widget-root .text-red-600{color:var(--color-red-600)}.voxket-widget-root .text-red-700{color:var(--color-red-700)}.voxket-widget-root .text-transparent{color:#0000}.voxket-widget-root .text-white{color:var(--color-white)}.voxket-widget-root .text-yellow-400{color:var(--color-yellow-400)}.voxket-widget-root .text-yellow-700{color:var(--color-yellow-700)}.voxket-widget-root .capitalize{text-transform:capitalize}.voxket-widget-root .lowercase{text-transform:lowercase}.voxket-widget-root .normal-case{text-transform:none}.voxket-widget-root .uppercase{text-transform:uppercase}.voxket-widget-root .italic{font-style:italic}.voxket-widget-root .not-italic{font-style:normal}.voxket-widget-root .diagonal-fractions{--tw-numeric-fraction:diagonal-fractions;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.voxket-widget-root .lining-nums{--tw-numeric-figure:lining-nums;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.voxket-widget-root .oldstyle-nums{--tw-numeric-figure:oldstyle-nums;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.voxket-widget-root .ordinal{--tw-ordinal:ordinal;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.voxket-widget-root .proportional-nums{--tw-numeric-spacing:proportional-nums;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.voxket-widget-root .slashed-zero{--tw-slashed-zero:slashed-zero;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.voxket-widget-root .stacked-fractions{--tw-numeric-fraction:stacked-fractions;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.voxket-widget-root .tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.voxket-widget-root .normal-nums{font-variant-numeric:normal}.voxket-widget-root .line-through{text-decoration-line:line-through}.voxket-widget-root .no-underline{text-decoration-line:none}.voxket-widget-root .overline{text-decoration-line:overline}.voxket-widget-root .underline{text-decoration-line:underline}.voxket-widget-root .underline-offset-4{text-underline-offset:4px}.voxket-widget-root .antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.voxket-widget-root .subpixel-antialiased{-webkit-font-smoothing:auto;-moz-osx-font-smoothing:auto}.voxket-widget-root .placeholder-gray-400::-moz-placeholder{color:var(--color-gray-400)}.voxket-widget-root .placeholder-gray-400::placeholder{color:var(--color-gray-400)}.voxket-widget-root .placeholder-gray-500::-moz-placeholder{color:var(--color-gray-500)}.voxket-widget-root .placeholder-gray-500::placeholder{color:var(--color-gray-500)}.voxket-widget-root .opacity-0{opacity:0}.voxket-widget-root .opacity-15{opacity:.15}.voxket-widget-root .opacity-20{opacity:.2}.voxket-widget-root .opacity-30{opacity:.3}.voxket-widget-root .opacity-40{opacity:.4}.voxket-widget-root .opacity-50{opacity:.5}.voxket-widget-root .opacity-60{opacity:.6}.voxket-widget-root .opacity-70{opacity:.7}.voxket-widget-root .opacity-80{opacity:.8}.voxket-widget-root .opacity-100{opacity:1}.voxket-widget-root .shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a),0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .\!ring-0{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(0px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor)!important;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)!important}.voxket-widget-root .inset-ring{--tw-inset-ring-shadow:inset 0 0 0 1px var(--tw-inset-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .shadow-black\/40{--tw-shadow-color:#0006}@supports (color:color-mix(in lab,red,red)){.shadow-black\/40{--tw-shadow-color:color-mix(in oklab,color-mix(in oklab,var(--color-black)40%,transparent)var(--tw-shadow-alpha),transparent)}.voxket-widget-root .outline-hidden{--tw-outline-style:none;outline-style:none}@media (forced-colors:active){.outline-hidden{outline-offset:2px;outline:2px solid #0000}.voxket-widget-root .outline{outline-style:var(--tw-outline-style);outline-width:1px}.voxket-widget-root .blur{--tw-blur:blur(8px);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.voxket-widget-root .blur-2xl{--tw-blur:blur(var(--blur-2xl));filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.voxket-widget-root .blur-sm{--tw-blur:blur(var(--blur-sm));filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.voxket-widget-root .blur-xl{--tw-blur:blur(var(--blur-xl));filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.voxket-widget-root .drop-shadow{--tw-drop-shadow-size:drop-shadow(0 1px 2px var(--tw-drop-shadow-color,#0000001a))drop-shadow(0 1px 1px var(--tw-drop-shadow-color,#0000000f));--tw-drop-shadow:drop-shadow(0 1px 2px #0000001a)drop-shadow(0 1px 1px #0000000f);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.voxket-widget-root .\!filter{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)!important}.voxket-widget-root .filter{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.voxket-widget-root .filter\!{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)!important}.voxket-widget-root .backdrop-blur{--tw-backdrop-blur:blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.voxket-widget-root .backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.voxket-widget-root .backdrop-blur-md{--tw-backdrop-blur:blur(var(--blur-md));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.voxket-widget-root .backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.voxket-widget-root .backdrop-blur-xl{--tw-backdrop-blur:blur(var(--blur-xl));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.voxket-widget-root .backdrop-grayscale{--tw-backdrop-grayscale:grayscale(100%);-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.voxket-widget-root .backdrop-invert{--tw-backdrop-invert:invert(100%);-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.voxket-widget-root .backdrop-sepia{--tw-backdrop-sepia:sepia(100%);-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.voxket-widget-root .backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.voxket-widget-root .transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.voxket-widget-root .transition\!{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events!important;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function))!important;transition-duration:var(--tw-duration,var(--default-transition-duration))!important}.voxket-widget-root .transition-\[color\, .voxket-widget-root border\, .voxket-widget-root background-color\]{transition-property:color,border,background-color;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.voxket-widget-root .transition-\[height\]{transition-property:height;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.voxket-widget-root .transition-\[opacity\, .voxket-widget-root translate\]{transition-property:opacity,translate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.voxket-widget-root .transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.voxket-widget-root .transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.voxket-widget-root .transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.voxket-widget-root .delay-200{transition-delay:.2s}.voxket-widget-root .duration-150{--tw-duration:.15s;transition-duration:.15s}.voxket-widget-root .duration-200{--tw-duration:.2s;transition-duration:.2s}.voxket-widget-root .duration-250{--tw-duration:.25s;transition-duration:.25s}.voxket-widget-root .duration-300{--tw-duration:.3s;transition-duration:.3s}.voxket-widget-root .duration-700{--tw-duration:.7s;transition-duration:.7s}.voxket-widget-root .ease-in{--tw-ease:var(--ease-in);transition-timing-function:var(--ease-in)}.voxket-widget-root .ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.voxket-widget-root .ease-linear{--tw-ease:linear;transition-timing-function:linear}.voxket-widget-root .ease-out{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}.voxket-widget-root .\!outline-none{--tw-outline-style:none!important;outline-style:none!important}.voxket-widget-root .outline-none{--tw-outline-style:none;outline-style:none}.voxket-widget-root .select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.voxket-widget-root :where(.divide-x-reverse>:not(:last-child)){--tw-divide-x-reverse:1}.voxket-widget-root .ring-inset{--tw-ring-inset:inset}@media (hover:hover){.group-hover\:scale-\[1\.02\]:is(:where(.group):hover *){scale:1.02}.voxket-widget-root .group-hover\:opacity-100:is(:where(.group):hover *){opacity:1}.voxket-widget-root .group-data-\[state\=off\]\/track\:bg-white:is(:where(.group\/track)[data-state=off] *), .voxket-widget-root .group-data-\[state\=on\]\/track\:bg-white:is(:where(.group\/track)[data-state=on] *){background-color:var(--color-white)}.voxket-widget-root .focus-within\:border-blue-500\/50:focus-within{border-color:#3080ff80}@supports (color:color-mix(in lab,red,red)){.focus-within\:border-blue-500\/50:focus-within{border-color:color-mix(in oklab,var(--color-blue-500)50%,transparent)}.voxket-widget-root .focus-within\:shadow-lg:focus-within{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .focus-within\:ring-2:focus-within{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(2px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .focus-within\:ring-blue-500\/30:focus-within{--tw-ring-color:#3080ff4d}@supports (color:color-mix(in lab,red,red)){.focus-within\:ring-blue-500\/30:focus-within{--tw-ring-color:color-mix(in oklab,var(--color-blue-500)30%,transparent)}@media (hover:hover){.hover\:scale-105:hover{--tw-scale-x:105%;--tw-scale-y:105%;--tw-scale-z:105%;scale:var(--tw-scale-x)var(--tw-scale-y)}.voxket-widget-root .hover\:border-gray-300:hover{border-color:var(--color-gray-300)}.voxket-widget-root .hover\:bg-\[\#2563EB\]:hover{background-color:#2563eb}.voxket-widget-root .hover\:bg-black\/10:hover{background-color:#0000001a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-black\/10:hover{background-color:color-mix(in oklab,var(--color-black)10%,transparent)}.voxket-widget-root .hover\:bg-blue-50:hover{background-color:var(--color-blue-50)}.voxket-widget-root .hover\:bg-blue-600:hover{background-color:var(--color-blue-600)}.voxket-widget-root .hover\:bg-blue-700:hover{background-color:var(--color-blue-700)}.voxket-widget-root .hover\:bg-gray-50:hover{background-color:var(--color-gray-50)}.voxket-widget-root .hover\:bg-gray-100:hover{background-color:var(--color-gray-100)}.voxket-widget-root .hover\:bg-gray-200:hover{background-color:var(--color-gray-200)}.voxket-widget-root .hover\:bg-gray-300:hover{background-color:var(--color-gray-300)}.voxket-widget-root .hover\:bg-gray-600:hover{background-color:var(--color-gray-600)}.voxket-widget-root .hover\:bg-gray-600\/50:hover{background-color:#4a556580}@supports (color:color-mix(in lab,red,red)){.hover\:bg-gray-600\/50:hover{background-color:color-mix(in oklab,var(--color-gray-600)50%,transparent)}.voxket-widget-root .hover\:bg-gray-700:hover{background-color:var(--color-gray-700)}.voxket-widget-root .hover\:bg-gray-700\/50:hover{background-color:#36415380}@supports (color:color-mix(in lab,red,red)){.hover\:bg-gray-700\/50:hover{background-color:color-mix(in oklab,var(--color-gray-700)50%,transparent)}.voxket-widget-root .hover\:bg-gray-800:hover{background-color:var(--color-gray-800)}.voxket-widget-root .hover\:bg-green-600:hover{background-color:var(--color-green-600)}.voxket-widget-root .hover\:bg-green-700:hover{background-color:var(--color-green-700)}.voxket-widget-root .hover\:bg-purple-600:hover{background-color:var(--color-purple-600)}.voxket-widget-root .hover\:bg-red-100:hover{background-color:var(--color-red-100)}.voxket-widget-root .hover\:bg-red-600:hover{background-color:var(--color-red-600)}.voxket-widget-root .hover\:bg-red-700:hover{background-color:var(--color-red-700)}.voxket-widget-root .hover\:bg-red-800\/30:hover{background-color:#9f07124d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-red-800\/30:hover{background-color:color-mix(in oklab,var(--color-red-800)30%,transparent)}.voxket-widget-root .hover\:bg-white\/30:hover{background-color:#ffffff4d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-white\/30:hover{background-color:color-mix(in oklab,var(--color-white)30%,transparent)}.voxket-widget-root .hover\:from-\[\#2563EB\]:hover{--tw-gradient-from:#2563eb;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .hover\:from-blue-600:hover{--tw-gradient-from:var(--color-blue-600);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .hover\:to-\[\#7C3AED\]:hover{--tw-gradient-to:#7c3aed;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .hover\:to-purple-700:hover{--tw-gradient-to:var(--color-purple-700);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.voxket-widget-root .hover\:text-blue-900:hover{color:var(--color-blue-900)}.voxket-widget-root .hover\:text-gray-200:hover{color:var(--color-gray-200)}.voxket-widget-root .hover\:text-gray-300:hover{color:var(--color-gray-300)}.voxket-widget-root .hover\:text-gray-700:hover{color:var(--color-gray-700)}.voxket-widget-root .hover\:text-gray-800:hover{color:var(--color-gray-800)}.voxket-widget-root .hover\:text-white:hover{color:var(--color-white)}.voxket-widget-root .hover\:underline:hover{text-decoration-line:underline}.voxket-widget-root .hover\:shadow-md:hover{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a),0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .hover\:shadow-xl:hover{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a),0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .focus\:border-blue-500:focus{border-color:var(--color-blue-500)}.voxket-widget-root .focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(2px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .focus\:ring-blue-400\/40:focus{--tw-ring-color:#54a2ff66}@supports (color:color-mix(in lab,red,red)){.focus\:ring-blue-400\/40:focus{--tw-ring-color:color-mix(in oklab,var(--color-blue-400)40%,transparent)}.voxket-widget-root .focus\:ring-blue-500:focus{--tw-ring-color:var(--color-blue-500)}.voxket-widget-root .focus\:ring-offset-2:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,)0 0 0 var(--tw-ring-offset-width)var(--tw-ring-offset-color)}.voxket-widget-root .focus\:ring-offset-gray-900:focus{--tw-ring-offset-color:var(--color-gray-900)}.voxket-widget-root .focus\:ring-offset-white:focus{--tw-ring-offset-color:var(--color-white)}.voxket-widget-root .focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.voxket-widget-root .focus-visible\:ring-\[3px\]:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(3px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .active\:scale-95:active{--tw-scale-x:95%;--tw-scale-y:95%;--tw-scale-z:95%;scale:var(--tw-scale-x)var(--tw-scale-y)}.voxket-widget-root .disabled\:pointer-events-none:disabled{pointer-events:none}.voxket-widget-root .disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.voxket-widget-root .disabled\:bg-gray-300:disabled{background-color:var(--color-gray-300)}.voxket-widget-root .disabled\:bg-gray-600:disabled{background-color:var(--color-gray-600)}.voxket-widget-root .disabled\:opacity-50:disabled{opacity:.5}.voxket-widget-root .disabled\:opacity-70:disabled{opacity:.7}.voxket-widget-root .has-\[\>svg\]\:grid-cols-\[calc\(var\(--spacing\)\*4\)_1fr\]:has(>svg){grid-template-columns:calc(var(--spacing)*4)1fr}.voxket-widget-root .has-\[\>svg\]\:gap-x-3:has(>svg){-moz-column-gap:calc(var(--spacing)*3);column-gap:calc(var(--spacing)*3)}.voxket-widget-root .has-\[\>svg\]\:px-2\.5:has(>svg){padding-inline:calc(var(--spacing)*2.5)}.voxket-widget-root .has-\[\>svg\]\:px-3:has(>svg){padding-inline:calc(var(--spacing)*3)}.voxket-widget-root .has-\[\>svg\]\:px-4:has(>svg){padding-inline:calc(var(--spacing)*4)}.voxket-widget-root .aria-invalid\:border-0[aria-invalid=true]{border-style:var(--tw-border-style);border-width:0}.voxket-widget-root .aria-invalid\:ring-0[aria-invalid=true]{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(0px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.voxket-widget-root .data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.voxket-widget-root .data-\[lk-highlighted\=true\]\:bg-\[\#5c64f6\][data-lk-highlighted=true]{background-color:#5c64f6}.voxket-widget-root .data-\[lk-muted\=true\]\:bg-\[\#222222\][data-lk-muted=true]{background-color:#222}.voxket-widget-root .data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y:calc(var(--spacing)*1);translate:var(--tw-translate-x)var(--tw-translate-y)}.voxket-widget-root .data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x:calc(var(--spacing)*-1);translate:var(--tw-translate-x)var(--tw-translate-y)}.voxket-widget-root .data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x:calc(var(--spacing)*1);translate:var(--tw-translate-x)var(--tw-translate-y)}.voxket-widget-root .data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y:calc(var(--spacing)*-1);translate:var(--tw-translate-x)var(--tw-translate-y)}.voxket-widget-root .data-\[size\=default\]\:h-9[data-size=default]{height:calc(var(--spacing)*9)}.voxket-widget-root .data-\[size\=sm\]\:h-8[data-size=sm]{height:calc(var(--spacing)*8)}.voxket-widget-root :is(.\*\:data-\[slot\=select-value\]\:line-clamp-1>*)[data-slot=select-value]{-webkit-line-clamp:1;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.voxket-widget-root :is(.\*\:data-\[slot\=select-value\]\:flex>*)[data-slot=select-value]{display:flex}.voxket-widget-root :is(.\*\:data-\[slot\=select-value\]\:items-center>*)[data-slot=select-value]{align-items:center}.voxket-widget-root :is(.\*\:data-\[slot\=select-value\]\:gap-2>*)[data-slot=select-value]{gap:calc(var(--spacing)*2)}@media (min-width:48rem){.md\:px-0{padding-inline:calc(var(--spacing)*0)}@media (min-width:64rem){.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}@media (prefers-color-scheme:dark){.dark\:border-gray-700{border-color:var(--color-gray-700)}.voxket-widget-root .dark\:bg-gray-900{background-color:var(--color-gray-900)}.voxket-widget-root .dark\:bg-white{background-color:var(--color-white)}.voxket-widget-root .dark\:text-gray-400{color:var(--color-gray-400)}.voxket-widget-root .dark\:text-white{color:var(--color-white)}.voxket-widget-root .dark\:aria-invalid\:ring-0[aria-invalid=true]{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(0px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.voxket-widget-root .\[\&_p\]\:leading-relaxed p{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.voxket-widget-root .\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.voxket-widget-root .\[\&_svg\]\:shrink-0 svg{flex-shrink:0}.voxket-widget-root .\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-4 svg:not([class*=size-]){width:calc(var(--spacing)*4);height:calc(var(--spacing)*4)}.voxket-widget-root :is(.\*\:\[span\]\:last\:flex>*):is(span):last-child{display:flex}.voxket-widget-root :is(.\*\:\[span\]\:last\:items-center>*):is(span):last-child{align-items:center}.voxket-widget-root :is(.\*\:\[span\]\:last\:gap-2>*):is(span):last-child{gap:calc(var(--spacing)*2)}.voxket-widget-root .\[\&\>svg\]\:size-4>svg{width:calc(var(--spacing)*4);height:calc(var(--spacing)*4)}.voxket-widget-root .\[\&\>svg\]\:translate-y-0\.5>svg{--tw-translate-y:calc(var(--spacing)*.5);translate:var(--tw-translate-x)var(--tw-translate-y)}.voxket-widget-root .\[\&\>svg\]\:text-current>svg{color:currentColor}.voxket-widget-root .\[\&\>video\]\:h-\[90px\]>video{height:90px}.voxket-widget-root .\[\&\>video\]\:w-auto>video{width:auto}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-100:oklch(93.6% .032 17.717);--color-red-200:oklch(88.5% .062 18.334);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-red-800:oklch(44.4% .177 26.899);--color-red-900:oklch(39.6% .141 25.723);--color-orange-600:oklch(64.6% .222 41.116);--color-yellow-50:oklch(98.7% .026 102.212);--color-yellow-200:oklch(94.5% .129 101.54);--color-yellow-400:oklch(85.2% .199 91.936);--color-yellow-700:oklch(55.4% .135 66.442);--color-green-50:oklch(98.2% .018 155.826);--color-green-200:oklch(92.5% .084 155.995);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--color-green-700:oklch(52.7% .154 150.069);--color-blue-50:oklch(97% .014 254.604);--color-blue-100:oklch(93.2% .032 255.585);--color-blue-200:oklch(88.2% .059 254.128);--color-blue-300:oklch(80.9% .105 251.813);--color-blue-400:oklch(70.7% .165 254.624);--color-blue-500:oklch(62.3% .214 259.815);--color-blue-600:oklch(54.6% .245 262.881);--color-blue-700:oklch(48.8% .243 264.376);--color-blue-800:oklch(42.4% .199 265.638);--color-blue-900:oklch(37.9% .146 265.522);--color-indigo-600:oklch(51.1% .262 276.966);--color-purple-500:oklch(62.7% .265 303.9);--color-purple-600:oklch(55.8% .288 302.321);--color-purple-700:oklch(49.6% .265 301.924);--color-pink-500:oklch(65.6% .241 354.308);--color-pink-600:oklch(59.2% .249 .584);--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--color-gray-200:oklch(92.8% .006 264.531);--color-gray-300:oklch(87.2% .01 258.338);--color-gray-400:oklch(70.7% .022 261.325);--color-gray-500:oklch(55.1% .027 264.364);--color-gray-600:oklch(44.6% .03 256.802);--color-gray-700:oklch(37.3% .034 259.733);--color-gray-800:oklch(27.8% .033 256.848);--color-gray-900:oklch(21% .034 264.665);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-2xl:42rem;--container-3xl:48rem;--container-4xl:56rem;--container-5xl:64rem;--container-6xl:72rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75/1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--text-3xl:1.875rem;--text-3xl--line-height: 1.2 ;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wider:.05em;--leading-tight:1.25;--leading-snug:1.375;--leading-relaxed:1.625;--radius-sm:.25rem;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--ease-in:cubic-bezier(.4,0,1,1);--ease-out:cubic-bezier(0,0,.2,1);--ease-in-out:cubic-bezier(.4,0,.2,1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2s cubic-bezier(.4,0,.6,1)infinite;--blur-sm:8px;--blur-md:12px;--blur-lg:16px;--blur-xl:24px;--blur-2xl:40px;--aspect-video:16/9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}.voxket-widget-root ::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}.voxket-widget-root hr{height:0;color:inherit;border-top-width:1px}.voxket-widget-root abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}.voxket-widget-root h1, .voxket-widget-root h2, .voxket-widget-root h3, .voxket-widget-root h4, .voxket-widget-root h5, .voxket-widget-root h6{font-size:inherit;font-weight:inherit}.voxket-widget-root a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}.voxket-widget-root b, .voxket-widget-root strong{font-weight:bolder}.voxket-widget-root code, .voxket-widget-root kbd, .voxket-widget-root samp, .voxket-widget-root pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}.voxket-widget-root small{font-size:80%}.voxket-widget-root sub, .voxket-widget-root sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}.voxket-widget-root sub{bottom:-.25em}.voxket-widget-root sup{top:-.5em}.voxket-widget-root table{text-indent:0;border-color:inherit;border-collapse:collapse}.voxket-widget-root :-moz-focusring{outline:auto}.voxket-widget-root progress{vertical-align:baseline}.voxket-widget-root summary{display:list-item}.voxket-widget-root ol, .voxket-widget-root ul, .voxket-widget-root menu{list-style:none}.voxket-widget-root img, .voxket-widget-root svg, .voxket-widget-root video, .voxket-widget-root canvas, .voxket-widget-root audio, .voxket-widget-root iframe, .voxket-widget-root embed, .voxket-widget-root object{vertical-align:middle;display:block}.voxket-widget-root img, .voxket-widget-root video{max-width:100%;height:auto}.voxket-widget-root button, .voxket-widget-root input, .voxket-widget-root select, .voxket-widget-root optgroup, .voxket-widget-root textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}.voxket-widget-root ::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}.voxket-widget-root :where(select:is([multiple], .voxket-widget-root [size])) optgroup{font-weight:bolder}.voxket-widget-root :where(select:is([multiple], .voxket-widget-root [size])) optgroup option{padding-inline-start:20px}.voxket-widget-root ::file-selector-button{margin-inline-end:4px}.voxket-widget-root ::-moz-placeholder{opacity:1}.voxket-widget-root ::placeholder{opacity:1}@supports (not (-webkit-appearance:-apple-pay-button)) or (contain-intrinsic-size:1px){::-moz-placeholder{color:currentColor}.voxket-widget-root ::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::-moz-placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}.voxket-widget-root ::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}.voxket-widget-root textarea{resize:vertical}.voxket-widget-root ::-webkit-search-decoration{-webkit-appearance:none}.voxket-widget-root ::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}.voxket-widget-root ::-webkit-datetime-edit{display:inline-flex}.voxket-widget-root ::-webkit-datetime-edit-fields-wrapper{padding:0}.voxket-widget-root ::-webkit-datetime-edit{padding-block:0}.voxket-widget-root ::-webkit-datetime-edit-year-field{padding-block:0}.voxket-widget-root ::-webkit-datetime-edit-month-field{padding-block:0}.voxket-widget-root ::-webkit-datetime-edit-day-field{padding-block:0}.voxket-widget-root ::-webkit-datetime-edit-hour-field{padding-block:0}.voxket-widget-root ::-webkit-datetime-edit-minute-field{padding-block:0}.voxket-widget-root ::-webkit-datetime-edit-second-field{padding-block:0}.voxket-widget-root ::-webkit-datetime-edit-millisecond-field{padding-block:0}.voxket-widget-root ::-webkit-datetime-edit-meridiem-field{padding-block:0}.voxket-widget-root :-moz-ui-invalid{box-shadow:none}.voxket-widget-root button, .voxket-widget-root input:where([type=button], .voxket-widget-root [type=reset], .voxket-widget-root [type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}.voxket-widget-root ::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}.voxket-widget-root ::-webkit-inner-spin-button{height:auto}.voxket-widget-root ::-webkit-outer-spin-button{height:auto}.voxket-widget-root [hidden]:where(:not([hidden=until-found])){display:none!important}@layer components,utilities;.voxket-widget-root{color-scheme:light dark;color:#ffffffde;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background-color:#0000;border-radius:1rem;font-family:Inter,system-ui,Avenir,Helvetica,Arial,sans-serif;font-weight:400;line-height:1.5}.voxket-widget-root.theme-light{color:#000000de}.voxket-widget-root.theme-dark, .voxket-widget-root.theme-vox{color:#ffffffde}.voxket-widget-root ::-webkit-scrollbar{display:none}.voxket-widget-root .scrollbar-hide{scrollbar-width:none;-ms-overflow-style:none}.voxket-widget-root .scrollbar-hide::-webkit-scrollbar{display:none}.voxket-widget-root .chat-scrollable{scrollbar-width:thin;scrollbar-color:#9b9b9b4d transparent;flex-direction:column;display:flex}.voxket-widget-root .chat-scrollable::-webkit-scrollbar{width:6px;display:block}.voxket-widget-root .chat-scrollable::-webkit-scrollbar-track{background:0 0}.voxket-widget-root .chat-scrollable::-webkit-scrollbar-thumb{background-color:#9b9b9b4d;border-radius:3px}.voxket-widget-root .chat-scrollable::-webkit-scrollbar-thumb:hover{background-color:#9b9b9b80}.voxket-widget-root .chat-messages-container{flex-direction:column;justify-content:flex-end;width:100%;max-width:none;min-height:100%;display:flex}@keyframes pulse-ring{0%{opacity:1;transform:scale(1)}.voxket-widget-root 50%{opacity:.6;transform:scale(1.2)}.voxket-widget-root to{opacity:0;transform:scale(1.4)}@keyframes glow{0%,to{box-shadow:0 0 20px #3b82f680}.voxket-widget-root 50%{box-shadow:0 0 30px #3b82f6cc}.voxket-widget-root .pulse-ring{animation:2s cubic-bezier(.4,0,.6,1) infinite pulse-ring}.voxket-widget-root .mic-glow{animation:2s ease-in-out infinite glow}.voxket-widget-root .animate-spin{animation:1s linear infinite spin}@keyframes spin{to{transform:rotate(360deg)}.voxket-widget-root button{cursor:pointer}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-pan-x{syntax:"*";inherits:false}@property --tw-pan-y{syntax:"*";inherits:false}@property --tw-pinch-zoom{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-space-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"<length-percentage>";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"<length-percentage>";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"<length-percentage>";inherits:false;initial-value:100%}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes pulse{50%{opacity:.5}
7
- `;
8
- document.head.appendChild(style);
9
- console.log('📝 Voxket Widget CSS injected and scoped');
10
- }
11
- })();
12
1
  "use strict";var Dw=Object.defineProperty;var jw=(t,e,n)=>e in t?Dw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var at=(t,e,n)=>jw(t,typeof e!="symbol"?e+"":e,n);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const R=require("react"),bu=require("react-dom"),Wa=require("class-variance-authority"),xu=require("clsx");function R0(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const v=R0(R),qa=R0(bu);function Lw(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var So={exports:{}},vs={};/**
13
2
  * @license React
14
3
  * react-jsx-runtime.production.min.js
@@ -73,9 +62,9 @@ t=0 0\r
73
62
  `},e.getDirection=function(n,i){const r=e.splitLines(n);for(let s=0;s<r.length;s++)switch(r[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[s].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(n){return e.splitLines(n)[0].split(" ")[0].substring(2)},e.isRejected=function(n){return n.split(" ",2)[1]==="0"},e.parseMLine=function(n){const r=e.splitLines(n)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},e.parseOLine=function(n){const r=e.matchPrefix(n,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},e.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;const i=e.splitLines(n);for(let r=0;r<i.length;r++)if(i[r].length<2||i[r].charAt(1)!=="=")return!1;return!0},t.exports=e}(jc)),jc.exports}var Jv=Ak(),Or=pk(Jv),Ik=Bw({__proto__:null,default:Or},[Jv]);function Xo(t){if(!t.RTCIceCandidate||t.RTCIceCandidate&&"foundation"in t.RTCIceCandidate.prototype)return;const e=t.RTCIceCandidate;t.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const r=new e(i),s=Or.parseCandidate(i.candidate);for(const o in s)o in r||Object.defineProperty(r,o,{value:s[o]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new e(i)},t.RTCIceCandidate.prototype=e.prototype,rr(t,"icecandidate",n=>(n.candidate&&Object.defineProperty(n,"candidate",{value:new t.RTCIceCandidate(n.candidate),writable:"false"}),n))}function td(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||rr(t,"icecandidate",e=>{if(e.candidate){const n=Or.parseCandidate(e.candidate.candidate);n.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[n.priority>>24])}return e})}function Qo(t,e){if(!t.RTCPeerConnection)return;"sctp"in t.RTCPeerConnection.prototype||Object.defineProperty(t.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const n=function(a){if(!a||!a.sdp)return!1;const c=Or.splitSections(a.sdp);return c.shift(),c.some(l=>{const d=Or.parseMLine(l);return d&&d.kind==="application"&&d.protocol.indexOf("SCTP")!==-1})},i=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const l=parseInt(c[1],10);return l!==l?-1:l},r=function(a){let c=65536;return e.browser==="firefox"&&(e.version<57?a===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},s=function(a,c){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);const d=Or.matchPrefix(a.sdp,"a=max-message-size:");return d.length>0?l=parseInt(d[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(l=2147483637),l},o=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(n(arguments[0])){const c=i(arguments[0]),l=r(c),d=s(arguments[0],c);let u;l===0&&d===0?u=Number.POSITIVE_INFINITY:l===0||d===0?u=Math.max(l,d):u=Math.min(l,d);const f={};Object.defineProperty(f,"maxMessageSize",{get(){return u}}),this._sctp=f}return o.apply(this,arguments)}}function ea(t){if(!(t.RTCPeerConnection&&"createDataChannel"in t.RTCPeerConnection.prototype))return;function e(i,r){const s=i.send;i.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(i.readyState==="open"&&r.sctp&&c>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return s.apply(i,arguments)}}const n=t.RTCPeerConnection.prototype.createDataChannel;t.RTCPeerConnection.prototype.createDataChannel=function(){const r=n.apply(this,arguments);return e(r,this),r},rr(t,"datachannel",i=>(e(i.channel,i.target),i))}function nd(t){if(!t.RTCPeerConnection||"connectionState"in t.RTCPeerConnection.prototype)return;const e=t.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(n){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),n&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=n)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(n=>{const i=e[n];e[n]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const o=new Event("connectionstatechange",r);s.dispatchEvent(o)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function id(t,e){if(!t.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const n=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(`
74
63
  a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
75
64
  `).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
76
- `);t.RTCSessionDescription&&r instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return n.apply(this,arguments)}}function ta(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function na(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return n.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?n.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>n.apply(this,[o]))})}var Mk=Object.freeze({__proto__:null,removeExtmapAllowMixed:id,shimAddIceCandidateNullOrEmpty:ta,shimConnectionState:nd,shimMaxMessageSize:Qo,shimParameterlessSetLocalDescription:na,shimRTCIceCandidate:Xo,shimRTCIceCandidateRelayProtocol:td,shimSendThrowTypeError:ea});function _k(){let{window:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=wv,i=Pk(t),r={browserDetails:i,commonShim:Mk,extractVersion:Is,disableLog:Tk,disableWarnings:Ek,sdp:Ik};switch(i.browser){case"chrome":if(!$h||!Ql||!e.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(i.version===null)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=$h,ta(t,i),na(t),kv(t,i),Tv(t),Ql(t,i),Ev(t),Iv(t,i),Pv(t),Rv(t),Mv(t,i),Xo(t),td(t),nd(t),Qo(t,i),ea(t),id(t,i);break;case"firefox":if(!Hh||!ed||!e.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=Hh,ta(t,i),na(t),_v(t,i),ed(t,i),Nv(t),jv(t),Ov(t),Dv(t),Lv(t),Vv(t),Fv(t),Uv(t),Bv(t),Xo(t),nd(t),Qo(t,i),ea(t);break;case"safari":if(!zh||!e.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=zh,ta(t,i),na(t),Kv(t),Zv(t),zv(t),$v(t),Hv(t),Gv(t),Wv(t),Yv(t),Xo(t),td(t),Qo(t,i),ea(t),id(t,i);break;default:n("Unsupported browser!");break}return r}_k({window:typeof window>"u"?void 0:window});const Nk=10,Ss="lk_e2ee",Ok="LKFrameEncryptionKey",Dk={sharedKey:!1,ratchetSalt:Ok,ratchetWindowSize:8,failureTolerance:Nk,keyringSize:16};var ui;(function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"})(ui||(ui={}));var qh;(function(t){t.KeyRatcheted="keyRatcheted"})(qh||(qh={}));var di;(function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"})(di||(di={}));var Kh;(function(t){t.Error="cryptorError"})(Kh||(Kh={}));function jk(){return Lk()||rd()}function rd(){return typeof window.RTCRtpScriptTransform<"u"}function Lk(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class NL extends Nn.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(n,i,r)=>{Ce.debug("key ratcheted event received",{ratchetResult:n,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Dk),e),this.on(ui.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,n,i){const r={key:e,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(n??"shared","-").concat(i??0),r),this.emit(ui.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,n){this.emit(ui.RatchetRequest,e,n)}}class ki extends Error{constructor(e,n){super(n||"an error has occured"),this.name="LiveKitError",this.code=e}}var Te;(function(t){t[t.NotAllowed=0]="NotAllowed",t[t.ServerUnreachable=1]="ServerUnreachable",t[t.InternalError=2]="InternalError",t[t.Cancelled=3]="Cancelled",t[t.LeaveRequest=4]="LeaveRequest",t[t.Timeout=5]="Timeout"})(Te||(Te={}));class Ue extends ki{constructor(e,n,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=Te[n]}}class Iu extends ki{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Wn extends ki{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Vk extends ki{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class ht extends ki{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class sd extends ki{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Gh extends ki{constructor(e,n){super(15,e),this.name="PublishTrackError",this.status=n}}class Zh extends ki{constructor(e,n){super(15,e),this.reason=n,this.reasonName=typeof n=="string"?n:Ru[n]}}var Ca;(function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"})(Ca||(Ca={}));(function(t){function e(n){if(n&&"name"in n)return n.name==="NotFoundError"||n.name==="DevicesNotFoundError"?t.NotFound:n.name==="NotAllowedError"||n.name==="PermissionDeniedError"?t.PermissionDenied:n.name==="NotReadableError"||n.name==="TrackStartError"?t.DeviceInUse:t.Other}t.getFailure=e})(Ca||(Ca={}));var Yh;(function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"})(Yh||(Yh={}));var U;(function(t){t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting",t.Reconnected="reconnected",t.Disconnected="disconnected",t.ConnectionStateChanged="connectionStateChanged",t.Moved="moved",t.MediaDevicesChanged="mediaDevicesChanged",t.ParticipantConnected="participantConnected",t.ParticipantDisconnected="participantDisconnected",t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalAudioSilenceDetected="localAudioSilenceDetected",t.ActiveSpeakersChanged="activeSpeakersChanged",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.ParticipantAttributesChanged="participantAttributesChanged",t.ParticipantActive="participantActive",t.RoomMetadataChanged="roomMetadataChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.AudioPlaybackStatusChanged="audioPlaybackChanged",t.VideoPlaybackStatusChanged="videoPlaybackChanged",t.MediaDevicesError="mediaDevicesError",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.SignalConnected="signalConnected",t.RecordingStatusChanged="recordingStatusChanged",t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ActiveDeviceChanged="activeDeviceChanged",t.ChatMessage="chatMessage",t.LocalTrackSubscribed="localTrackSubscribed",t.MetricsReceived="metricsReceived"})(U||(U={}));var Z;(function(t){t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.IsSpeakingChanged="isSpeakingChanged",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.MediaDevicesError="mediaDevicesError",t.AudioStreamAcquired="audioStreamAcquired",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.PCTrackAdded="pcTrackAdded",t.AttributesChanged="attributesChanged",t.LocalTrackSubscribed="localTrackSubscribed",t.ChatMessage="chatMessage",t.Active="active"})(Z||(Z={}));var ae;(function(t){t.TransportsCreated="transportsCreated",t.Connected="connected",t.Disconnected="disconnected",t.Resuming="resuming",t.Resumed="resumed",t.Restarting="restarting",t.Restarted="restarted",t.SignalResumed="signalResumed",t.SignalRestarted="signalRestarted",t.Closing="closing",t.MediaTrackAdded="mediaTrackAdded",t.ActiveSpeakersUpdate="activeSpeakersUpdate",t.DataPacketReceived="dataPacketReceived",t.RTPVideoMapUpdate="rtpVideoMapUpdate",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ParticipantUpdate="participantUpdate",t.RoomUpdate="roomUpdate",t.SpeakersChanged="speakersChanged",t.StreamStateChanged="streamStateChanged",t.ConnectionQualityUpdate="connectionQualityUpdate",t.SubscriptionError="subscriptionError",t.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",t.RemoteMute="remoteMute",t.SubscribedQualityUpdate="subscribedQualityUpdate",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackSubscribed="localTrackSubscribed",t.Offline="offline",t.SignalRequestResponse="signalRequestResponse",t.SignalConnected="signalConnected",t.RoomMoved="roomMoved"})(ae||(ae={}));var re;(function(t){t.Message="message",t.Muted="muted",t.Unmuted="unmuted",t.Restarted="restarted",t.Ended="ended",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",t.UpdateSettings="updateSettings",t.UpdateSubscription="updateSubscription",t.AudioPlaybackStarted="audioPlaybackStarted",t.AudioPlaybackFailed="audioPlaybackFailed",t.AudioSilenceDetected="audioSilenceDetected",t.VisibilityChanged="visibilityChanged",t.VideoDimensionsChanged="videoDimensionsChanged",t.VideoPlaybackStarted="videoPlaybackStarted",t.VideoPlaybackFailed="videoPlaybackFailed",t.ElementAttached="elementAttached",t.ElementDetached="elementDetached",t.UpstreamPaused="upstreamPaused",t.UpstreamResumed="upstreamResumed",t.SubscriptionPermissionChanged="subscriptionPermissionChanged",t.SubscriptionStatusChanged="subscriptionStatusChanged",t.SubscriptionFailed="subscriptionFailed",t.TrackProcessorUpdate="trackProcessorUpdate",t.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",t.TranscriptionReceived="transcriptionReceived",t.TimeSyncUpdate="timeSyncUpdate",t.PreConnectBufferFlushed="preConnectBufferFlushed"})(re||(re={}));function Fk(t){return typeof t>"u"?t:typeof structuredClone=="function"?typeof t=="object"&&t!==null?structuredClone(Object.assign({},t)):structuredClone(t):JSON.parse(JSON.stringify(t))}const Uk=/version\/(\d+(\.?_?\d+)+)/i;let Lc;function $t(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const n=navigator.userAgent.toLowerCase();if(Lc===void 0||e){const i=Bk.find(r=>{let{test:s}=r;return s.test(n)});Lc=i==null?void 0:i.describe(n)}return Lc}const Bk=[{test:/firefox|iceweasel|fxios/i,describe(t){return{name:"Firefox",version:ia(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Vc(t)}}},{test:/chrom|crios|crmo/i,describe(t){return{name:"Chrome",version:ia(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Vc(t)}}},{test:/safari|applewebkit/i,describe(t){return{name:"Safari",version:ia(Uk,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:Vc(t)}}}];function ia(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(t);return i&&i.length>=n&&i[n]||""}function Vc(t){return t.includes("mac os")?ia(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}var $k="2.13.8";const Hk=$k,zk=16;class bt{}bt.setTimeout=function(){return setTimeout(...arguments)};bt.setInterval=function(){return setInterval(...arguments)};bt.clearTimeout=function(){return clearTimeout(...arguments)};bt.clearInterval=function(){return clearInterval(...arguments)};const Wk=5e3,ws=[];var Jt;(function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"})(Jt||(Jt={}));class V extends Nn.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=V.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Ce,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Wk):this.handleAppVisibilityChanged()},this.log=Gn((r=i.loggerName)!==null&&r!==void 0?r:fn.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=V.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),we(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let n="audio";this.kind===V.Kind.Video&&(n="video"),this.attachedElements.length===0&&this.kind===V.Kind.Video&&this.addAppVisibilityListener(),e||(n==="audio"&&(ws.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&ws.splice(ws.indexOf(e),1)),e||(e=document.createElement(n))),this.attachedElements.includes(e)||this.attachedElements.push(e),kr(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?re.AudioPlaybackStarted:re.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?re.AudioPlaybackFailed:re.VideoPlaybackFailed,s):s.name==="AbortError"?Ce.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):Ce.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&i.some(o=>o.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(re.ElementAttached,e),e}detach(e){try{if(e){Dr(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(re.ElementDetached,e)),e}const n=[];return this.attachedElements.forEach(i=>{Dr(this.mediaStreamTrack,i),n.push(i),this.recycleElement(i),this.emit(re.ElementDetached,i)}),this.attachedElements=[],n}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Gn(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let n=!0;e.pause(),ws.forEach(i=>{i.parentElement||(n=!1)}),n&&ws.push(e)}}handleAppVisibilityChanged(){return A(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===V.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Ot()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ot()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function kr(t,e){let n;e.srcObject instanceof MediaStream?n=e.srcObject:n=new MediaStream;let i;t.kind==="audio"?i=n.getAudioTracks():i=n.getVideoTracks(),i.includes(t)||(i.forEach(r=>{n.removeTrack(r)}),n.addTrack(t)),(!Xi()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=n.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==n&&(e.srcObject=n,(Xi()||qr())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=n,e.play().catch(()=>{})},0))}function Dr(t,e){if(e.srcObject instanceof MediaStream){const n=e.srcObject;n.removeTrack(t),n.getTracks().length>0?e.srcObject=n:e.srcObject=null}}(function(t){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=t.Kind||(t.Kind={}));let n;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(n=t.Source||(t.Source={}));let i;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(i=t.StreamState||(t.StreamState={}));function r(l){switch(l){case e.Audio:return cn.AUDIO;case e.Video:return cn.VIDEO;default:return cn.DATA}}t.kindToProto=r;function s(l){switch(l){case cn.AUDIO:return e.Audio;case cn.VIDEO:return e.Video;default:return e.Unknown}}t.kindFromProto=s;function o(l){switch(l){case n.Camera:return lt.CAMERA;case n.Microphone:return lt.MICROPHONE;case n.ScreenShare:return lt.SCREEN_SHARE;case n.ScreenShareAudio:return lt.SCREEN_SHARE_AUDIO;default:return lt.UNKNOWN}}t.sourceToProto=o;function a(l){switch(l){case lt.CAMERA:return n.Camera;case lt.MICROPHONE:return n.Microphone;case lt.SCREEN_SHARE:return n.ScreenShare;case lt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}t.sourceFromProto=a;function c(l){switch(l){case Gl.ACTIVE:return i.Active;case Gl.PAUSED:return i.Paused;default:return i.Unknown}}t.streamStateFromProto=c})(V||(V={}));class je{constructor(e,n,i,r,s){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(n!==void 0&&i!==void 0)this.width=e,this.height=n,this.aspectRatio=e/n,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const qk=["vp8","h264"],Kk=["vp8","h264","vp9","av1"];function Gk(t){return!!qk.find(e=>e===t)}var Jh;(function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"})(Jh||(Jh={}));var od;(function(t){t.telephone={maxBitrate:12e3},t.speech={maxBitrate:24e3},t.music={maxBitrate:48e3},t.musicStereo={maxBitrate:64e3},t.musicHighQuality={maxBitrate:96e3},t.musicHighQualityStereo={maxBitrate:128e3}})(od||(od={}));const zs={h90:new je(160,90,9e4,20),h180:new je(320,180,16e4,20),h216:new je(384,216,18e4,20),h360:new je(640,360,45e4,20),h540:new je(960,540,8e5,25),h720:new je(1280,720,17e5,30),h1080:new je(1920,1080,3e6,30),h1440:new je(2560,1440,5e6,30),h2160:new je(3840,2160,8e6,30)},ad={h120:new je(160,120,7e4,20),h180:new je(240,180,125e3,20),h240:new je(320,240,14e4,20),h360:new je(480,360,33e4,20),h480:new je(640,480,5e5,20),h540:new je(720,540,6e5,25),h720:new je(960,720,13e5,30),h1080:new je(1440,1080,23e5,30),h1440:new je(1920,1440,38e5,30)},Mu={h360fps3:new je(640,360,2e5,3,"medium"),h360fps15:new je(640,360,4e5,15,"medium"),h720fps5:new je(1280,720,8e5,5,"medium"),h720fps15:new je(1280,720,15e5,15,"medium"),h720fps30:new je(1280,720,2e6,30,"medium"),h1080fps15:new je(1920,1080,25e5,15,"medium"),h1080fps30:new je(1920,1080,5e6,30,"medium"),original:new je(0,0,7e6,30,"medium")},Zk="|",Xh="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Yk(t){const e=t.split(Zk);return e.length>1?[e[0],t.substr(e[0].length+1)]:[t,""]}function jt(t){return A(this,void 0,void 0,function*(){return new Promise(e=>bt.setTimeout(e,t))})}function cd(){return"addTransceiver"in RTCPeerConnection.prototype}function ld(){return"addTrack"in RTCPeerConnection.prototype}function Jk(){if(!("getCapabilities"in RTCRtpSender)||Xi())return!1;const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType==="video/AV1"){e=!0;break}}return e}function Xk(){if(!("getCapabilities"in RTCRtpSender)||qr())return!1;if(Xi()){const n=$t();if(n!=null&&n.version&&mi(n.version,"16")<0)return!1}const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType==="video/VP9"){e=!0;break}}return e}function Kn(t){return t==="av1"||t==="vp9"}function dd(t){return document?(t||(t=document.createElement("audio")),"setSinkId"in t):!1}function Qk(){return typeof RTCPeerConnection>"u"?!1:cd()||ld()}function qr(){var t;return((t=$t())===null||t===void 0?void 0:t.name)==="Firefox"}function Xi(){var t;return((t=$t())===null||t===void 0?void 0:t.name)==="Safari"}function Qh(){const t=$t();return(t==null?void 0:t.name)==="Safari"||(t==null?void 0:t.os)==="iOS"}function eT(){const t=$t();return(t==null?void 0:t.name)==="Safari"&&t.version.startsWith("17.")}function tT(t){return t||(t=$t()),(t==null?void 0:t.name)==="Safari"&&mi(t.version,"18.3")>0}function Xv(){var t,e;return Ot()?(e=(t=navigator.userAgentData)===null||t===void 0?void 0:t.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function nT(){const t=$t(),e="17.2";if(t)return t.name!=="Safari"&&t.os!=="iOS"||t.os==="iOS"&&t.osVersion&&mi(e,t.osVersion)>=0?!0:t.name==="Safari"&&mi(e,t.version)>=0}function Ot(){return typeof document<"u"}function In(){return navigator.product=="ReactNative"}function ud(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function Qv(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ey(){if(!In())return;let t=Qv();if(t)return t.platform}function em(){if(Ot())return window.devicePixelRatio;if(In()){let t=Qv();if(t)return t.devicePixelRatio}return 1}function mi(t,e){const n=t.split("."),i=e.split("."),r=Math.min(n.length,i.length);for(let s=0;s<r;++s){const o=parseInt(n[s],10),a=parseInt(i[s],10);if(o>a)return 1;if(o<a)return-1;if(s===r-1&&o===a)return 0}return t===""&&e!==""?-1:e===""?1:n.length==i.length?0:n.length<i.length?-1:1}function iT(t){for(const e of t)e.target.handleResize(e)}function rT(t){for(const e of t)e.target.handleVisibilityChanged(e)}let Fc=null;const tm=()=>(Fc||(Fc=new ResizeObserver(iT)),Fc);let Uc=null;const nm=()=>(Uc||(Uc=new IntersectionObserver(rT,{root:null,rootMargin:"0px"})),Uc);function sT(){var t;const e=new zC({sdk:rv.JS,protocol:zk,version:Hk});return In()&&(e.os=(t=ey())!==null&&t!==void 0?t:""),e}function im(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=t,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(t/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=n,a}let Cs;function Bc(){if(!Cs){const t=new AudioContext,e=t.createOscillator(),n=t.createGain();n.gain.setValueAtTime(0,0);const i=t.createMediaStreamDestination();if(e.connect(n),n.connect(i),e.start(),[Cs]=i.stream.getAudioTracks(),!Cs)throw Error("Could not get empty media stream audio track");Cs.enabled=!1}return Cs.clone()}class Tr{constructor(e,n){this.onFinally=n,this.promise=new Promise((i,r)=>A(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,e&&(yield e(i,r))})).finally(()=>{var i;return(i=this.onFinally)===null||i===void 0?void 0:i.call(this)})}}function oT(t,e){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},e),i=Nu();if(!i)throw new Error("Audio Context not supported on this browser");const r=n.cloneTrack?t.mediaStreamTrack.clone():t.mediaStreamTrack,s=i.createMediaStreamSource(new MediaStream([r])),o=i.createAnalyser();o.minDecibels=n.minDecibels,o.maxDecibels=n.maxDecibels,o.fftSize=n.fftSize,o.smoothingTimeConstant=n.smoothingTimeConstant,s.connect(o);const a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let d=0;for(const f of a)d+=Math.pow(f/255,2);return Math.sqrt(d/a.length)},analyser:o,cleanup:()=>A(this,void 0,void 0,function*(){yield i.close(),n.cloneTrack&&r.stop()})}}function aT(t){return Kk.includes(t)}function fi(t){if(typeof t=="string"||typeof t=="number")return t;if(Array.isArray(t))return t[0];if(t.exact)return Array.isArray(t.exact)?t.exact[0]:t.exact;if(t.ideal)return Array.isArray(t.ideal)?t.ideal[0]:t.ideal;throw Error("could not unwrap constraint")}function cT(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}function fd(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function lT(t,e){return t.segments.map(n=>{let{id:i,text:r,language:s,startTime:o,endTime:a,final:c}=n;var l;const d=(l=e.get(i))!==null&&l!==void 0?l:Date.now(),u=Date.now();return c?e.delete(i):e.set(i,d),{id:i,text:r,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:s,firstReceivedTime:d,lastReceivedTime:u}})}function dT(t){const{id:e,timestamp:n,message:i,editTimestamp:r}=t;return{id:e,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function rm(t){switch(t.reason){case Te.LeaveRequest:return t.context;case Te.Cancelled:return dn.CLIENT_INITIATED;case Te.NotAllowed:return dn.USER_REJECTED;case Te.ServerUnreachable:return dn.JOIN_FAILURE;default:return dn.UNKNOWN_REASON}}function ra(t){return t!==void 0?Number(t):void 0}function Li(t){return t!==void 0?BigInt(t):void 0}function jr(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function Tn(t){return!!t&&t.kind==V.Kind.Audio}function ns(t){return!!t&&t.kind==V.Kind.Video}function ii(t){return jr(t)&&ns(t)}function Un(t){return jr(t)&&Tn(t)}function hd(t){return!!t&&!t.isLocal}function uT(t){return!!t&&!t.isLocal}function $c(t){return hd(t)&&ns(t)}function fT(t){return t.isLocal}function hT(t,e){const n=[];let i=new TextEncoder().encode(t);for(;i.length>e;){let r=e;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}n.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&n.push(i),n}function ty(t,e,n){var i,r,s,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:l}=iy(t??{}),d=e==null?void 0:e.processor,u=n==null?void 0:n.processor,f=a??{};return f.audio===!0&&(f.audio={}),f.video===!0&&(f.video={}),f.audio&&(md(f.audio,e),(i=(s=f.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||d)&&(f.audio.processor=c??d)),f.video&&(md(f.video,n),(r=(o=f.video).deviceId)!==null&&r!==void 0||(o.deviceId={ideal:"default"}),(l||u)&&(f.video.processor=l??u)),f}function md(t,e){return Object.keys(e).forEach(n=>{t[n]===void 0&&(t[n]=e[n])}),t}function _u(t){var e,n,i,r;const s={};if(t.video)if(typeof t.video=="object"){const o={},a=o,c=t.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":md(a,c.resolution);break;default:a[l]=c[l]}}),s.video=o,(e=(i=s.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else s.video=t.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return t.audio?typeof t.audio=="object"?(s.audio=t.audio,(n=(r=s.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function ny(t){return A(this,arguments,void 0,function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const i=Nu();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,o=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield jt(n),r.getByteTimeDomainData(o);const c=o.some(l=>l!==128&&l!==0);return i.close(),!c}return!1}()})}function Nu(){var t;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const n=new e({latencyHint:"interactive"});if(n.state==="suspended"&&typeof window<"u"&&(!((t=window.document)===null||t===void 0)&&t.body)){const i=()=>A(this,void 0,void 0,function*(){var r;try{n.state==="suspended"&&(yield n.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)});window.document.body.addEventListener("click",i)}return n}}function mT(t){return t==="audioinput"?V.Source.Microphone:t==="videoinput"?V.Source.Camera:V.Source.Unknown}function pd(t){return t===V.Source.Microphone?"audioinput":t===V.Source.Camera?"videoinput":void 0}function pT(t){var e,n;let i=(e=t.video)!==null&&e!==void 0?e:!0;return t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(i=typeof i=="boolean"?{}:i,Xi()?i=Object.assign(Object.assign({},i),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:(n=t.audio)!==null&&n!==void 0?n:!1,video:i,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}}function sa(t){return t.split("/")[1].toLowerCase()}function gT(t){const e=[];return t.forEach(n=>{n.track!==void 0&&e.push(new Eu({cid:n.track.mediaStreamID,track:n.trackInfo}))}),e}function we(t){return"mediaStreamTrack"in t?{trackID:t.sid,source:t.source,muted:t.isMuted,enabled:t.mediaStreamTrack.enabled,kind:t.kind,streamID:t.mediaStreamID,streamTrackID:t.mediaStreamTrack.id}:{trackID:t.trackSid,enabled:t.isEnabled,muted:t.isMuted,trackInfo:Object.assign({mimeType:t.mimeType,name:t.trackName,encrypted:t.isEncrypted,kind:t.kind,source:t.source},t.track?we(t.track):{})}}function vT(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function yT(t,e){var n;t===void 0&&(t={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(t)],r={};for(const s of i)t[s]!==e[s]&&(r[s]=(n=e[s])!==null&&n!==void 0?n:"");return r}function iy(t){const e=Object.assign({},t);let n,i;return typeof e.audio=="object"&&e.audio.processor&&(n=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:Fk(e)}}function bT(t){switch(t){case lt.CAMERA:return V.Source.Camera;case lt.MICROPHONE:return V.Source.Microphone;case lt.SCREEN_SHARE:return V.Source.ScreenShare;case lt.SCREEN_SHARE_AUDIO:return V.Source.ScreenShareAudio;default:return V.Source.Unknown}}class xT extends Nn.EventEmitter{constructor(e){super(),this.onWorkerMessage=n=>{var i,r;const{kind:s,data:o}=n.data;switch(s){case"error":Ce.error(o.error.message),this.emit(di.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit(di.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const a=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!a)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(di.ParticipantEncryptionStatusChanged,o.enabled,a)}break;case"ratchetKey":this.keyProvider.emit(ui.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break}},this.onWorkerError=n=>{Ce.error("e2ee worker encountered an error:",{error:n.error}),this.emit(di.EncryptionError,n.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!jk())throw new Iu("tried to setup end-to-end encryption on an unsupported browser");if(Ce.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const n={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:xk.getLevel()}};this.worker&&(Ce.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(n))}}setParticipantCryptorEnabled(e,n){Ce.debug("set e2ee to ".concat(e," for participant ").concat(n)),this.postEnable(e,n)}setSifTrailer(e){!e||e.length===0?Ce.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(ae.RTPVideoMapUpdate,n=>{this.postRTPMap(n)})}setupEventListeners(e,n){e.on(U.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==Ft.NONE,r.identity)),e.on(U.ConnectionStateChanged,i=>{i===ge.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==Ft.NONE,r.identity)})})}).on(U.TrackUnsubscribed,(i,r,s)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(U.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(U.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");n.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(Z.LocalTrackPublished,i=>A(this,void 0,void 0,function*(){this.setupE2EESender(i.track,i.track.sender)})),n.on(ui.SetKey,i=>this.postKey(i)).on(ui.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}postRatchetRequest(e,n){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:n}};this.worker.postMessage(i)}postKey(e){let{key:n,participantIdentity:i,keyIndex:r}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity),key:n,keyIndex:r}};this.worker.postMessage(o)}postEnable(e,n){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:n}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var n;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((n=this.room)===null||n===void 0)&&n.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const n={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(n)}setupE2EEReceiver(e,n,i){if(e.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,n,e.kind==="video"?sa(i.mimeType):void 0)}}setupE2EESender(e,n){if(!jr(e)||!n){n||Ce.warn("early return because sender is not ready");return}this.handleSender(n,e.mediaStreamID,void 0)}handleReceiver(e,n,i,r){return A(this,void 0,void 0,function*(){if(this.worker){if(rd()){const s={kind:"decode",participantIdentity:i,trackId:n,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Ss in e&&r){const c={kind:"updateCodec",data:{trackId:n,codec:r,participantIdentity:i}};this.worker.postMessage(c);return}let s=e.writableStream,o=e.readableStream;if(!s||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,s=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:s,trackId:n,codec:r,participantIdentity:i,isReuse:Ss in e}};this.worker.postMessage(a,[o,s])}e[Ss]=!0}})}handleSender(e,n,i){var r;if(!(Ss in e||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(rd()){Ce.info("initialize script transform");const s={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:n,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{Ce.info("initialize encoded streams");const s=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:s.readable,writableStream:s.writable,codec:i,trackId:n,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[s.readable,s.writable])}e[Ss]=!0}}}const Hc="default";class gt{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new gt),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return A(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;if(((s=gt.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){Ce.debug("awaiting getUserMedia promise");try{n?yield gt.userMediaPromiseMap.get(n):yield Promise.all(gt.userMediaPromiseMap.values())}catch{Ce.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Xi()&&i.hasDeviceInUse(n))&&(o.filter(c=>c.kind===n).length===0||o.some(c=>{const l=c.label==="",d=n?c.kind===n:!0;return l&&d}))){const c={video:n!=="audioinput"&&n!=="audiooutput",audio:n!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(d=>{d.stop()})}return i._previousDevices=o,n&&(o=o.filter(a=>a.kind===n)),o}()})}normalizeDeviceId(e,n,i){return A(this,void 0,void 0,function*(){if(n!==Hc)return n;const r=yield this.getDevices(e),s=r.find(a=>a.deviceId===Hc);if(!s){Ce.warn("could not reliably determine default device");return}const o=r.find(a=>a.deviceId!==Hc&&a.groupId===(i??s.groupId));if(!o){Ce.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?gt.userMediaPromiseMap.has(e):gt.userMediaPromiseMap.size>0}}gt.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];gt.userMediaPromiseMap=new Map;var Ls;(function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"})(Ls||(Ls={}));class ST{constructor(){this.pendingTasks=new Map,this.taskMutex=new Nt,this.nextTaskIndex=0}run(e){return A(this,void 0,void 0,function*(){const n={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Ls.WAITING};this.pendingTasks.set(n.id,n);const i=yield this.taskMutex.lock();try{return n.executedAt=Date.now(),n.status=Ls.RUNNING,yield e()}finally{n.status=Ls.COMPLETED,this.pendingTasks.delete(n.id),i()}})}flush(){return A(this,void 0,void 0,function*(){return this.run(()=>A(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function wT(t,e){const n=new URL(cT(t));return e.forEach((i,r)=>{n.searchParams.set(r,i)}),ry(n,"rtc")}function CT(t){const e=new URL(fd(t));return ry(e,"validate")}function kT(t){return t.endsWith("/")?t:"".concat(t,"/")}function ry(t,e){return t.pathname="".concat(kT(t.pathname)).concat(e),t.toString()}const TT=["syncState","trickle","offer","answer","simulate","leave"];function ET(t){const e=TT.indexOf(t.case)>=0;return Ce.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}var Be;(function(t){t[t.CONNECTING=0]="CONNECTING",t[t.CONNECTED=1]="CONNECTED",t[t.RECONNECTING=2]="RECONNECTING",t[t.DISCONNECTING=3]="DISCONNECTING",t[t.DISCONNECTED=4]="DISCONNECTED"})(Be||(Be={}));class Ou{get currentState(){return this.state}get isDisconnected(){return this.state===Be.DISCONNECTING||this.state===Be.DISCONNECTED}get isEstablishingConnection(){return this.state===Be.CONNECTING||this.state===Be.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=Be.DISCONNECTED,this.log=Ce,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=Gn((i=n.loggerName)!==null&&i!==void 0?i:fn.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=e,this.requestQueue=new ST,this.queuedRequests=[],this.closingLock=new Nt,this.connectionLock=new Nt,this.state=Be.DISCONNECTED}get logContext(){var e,n;return(n=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&n!==void 0?n:{}}join(e,n,i,r){return A(this,void 0,void 0,function*(){return this.state=Be.CONNECTING,this.options=i,yield this.connect(e,n,i,r)})}reconnect(e,n,i,r){return A(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=Be.RECONNECTING,this.clearPingInterval(),yield this.connect(e,n,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}))})}connect(e,n,i,r){this.connectOptions=i;const s=sT(),o=PT(n,s,i),a=wT(e,o),c=CT(a);return new Promise((l,d)=>A(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const f=()=>A(this,void 0,void 0,function*(){this.close(),clearTimeout(p),d(new Ue("room connection has been cancelled (signal)",Te.Cancelled))}),p=setTimeout(()=>{this.close(),d(new Ue("room connection has timed out (signal)",Te.ServerUnreachable))},i.websocketTimeout);r!=null&&r.aborted&&f(),r==null||r.addEventListener("abort",f);const g=new URL(a);g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(g),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(a),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(p)},this.ws.onerror=h=>A(this,void 0,void 0,function*(){if(this.state!==Be.CONNECTED){this.state=Be.DISCONNECTED,clearTimeout(p);try{const y=yield fetch(c);if(y.status.toFixed(0).startsWith("4")){const b=yield y.text();d(new Ue(b,Te.NotAllowed,y.status))}else d(new Ue("Encountered unknown websocket error during connection: ".concat(h.toString()),Te.InternalError,y.status))}catch(y){d(new Ue(y instanceof Error?y.message:"server was not reachable",Te.ServerUnreachable))}return}this.handleWSError(h)}),this.ws.onmessage=h=>A(this,void 0,void 0,function*(){var y,b,w;let C;if(typeof h.data=="string"){const S=JSON.parse(h.data);C=Dh.fromJson(S,{ignoreUnknownFields:!0})}else if(h.data instanceof ArrayBuffer)C=Dh.fromBinary(new Uint8Array(h.data));else{this.log.error("could not decode websocket message: ".concat(typeof h.data),this.logContext);return}if(this.state!==Be.CONNECTED){let S=!1;if(((y=C.message)===null||y===void 0?void 0:y.case)==="join"?(this.state=Be.CONNECTED,r==null||r.removeEventListener("abort",f),this.pingTimeoutDuration=C.message.value.pingTimeout,this.pingIntervalDuration=C.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),l(C.message.value)):this.state===Be.RECONNECTING&&C.message.case!=="leave"?(this.state=Be.CONNECTED,r==null||r.removeEventListener("abort",f),this.startPingInterval(),((b=C.message)===null||b===void 0?void 0:b.case)==="reconnect"?l(C.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),l(void 0),S=!0)):this.isEstablishingConnection&&C.message.case==="leave"?d(new Ue("Received leave request while trying to (re)connect",Te.LeaveRequest,void 0,C.message.value.reason)):i.reconnect||d(new Ue("did not receive join response, got ".concat((w=C.message)===null||w===void 0?void 0:w.case," instead"),Te.InternalError)),!S)return}this.signalLatency&&(yield jt(this.signalLatency)),this.handleSignalResponse(C)}),this.ws.onclose=h=>{this.isEstablishingConnection&&d(new Ue("Websocket got closed during a (re)connection attempt",Te.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:h.reason,code:h.code,wasClean:h.wasClean,state:this.state})),this.handleOnClose(h.reason)}}finally{u()}}))}close(){return A(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),n&&(e.state=Be.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const r=new Promise(s=>{e.ws?e.ws.onclose=()=>{s()}:s()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([r,jt(250)])),e.ws=void 0}}finally{n&&(e.state=Be.DISCONNECTED),i()}}()})}sendOffer(e,n){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:ka(e,n)})}sendAnswer(e,n){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:ka(e,n)})}sendIceCandidate(e,n){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new ku({candidateInit:JSON.stringify(e),target:n})})}sendMuteTrack(e,n){return this.sendRequest({case:"mute",value:new Tu({sid:e,muted:n})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,n){return A(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const a=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new fv({requestId:a,metadata:i,name:r,attributes:o})}),a}()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,n){return this.sendRequest({case:"updateLayers",value:new uv({trackSid:e,layers:n})})}sendUpdateSubscriptionPermissions(e,n){return this.sendRequest({case:"subscriptionPermission",value:new pv({allParticipants:e,trackPermissions:n})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ze.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new bv({timestamp:ze.parse(Date.now()),rtt:ze.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,n){return this.sendRequest({case:"updateAudioTrack",value:new dv({trackSid:e,features:n})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ya({reason:dn.CLIENT_INITIATED,action:Nr.DISCONNECT})})}sendRequest(e){return A(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!r&&!ET(n)&&i.state===Be.RECONNECTING){i.queuedRequests.push(()=>A(i,void 0,void 0,function*(){yield this.sendRequest(n,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield jt(i.signalLatency)),!i.ws||i.ws.readyState!==i.ws.OPEN){i.log.error("cannot send signal request before connected, type: ".concat(n==null?void 0:n.case),i.logContext);return}const o=new KC({message:n});try{i.useJSON?i.ws.send(o.toJsonString()):i.ws.send(o.toBinary())}catch(a){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:a}))}}()})}handleSignalResponse(e){var n,i;const r=e.message;if(r==null){this.log.debug("received unsupported message",this.logContext);return}let s=!1;if(r.case==="answer"){const o=sm(r.value);this.onAnswer&&this.onAnswer(o,r.value.id)}else if(r.case==="offer"){const o=sm(r.value);this.onOffer&&this.onOffer(o,r.value.id)}else if(r.case==="trickle"){const o=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(o,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((n=r.value.participants)!==null&&n!==void 0?n:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:r.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return A(this,void 0,void 0,function*(){if(this.state===Be.DISCONNECTED)return;const n=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),n&&n(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=bt.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&bt.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=bt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&bt.clearInterval(this.pingInterval)}}function sm(t){const e={type:"offer",sdp:t.sdp};switch(t.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=t.type;break}return e}function ka(t,e){return new Ji({sdp:t.sdp,type:t.type,id:e})}function PT(t,e,n){var i;const r=new URLSearchParams;return r.set("access_token",t),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid)),r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",In()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),n.adaptiveStream&&r.set("adaptive_stream","1"),n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}class om{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const n=this.buffer[0];if(this._totalSize-n.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class RT{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,n){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const r=i+this.ttl;return this._map.set(e,{value:n,expiresAt:r}),this}get(e){const n=this._map.get(e);if(n){if(n.expiresAt<Date.now()){this._map.delete(e);return}return n.value}}has(e){const n=this._map.get(e);return n?n.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[n,i]of this._map.entries())i.expiresAt<e&&this._map.delete(n);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,n,this.asValueMap())}map(e){this.cleanup();const n=[],i=this.asValueMap();for(const[r,s]of i.entries())n.push(e(s,r,i));return n}asValueMap(){const e=new Map;for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(n,i.value);return e}}var nn={},zc={},Wc={exports:{}},am;function Du(){if(am)return Wc.exports;am=1;var t=Wc.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var n="candidate:%s %d %s %d %s %d typ %s";return n+=e.raddr!=null?" raddr %s rport %d":"%v%v",n+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(n+=" generation %d"),n+=e["network-id"]!=null?" network-id %d":"%v",n+=e["network-cost"]!=null?" network-cost %d":"%v",n}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var n="ssrc:%d";return e.attribute!=null&&(n+=" %s",e.value!=null&&(n+=":%s")),n}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var n="mediaclk:";return n+=e.id!=null?"id=%s %s":"%v%s",n+=e.mediaClockValue!=null?"=%s":"",n+=e.rateNumerator!=null?" rate=%s":"",n+=e.rateDenominator!=null?"/%s":"",n}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(t).forEach(function(e){var n=t[e];n.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),Wc.exports}var cm;function AT(){return cm||(cm=1,function(t){var e=function(a){return String(Number(a))===a?Number(a):a},n=function(a,c,l,d){if(d&&!l)c[d]=e(a[1]);else for(var u=0;u<l.length;u+=1)a[u+1]!=null&&(c[l[u]]=e(a[u+1]))},i=function(a,c,l){var d=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:d&&!c[a.name]&&(c[a.name]={});var u=a.push?{}:d?c[a.name]:c;n(l.match(a.reg),u,a.names,a.name),a.push&&c[a.push].push(u)},r=Du(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(a){var c={},l=[],d=c;return a.split(/(\r\n|\r|\n)/).filter(s).forEach(function(u){var f=u[0],p=u.slice(2);f==="m"&&(l.push({rtp:[],fmtp:[]}),d=l[l.length-1]);for(var g=0;g<(r[f]||[]).length;g+=1){var h=r[f][g];if(h.reg.test(p))return i(h,d,p)}}),c.media=l,c};var o=function(a,c){var l=c.split(/=(.+)/,2);return l.length===2?a[l[0]]=e(l[1]):l.length===1&&c.length>1&&(a[l[0]]=void 0),a};t.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(a){return a.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(a){for(var c=[],l=a.split(" ").map(e),d=0;d<l.length;d+=3)c.push({component:l[d],ip:l[d+1],port:l[d+2]});return c},t.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(l){var d,u=!1;return l[0]!=="~"?d=e(l):(d=e(l.substring(1,l.length)),u=!0),{scid:d,paused:u}})})}}(zc)),zc}var qc,lm;function IT(){if(lm)return qc;lm=1;var t=Du(),e=/%[sdv%]/g,n=function(o){var a=1,c=arguments,l=c.length;return o.replace(e,function(d){if(a>=l)return d;var u=c[a];switch(a+=1,d){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(o,a,c){var l=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,d=[o+"="+l];if(a.names)for(var u=0;u<a.names.length;u+=1){var f=a.names[u];a.name?d.push(c[a.name][f]):d.push(c[a.names[u]])}else d.push(c[a.name]);return n.apply(null,d)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return qc=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=a.outerOrder||r,l=a.innerOrder||s,d=[];return c.forEach(function(u){t[u].forEach(function(f){f.name in o&&o[f.name]!=null?d.push(i(u,f,o)):f.push in o&&o[f.push]!=null&&o[f.push].forEach(function(p){d.push(i(u,f,p))})})}),o.media.forEach(function(u){d.push(i("m",t.m[0],u)),l.forEach(function(f){t[f].forEach(function(p){p.name in u&&u[p.name]!=null?d.push(i(f,p,u)):p.push in u&&u[p.push]!=null&&u[p.push].forEach(function(g){d.push(i(f,p,g))})})})}),d.join(`\r
65
+ `);t.RTCSessionDescription&&r instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return n.apply(this,arguments)}}function ta(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function na(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return n.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?n.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>n.apply(this,[o]))})}var Mk=Object.freeze({__proto__:null,removeExtmapAllowMixed:id,shimAddIceCandidateNullOrEmpty:ta,shimConnectionState:nd,shimMaxMessageSize:Qo,shimParameterlessSetLocalDescription:na,shimRTCIceCandidate:Xo,shimRTCIceCandidateRelayProtocol:td,shimSendThrowTypeError:ea});function _k(){let{window:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=wv,i=Pk(t),r={browserDetails:i,commonShim:Mk,extractVersion:Is,disableLog:Tk,disableWarnings:Ek,sdp:Ik};switch(i.browser){case"chrome":if(!$h||!Ql||!e.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(i.version===null)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=$h,ta(t,i),na(t),kv(t,i),Tv(t),Ql(t,i),Ev(t),Iv(t,i),Pv(t),Rv(t),Mv(t,i),Xo(t),td(t),nd(t),Qo(t,i),ea(t),id(t,i);break;case"firefox":if(!Hh||!ed||!e.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=Hh,ta(t,i),na(t),_v(t,i),ed(t,i),Nv(t),jv(t),Ov(t),Dv(t),Lv(t),Vv(t),Fv(t),Uv(t),Bv(t),Xo(t),nd(t),Qo(t,i),ea(t);break;case"safari":if(!zh||!e.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=zh,ta(t,i),na(t),Kv(t),Zv(t),zv(t),$v(t),Hv(t),Gv(t),Wv(t),Yv(t),Xo(t),td(t),Qo(t,i),ea(t),id(t,i);break;default:n("Unsupported browser!");break}return r}_k({window:typeof window>"u"?void 0:window});const Nk=10,Ss="lk_e2ee",Ok="LKFrameEncryptionKey",Dk={sharedKey:!1,ratchetSalt:Ok,ratchetWindowSize:8,failureTolerance:Nk,keyringSize:16};var ui;(function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"})(ui||(ui={}));var qh;(function(t){t.KeyRatcheted="keyRatcheted"})(qh||(qh={}));var di;(function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"})(di||(di={}));var Kh;(function(t){t.Error="cryptorError"})(Kh||(Kh={}));function jk(){return Lk()||rd()}function rd(){return typeof window.RTCRtpScriptTransform<"u"}function Lk(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class _L extends Nn.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(n,i,r)=>{Ce.debug("key ratcheted event received",{ratchetResult:n,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Dk),e),this.on(ui.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,n,i){const r={key:e,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(n??"shared","-").concat(i??0),r),this.emit(ui.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,n){this.emit(ui.RatchetRequest,e,n)}}class ki extends Error{constructor(e,n){super(n||"an error has occured"),this.name="LiveKitError",this.code=e}}var Te;(function(t){t[t.NotAllowed=0]="NotAllowed",t[t.ServerUnreachable=1]="ServerUnreachable",t[t.InternalError=2]="InternalError",t[t.Cancelled=3]="Cancelled",t[t.LeaveRequest=4]="LeaveRequest",t[t.Timeout=5]="Timeout"})(Te||(Te={}));class Ue extends ki{constructor(e,n,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=Te[n]}}class Iu extends ki{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Wn extends ki{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Vk extends ki{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class ht extends ki{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class sd extends ki{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Gh extends ki{constructor(e,n){super(15,e),this.name="PublishTrackError",this.status=n}}class Zh extends ki{constructor(e,n){super(15,e),this.reason=n,this.reasonName=typeof n=="string"?n:Ru[n]}}var Ca;(function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"})(Ca||(Ca={}));(function(t){function e(n){if(n&&"name"in n)return n.name==="NotFoundError"||n.name==="DevicesNotFoundError"?t.NotFound:n.name==="NotAllowedError"||n.name==="PermissionDeniedError"?t.PermissionDenied:n.name==="NotReadableError"||n.name==="TrackStartError"?t.DeviceInUse:t.Other}t.getFailure=e})(Ca||(Ca={}));var Yh;(function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"})(Yh||(Yh={}));var U;(function(t){t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting",t.Reconnected="reconnected",t.Disconnected="disconnected",t.ConnectionStateChanged="connectionStateChanged",t.Moved="moved",t.MediaDevicesChanged="mediaDevicesChanged",t.ParticipantConnected="participantConnected",t.ParticipantDisconnected="participantDisconnected",t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalAudioSilenceDetected="localAudioSilenceDetected",t.ActiveSpeakersChanged="activeSpeakersChanged",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.ParticipantAttributesChanged="participantAttributesChanged",t.ParticipantActive="participantActive",t.RoomMetadataChanged="roomMetadataChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.AudioPlaybackStatusChanged="audioPlaybackChanged",t.VideoPlaybackStatusChanged="videoPlaybackChanged",t.MediaDevicesError="mediaDevicesError",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.SignalConnected="signalConnected",t.RecordingStatusChanged="recordingStatusChanged",t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ActiveDeviceChanged="activeDeviceChanged",t.ChatMessage="chatMessage",t.LocalTrackSubscribed="localTrackSubscribed",t.MetricsReceived="metricsReceived"})(U||(U={}));var Z;(function(t){t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.IsSpeakingChanged="isSpeakingChanged",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.MediaDevicesError="mediaDevicesError",t.AudioStreamAcquired="audioStreamAcquired",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.PCTrackAdded="pcTrackAdded",t.AttributesChanged="attributesChanged",t.LocalTrackSubscribed="localTrackSubscribed",t.ChatMessage="chatMessage",t.Active="active"})(Z||(Z={}));var ae;(function(t){t.TransportsCreated="transportsCreated",t.Connected="connected",t.Disconnected="disconnected",t.Resuming="resuming",t.Resumed="resumed",t.Restarting="restarting",t.Restarted="restarted",t.SignalResumed="signalResumed",t.SignalRestarted="signalRestarted",t.Closing="closing",t.MediaTrackAdded="mediaTrackAdded",t.ActiveSpeakersUpdate="activeSpeakersUpdate",t.DataPacketReceived="dataPacketReceived",t.RTPVideoMapUpdate="rtpVideoMapUpdate",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ParticipantUpdate="participantUpdate",t.RoomUpdate="roomUpdate",t.SpeakersChanged="speakersChanged",t.StreamStateChanged="streamStateChanged",t.ConnectionQualityUpdate="connectionQualityUpdate",t.SubscriptionError="subscriptionError",t.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",t.RemoteMute="remoteMute",t.SubscribedQualityUpdate="subscribedQualityUpdate",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackSubscribed="localTrackSubscribed",t.Offline="offline",t.SignalRequestResponse="signalRequestResponse",t.SignalConnected="signalConnected",t.RoomMoved="roomMoved"})(ae||(ae={}));var re;(function(t){t.Message="message",t.Muted="muted",t.Unmuted="unmuted",t.Restarted="restarted",t.Ended="ended",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",t.UpdateSettings="updateSettings",t.UpdateSubscription="updateSubscription",t.AudioPlaybackStarted="audioPlaybackStarted",t.AudioPlaybackFailed="audioPlaybackFailed",t.AudioSilenceDetected="audioSilenceDetected",t.VisibilityChanged="visibilityChanged",t.VideoDimensionsChanged="videoDimensionsChanged",t.VideoPlaybackStarted="videoPlaybackStarted",t.VideoPlaybackFailed="videoPlaybackFailed",t.ElementAttached="elementAttached",t.ElementDetached="elementDetached",t.UpstreamPaused="upstreamPaused",t.UpstreamResumed="upstreamResumed",t.SubscriptionPermissionChanged="subscriptionPermissionChanged",t.SubscriptionStatusChanged="subscriptionStatusChanged",t.SubscriptionFailed="subscriptionFailed",t.TrackProcessorUpdate="trackProcessorUpdate",t.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",t.TranscriptionReceived="transcriptionReceived",t.TimeSyncUpdate="timeSyncUpdate",t.PreConnectBufferFlushed="preConnectBufferFlushed"})(re||(re={}));function Fk(t){return typeof t>"u"?t:typeof structuredClone=="function"?typeof t=="object"&&t!==null?structuredClone(Object.assign({},t)):structuredClone(t):JSON.parse(JSON.stringify(t))}const Uk=/version\/(\d+(\.?_?\d+)+)/i;let Lc;function $t(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const n=navigator.userAgent.toLowerCase();if(Lc===void 0||e){const i=Bk.find(r=>{let{test:s}=r;return s.test(n)});Lc=i==null?void 0:i.describe(n)}return Lc}const Bk=[{test:/firefox|iceweasel|fxios/i,describe(t){return{name:"Firefox",version:ia(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Vc(t)}}},{test:/chrom|crios|crmo/i,describe(t){return{name:"Chrome",version:ia(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Vc(t)}}},{test:/safari|applewebkit/i,describe(t){return{name:"Safari",version:ia(Uk,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:Vc(t)}}}];function ia(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(t);return i&&i.length>=n&&i[n]||""}function Vc(t){return t.includes("mac os")?ia(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}var $k="2.13.8";const Hk=$k,zk=16;class bt{}bt.setTimeout=function(){return setTimeout(...arguments)};bt.setInterval=function(){return setInterval(...arguments)};bt.clearTimeout=function(){return clearTimeout(...arguments)};bt.clearInterval=function(){return clearInterval(...arguments)};const Wk=5e3,ws=[];var Jt;(function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"})(Jt||(Jt={}));class V extends Nn.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=V.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Ce,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Wk):this.handleAppVisibilityChanged()},this.log=Gn((r=i.loggerName)!==null&&r!==void 0?r:fn.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=V.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),we(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let n="audio";this.kind===V.Kind.Video&&(n="video"),this.attachedElements.length===0&&this.kind===V.Kind.Video&&this.addAppVisibilityListener(),e||(n==="audio"&&(ws.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&ws.splice(ws.indexOf(e),1)),e||(e=document.createElement(n))),this.attachedElements.includes(e)||this.attachedElements.push(e),kr(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?re.AudioPlaybackStarted:re.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?re.AudioPlaybackFailed:re.VideoPlaybackFailed,s):s.name==="AbortError"?Ce.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):Ce.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&i.some(o=>o.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(re.ElementAttached,e),e}detach(e){try{if(e){Dr(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(re.ElementDetached,e)),e}const n=[];return this.attachedElements.forEach(i=>{Dr(this.mediaStreamTrack,i),n.push(i),this.recycleElement(i),this.emit(re.ElementDetached,i)}),this.attachedElements=[],n}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Gn(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let n=!0;e.pause(),ws.forEach(i=>{i.parentElement||(n=!1)}),n&&ws.push(e)}}handleAppVisibilityChanged(){return A(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===V.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Ot()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ot()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function kr(t,e){let n;e.srcObject instanceof MediaStream?n=e.srcObject:n=new MediaStream;let i;t.kind==="audio"?i=n.getAudioTracks():i=n.getVideoTracks(),i.includes(t)||(i.forEach(r=>{n.removeTrack(r)}),n.addTrack(t)),(!Xi()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=n.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==n&&(e.srcObject=n,(Xi()||qr())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=n,e.play().catch(()=>{})},0))}function Dr(t,e){if(e.srcObject instanceof MediaStream){const n=e.srcObject;n.removeTrack(t),n.getTracks().length>0?e.srcObject=n:e.srcObject=null}}(function(t){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=t.Kind||(t.Kind={}));let n;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(n=t.Source||(t.Source={}));let i;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(i=t.StreamState||(t.StreamState={}));function r(l){switch(l){case e.Audio:return cn.AUDIO;case e.Video:return cn.VIDEO;default:return cn.DATA}}t.kindToProto=r;function s(l){switch(l){case cn.AUDIO:return e.Audio;case cn.VIDEO:return e.Video;default:return e.Unknown}}t.kindFromProto=s;function o(l){switch(l){case n.Camera:return lt.CAMERA;case n.Microphone:return lt.MICROPHONE;case n.ScreenShare:return lt.SCREEN_SHARE;case n.ScreenShareAudio:return lt.SCREEN_SHARE_AUDIO;default:return lt.UNKNOWN}}t.sourceToProto=o;function a(l){switch(l){case lt.CAMERA:return n.Camera;case lt.MICROPHONE:return n.Microphone;case lt.SCREEN_SHARE:return n.ScreenShare;case lt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}t.sourceFromProto=a;function c(l){switch(l){case Gl.ACTIVE:return i.Active;case Gl.PAUSED:return i.Paused;default:return i.Unknown}}t.streamStateFromProto=c})(V||(V={}));class je{constructor(e,n,i,r,s){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(n!==void 0&&i!==void 0)this.width=e,this.height=n,this.aspectRatio=e/n,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const qk=["vp8","h264"],Kk=["vp8","h264","vp9","av1"];function Gk(t){return!!qk.find(e=>e===t)}var Jh;(function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"})(Jh||(Jh={}));var od;(function(t){t.telephone={maxBitrate:12e3},t.speech={maxBitrate:24e3},t.music={maxBitrate:48e3},t.musicStereo={maxBitrate:64e3},t.musicHighQuality={maxBitrate:96e3},t.musicHighQualityStereo={maxBitrate:128e3}})(od||(od={}));const zs={h90:new je(160,90,9e4,20),h180:new je(320,180,16e4,20),h216:new je(384,216,18e4,20),h360:new je(640,360,45e4,20),h540:new je(960,540,8e5,25),h720:new je(1280,720,17e5,30),h1080:new je(1920,1080,3e6,30),h1440:new je(2560,1440,5e6,30),h2160:new je(3840,2160,8e6,30)},ad={h120:new je(160,120,7e4,20),h180:new je(240,180,125e3,20),h240:new je(320,240,14e4,20),h360:new je(480,360,33e4,20),h480:new je(640,480,5e5,20),h540:new je(720,540,6e5,25),h720:new je(960,720,13e5,30),h1080:new je(1440,1080,23e5,30),h1440:new je(1920,1440,38e5,30)},Mu={h360fps3:new je(640,360,2e5,3,"medium"),h360fps15:new je(640,360,4e5,15,"medium"),h720fps5:new je(1280,720,8e5,5,"medium"),h720fps15:new je(1280,720,15e5,15,"medium"),h720fps30:new je(1280,720,2e6,30,"medium"),h1080fps15:new je(1920,1080,25e5,15,"medium"),h1080fps30:new je(1920,1080,5e6,30,"medium"),original:new je(0,0,7e6,30,"medium")},Zk="|",Xh="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Yk(t){const e=t.split(Zk);return e.length>1?[e[0],t.substr(e[0].length+1)]:[t,""]}function jt(t){return A(this,void 0,void 0,function*(){return new Promise(e=>bt.setTimeout(e,t))})}function cd(){return"addTransceiver"in RTCPeerConnection.prototype}function ld(){return"addTrack"in RTCPeerConnection.prototype}function Jk(){if(!("getCapabilities"in RTCRtpSender)||Xi())return!1;const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType==="video/AV1"){e=!0;break}}return e}function Xk(){if(!("getCapabilities"in RTCRtpSender)||qr())return!1;if(Xi()){const n=$t();if(n!=null&&n.version&&mi(n.version,"16")<0)return!1}const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType==="video/VP9"){e=!0;break}}return e}function Kn(t){return t==="av1"||t==="vp9"}function dd(t){return document?(t||(t=document.createElement("audio")),"setSinkId"in t):!1}function Qk(){return typeof RTCPeerConnection>"u"?!1:cd()||ld()}function qr(){var t;return((t=$t())===null||t===void 0?void 0:t.name)==="Firefox"}function Xi(){var t;return((t=$t())===null||t===void 0?void 0:t.name)==="Safari"}function Qh(){const t=$t();return(t==null?void 0:t.name)==="Safari"||(t==null?void 0:t.os)==="iOS"}function eT(){const t=$t();return(t==null?void 0:t.name)==="Safari"&&t.version.startsWith("17.")}function tT(t){return t||(t=$t()),(t==null?void 0:t.name)==="Safari"&&mi(t.version,"18.3")>0}function Xv(){var t,e;return Ot()?(e=(t=navigator.userAgentData)===null||t===void 0?void 0:t.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function nT(){const t=$t(),e="17.2";if(t)return t.name!=="Safari"&&t.os!=="iOS"||t.os==="iOS"&&t.osVersion&&mi(e,t.osVersion)>=0?!0:t.name==="Safari"&&mi(e,t.version)>=0}function Ot(){return typeof document<"u"}function In(){return navigator.product=="ReactNative"}function ud(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function Qv(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ey(){if(!In())return;let t=Qv();if(t)return t.platform}function em(){if(Ot())return window.devicePixelRatio;if(In()){let t=Qv();if(t)return t.devicePixelRatio}return 1}function mi(t,e){const n=t.split("."),i=e.split("."),r=Math.min(n.length,i.length);for(let s=0;s<r;++s){const o=parseInt(n[s],10),a=parseInt(i[s],10);if(o>a)return 1;if(o<a)return-1;if(s===r-1&&o===a)return 0}return t===""&&e!==""?-1:e===""?1:n.length==i.length?0:n.length<i.length?-1:1}function iT(t){for(const e of t)e.target.handleResize(e)}function rT(t){for(const e of t)e.target.handleVisibilityChanged(e)}let Fc=null;const tm=()=>(Fc||(Fc=new ResizeObserver(iT)),Fc);let Uc=null;const nm=()=>(Uc||(Uc=new IntersectionObserver(rT,{root:null,rootMargin:"0px"})),Uc);function sT(){var t;const e=new zC({sdk:rv.JS,protocol:zk,version:Hk});return In()&&(e.os=(t=ey())!==null&&t!==void 0?t:""),e}function im(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=t,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(t/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=n,a}let Cs;function Bc(){if(!Cs){const t=new AudioContext,e=t.createOscillator(),n=t.createGain();n.gain.setValueAtTime(0,0);const i=t.createMediaStreamDestination();if(e.connect(n),n.connect(i),e.start(),[Cs]=i.stream.getAudioTracks(),!Cs)throw Error("Could not get empty media stream audio track");Cs.enabled=!1}return Cs.clone()}class Tr{constructor(e,n){this.onFinally=n,this.promise=new Promise((i,r)=>A(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,e&&(yield e(i,r))})).finally(()=>{var i;return(i=this.onFinally)===null||i===void 0?void 0:i.call(this)})}}function oT(t,e){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},e),i=Nu();if(!i)throw new Error("Audio Context not supported on this browser");const r=n.cloneTrack?t.mediaStreamTrack.clone():t.mediaStreamTrack,s=i.createMediaStreamSource(new MediaStream([r])),o=i.createAnalyser();o.minDecibels=n.minDecibels,o.maxDecibels=n.maxDecibels,o.fftSize=n.fftSize,o.smoothingTimeConstant=n.smoothingTimeConstant,s.connect(o);const a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let d=0;for(const f of a)d+=Math.pow(f/255,2);return Math.sqrt(d/a.length)},analyser:o,cleanup:()=>A(this,void 0,void 0,function*(){yield i.close(),n.cloneTrack&&r.stop()})}}function aT(t){return Kk.includes(t)}function fi(t){if(typeof t=="string"||typeof t=="number")return t;if(Array.isArray(t))return t[0];if(t.exact)return Array.isArray(t.exact)?t.exact[0]:t.exact;if(t.ideal)return Array.isArray(t.ideal)?t.ideal[0]:t.ideal;throw Error("could not unwrap constraint")}function cT(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}function fd(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function lT(t,e){return t.segments.map(n=>{let{id:i,text:r,language:s,startTime:o,endTime:a,final:c}=n;var l;const d=(l=e.get(i))!==null&&l!==void 0?l:Date.now(),u=Date.now();return c?e.delete(i):e.set(i,d),{id:i,text:r,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:s,firstReceivedTime:d,lastReceivedTime:u}})}function dT(t){const{id:e,timestamp:n,message:i,editTimestamp:r}=t;return{id:e,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function rm(t){switch(t.reason){case Te.LeaveRequest:return t.context;case Te.Cancelled:return dn.CLIENT_INITIATED;case Te.NotAllowed:return dn.USER_REJECTED;case Te.ServerUnreachable:return dn.JOIN_FAILURE;default:return dn.UNKNOWN_REASON}}function ra(t){return t!==void 0?Number(t):void 0}function Li(t){return t!==void 0?BigInt(t):void 0}function jr(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function Tn(t){return!!t&&t.kind==V.Kind.Audio}function ns(t){return!!t&&t.kind==V.Kind.Video}function ii(t){return jr(t)&&ns(t)}function Un(t){return jr(t)&&Tn(t)}function hd(t){return!!t&&!t.isLocal}function uT(t){return!!t&&!t.isLocal}function $c(t){return hd(t)&&ns(t)}function fT(t){return t.isLocal}function hT(t,e){const n=[];let i=new TextEncoder().encode(t);for(;i.length>e;){let r=e;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}n.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&n.push(i),n}function ty(t,e,n){var i,r,s,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:l}=iy(t??{}),d=e==null?void 0:e.processor,u=n==null?void 0:n.processor,f=a??{};return f.audio===!0&&(f.audio={}),f.video===!0&&(f.video={}),f.audio&&(md(f.audio,e),(i=(s=f.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||d)&&(f.audio.processor=c??d)),f.video&&(md(f.video,n),(r=(o=f.video).deviceId)!==null&&r!==void 0||(o.deviceId={ideal:"default"}),(l||u)&&(f.video.processor=l??u)),f}function md(t,e){return Object.keys(e).forEach(n=>{t[n]===void 0&&(t[n]=e[n])}),t}function _u(t){var e,n,i,r;const s={};if(t.video)if(typeof t.video=="object"){const o={},a=o,c=t.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":md(a,c.resolution);break;default:a[l]=c[l]}}),s.video=o,(e=(i=s.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else s.video=t.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return t.audio?typeof t.audio=="object"?(s.audio=t.audio,(n=(r=s.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function ny(t){return A(this,arguments,void 0,function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const i=Nu();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,o=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield jt(n),r.getByteTimeDomainData(o);const c=o.some(l=>l!==128&&l!==0);return i.close(),!c}return!1}()})}function Nu(){var t;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const n=new e({latencyHint:"interactive"});if(n.state==="suspended"&&typeof window<"u"&&(!((t=window.document)===null||t===void 0)&&t.body)){const i=()=>A(this,void 0,void 0,function*(){var r;try{n.state==="suspended"&&(yield n.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)});window.document.body.addEventListener("click",i)}return n}}function mT(t){return t==="audioinput"?V.Source.Microphone:t==="videoinput"?V.Source.Camera:V.Source.Unknown}function pd(t){return t===V.Source.Microphone?"audioinput":t===V.Source.Camera?"videoinput":void 0}function pT(t){var e,n;let i=(e=t.video)!==null&&e!==void 0?e:!0;return t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(i=typeof i=="boolean"?{}:i,Xi()?i=Object.assign(Object.assign({},i),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:(n=t.audio)!==null&&n!==void 0?n:!1,video:i,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}}function sa(t){return t.split("/")[1].toLowerCase()}function gT(t){const e=[];return t.forEach(n=>{n.track!==void 0&&e.push(new Eu({cid:n.track.mediaStreamID,track:n.trackInfo}))}),e}function we(t){return"mediaStreamTrack"in t?{trackID:t.sid,source:t.source,muted:t.isMuted,enabled:t.mediaStreamTrack.enabled,kind:t.kind,streamID:t.mediaStreamID,streamTrackID:t.mediaStreamTrack.id}:{trackID:t.trackSid,enabled:t.isEnabled,muted:t.isMuted,trackInfo:Object.assign({mimeType:t.mimeType,name:t.trackName,encrypted:t.isEncrypted,kind:t.kind,source:t.source},t.track?we(t.track):{})}}function vT(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function yT(t,e){var n;t===void 0&&(t={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(t)],r={};for(const s of i)t[s]!==e[s]&&(r[s]=(n=e[s])!==null&&n!==void 0?n:"");return r}function iy(t){const e=Object.assign({},t);let n,i;return typeof e.audio=="object"&&e.audio.processor&&(n=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:Fk(e)}}function bT(t){switch(t){case lt.CAMERA:return V.Source.Camera;case lt.MICROPHONE:return V.Source.Microphone;case lt.SCREEN_SHARE:return V.Source.ScreenShare;case lt.SCREEN_SHARE_AUDIO:return V.Source.ScreenShareAudio;default:return V.Source.Unknown}}class xT extends Nn.EventEmitter{constructor(e){super(),this.onWorkerMessage=n=>{var i,r;const{kind:s,data:o}=n.data;switch(s){case"error":Ce.error(o.error.message),this.emit(di.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit(di.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const a=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!a)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(di.ParticipantEncryptionStatusChanged,o.enabled,a)}break;case"ratchetKey":this.keyProvider.emit(ui.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break}},this.onWorkerError=n=>{Ce.error("e2ee worker encountered an error:",{error:n.error}),this.emit(di.EncryptionError,n.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!jk())throw new Iu("tried to setup end-to-end encryption on an unsupported browser");if(Ce.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const n={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:xk.getLevel()}};this.worker&&(Ce.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(n))}}setParticipantCryptorEnabled(e,n){Ce.debug("set e2ee to ".concat(e," for participant ").concat(n)),this.postEnable(e,n)}setSifTrailer(e){!e||e.length===0?Ce.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(ae.RTPVideoMapUpdate,n=>{this.postRTPMap(n)})}setupEventListeners(e,n){e.on(U.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==Ft.NONE,r.identity)),e.on(U.ConnectionStateChanged,i=>{i===ge.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==Ft.NONE,r.identity)})})}).on(U.TrackUnsubscribed,(i,r,s)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(U.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(U.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");n.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(Z.LocalTrackPublished,i=>A(this,void 0,void 0,function*(){this.setupE2EESender(i.track,i.track.sender)})),n.on(ui.SetKey,i=>this.postKey(i)).on(ui.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}postRatchetRequest(e,n){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:n}};this.worker.postMessage(i)}postKey(e){let{key:n,participantIdentity:i,keyIndex:r}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity),key:n,keyIndex:r}};this.worker.postMessage(o)}postEnable(e,n){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:n}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var n;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((n=this.room)===null||n===void 0)&&n.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const n={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(n)}setupE2EEReceiver(e,n,i){if(e.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,n,e.kind==="video"?sa(i.mimeType):void 0)}}setupE2EESender(e,n){if(!jr(e)||!n){n||Ce.warn("early return because sender is not ready");return}this.handleSender(n,e.mediaStreamID,void 0)}handleReceiver(e,n,i,r){return A(this,void 0,void 0,function*(){if(this.worker){if(rd()){const s={kind:"decode",participantIdentity:i,trackId:n,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Ss in e&&r){const c={kind:"updateCodec",data:{trackId:n,codec:r,participantIdentity:i}};this.worker.postMessage(c);return}let s=e.writableStream,o=e.readableStream;if(!s||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,s=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:s,trackId:n,codec:r,participantIdentity:i,isReuse:Ss in e}};this.worker.postMessage(a,[o,s])}e[Ss]=!0}})}handleSender(e,n,i){var r;if(!(Ss in e||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(rd()){Ce.info("initialize script transform");const s={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:n,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{Ce.info("initialize encoded streams");const s=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:s.readable,writableStream:s.writable,codec:i,trackId:n,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[s.readable,s.writable])}e[Ss]=!0}}}const Hc="default";class gt{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new gt),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return A(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;if(((s=gt.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){Ce.debug("awaiting getUserMedia promise");try{n?yield gt.userMediaPromiseMap.get(n):yield Promise.all(gt.userMediaPromiseMap.values())}catch{Ce.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Xi()&&i.hasDeviceInUse(n))&&(o.filter(c=>c.kind===n).length===0||o.some(c=>{const l=c.label==="",d=n?c.kind===n:!0;return l&&d}))){const c={video:n!=="audioinput"&&n!=="audiooutput",audio:n!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(d=>{d.stop()})}return i._previousDevices=o,n&&(o=o.filter(a=>a.kind===n)),o}()})}normalizeDeviceId(e,n,i){return A(this,void 0,void 0,function*(){if(n!==Hc)return n;const r=yield this.getDevices(e),s=r.find(a=>a.deviceId===Hc);if(!s){Ce.warn("could not reliably determine default device");return}const o=r.find(a=>a.deviceId!==Hc&&a.groupId===(i??s.groupId));if(!o){Ce.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?gt.userMediaPromiseMap.has(e):gt.userMediaPromiseMap.size>0}}gt.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];gt.userMediaPromiseMap=new Map;var Ls;(function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"})(Ls||(Ls={}));class ST{constructor(){this.pendingTasks=new Map,this.taskMutex=new Nt,this.nextTaskIndex=0}run(e){return A(this,void 0,void 0,function*(){const n={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Ls.WAITING};this.pendingTasks.set(n.id,n);const i=yield this.taskMutex.lock();try{return n.executedAt=Date.now(),n.status=Ls.RUNNING,yield e()}finally{n.status=Ls.COMPLETED,this.pendingTasks.delete(n.id),i()}})}flush(){return A(this,void 0,void 0,function*(){return this.run(()=>A(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function wT(t,e){const n=new URL(cT(t));return e.forEach((i,r)=>{n.searchParams.set(r,i)}),ry(n,"rtc")}function CT(t){const e=new URL(fd(t));return ry(e,"validate")}function kT(t){return t.endsWith("/")?t:"".concat(t,"/")}function ry(t,e){return t.pathname="".concat(kT(t.pathname)).concat(e),t.toString()}const TT=["syncState","trickle","offer","answer","simulate","leave"];function ET(t){const e=TT.indexOf(t.case)>=0;return Ce.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}var Be;(function(t){t[t.CONNECTING=0]="CONNECTING",t[t.CONNECTED=1]="CONNECTED",t[t.RECONNECTING=2]="RECONNECTING",t[t.DISCONNECTING=3]="DISCONNECTING",t[t.DISCONNECTED=4]="DISCONNECTED"})(Be||(Be={}));class Ou{get currentState(){return this.state}get isDisconnected(){return this.state===Be.DISCONNECTING||this.state===Be.DISCONNECTED}get isEstablishingConnection(){return this.state===Be.CONNECTING||this.state===Be.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=Be.DISCONNECTED,this.log=Ce,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=Gn((i=n.loggerName)!==null&&i!==void 0?i:fn.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=e,this.requestQueue=new ST,this.queuedRequests=[],this.closingLock=new Nt,this.connectionLock=new Nt,this.state=Be.DISCONNECTED}get logContext(){var e,n;return(n=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&n!==void 0?n:{}}join(e,n,i,r){return A(this,void 0,void 0,function*(){return this.state=Be.CONNECTING,this.options=i,yield this.connect(e,n,i,r)})}reconnect(e,n,i,r){return A(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=Be.RECONNECTING,this.clearPingInterval(),yield this.connect(e,n,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}))})}connect(e,n,i,r){this.connectOptions=i;const s=sT(),o=PT(n,s,i),a=wT(e,o),c=CT(a);return new Promise((l,d)=>A(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const f=()=>A(this,void 0,void 0,function*(){this.close(),clearTimeout(p),d(new Ue("room connection has been cancelled (signal)",Te.Cancelled))}),p=setTimeout(()=>{this.close(),d(new Ue("room connection has timed out (signal)",Te.ServerUnreachable))},i.websocketTimeout);r!=null&&r.aborted&&f(),r==null||r.addEventListener("abort",f);const g=new URL(a);g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(g),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(a),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(p)},this.ws.onerror=h=>A(this,void 0,void 0,function*(){if(this.state!==Be.CONNECTED){this.state=Be.DISCONNECTED,clearTimeout(p);try{const y=yield fetch(c);if(y.status.toFixed(0).startsWith("4")){const b=yield y.text();d(new Ue(b,Te.NotAllowed,y.status))}else d(new Ue("Encountered unknown websocket error during connection: ".concat(h.toString()),Te.InternalError,y.status))}catch(y){d(new Ue(y instanceof Error?y.message:"server was not reachable",Te.ServerUnreachable))}return}this.handleWSError(h)}),this.ws.onmessage=h=>A(this,void 0,void 0,function*(){var y,b,w;let C;if(typeof h.data=="string"){const S=JSON.parse(h.data);C=Dh.fromJson(S,{ignoreUnknownFields:!0})}else if(h.data instanceof ArrayBuffer)C=Dh.fromBinary(new Uint8Array(h.data));else{this.log.error("could not decode websocket message: ".concat(typeof h.data),this.logContext);return}if(this.state!==Be.CONNECTED){let S=!1;if(((y=C.message)===null||y===void 0?void 0:y.case)==="join"?(this.state=Be.CONNECTED,r==null||r.removeEventListener("abort",f),this.pingTimeoutDuration=C.message.value.pingTimeout,this.pingIntervalDuration=C.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),l(C.message.value)):this.state===Be.RECONNECTING&&C.message.case!=="leave"?(this.state=Be.CONNECTED,r==null||r.removeEventListener("abort",f),this.startPingInterval(),((b=C.message)===null||b===void 0?void 0:b.case)==="reconnect"?l(C.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),l(void 0),S=!0)):this.isEstablishingConnection&&C.message.case==="leave"?d(new Ue("Received leave request while trying to (re)connect",Te.LeaveRequest,void 0,C.message.value.reason)):i.reconnect||d(new Ue("did not receive join response, got ".concat((w=C.message)===null||w===void 0?void 0:w.case," instead"),Te.InternalError)),!S)return}this.signalLatency&&(yield jt(this.signalLatency)),this.handleSignalResponse(C)}),this.ws.onclose=h=>{this.isEstablishingConnection&&d(new Ue("Websocket got closed during a (re)connection attempt",Te.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:h.reason,code:h.code,wasClean:h.wasClean,state:this.state})),this.handleOnClose(h.reason)}}finally{u()}}))}close(){return A(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),n&&(e.state=Be.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const r=new Promise(s=>{e.ws?e.ws.onclose=()=>{s()}:s()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([r,jt(250)])),e.ws=void 0}}finally{n&&(e.state=Be.DISCONNECTED),i()}}()})}sendOffer(e,n){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:ka(e,n)})}sendAnswer(e,n){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:ka(e,n)})}sendIceCandidate(e,n){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new ku({candidateInit:JSON.stringify(e),target:n})})}sendMuteTrack(e,n){return this.sendRequest({case:"mute",value:new Tu({sid:e,muted:n})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,n){return A(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const a=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new fv({requestId:a,metadata:i,name:r,attributes:o})}),a}()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,n){return this.sendRequest({case:"updateLayers",value:new uv({trackSid:e,layers:n})})}sendUpdateSubscriptionPermissions(e,n){return this.sendRequest({case:"subscriptionPermission",value:new pv({allParticipants:e,trackPermissions:n})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ze.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new bv({timestamp:ze.parse(Date.now()),rtt:ze.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,n){return this.sendRequest({case:"updateAudioTrack",value:new dv({trackSid:e,features:n})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ya({reason:dn.CLIENT_INITIATED,action:Nr.DISCONNECT})})}sendRequest(e){return A(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!r&&!ET(n)&&i.state===Be.RECONNECTING){i.queuedRequests.push(()=>A(i,void 0,void 0,function*(){yield this.sendRequest(n,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield jt(i.signalLatency)),!i.ws||i.ws.readyState!==i.ws.OPEN){i.log.error("cannot send signal request before connected, type: ".concat(n==null?void 0:n.case),i.logContext);return}const o=new KC({message:n});try{i.useJSON?i.ws.send(o.toJsonString()):i.ws.send(o.toBinary())}catch(a){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:a}))}}()})}handleSignalResponse(e){var n,i;const r=e.message;if(r==null){this.log.debug("received unsupported message",this.logContext);return}let s=!1;if(r.case==="answer"){const o=sm(r.value);this.onAnswer&&this.onAnswer(o,r.value.id)}else if(r.case==="offer"){const o=sm(r.value);this.onOffer&&this.onOffer(o,r.value.id)}else if(r.case==="trickle"){const o=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(o,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((n=r.value.participants)!==null&&n!==void 0?n:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:r.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return A(this,void 0,void 0,function*(){if(this.state===Be.DISCONNECTED)return;const n=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),n&&n(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=bt.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&bt.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=bt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&bt.clearInterval(this.pingInterval)}}function sm(t){const e={type:"offer",sdp:t.sdp};switch(t.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=t.type;break}return e}function ka(t,e){return new Ji({sdp:t.sdp,type:t.type,id:e})}function PT(t,e,n){var i;const r=new URLSearchParams;return r.set("access_token",t),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid)),r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",In()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),n.adaptiveStream&&r.set("adaptive_stream","1"),n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}class om{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const n=this.buffer[0];if(this._totalSize-n.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class RT{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,n){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const r=i+this.ttl;return this._map.set(e,{value:n,expiresAt:r}),this}get(e){const n=this._map.get(e);if(n){if(n.expiresAt<Date.now()){this._map.delete(e);return}return n.value}}has(e){const n=this._map.get(e);return n?n.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[n,i]of this._map.entries())i.expiresAt<e&&this._map.delete(n);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,n,this.asValueMap())}map(e){this.cleanup();const n=[],i=this.asValueMap();for(const[r,s]of i.entries())n.push(e(s,r,i));return n}asValueMap(){const e=new Map;for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(n,i.value);return e}}var nn={},zc={},Wc={exports:{}},am;function Du(){if(am)return Wc.exports;am=1;var t=Wc.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var n="candidate:%s %d %s %d %s %d typ %s";return n+=e.raddr!=null?" raddr %s rport %d":"%v%v",n+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(n+=" generation %d"),n+=e["network-id"]!=null?" network-id %d":"%v",n+=e["network-cost"]!=null?" network-cost %d":"%v",n}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var n="ssrc:%d";return e.attribute!=null&&(n+=" %s",e.value!=null&&(n+=":%s")),n}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var n="mediaclk:";return n+=e.id!=null?"id=%s %s":"%v%s",n+=e.mediaClockValue!=null?"=%s":"",n+=e.rateNumerator!=null?" rate=%s":"",n+=e.rateDenominator!=null?"/%s":"",n}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(t).forEach(function(e){var n=t[e];n.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),Wc.exports}var cm;function AT(){return cm||(cm=1,function(t){var e=function(a){return String(Number(a))===a?Number(a):a},n=function(a,c,l,d){if(d&&!l)c[d]=e(a[1]);else for(var u=0;u<l.length;u+=1)a[u+1]!=null&&(c[l[u]]=e(a[u+1]))},i=function(a,c,l){var d=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:d&&!c[a.name]&&(c[a.name]={});var u=a.push?{}:d?c[a.name]:c;n(l.match(a.reg),u,a.names,a.name),a.push&&c[a.push].push(u)},r=Du(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(a){var c={},l=[],d=c;return a.split(/(\r\n|\r|\n)/).filter(s).forEach(function(u){var f=u[0],p=u.slice(2);f==="m"&&(l.push({rtp:[],fmtp:[]}),d=l[l.length-1]);for(var g=0;g<(r[f]||[]).length;g+=1){var h=r[f][g];if(h.reg.test(p))return i(h,d,p)}}),c.media=l,c};var o=function(a,c){var l=c.split(/=(.+)/,2);return l.length===2?a[l[0]]=e(l[1]):l.length===1&&c.length>1&&(a[l[0]]=void 0),a};t.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(a){return a.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(a){for(var c=[],l=a.split(" ").map(e),d=0;d<l.length;d+=3)c.push({component:l[d],ip:l[d+1],port:l[d+2]});return c},t.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(l){var d,u=!1;return l[0]!=="~"?d=e(l):(d=e(l.substring(1,l.length)),u=!0),{scid:d,paused:u}})})}}(zc)),zc}var qc,lm;function IT(){if(lm)return qc;lm=1;var t=Du(),e=/%[sdv%]/g,n=function(o){var a=1,c=arguments,l=c.length;return o.replace(e,function(d){if(a>=l)return d;var u=c[a];switch(a+=1,d){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(o,a,c){var l=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,d=[o+"="+l];if(a.names)for(var u=0;u<a.names.length;u+=1){var f=a.names[u];a.name?d.push(c[a.name][f]):d.push(c[a.names[u]])}else d.push(c[a.name]);return n.apply(null,d)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return qc=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=a.outerOrder||r,l=a.innerOrder||s,d=[];return c.forEach(function(u){t[u].forEach(function(f){f.name in o&&o[f.name]!=null?d.push(i(u,f,o)):f.push in o&&o[f.push]!=null&&o[f.push].forEach(function(p){d.push(i(u,f,p))})})}),o.media.forEach(function(u){d.push(i("m",t.m[0],u)),l.forEach(function(f){t[f].forEach(function(p){p.name in u&&u[p.name]!=null?d.push(i(f,p,u)):p.push in u&&u[p.push]!=null&&u[p.push].forEach(function(g){d.push(i(f,p,g))})})})}),d.join(`\r
77
66
  `)+`\r
78
- `},qc}var dm;function MT(){if(dm)return nn;dm=1;var t=AT(),e=IT(),n=Du();return nn.grammar=n,nn.write=e,nn.parse=t.parse,nn.parseParams=t.parseParams,nn.parseFmtpConfig=t.parseFmtpConfig,nn.parsePayloads=t.parsePayloads,nn.parseRemoteCandidates=t.parseRemoteCandidates,nn.parseImageAttributes=t.parseImageAttributes,nn.parseSimulcastStreamList=t.parseSimulcastStreamList,nn}var si=MT();function ju(t,e,n){var i,r,s;e===void 0&&(e=50),n===void 0&&(n={});var o=(i=n.isImmediate)!=null&&i,a=(r=n.callback)!=null&&r,c=n.maxWait,l=Date.now(),d=[];function u(){if(c!==void 0){var p=Date.now()-l;if(p+e>=c)return c-p}return e}var f=function(){var p=[].slice.call(arguments),g=this;return new Promise(function(h,y){var b=o&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!o){var C=t.apply(g,p);a&&a(C),d.forEach(function(S){return(0,S.resolve)(C)}),d=[]}},u()),b){var w=t.apply(g,p);return a&&a(w),h(w)}d.push({resolve:h,reject:y})})};return f.cancel=function(p){s!==void 0&&clearTimeout(s),d.forEach(function(g){return(0,g.reject)(p)}),d=[]},f}const _T=.7,NT=20,Lr={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class um extends Nn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=Ce,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=ju(r=>A(this,void 0,void 0,function*(){this.emit(Lr.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),NT),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Gn((i=n.loggerName)!==null&&i!==void 0?i:fn.PCTransport),this.loggerOptions=n,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=n=>{var i;n.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,n.candidate))},e.onicecandidateerror=n=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,n)},e.oniceconnectionstatechange=()=>{var n;(n=this.onIceConnectionStateChange)===null||n===void 0||n.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var n;(n=this.onSignalingStatechange)===null||n===void 0||n.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var n;(n=this.onConnectionStateChange)===null||n===void 0||n.call(this,e.connectionState)},e.ondatachannel=n=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,n)},e.ontrack=n=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,n)},e}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return A(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,n){return A(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&n>0&&n!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:n,latestOfferId:this.latestOfferId})),!1;let r;if(e.type==="offer"){let{stereoMids:s,nackMids:o}=OT(e);this.remoteStereoMids=s,this.remoteNackMids=o}else if(e.type==="answer"){const s=si.parse((i=e.sdp)!==null&&i!==void 0?i:"");s.media.forEach(o=>{o.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||o.mid!=a.transceiver.mid)return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(c=d.payload,!0):!1),c===0)return!0;let l=!1;for(const d of o.fmtp)if(d.payload===c){d.config=d.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),l=!0;break}return l||a.maxbr>0&&o.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),r=si.write(s)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Lr.NegotiationComplete),e.sdp&&si.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Lr.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return A(this,void 0,void 0,function*(){var n;const i=this.latestOfferId+1;if(this.latestOfferId=i,this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const s=si.parse((n=r.sdp)!==null&&n!==void 0?n:"");if(s.media.forEach(o=>{hm(o),o.type==="audio"?fm(o,[],[]):o.type==="video"&&this.trackBitrates.some(a=>{if(!o.msid||!a.cid||!o.msid.includes(a.cid))return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(c=d.payload,!0):!1),c===0||(Kn(a.codec)&&this.ensureVideoDDExtensionForSVC(o,s),a.codec!=="av1"))return!0;const l=Math.round(a.maxbr*_T);for(const d of o.fmtp)if(d.payload===c){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>i){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));return}yield this.setMungedSDP(r,si.write(s)),this.onOffer(r,this.latestOfferId)})}createAndSetAnswer(){return A(this,void 0,void 0,function*(){var e;const n=yield this.pc.createAnswer(),i=si.parse((e=n.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{hm(r),r.type==="audio"&&fm(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,si.write(i)),n})}createDataChannel(e,n){return this.pc.createDataChannel(e,n)}addTransceiver(e,n){return this.pc.addTransceiver(e,n)}addTrack(e){if(!this._pc)throw new ht("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var n;if(!this._pc)throw new ht("PC closed, cannot configure");return(n=this._pc)===null||n===void 0?void 0:n.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var n;return(n=this._pc)===null||n===void 0?void 0:n.removeTrack(e)}getConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&n!==void 0?n:"closed"}getICEConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&n!==void 0?n:"closed"}getSignallingState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&n!==void 0?n:"closed"}getTransceivers(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&n!==void 0?n:[]}getSenders(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&n!==void 0?n:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return A(this,void 0,void 0,function*(){var e;if(!this._pc)return;let n="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":n=a.selectedCandidatePairId;break;case"candidate-pair":n===""&&a.selected&&(n=a.id),i.set(a.id,a);break;case"remote-candidate":r.set(a.id,"".concat(a.address,":").concat(a.port));break}}),n==="")return;const o=(e=i.get(n))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return r.get(o)})}setMungedSDP(e,n,i){return A(this,void 0,void 0,function*(){if(n){const r=e.sdp;e.sdp=n;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:n})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const o={error:s,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new sd(s)}})}ensureVideoDDExtensionForSVC(e,n){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===Xh))){if(this.ddExtID===0){let o=0;n.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:Xh})}}}function fm(t,e,n){let i=0;t.rtp.some(r=>r.codec==="opus"?(i=r.payload,!0):!1),i>0&&(t.rtcpFb||(t.rtcpFb=[]),n.includes(t.mid)&&!t.rtcpFb.some(r=>r.payload===i&&r.type==="nack")&&t.rtcpFb.push({payload:i,type:"nack"}),e.includes(t.mid)&&t.fmtp.some(r=>r.payload===i?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function OT(t){var e;const n=[],i=[],r=si.parse((e=t.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(o=>{var a;o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(c=>c.payload===s&&c.type==="nack")&&i.push(o.mid),o.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&n.push(o.mid),!0):!1))}),{stereoMids:n,nackMids:i}}function hm(t){if(t.connection){const e=t.connection.ip.indexOf(":")>=0;(t.connection.version===4&&e||t.connection.version===6&&!e)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}const gd="vp8",DT={audioPreset:od.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Mu.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:gd,backupCodec:!0,preConnectBuffer:!1},sy={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},oy={deviceId:{ideal:"default"},resolution:zs.h720.resolution},jT={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new wk,disconnectOnPageLeave:!0,webAudioMix:!1},Lu={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Je;(function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"})(Je||(Je={}));class LT{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,n,i){var r;this.peerConnectionTimeout=Lu.peerConnectionTimeout,this.log=Ce,this.updateState=()=>{var s;const o=this.state,a=this.requiredTransports.map(c=>c.getConnectionState());a.every(c=>c==="connected")?this.state=Je.CONNECTED:a.some(c=>c==="failed")?this.state=Je.FAILED:a.some(c=>c==="connecting")?this.state=Je.CONNECTING:a.every(c=>c==="closed")?this.state=Je.CLOSED:a.some(c=>c==="closed")?this.state=Je.CLOSING:a.every(c=>c==="new")&&(this.state=Je.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(Je[o]," to ").concat(Je[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Gn((r=i.loggerName)!==null&&r!==void 0?r:fn.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!n,this.isSubscriberConnectionRequired=n,this.publisher=new um(e,i),this.subscriber=new um(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,ln.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,ln.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,s)},this.subscriber.onTrack=s=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,s)},this.publisher.onOffer=(s,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s,o)},this.state=Je.NEW,this.connectionLock=new Nt,this.remoteOfferLock=new Nt}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,n){return this.publisher.setRemoteDescription(e,n)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return A(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const n of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(n)}catch(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return A(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,n){return A(this,void 0,void 0,function*(){n===ln.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,n){return A(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const i=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(e,n))?yield this.subscriber.createAndSetAnswer():void 0}finally{i()}})}updateConfiguration(e,n){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),n&&this.triggerIceRestart()}ensurePCTransportConnection(e,n){return A(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,n)))}finally{r()}})}negotiate(e){return A(this,void 0,void 0,function*(){return new Promise((n,i)=>A(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",s),this.publisher.once(Lr.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Lr.NegotiationComplete,()=>{clearTimeout(r),n()})}),yield this.publisher.negotiate(o=>{clearTimeout(r),i(o)})}))})}addPublisherTransceiver(e,n){return this.publisher.addTransceiver(e,n)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,n){return this.publisher.createDataChannel(e,n)}getConnectedAddress(e){return e===ln.PUBLISHER?this.publisher.getConnectedAddress():e===ln.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,n){return A(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((c,l)=>A(s,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection",this.logContext),bt.clearTimeout(u),l(new Ue("room connection has been cancelled",Te.Cancelled))};r!=null&&r.signal.aborted&&d(),r==null||r.signal.addEventListener("abort",d);const u=bt.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",d),l(new Ue("could not establish pc connection",Te.InternalError))},o);for(;this.state!==Je.CONNECTED;)if(yield jt(50),r!=null&&r.signal.aborted){l(new Ue("room connection has been cancelled",Te.Cancelled));return}bt.clearTimeout(u),r==null||r.signal.removeEventListener("abort",d),c()}))}()})}}class Qe extends Error{constructor(e,n,i){super(n),this.code=e,this.message=mm(n,Qe.MAX_MESSAGE_BYTES),this.data=i?mm(i,Qe.MAX_DATA_BYTES):void 0}static fromProto(e){return new Qe(e.code,e.message,e.data)}toProto(){return new ev({code:this.code,message:this.message,data:this.data})}static builtIn(e,n){return new Qe(Qe.ErrorCode[e],Qe.ErrorMessage[e],n)}}Qe.MAX_MESSAGE_BYTES=256;Qe.MAX_DATA_BYTES=15360;Qe.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404};Qe.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const ay=15360;function Vu(t){return new TextEncoder().encode(t).length}function mm(t,e){if(Vu(t)<=e)return t;let n=0,i=t.length;const r=new TextEncoder;for(;n<i;){const s=Math.floor((n+i+1)/2);r.encode(t.slice(0,s)).length<=e?n=s:i=s-1}return t.slice(0,n)}const Fu=2e3;function Xa(t,e){if(!e)return 0;let n,i;return"bytesReceived"in t?(n=t.bytesReceived,i=e.bytesReceived):"bytesSent"in t&&(n=t.bytesSent,i=e.bytesSent),n===void 0||i===void 0||t.timestamp===void 0||e.timestamp===void 0?0:(n-i)*8*1e3/(t.timestamp-e.timestamp)}const Uu=typeof MediaRecorder<"u";class VT{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const FT=Uu?MediaRecorder:VT;class UT extends FT{constructor(e,n){if(!Uu)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),n);let i,r;const s=()=>r===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r==null||r.close(),r=void 0},a=c=>{r==null||r.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r=void 0};this.byteStream=new ReadableStream({start:c=>{r=c,i=l=>A(this,void 0,void 0,function*(){const d=yield l.data.arrayBuffer();s()||c.enqueue(new Uint8Array(d))}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function BT(){return Uu}const $T=1e3,HT=1e4;class cy extends V{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,n,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,n,s),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=ju(()=>A(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>A(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(re.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Nt,this.pauseUpstreamLock=new Nt,this.processorLock=new Nt,this.restartLock=new Nt,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==V.Kind.Video)return;const{width:e,height:n}=this._mediaStreamTrack.getSettings();if(e&&n)return{width:e,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,n;return(n=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&n!==void 0?n:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,n){return A(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!n)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Dr(this._mediaStreamTrack,s)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){const s=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(kr(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}finally{s()}}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{kr(r??e,s)}))})}waitForDimensions(){return A(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:$T;return function*(){var i;if(e.kind===V.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=$t())===null||i===void 0?void 0:i.os)==="iOS"&&(yield jt(10));const r=Date.now();for(;Date.now()-r<n;){const s=e.dimensions;if(s)return s;yield jt(50)}throw new Wn("unable to get track dimensions after timeout")}()})}setDeviceId(e){return A(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===fi(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),fi(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return A(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===V.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===V.Kind.Audio?"audioinput":"videoinput";return n?gt.getInstance().normalizeDeviceId(s,i,r):i}()})}mute(){return A(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return A(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,n){return A(this,void 0,void 0,function*(){if(!this.sender)throw new Wn("unable to replace an unpublished track");let i,r;return typeof n=="boolean"?i=n:n!==void 0&&(i=n.userProvidedTrack,r=n.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return A(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,s=Ck(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===V.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(l=>{Dr(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(re.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?re.Muted:re.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return A(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xv()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return A(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(re.UpstreamPaused,this);const i=$t();if((i==null?void 0:i.name)==="Safari"&&mi(i.version,"12.0")<0)throw new Iu("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{n()}})}resumeUpstream(){return A(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(re.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}})}getRTCStatsReport(){return A(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return A(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;const o=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const a=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:a,audioContext:i.audioContext};if(yield n.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(kr(i._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))),i.processor=n,i.processorElement=a,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(Dr(i._mediaStreamTrack,l),kr(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(re.TrackProcessorUpdate,i.processor)}finally{o()}}()})}getProcessor(){return this.processor}stopProcessor(){return A(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,n||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(re.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!BT()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(!this.localTrackRecorder)this.localTrackRecorder=new UT(this,{mimeType:"audio/webm;codecs=opus"});else{this.log.warn("preconnect buffer already started");return}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},HT)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}}class Ta extends cy{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,V.Kind.Audio,n,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>A(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=Xa(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(re.AudioTrackFeatureUpdate,this,pt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(re.AudioTrackFeatureUpdate,this,pt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return A(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===V.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return A(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==fi(this._constraints.deviceId);return this.source===V.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{n()}})}restartTrack(e){return A(this,void 0,void 0,function*(){let n;if(e){const i=_u({audio:e});typeof i.audio!="boolean"&&(n=i.audio)}yield this.restart(n)})}restart(e){const n=Object.create(null,{restart:{get:()=>super.restart}});return A(this,void 0,void 0,function*(){const i=yield n.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){Ot()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Fu)))}setProcessor(e){return A(this,void 0,void 0,function*(){var n;const i=yield this.processorLock.lock();try{if(!In()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(n=this.sender)===null||n===void 0?void 0:n.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(re.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return A(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const n=yield this.sender.getStats();let i;return n.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return A(this,void 0,void 0,function*(){const e=yield ny(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(re.AudioSilenceDetected)),e})}}function zT(t,e,n){switch(t.kind){case"audio":return new Ta(t,e,!1,void 0,n);case"video":return new Ea(t,e,!1,n);default:throw new Wn("unsupported track type: ".concat(t.kind))}}const WT=Object.values(zs),qT=Object.values(ad),KT=Object.values(Mu),GT=[zs.h180,zs.h360],ZT=[ad.h180,ad.h360],YT=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(n=>{var i,r;return new je(Math.floor(t.width/n.scaleResolutionDownBy),Math.floor(t.height/n.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(n.scaleResolutionDownBy,2)*(((i=t.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=n.fps)!==null&&r!==void 0?r:30))))),n.fps,t.encoding.priority)}),vd=["q","h","f"];function yd(t,e,n,i){var r,s;let o=i==null?void 0:i.videoEncoding;t&&(o=i==null?void 0:i.screenShareEncoding);const a=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!o&&!a&&!c||!e||!n)return[{}];o||(o=XT(t,e,n,l),Ce.debug("using video encoding",o));const d=o.maxFramerate,u=new je(e,n,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Kn(l)){const g=new ly(c),h=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const y=$t();if(Xi()||In()||(y==null?void 0:y.name)==="Chrome"&&mi(y==null?void 0:y.version,"113")<0){const b=g.suffix=="h"?2:3,w=tT(y);for(let C=0;C<g.spatial;C+=1)h.push({rid:vd[2-C],maxBitrate:o.maxBitrate/Math.pow(b,C),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:w?Math.pow(2,C):void 0});h[0].scalabilityMode=c}else h.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(h[0].priority=u.encoding.priority,h[0].networkPriority=u.encoding.priority),Ce.debug("using svc encoding",{encodings:h}),h}if(!a)return[o];let f=[];t?f=(r=gm(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:pm(t,u):f=(s=gm(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:pm(t,u);let p;if(f.length>0){const g=f[0];f.length>1&&([,p]=f);const h=Math.max(e,n);if(h>=960&&p)return Kc(e,n,[g,p,u],d);if(h>=480)return Kc(e,n,[g,u],d)}return Kc(e,n,[u])}function JT(t,e,n){var i,r,s,o;if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;e!==n.backupCodec.codec&&Ce.warn("requested a different codec than specified as backup",{serverRequested:e,backup:n.backupCodec.codec}),n.videoCodec=e,n.videoEncoding=n.backupCodec.encoding;const a=t.mediaStreamTrack.getSettings(),c=(i=a.width)!==null&&i!==void 0?i:(r=t.dimensions)===null||r===void 0?void 0:r.width,l=(s=a.height)!==null&&s!==void 0?s:(o=t.dimensions)===null||o===void 0?void 0:o.height;return t.source===V.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),yd(t.source===V.Source.ScreenShare,c,l,n)}function XT(t,e,n,i){const r=QT(t,e,n);let{encoding:s}=r[0];const o=Math.max(e,n);for(let a=0;a<r.length;a+=1){const c=r[a];if(s=c.encoding,c.width>=o)break}if(i)switch(i){case"av1":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function QT(t,e,n){if(t)return KT;const i=e>n?e/n:n/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?WT:qT}function pm(t,e){if(t)return YT(e);const{width:n,height:i}=e,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?GT:ZT}function Kc(t,e,n,i){const r=[];if(n.forEach((s,o)=>{if(o>=vd.length)return;const a=Math.min(t,e),l={rid:vd[o],scaleResolutionDownBy:Math.max(1,a/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},d=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;d&&(l.maxFramerate=d);const u=qr()||o===0;s.encoding.priority&&u&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),In()&&ey()==="ios"){let s;r.forEach(a=>{s?a.maxFramerate&&a.maxFramerate>s&&(s=a.maxFramerate):s=a.maxFramerate});let o=!0;r.forEach(a=>{var c;a.maxFramerate!=s&&(o&&(o=!1,Ce.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Ce.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),a.maxFramerate=s)})}return r}function gm(t){if(t)return t.sort((e,n)=>{const{encoding:i}=e,{encoding:r}=n;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class ly{constructor(e){const n=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!n)throw new Error("invalid scalability mode");if(this.spatial=parseInt(n[1]),this.temporal=parseInt(n[2]),n.length>3)switch(n[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=n[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function e2(t){return t.source===V.Source.ScreenShare||t.constraints.height&&fi(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const t2=5e3;class Ea extends cy{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,V.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>A(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}const o=new Map(s.map(a=>[a.rid,a]));if(this.prevStats){let a=0;o.forEach((c,l)=>{var d;const u=(d=this.prevStats)===null||d===void 0?void 0:d.get(l);a+=Xa(c,u)}),this._currentBitrate=a}this.prevStats=o}),this.senderLock=new Nt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var n;if(this.signalClient=e,!Ot())return;const i=(n=this.sender)===null||n===void 0?void 0:n.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Fu))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return A(this,void 0,void 0,function*(){var n,i,r,s,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=zn(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0)s=l.value,a=!1,yield(o=s.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(d){i={error:d}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return A(this,void 0,void 0,function*(){var n,i,r,s,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=zn(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0){s=l.value,a=!1;const d=s;yield(o=d.sender)===null||o===void 0?void 0:o.replaceTrack(d.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return A(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===V.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return A(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.source===V.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{n()}})}setTrackMuted(e){super.setTrackMuted(e);for(const n of this.simulcastCodecs.values())n.mediaStreamTrack.enabled=!e}getSenderStats(){return A(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const n=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const o={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},a=i.get(r.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),n.push(o)}}),n.sort((r,s)=>{var o,a;return((o=s.frameWidth)!==null&&o!==void 0?o:0)-((a=r.frameWidth)!==null&&a!==void 0?a:0)}),n})}setPublishingQuality(e){const n=[];for(let i=Jt.LOW;i<=Jt.HIGH;i+=1)n.push(new Pu({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Kn(this.codec),n)}restartTrack(e){return A(this,void 0,void 0,function*(){var n,i,r,s,o;let a;if(e){const u=_u({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a);try{for(var c=!0,l=zn(this.simulcastCodecs.values()),d;d=yield l.next(),n=d.done,!n;c=!0){s=d.value,c=!1;const u=s;u.sender&&((o=u.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}setProcessor(e){const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return A(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var o,a,c,l,d,u;if(yield n.setProcessor.call(r,i,s),!((d=r.processor)===null||d===void 0)&&d.processedTrack)try{for(var f=!0,p=zn(r.simulcastCodecs.values()),g;g=yield p.next(),o=g.done,!o;f=!0)l=g.value,f=!1,yield(u=l.sender)===null||u===void 0?void 0:u.replaceTrack(r.processor.processedTrack)}catch(h){a={error:h}}finally{try{!f&&!o&&(c=p.return)&&(yield c.call(p))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return A(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const n=this.sender.getParameters();n.degradationPreference=e,this.sender.setParameters(n)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},this.logContext))}})}addSimulcastTrack(e,n){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:n};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,n){const i=this.simulcastCodecs.get(e);i&&(i.sender=n,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},t2))}setPublishingCodecs(e){return A(this,void 0,void 0,function*(){var n,i,r,s,o,a,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Kn(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(n=!0,i=zn(e);r=yield i.next(),s=r.done,!s;n=!0){c=r.value,n=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(Kn(d.codec),d.qualities);else{const u=this.simulcastCodecs.get(d.codec);if(this.log.debug("try setPublishingCodec for ".concat(d.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const f of d.qualities)if(f.enabled){l.push(d.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(d.codec),this.logContext),yield vm(u.sender,u.encodings,d.qualities,this.senderLock,Kn(d.codec),this.log,this.logContext))}}}catch(d){o={error:d}}finally{try{!n&&!s&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return l})}setPublishingLayers(e,n){return A(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:n})),!(!this.sender||!this.encodings)&&(yield vm(this.sender,this.encodings,n,this.senderLock,e,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return A(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xv()&&this.isInBackground&&this.source===V.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function vm(t,e,n,i,r,s,o){return A(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:t,qualities:n,senderEncodings:e}));try{const c=t.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:e}));return}let d=!1;!1&&l[0].scalabilityMode||(r&&n.some(p=>p.enabled)&&n.forEach(p=>p.enabled=!0),l.forEach((f,p)=>{var g;let h=(g=f.rid)!==null&&g!==void 0?g:"";h===""&&(h="q");const y=dy(h),b=n.find(w=>w.quality===y);b&&f.active!==b.enabled&&(d=!0,f.active=b.enabled,s.debug("setting layer ".concat(b.quality," to ").concat(f.active?"enabled":"disabled"),o),qr()&&(b.enabled?(f.scaleResolutionDownBy=e[p].scaleResolutionDownBy,f.maxBitrate=e[p].maxBitrate,f.maxFrameRate=e[p].maxFrameRate):(f.scaleResolutionDownBy=4,f.maxBitrate=10,f.maxFrameRate=2)))})),d&&(c.encodings=l,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield t.setParameters(c))}finally{a()}})}function dy(t){switch(t){case"f":return Jt.HIGH;case"h":return Jt.MEDIUM;case"q":return Jt.LOW;default:return Jt.HIGH}}function ym(t,e,n,i){if(!n)return[new Hi({quality:Jt.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,s=new ly(r),o=[],a=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)o.push(new Hi({quality:Math.min(Jt.HIGH,s.spatial-1)-l,width:Math.ceil(t/Math.pow(a,l)),height:Math.ceil(e/Math.pow(a,l)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return o}return n.map(r=>{var s,o,a;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=dy((o=r.rid)!==null&&o!==void 0?o:"");return new Hi({quality:l,width:Math.ceil(t/c),height:Math.ceil(e/c),bitrate:(a=r.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const bm="_lossy",xm="_reliable",n2=2*1e3,Gc="leave-reconnect",i2=3e4;var rn;(function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"})(rn||(rn={}));class r2 extends Nn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var n;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Lu.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=rn.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Ce,this.reliableDataSequence=1,this.reliableMessageBuffer=new om,this.reliableReceivedState=new RT(i2),this.handleDataChannel=i=>A(this,[i],void 0,function(r){var s=this;let{channel:o}=r;return function*(){if(o){if(o.label===xm)s.reliableDCSub=o;else if(o.label===bm)s.lossyDCSub=o;else return;s.log.debug("on data channel ".concat(o.id,", ").concat(o.label),s.logContext),o.onmessage=s.handleDataMessage}}()}),this.handleDataMessage=i=>A(this,void 0,void 0,function*(){var r,s;const o=yield this.dataProcessLock.lock();try{let a;if(i.data instanceof ArrayBuffer)a=i.data;else if(i.data instanceof Blob)a=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=Mt.fromBinary(new Uint8Array(a));if(c.sequence>0&&c.participantSid!==""){const l=this.reliableReceivedState.get(c.participantSid);if(l&&c.sequence<=l)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(ae.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&o2(c,c.value.value),this.emit(ae.DataPacketReceived,c))}finally{o()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?be.LOSSY:be.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(ae.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){s(o);return}i===Gc&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=bt.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===rn.Connected&&i();const s=()=>{this.off(ae.Disconnected,o),i()},o=()=>{this.off(ae.Restarted,s),r()};this.once(ae.Restarted,s),this.once(ae.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(ae.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return i===be.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount),r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Be.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(dr.RR_SIGNAL_DISCONNECTED))},this.log=Gn((n=e.loggerName)!==null&&n!==void 0?n:fn.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Ou(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Nt,this.dataProcessLock=new Nt,this.dcBufferStatus=new Map([[be.LOSSY,!0],[be.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(ae.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(ae.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(ae.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(ae.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(ae.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(ae.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(ae.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(ae.SignalRequestResponse,i)}get logContext(){var e,n,i,r,s,o;return{room:(n=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||n===void 0?void 0:n.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(o=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,n,i,r){return A(this,void 0,void 0,function*(){this.url=e,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,n,i,r);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),(!this.subscriberPrimary||s.fastPublish)&&this.negotiate(),this.clientConfiguration=s.clientConfiguration,this.emit(ae.SignalConnected,s),s}catch(s){if(s instanceof Ue&&s.reason===Te.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,n,i,r);throw s}})}close(){return A(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(ae.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return A(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const n=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};n(this.lossyDC),n(this.lossyDCSub),n(this.reliableDC),n(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new om,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return A(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Wn("a track with the same ID has already been published");return new Promise((n,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new Ue("publication of local track timed out, no response from server",Te.Timeout))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),n(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:n}=this.pendingTrackResolvers[e.track.id];n&&n(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(n){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:n}))}return!1}updateMuteStatus(e,n){this.client.sendMuteTrack(e,n)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return A(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return A(this,void 0,void 0,function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==Je.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new LT(r,e.subscriberPrimary,this.loggerOptions),this.emit(ae.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,o)=>{this.client.sendIceCandidate(s,o)},this.pcManager.onPublisherOffer=(s,o)=>{this.client.sendOffer(s,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,o,a)=>A(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),s===Je.CONNECTED){const d=this.pcState===rn.New;this.pcState=rn.Connected,d&&this.emit(ae.Connected,e)}else s===Je.FAILED&&this.pcState===rn.Connected&&(this.pcState=rn.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?dr.RR_SUBSCRIBER_FAILED:dr.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===Be.RECONNECTING,l=[Je.FAILED,Je.CLOSING,Je.CLOSED].includes(s);c&&l&&!this._isClosed&&this.emit(ae.Offline)}),this.pcManager.onTrack=s=>{this.emit(ae.MediaTrackAdded,s.track,s.streams[0],s.receiver)},s2((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,n)=>A(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,n))}),this.client.onTrickle=(e,n)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:n})),this.pcManager.addIceCandidate(e,n))},this.client.onOffer=(e,n)=>A(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=n,!this.pcManager)return;const i=yield this.pcManager.createSubscriberAnswerFromOffer(e,n);i&&this.client.sendAnswer(i,n)}),this.client.onLocalTrackPublished=e=>{var n;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(n=e.track)===null||n===void 0?void 0:n.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(ae.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(ae.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,n)=>{this.emit(ae.RemoteMute,e,n)},this.client.onSubscribedQualityUpdate=e=>{this.emit(ae.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var n;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(ae.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",dr.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Nr.DISCONNECT:this.emit(ae.Disconnected,e==null?void 0:e.reason),this.close();break;case Nr.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Gc);break;case Nr.RESUME:this.handleDisconnect(Gc)}}}makeRTCConfiguration(e){var n;const i=Object.assign({},this.rtcConfig);if(!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(s=>{const o={urls:s.urls};s.username&&(o.username=s.username),s.credential&&(o.credential=s.credential),r.push(o)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Hs.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(bm,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(xm,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,n,i){return A(this,void 0,void 0,function*(){if(cd())return yield this.createTransceiverRTCRtpSender(e,n,i);if(ld())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ht("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,n,i,r){return A(this,void 0,void 0,function*(){if(cd())return this.createSimulcastTransceiverSender(e,n,i,r);if(ld())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ht("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,n,i){return A(this,void 0,void 0,function*(){if(!this.pcManager)throw new ht("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),ns(e)&&(e.codec=n.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,n,i,r){return A(this,void 0,void 0,function*(){if(!this.pcManager)throw new ht("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const o=yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return A(this,void 0,void 0,function*(){if(!this.pcManager)throw new ht("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return A(this,void 0,void 0,function*(){var n,i,r;if(!this._isClosed){if(this.attemptingReconnect){Ce.warn("already attempting reconnect, returning early",this.logContext);return}(((n=this.clientConfiguration)===null||n===void 0?void 0:n.resumeConnection)===Hs.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Je.NEW)===Je.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let o=!0;s instanceof ht?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),o=!1):s instanceof ur||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",dr.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(ae.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(n){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:n}))}return null}restartConnection(e){return A(this,void 0,void 0,function*(){var n,i,r;try{if(!this.url||!this.token)throw new ht("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(ae.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new ur;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof Ue&&o.reason===Te.NotAllowed?new ht("could not reconnect, token might be expired"):new ur}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(ae.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==Be.CONNECTED)throw new ur("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(ae.Restarted)}catch(s){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return A(this,void 0,void 0,function*(){var n;if(!this.url||!this.token)throw new ht("could not reconnect, url or token not saved");if(!this.pcManager)throw new ht("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(ae.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof Ue&&r.reason===Te.NotAllowed?new ht("could not reconnect, token might be expired"):r instanceof Ue&&r.reason===Te.LeaveRequest?r:new ur(s)}if(this.emit(ae.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Be.CONNECTED)throw new ur("Signal connection got severed during reconnect");this.client.setReconnected(),((n=this.reliableDC)===null||n===void 0?void 0:n.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(ae.Resumed)})}waitForPCInitialConnection(e,n){return A(this,void 0,void 0,function*(){if(!this.pcManager)throw new ht("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,e)})}waitForPCReconnected(){return A(this,void 0,void 0,function*(){this.pcState=rn.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield jt(n2),!this.pcManager)throw new ht("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=rn.Connected}catch(e){throw this.pcState=rn.Disconnected,new Ue("could not establish PC connection, ".concat(e.message),Te.InternalError)}})}publishRpcResponse(e,n,i,r){return A(this,void 0,void 0,function*(){const s=new Mt({destinationIdentities:[e],kind:be.RELIABLE,value:{case:"rpcResponse",value:new Q0({requestId:n,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,be.RELIABLE)})}publishRpcAck(e,n){return A(this,void 0,void 0,function*(){const i=new Mt({destinationIdentities:[e],kind:be.RELIABLE,value:{case:"rpcAck",value:new X0({requestId:n})}});yield this.sendDataPacket(i,be.RELIABLE)})}sendDataPacket(e,n){return A(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(n),n===be.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),r=this.dataChannelForKind(n);if(r){if(n===be.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;r.send(i)}this.updateAndEmitDCBufferStatus(n)})}resendReliableMessagesForResume(e){return A(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(be.RELIABLE);const n=this.dataChannelForKind(be.RELIABLE);n&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{n.send(i.data)})),this.updateAndEmitDCBufferStatus(be.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((n,i)=>A(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))n();else{const r=()=>i("Engine closed");for(this.once(ae.Closing,r);!this.dcBufferStatus.get(e);)yield jt(10);this.off(ae.Closing,r),n()}}))}ensureDataTransportConnected(e){return A(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!i.pcManager)throw new ht("PC manager is closed");const o=r?i.pcManager.subscriber:i.pcManager.publisher,a=r?"Subscriber":"Publisher";if(!o)throw new Ue("".concat(a," connection not set"),Te.InternalError);let c=!1;!r&&!i.dataChannelForKind(n,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const l=i.dataChannelForKind(n,r);if((l==null?void 0:l.readyState)==="open")return;const d=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<d;){if(o.isICEConnected&&((s=i.dataChannelForKind(n,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield jt(50)}throw new Ue("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()),Te.InternalError)}()})}ensurePublisherConnected(e){return A(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Je.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return A(this,void 0,void 0,function*(){return new Promise((e,n)=>A(this,void 0,void 0,function*(){if(!this.pcManager){n(new sd("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(ae.Closing,r),this.pcManager.publisher.once(Lr.RTPVideoPayloadTypes,s=>{const o=new Map;s.forEach(a=>{const c=a.codec.toLowerCase();aT(c)&&o.set(a.payload,c)}),this.emit(ae.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof sd&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",dr.RR_UNKNOWN),n(s)}finally{this.off(ae.Closing,r)}}))})}dataChannelForKind(e,n){if(n){if(e===be.LOSSY)return this.lossyDCSub;if(e===be.RELIABLE)return this.reliableDCSub}else{if(e===be.LOSSY)return this.lossyDC;if(e===be.RELIABLE)return this.reliableDC}}sendSyncState(e,n){var i,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),a=(r=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&r!==void 0?r:!0,c=new Array,l=new Array;e.forEach(d=>{d.isDesired!==a&&c.push(d.trackSid),d.isEnabled||l.push(d.trackSid)}),this.client.sendSyncState(new gv({answer:s?ka({sdp:s.sdp,type:s.type}):void 0,offer:o?ka({sdp:o.sdp,type:o.type}):void 0,subscription:new Za({trackSids:c,subscribe:!a,participantTracks:[]}),publishTracks:gT(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((d,u)=>new vv({publisherSid:u,lastSeq:d}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new yv({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(be.LOSSY),ln.PUBLISHER),n(this.dataChannelForKind(be.RELIABLE),ln.PUBLISHER),n(this.dataChannelForKind(be.LOSSY,!0),ln.SUBSCRIBER),n(this.dataChannelForKind(be.RELIABLE,!0),ln.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&bt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ot()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Ot()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class ur extends Error{}function s2(t){return t!==void 0&&t>13}function o2(t,e){const n=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=n,e.participantIdentity=n;const i=t.destinationIdentities.length!==0?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=i,e.destinationIdentities=i}class bd{constructor(e,n){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=n}updateToken(e){this.token=e}isCloud(){return ud(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return A(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const n=this.regionSettings.regions.filter(i=>!this.attemptedRegions.find(r=>r.url===i.url));if(n.length>0){const i=n[0];return this.attemptedRegions.push(i),Ce.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return A(this,void 0,void 0,function*(){const n=yield fetch("".concat(a2(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(n.ok){const i=yield n.json();return this.lastUpdateAt=Date.now(),i}else throw new Ue("Could not fetch region settings: ".concat(n.statusText),n.status===401?Te.NotAllowed:Te.InternalError,n.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function a2(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class uy{get info(){return this._info}constructor(e,n,i){this.reader=n,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class c2 extends uy{handleChunkReceived(e){var n;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>A(this,void 0,void 0,function*(){try{const{done:n,value:i}=yield e.read();return n?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch{return{done:!0,value:void 0}}}),return(){return A(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return A(this,void 0,void 0,function*(){var e,n,i,r;let s=new Set;try{for(var o=!0,a=zn(this),c;c=yield a.next(),e=c.done,!e;o=!0){r=c.value,o=!1;const l=r;s.add(l)}}catch(l){n={error:l}}finally{try{!o&&!e&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}return Array.from(s)})}}class l2 extends uy{constructor(e,n,i){super(e,n,i),this.receivedChunks=new Map}handleChunkReceived(e){var n;const i=ra(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),n=new TextDecoder;return{next:()=>A(this,void 0,void 0,function*(){try{const{done:i,value:r}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:n.decode(r.content)})}catch{return{done:!0,value:void 0}}}),return(){return A(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return A(this,void 0,void 0,function*(){var e,n,i,r;let s="";try{for(var o=!0,a=zn(this),c;c=yield a.next(),e=c.done,!e;o=!0)r=c.value,o=!1,s+=r}catch(l){n={error:l}}finally{try{!o&&!e&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}return s})}}class fy{constructor(e,n,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=n}write(e){return this.defaultWriter.write(e)}close(){return A(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class d2 extends fy{}class u2 extends fy{}class hy extends V{constructor(e,n,i,r,s){super(e,i,s),this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?re.Muted:re.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const n=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(re.Ended,this))};e.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return A(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Fu)),vT()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var n;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(n=this.receiver)===null||n===void 0?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(re.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class my extends hy{constructor(e,n,i,r,s,o){super(e,n,V.Kind.Audio,i,o),this.monitorReceiver=()=>A(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Xa(a,this.prevStats)),this.prevStats=a}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var n;for(const i of this.attachedElements)this.audioContext?(n=this.gainNode)===null||n===void 0||n.gain.setTargetAtTime(e,0,.1):i.volume=e;In()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(In())return 1;let e=0;return this.attachedElements.forEach(n=>{n.volume>e&&(e=n.volume)}),e}setSinkId(e){return A(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(n=>{if(dd(n))return n.setSinkId(e)}))})}attach(e){const n=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&dd(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&n&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let n;return e?(n=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(n=super.detach(),this.disconnectWebAudio()),n}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,n){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(re.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(re.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,n;(e=this.gainNode)===null||e===void 0||e.disconnect(),(n=this.sourceNode)===null||n===void 0||n.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return A(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n;return e.forEach(i=>{i.type==="inbound-rtp"&&(n={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),n})}}const Zc=100;class f2 extends hy{constructor(e,n,i,r,s){super(e,n,V.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>A(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=Xa(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=ju(()=>{this.updateDimensions()},Zc),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(n=>{e?Dr(this._mediaStreamTrack,n):kr(this._mediaStreamTrack,n)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(n=>n.element===e)===void 0){const n=new h2(e);this.observeElementInfo(n)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(n=>n===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const n=this.elementInfos.filter(i=>i===e);for(const i of n)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let n=[];if(e)return this.stopObservingElement(e),super.detach(e);n=super.detach();for(const i of n)this.stopObservingElement(i);return n}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return A(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,n={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),n&&i!==""&&r.get(i)&&(n.mimeType=r.get(i).mimeType),n})}stopObservingElement(e){const n=this.elementInfos.filter(i=>i.element===e);for(const i of n)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return A(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,n;const i=this.elementInfos.reduce((a,c)=>Math.max(a,c.visibilityChangedAt||0),0),r=!((n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,s=this.elementInfos.some(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!r||s;if(this.lastVisible!==o){if(!o&&Date.now()-i<Zc){bt.setTimeout(()=>{this.updateVisibility()},Zc);return}this.lastVisible=o,this.emit(re.VisibilityChanged,o,this)}}updateDimensions(){var e,n;let i=0,r=0;const s=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*s,c=o.height()*s;a+c>i+r&&(i=a,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((n=this.lastDimensions)===null||n===void 0?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(re.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return n==="screen"?em():n||(em()>2?2:1)}}class h2{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,n){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:o}=i;s===this.element&&(this.isIntersecting=o,this.isPiP=ks(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ks(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=ks(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=n??xd(e),this.isPiP=Ot()&&ks(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,n,i;this.isIntersecting=xd(this.element),this.isPiP=ks(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,nm().observe(this.element),tm().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,n,i,r,s;(e=nm())===null||e===void 0||e.unobserve(this.element),(n=tm())===null||n===void 0||n.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function ks(t){var e,n;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?xd(t,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function xd(t,e){const n=e||window;let i=t.offsetTop,r=t.offsetLeft;const s=t.offsetWidth,o=t.offsetHeight,{hidden:a}=t,{display:c}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,i+=t.offsetTop,r+=t.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+s>n.pageXOffset&&!a&&c!=="none"}class Bn extends Nn.EventEmitter{constructor(e,n,i,r){var s;super(),this.metadataMuted=!1,this.encryption=Ft.NONE,this.log=Ce,this.handleMuted=()=>{this.emit(re.Muted)},this.handleUnmuted=()=>{this.emit(re.Unmuted)},this.log=Gn((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:fn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=n,this.trackName=i,this.source=V.Source.Unknown}setTrack(e){this.track&&(this.track.off(re.Muted,this.handleMuted),this.track.off(re.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(re.Muted,this.handleMuted),e.on(re.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),we(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Ft.NONE}get audioTrack(){if(Tn(this.track))return this.track}get videoTrack(){if(ns(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=V.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===V.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(t){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(t.SubscriptionStatus||(t.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(t.PermissionStatus||(t.PermissionStatus={}))})(Bn||(Bn={}));class Sd extends Bn{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(re.Ended)},this.updateInfo(n),this.setTrack(i)}setTrack(e){this.track&&this.track.off(re.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(re.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return A(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return A(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return A(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return A(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Tn(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(pt.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(pt.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(pt.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(pt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(pt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(pt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Qa(t,e){return A(this,void 0,void 0,function*(){t??(t={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=iy(t);let o=s.audio,a=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),t.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const u=s.audio.deviceId;s.audio.deviceId={exact:u},n=!0,o=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:u}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const u=s.video.deviceId;s.video.deviceId={exact:u},n=!0,a=Object.assign(Object.assign({},s.video),{deviceId:{ideal:u}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const c=ty(s,sy,oy),l=_u(c),d=navigator.mediaDevices.getUserMedia(l);s.audio&&(gt.userMediaPromiseMap.set("audioinput",d),d.catch(()=>gt.userMediaPromiseMap.delete("audioinput"))),s.video&&(gt.userMediaPromiseMap.set("videoinput",d),d.catch(()=>gt.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(f=>A(this,void 0,void 0,function*(){const p=f.kind==="audio";let g=p?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let h;const y=p?l.audio:l.video;typeof y!="boolean"&&(h=y);const b=f.getSettings().deviceId;h!=null&&h.deviceId&&fi(h.deviceId)!==b?h.deviceId=b:h||(h={deviceId:b});const w=zT(f,h,e);return w.kind===V.Kind.Video?w.source=V.Source.Camera:w.kind===V.Kind.Audio&&(w.source=V.Source.Microphone),w.mediaStream=u,Tn(w)&&i?yield w.setProcessor(i):ns(w)&&r&&(yield w.setProcessor(r)),w})))}catch(u){if(!n)throw u;return Qa(Object.assign(Object.assign({},t),{audio:o,video:a}),e)}})}function m2(t){return A(this,void 0,void 0,function*(){return(yield Qa({audio:!1,video:!0}))[0]})}function p2(t){return A(this,void 0,void 0,function*(){return(yield Qa({audio:!0,video:!1}))[0]})}var ci;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(ci||(ci={}));function g2(t){switch(t){case As.EXCELLENT:return ci.Excellent;case As.GOOD:return ci.Good;case As.POOR:return ci.Poor;case As.LOST:return ci.Lost;default:return ci.Unknown}}class py extends Nn.EventEmitter{get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Yi.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===_r.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,n,i,r,s,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Yi.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=ci.Unknown,this.log=Ce,this.log=Gn((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:fn.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,n]of this.trackPublications)if(n.source===e)return n}getTrackPublicationByName(e){for(const[,n]of this.trackPublications)if(n.trackName===e)return n}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Tr,this.once(Z.Active,()=>{var e,n;(n=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||n===void 0||n.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const n=this.getTrackPublication(V.Source.Camera);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const n=this.getTrackPublication(V.Source.Microphone);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(V.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var n;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===_r.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==_r.ACTIVE&&this.emit(Z.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const n=this.metadata!==e,i=this.metadata;this.metadata=e,n&&this.emit(Z.ParticipantMetadataChanged,i)}_setName(e){const n=this.name!==e;this.name=e,n&&this.emit(Z.ParticipantNameChanged,e)}_setAttributes(e){const n=yT(this.attributes,e);this._attributes=e,Object.keys(n).length>0&&this.emit(Z.AttributesChanged,n)}setPermissions(e){var n,i,r,s,o,a;const c=this.permissions,l=e.canPublish!==((n=this.permissions)===null||n===void 0?void 0:n.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((d,u)=>{var f;return d!==((f=this.permissions)===null||f===void 0?void 0:f.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,l&&this.emit(Z.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(Z.IsSpeakingChanged,e))}setConnectionQuality(e){const n=this._connectionQuality;this._connectionQuality=g2(e),n!==this._connectionQuality&&this.emit(Z.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,n;this.activeFuture&&((n=(e=this.activeFuture).reject)===null||n===void 0||n.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(n=>Tn(n.track)&&n.track.setAudioContext(e))}addTrackPublication(e){e.on(re.Muted,()=>{this.emit(Z.TrackMuted,e)}),e.on(re.Unmuted,()=>{this.emit(Z.TrackUnmuted,e)});const n=e;switch(n.track&&(n.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case V.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case V.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function v2(t){var e,n,i;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new mv({participantIdentity:(e=t.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(n=t.participantSid)!==null&&n!==void 0?n:"",allTracks:(i=t.allowAll)!==null&&i!==void 0?i:!1,trackSids:t.allowedTrackSids||[]})}const Sm=15e3;class y2 extends py{constructor(e,n,i,r,s){super(e,n,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Ft.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Tr)},this.handleReconnected=()=>{var o,a;(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||a===void 0||a.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var o,a,c,l,d,u;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||a===void 0||a.call(o,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((l=(c=this.signalConnectedFuture).reject)===null||l===void 0||l.call(c,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(u=(d=this.activeAgentFuture)===null||d===void 0?void 0:d.reject)===null||u===void 0||u.call(d,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var a,c;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Tr),(c=(a=this.signalConnectedFuture).resolve)===null||c===void 0||c.call(a)},this.handleSignalRequestResponse=o=>{const{requestId:a,reason:c,message:l}=o,d=this.pendingSignalRequests.get(a);d&&(c!==Ru.OK&&d.reject(new Zh(l,c)),this.pendingSignalRequests.delete(a))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let a=o.value.value,c=null,l=null;a.value.case==="payload"?c=a.value.value:a.value.case==="error"&&(l=Qe.fromProto(a.value.value)),this.handleIncomingRpcResponse(a.requestId,c,l);break;case"rpcAck":let d=o.value.value;this.handleIncomingRpcAck(d.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(o=>v2(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,a)=>{if(a===void 0&&(a=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),we(o)));return}this.engine.updateMuteStatus(o.sid,a)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),we(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),we(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const a=this.audioTrackPublications.get(o.sid);if(!a){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(a.trackSid,a.getTrackFeatures())},this.handleSubscribedQualityUpdate=o=>A(this,void 0,void 0,function*(){var a,c,l,d,u;if(!(!((u=this.roomOptions)===null||u===void 0)&&u.dynacast))return;const f=this.videoTrackPublications.get(o.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!f.videoTrack)return;const p=yield f.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var g=!0,h=zn(p),y;y=yield h.next(),a=y.done,!a;g=!0){d=y.value,g=!1;const b=d;Gk(b)&&(this.log.debug("publish ".concat(b," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),we(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,b,f.options))}}catch(b){c={error:b}}finally{try{!g&&!a&&(l=h.return)&&(yield l.call(h))}finally{if(c)throw c.error}}}),this.handleLocalTrackUnpublished=o=>{const a=this.trackPublications.get(o.trackSid);if(!a){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(a.track)},this.handleTrackEnded=o=>A(this,void 0,void 0,function*(){if(o.source===V.Source.ScreenShare||o.source===V.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),we(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(Un(o)||ii(o))try{if(Ot())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:o.source===V.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),we(o))),a.onchange=()=>{a.state!=="denied"&&(o.isMuted||o.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),we(o))),Un(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),we(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Ft.NONE}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setupEngine(e){this.engine=e,this.engine.on(ae.RemoteMute,(n,i)=>{const r=this.trackPublications.get(n);!r||!r.track||(i?r.mute():r.unmute())}),this.engine.on(ae.Connected,this.handleReconnected).on(ae.SignalConnected,this.handleSignalConnected).on(ae.SignalRestarted,this.handleReconnected).on(ae.SignalResumed,this.handleReconnected).on(ae.Restarting,this.handleReconnecting).on(ae.Resuming,this.handleReconnecting).on(ae.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(ae.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(ae.Disconnected,this.handleDisconnected).on(ae.SignalRequestResponse,this.handleSignalRequestResponse).on(ae.DataPacketReceived,this.handleDataPacket),this.signalConnectedFuture=void 0}setMetadata(e){return A(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return A(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return A(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return A(this,arguments,void 0,function(n){var i=this;let{metadata:r,name:s,attributes:o}=n;return function*(){return new Promise((a,c)=>A(i,void 0,void 0,function*(){var l,d;try{let u=!1;const f=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(d=s??this.name)!==null&&d!==void 0?d:"",o),p=performance.now();for(this.pendingSignalRequests.set(f,{resolve:a,reject:g=>{c(g),u=!0},values:{name:s,metadata:r,attributes:o}});performance.now()-p<5e3&&!u;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!o||Object.entries(o).every(g=>{let[h,y]=g;return this.attributes[h]===y||y===""&&!this.attributes[h]}))){this.pendingSignalRequests.delete(f),a();return}yield jt(50)}c(new Zh("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))}()})}setCameraEnabled(e,n,i){return this.setTrackEnabled(V.Source.Camera,e,n,i)}setMicrophoneEnabled(e,n,i){return this.setTrackEnabled(V.Source.Microphone,e,n,i)}setScreenShareEnabled(e,n,i){return this.setTrackEnabled(V.Source.ScreenShare,e,n,i)}setPermissions(e){const n=this.permissions,i=super.setPermissions(e);return i&&n&&this.emit(Z.ParticipantPermissionsChanged,n),i}setE2EEEnabled(e){return A(this,void 0,void 0,function*(){this.encryptionType=e?Ft.GCM:Ft.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,n,i,r){return A(this,void 0,void 0,function*(){var s,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:n})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(n)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case V.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case V.Source.Microphone:c=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case V.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Wn(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(Z.MediaDevicesError,l,pd(e)),this.pendingPublishing.delete(e),l}for(const l of c)e===V.Source.Microphone&&Tn(l)&&(r!=null&&r.preConnectBuffer)&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer());try{const l=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),we(u))),l.push(this.publishTrack(u,r));[a]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(a!=null&&a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===V.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(V.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return A(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(V.Source.Camera)||this.pendingPublishing.has(V.Source.Microphone))){this.pendingPublishing.add(V.Source.Camera),this.pendingPublishing.add(V.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(n=>this.publishTrack(n)))}finally{this.pendingPublishing.delete(V.Source.Camera),this.pendingPublishing.delete(V.Source.Microphone)}}})}createTracks(e){return A(this,void 0,void 0,function*(){var n,i;e??(e={});const r=ty(e,(n=this.roomOptions)===null||n===void 0?void 0:n.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Qa(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(Tn(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=V.Source.Microphone,this.emit(Z.AudioStreamAcquired)),ns(a)&&(this.cameraError=void 0,a.source=V.Source.Camera),a))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return A(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Iu("getDisplayMedia not supported");e.resolution===void 0&&!eT()&&(e.resolution=Mu.h1080fps30.resolution);const n=pT(e),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new Wn("no video track found");const s=new Ea(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=V.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const o=[s];if(i.getAudioTracks().length>0){this.emit(Z.AudioStreamAcquired);const a=new Ta(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=V.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,n){return A(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,n)})}publishOrRepublishTrack(e,n){return A(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var a,c,l,d;Un(i)&&i.setAudioContext(s.audioContext),yield(a=s.reconnectFuture)===null||a===void 0?void 0:a.promise,s.republishPromise&&!o&&(yield s.republishPromise),jr(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let b;switch(i.source){case V.Source.Microphone:b="audioinput";break;case V.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(u=Object.assign(Object.assign({},u),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Ta(i,u,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Ea(i,u,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Wn("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let f;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(f=b)}),f)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),we(f))),f;const p="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,g=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:p;g&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),we(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=r.dtx)!==null&&l!==void 0||(r.dtx=!1),(d=r.red)!==null&&d!==void 0||(r.red=!1));const h=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!nT()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},s.logContext)),h.simulcast=!1),h.source&&(i.source=h.source);const y=new Promise((b,w)=>A(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Be.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:we(i)}));const C=setTimeout(()=>{w(new Gh("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(C);const S=yield this.publish(i,h,g);b(S)}else try{const C=yield this.publish(i,h,g);b(C)}catch(C){w(C)}}catch(C){w(C)}}));s.pendingPublishPromises.set(i,y);try{return yield y}catch(b){throw b}finally{s.pendingPublishPromises.delete(i)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Tr),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),we(e))),!1;const{canPublish:n,canPublishSources:i}=this.permissions;return n&&(i.length===0||i.map(r=>bT(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),we(e))),!1)}publish(e,n,i){return A(this,void 0,void 0,function*(){var r,s,o,a,c,l,d,u,f,p;if(!this.hasPermissionsToPublish(e))throw new Gh("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(_=>jr(e)&&_.source===e.source)&&e.source!==V.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),we(e))),n.stopMicTrackOnMute&&Tn(e)&&(e.stopOnMute=!0),e.source===V.Source.ScreenShare&&qr()&&(n.simulcast=!1),n.videoCodec==="av1"&&!Jk()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!Xk()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=gd),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(_=>n.videoCodec===sa(_.mime))||(n.videoCodec=sa(this.enabledPublishVideoCodecs[0].mime)));const h=n.videoCodec;e.on(re.Muted,this.onTrackMuted),e.on(re.Unmuted,this.onTrackUnmuted),e.on(re.Ended,this.handleTrackEnded),e.on(re.UpstreamPaused,this.onTrackUpstreamPaused),e.on(re.UpstreamResumed,this.onTrackUpstreamResumed),e.on(re.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const y=[],b=!(!((r=n.dtx)!==null&&r!==void 0)||r),w=e.getSourceTrackSettings();w.autoGainControl&&y.push(pt.TF_AUTO_GAIN_CONTROL),w.echoCancellation&&y.push(pt.TF_ECHO_CANCELLATION),w.noiseSuppression&&y.push(pt.TF_NOISE_SUPPRESSION),w.channelCount&&w.channelCount>1&&y.push(pt.TF_STEREO),b&&y.push(pt.TF_NO_DTX),Un(e)&&e.hasPreConnectBuffer&&y.push(pt.TF_PRECONNECT_BUFFER);const C=new Yl({cid:e.mediaStreamTrack.id,name:n.name,type:V.kindToProto(e.kind),muted:e.isMuted,source:V.sourceToProto(e.source),disableDtx:b,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=n.red)!==null&&s!==void 0)||s),stream:n==null?void 0:n.stream,backupCodecPolicy:n==null?void 0:n.backupCodecPolicy,audioFeatures:y});let S;if(e.kind===V.Kind.Video){let _={width:0,height:0};try{_=yield e.waitForDimensions()}catch{const I=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:zs.h720.resolution;_={width:I.width,height:I.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),we(e)),{dims:_}))}C.width=_.width,C.height=_.height,ii(e)&&(Kn(h)&&(e.source===V.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),we(e))))),n.scalabilityMode=(c=n.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),C.simulcastCodecs=[new Zl({codec:h,cid:e.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:gd}),n.backupCodec&&h!==n.backupCodec.codec&&C.encryption===Ft.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),C.simulcastCodecs.push(new Zl({codec:n.backupCodec.codec,cid:""})))),S=yd(e.source===V.Source.ScreenShare,C.width,C.height,n),C.layers=ym(C.width,C.height,S,Kn(n.videoCodec))}else e.kind===V.Kind.Audio&&(S=[{maxBitrate:(l=n.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(u=(d=n.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&u!==void 0?u:"high",networkPriority:(p=(f=n.audioPreset)===null||f===void 0?void 0:f.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new ht("cannot publish track when not connected");const x=()=>A(this,void 0,void 0,function*(){var _,k,I;if(!this.engine.pcManager)throw new ht("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,n,S),ii(e)&&((_=n.degradationPreference)!==null&&_!==void 0||(n.degradationPreference=e2(e)),e.setDegradationPreference(n.degradationPreference)),S)if(qr()&&e.kind===V.Kind.Audio){let N;for(const K of this.engine.pcManager.publisher.getTransceivers())if(K.sender===e.sender){N=K;break}N&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:N,codec:"opus",maxbr:!((k=S[0])===null||k===void 0)&&k.maxBitrate?S[0].maxBitrate/1e3:0})}else e.codec&&Kn(e.codec)&&(!((I=S[0])===null||I===void 0)&&I.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:C.cid,codec:e.codec,maxbr:S[0].maxBitrate/1e3});yield this.engine.negotiate()});let T;const E=new Promise((_,k)=>A(this,void 0,void 0,function*(){var I;try{T=yield this.engine.addTrack(C),_(T)}catch(N){e.sender&&(!((I=this.engine.pcManager)===null||I===void 0)&&I.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(K=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),we(e)),{error:K}))})),k(N)}}));if(this.enabledPublishVideoCodecs.length>0)T=(yield Promise.all([E,x()]))[0];else{T=yield E;let _;if(T.codecs.forEach(k=>{_===void 0&&(_=k.mimeType)}),_&&e.kind===V.Kind.Video){const k=sa(_);k!==h&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),we(e)),{codec:k})),n.videoCodec=k,S=yd(e.source===V.Source.ScreenShare,C.width,C.height,n))}yield x()}const P=new Sd(e.kind,T,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(P.options=n,e.sid=T.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:S,trackInfo:T})),ii(e)?e.startMonitor(this.engine.client):Un(e)&&e.startMonitor(),this.addTrackPublication(P),this.emit(Z.LocalTrackPublished,P),Un(e)&&T.audioFeatures.includes(pt.TF_PRECONNECT_BUFFER)){const _=e.getPreConnectBuffer();this.on(Z.LocalTrackSubscribed,k=>{if(k.trackSid===T.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),we(e))),e.stopPreConnectBuffer()}}),_&&new Promise((I,N)=>A(this,void 0,void 0,function*(){var K,J,se,ie,X,O;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),we(e)));const te=setTimeout(()=>{N(new Error("agent not active within 10 seconds"))},1e4),j=yield this.waitUntilActiveAgentPresent();clearTimeout(te),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),we(e)));const q=yield this.streamBytes({name:"preconnect-buffer",mimeType:"audio/opus",topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[j.identity],attributes:{trackId:P.trackSid,sampleRate:String((X=w.sampleRate)!==null&&X!==void 0?X:"48000"),channels:String((O=w.channelCount)!==null&&O!==void 0?O:"1")}});try{for(var oe=!0,L=zn(_),F;F=yield L.next(),K=F.done,!K;oe=!0){ie=F.value,oe=!1;const ee=ie;yield q.write(ee)}}catch(ee){J={error:ee}}finally{try{!oe&&!K&&(se=L.return)&&(yield se.call(L))}finally{if(J)throw J.error}}yield q.close(),I()}catch(te){N(te)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),we(e)))}).catch(I=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),we(e)),{error:I}))})}return P})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,n,i){return A(this,void 0,void 0,function*(){var r;if(this.encryptionType!==Ft.NONE)return;let s;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(s=p)}),!s)throw new Wn("track is not published");if(!ii(e))throw new Wn("track is not a video track");const o=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),a=JT(e,n,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),we(e)));return}const c=e.addSimulcastTrack(n,a);if(!c)return;const l=new Yl({cid:c.mediaStreamTrack.id,type:V.kindToProto(e.kind),muted:e.isMuted,source:V.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=ym(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new ht("cannot publish track when not connected");const d=()=>A(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate()}),f=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(n," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:f}))})}unpublishTrack(e,n){return A(this,void 0,void 0,function*(){var i,r;if(jr(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),we(e))),yield l)}const s=this.getPublicationForTrack(e),o=s?we(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=s.track,e.off(re.Muted,this.onTrackMuted),e.off(re.Unmuted,this.onTrackUnmuted),e.off(re.Ended,this.handleTrackEnded),e.off(re.UpstreamPaused,this.onTrackUpstreamPaused),e.off(re.UpstreamResumed,this.onTrackUpstreamResumed),e.off(re.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),n===void 0&&(n=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),n?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Je.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),ii(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case V.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case V.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(Z.LocalTrackUnpublished,s),s.setTrack(void 0),a&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return A(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return A(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((s,o)=>A(i,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(n&&(c.options=Object.assign(Object.assign({},c.options),n)),a.push(c))}),yield Promise.all(a.map(c=>A(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==V.Source.ScreenShare&&l.source!==V.Source.ScreenShareAudio&&(Un(l)||ii(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(a){o(a)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return A(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const s=r.reliable?be.RELIABLE:be.LOSSY,o=r.destinationIdentities,a=r.topic,c=new Mt({kind:s,value:{case:"user",value:new Z0({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:a})}});yield i.engine.sendDataPacket(c,s)}()})}publishDtmf(e,n){return A(this,void 0,void 0,function*(){const i=new Mt({kind:be.RELIABLE,value:{case:"sipDtmf",value:new Y0({code:e,digit:n})}});yield this.engine.sendDataPacket(i,be.RELIABLE)})}sendChatMessage(e,n){return A(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:n==null?void 0:n.attachments},r=new Mt({value:{case:"chatMessage",value:new Hl(Object.assign(Object.assign({},i),{timestamp:ze.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,be.RELIABLE),this.emit(Z.ChatMessage,i),i})}editChatMessage(e,n){return A(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},n),{message:e,editTimestamp:Date.now()}),r=new Mt({value:{case:"chatMessage",value:new Hl(Object.assign(Object.assign({},i),{timestamp:ze.parse(i.timestamp),editTimestamp:ze.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,be.RELIABLE),this.emit(Z.ChatMessage,i),i})}sendText(e,n){return A(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(i=n==null?void 0:n.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),l=(u,f)=>{var p;c[f]=u;const g=c.reduce((h,y)=>h+y,0);(p=n==null?void 0:n.onProgress)===null||p===void 0||p.call(n,g)},d=yield this.streamText({streamId:r,totalSize:o,destinationIdentities:n==null?void 0:n.destinationIdentities,topic:n==null?void 0:n.topic,attachedStreamIds:a,attributes:n==null?void 0:n.attributes});return yield d.write(e),l(1,0),yield d.close(),n!=null&&n.attachments&&a&&(yield Promise.all(n.attachments.map((u,f)=>A(this,void 0,void 0,function*(){return this._sendFile(a[f],u,{topic:n.topic,mimeType:u.type,onProgress:p=>{l(p,f+1)}})})))),d.info})}streamText(e){return A(this,void 0,void 0,function*(){var n,i;const r=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},o=new Wl({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:Li(s.timestamp),totalLength:Li(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new av({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?zl.UPDATE:zl.CREATE})}}),a=e==null?void 0:e.destinationIdentities,c=new Mt({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,be.RELIABLE);let l=0;const d=this,u=new WritableStream({write(g){return A(this,void 0,void 0,function*(){for(const h of hT(g,Sm)){yield d.engine.waitForBufferStatusLow(be.RELIABLE);const y=new ql({content:h,streamId:r,chunkIndex:Li(l)}),b=new Mt({destinationIdentities:a,value:{case:"streamChunk",value:y}});yield d.engine.sendDataPacket(b,be.RELIABLE),l+=1}})},close(){return A(this,void 0,void 0,function*(){const g=new Kl({streamId:r}),h=new Mt({destinationIdentities:a,value:{case:"streamTrailer",value:g}});yield d.engine.sendDataPacket(h,be.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let f=()=>A(this,void 0,void 0,function*(){yield p.close()});d.engine.once(ae.Closing,f);const p=new d2(u,s,()=>this.engine.off(ae.Closing,f));return p})}sendFile(e,n){return A(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,n),{id:i}})}_sendFile(e,n,i){return A(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:n.size,name:n.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:n.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=n.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return A(this,void 0,void 0,function*(){var n,i,r,s,o;const a=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,l={id:a,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown"},d=new Wl({totalLength:Li((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:a,topic:l.topic,timestamp:Li(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new cv({name:l.name})}}),u=new Mt({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(u,be.RELIABLE);let f=0;const p=new Nt,g=this.engine,h=this.log,y=new WritableStream({write(w){return A(this,void 0,void 0,function*(){const C=yield p.lock();let S=0;try{for(;S<w.byteLength;){const x=w.slice(S,S+Sm);yield g.waitForBufferStatusLow(be.RELIABLE);const T=new Mt({destinationIdentities:c,value:{case:"streamChunk",value:new ql({content:x,streamId:a,chunkIndex:Li(f)})}});yield g.sendDataPacket(T,be.RELIABLE),f+=1,S+=x.byteLength}}finally{C()}})},close(){return A(this,void 0,void 0,function*(){const w=new Kl({streamId:a}),C=new Mt({destinationIdentities:c,value:{case:"streamTrailer",value:w}});yield g.sendDataPacket(C,be.RELIABLE)})},abort(w){h.error("Sink error:",w)}});return new u2(y,l)})}performRpc(e){return A(this,arguments,void 0,function(n){var i=this;let{destinationIdentity:r,method:s,payload:o,responseTimeout:a=1e4}=n;return function*(){return new Promise((l,d)=>A(i,void 0,void 0,function*(){var u,f,p,g;if(Vu(o)>ay){d(Qe.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((f=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||f===void 0)&&f.version&&mi((g=(p=this.engine.latestJoinResponse)===null||p===void 0?void 0:p.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){d(Qe.builtIn("UNSUPPORTED_SERVER"));return}const h=crypto.randomUUID();yield this.publishRpcRequest(r,h,s,o,a-2e3);const y=setTimeout(()=>{this.pendingAcks.delete(h),d(Qe.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(h),clearTimeout(b)},2e3);this.pendingAcks.set(h,{resolve:()=>{clearTimeout(y)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(h),d(Qe.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(h,{resolve:(w,C)=>{clearTimeout(b),this.pendingAcks.has(h)&&(console.warn("RPC response received before ack",h),this.pendingAcks.delete(h),clearTimeout(y)),C?d(C):l(w??"")},participantIdentity:r})}))}()})}registerRpcMethod(e,n){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=n,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const n=this.pendingAcks.get(e);n?(n.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,n,i){const r=this.pendingResponses.get(e);r?(r.resolve(n,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,n,i,r,s){return A(this,void 0,void 0,function*(){const o=new Mt({destinationIdentities:[e],kind:be.RELIABLE,value:{case:"rpcRequest",value:new J0({id:n,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,be.RELIABLE)})}handleParticipantDisconnected(e){for(const[n,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(n);for(const[n,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,Qe.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(n=>n.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(n=>{var i,r;const s=this.trackPublications.get(n.sid);if(s){const o=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);o!==n.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),we(s)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(n.sid,o))}}),!0):!1}setActiveAgent(e){var n,i,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.resolve)===null||i===void 0||i.call(n,e):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Tr),this.activeAgentFuture.promise)}getPublicationForTrack(e){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(Un(r)||ii(r))&&r.mediaStreamTrack===e&&(n=i):e===r&&(n=i))}),n}waitForPendingPublicationOfSource(e){return A(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[o]=s;return o.source===e});if(r)return r[1];yield jt(20)}})}}class Pa extends Bn{constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Jt.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(re.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.disabled=!s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensions=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new Za({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new tv({participantSid:"",trackSids:[this.trackSid]})]});this.emit(re.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Bn.SubscriptionStatus.Unsubscribed:super.isSubscribed?Bn.SubscriptionStatus.Subscribed:Bn.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Bn.PermissionStatus.Allowed:Bn.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var n,i;this.isManualOperationAllowed()&&(((n=this.videoDimensions)===null||n===void 0?void 0:n.width)===e.width&&((i=this.videoDimensions)===null||i===void 0?void 0:i.height)===e.height||($c(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&$c(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(re.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(re.VisibilityChanged,this.handleVisibilityChange),r.off(re.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(re.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(re.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(re.VisibilityChanged,this.handleVisibilityChange),e.on(re.Ended,this.handleEnded),this.emit(re.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n)}setSubscriptionError(e){this.emit(re.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const n=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):n!==e.muted&&this.emit(e.muted?re.Muted:re.Unmuted)}emitSubscriptionUpdateIfChanged(e){const n=this.subscriptionStatus;e!==n&&this.emit(re.SubscriptionStatusChanged,n,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(re.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===V.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return $c(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new lv({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=Jt.HIGH,this.emit(re.UpdateSettings,e)}}class Ra extends py{static fromParticipantInfo(e,n,i){return new Ra(e,n.sid,n.identity,n.name,n.metadata,n.attributes,i,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,n,i,r,s,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Yi.STANDARD;super(n,i||"",r,s,o,a,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(re.UpdateSettings,n=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),we(e))),this.signalClient.sendUpdateTrackSettings(n)}),e.on(re.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),e.on(re.SubscriptionPermissionChanged,n=>{this.emit(Z.TrackSubscriptionPermissionChanged,e,n)}),e.on(re.SubscriptionStatusChanged,n=>{this.emit(Z.TrackSubscriptionStatusChanged,e,n)}),e.on(re.Subscribed,n=>{this.emit(Z.TrackSubscribed,n,e)}),e.on(re.Unsubscribed,n=>{this.emit(Z.TrackUnsubscribed,n,e)}),e.on(re.SubscriptionFailed,n=>{this.emit(Z.TrackSubscriptionFailed,e.trackSid,n)})}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setVolume(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:V.Source.Microphone;this.volumeMap.set(n,e);const i=this.getTrackPublication(n);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:V.Source.Microphone;const n=this.getTrackPublication(e);return n&&n.track?n.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,n,i,r,s,o){let a=this.getTrackPublicationBySid(n);if(a||n.startsWith("TR")||this.trackPublications.forEach(d=>{!a&&e.kind===d.kind.toString()&&(a=d)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),this.emit(Z.TrackSubscriptionFailed,n);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,n,i,r,s,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),we(a))),this.emit(Z.TrackSubscriptionFailed,n);return}const c=e.kind==="video";let l;return c?l=new f2(e,n,r,s):l=new my(e,n,r,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(i),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&hd(l)&&Tn(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const n=new Map,i=new Map;return e.tracks.forEach(r=>{var s,o;let a=this.getTrackPublicationBySid(r.sid);if(a)a.updateInfo(r);else{const c=V.kindFromProto(r.type);if(!c)return;a=new Pa(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(r),i.set(r.sid,a);const l=Array.from(this.trackPublications.values()).find(d=>d.source===(a==null?void 0:a.source));l&&a.source!==V.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:we(l),newTrack:we(a)})),this.addTrackPublication(a)}n.set(r.sid,a)}),this.trackPublications.forEach(r=>{n.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),we(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(Z.TrackPublished,r)}),!0}unpublishTrack(e,n){const i=this.trackPublications.get(e);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case V.Kind.Audio:this.audioTrackPublications.delete(e);break;case V.Kind.Video:this.videoTrackPublications.delete(e);break}n&&this.emit(Z.TrackUnpublished,i)}setAudioOutput(e){return A(this,void 0,void 0,function*(){this.audioOutput=e;const n=[];this.audioTrackPublications.forEach(i=>{var r;Tn(i.track)&&hd(i.track)&&n.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(n)})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var ge;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(ge||(ge={}));const b2=4*1e3;class pi extends Nn.EventEmitter{constructor(e){var n,i,r,s;if(super(),n=this,this.state=ge.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Ce,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(o,a,c)=>A(this,void 0,void 0,function*(){var l;if(!Qk())throw In()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const d=yield this.disconnectLock.lock();if(this.state===ge.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),d(),Promise.resolve();if(this.connectFuture)return d(),this.connectFuture.promise;this.setAndEmitConnectionState(ge.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==o&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ud(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new bd(o,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().then(p=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(p)}).catch(p=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:p}))}));const u=(p,g,h)=>A(this,void 0,void 0,function*(){var y,b;this.abortController&&this.abortController.abort();const w=new AbortController;this.abortController=w,d==null||d();try{yield this.attemptConnection(h??o,a,c,w),this.abortController=void 0,p()}catch(C){if(this.regionUrlProvider&&C instanceof Ue&&C.reason!==Te.Cancelled&&C.reason!==Te.NotAllowed){let S=null;try{S=yield this.regionUrlProvider.getNextBestRegionUrl((y=this.abortController)===null||y===void 0?void 0:y.signal)}catch(x){if(x instanceof Ue&&(x.status===401||x.reason===Te.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(x);return}}S&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(C.message,". Retrying with another region: ").concat(S),this.logContext),this.recreateEngine(),yield u(p,g,S)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,rm(C)),g(C))}else{let S=dn.UNKNOWN_REASON;C instanceof Ue&&(S=rm(C)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,S),g(C)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Tr((p,g)=>{u(p,g,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,a,c,l,d,u)=>A(this,void 0,void 0,function*(){var f,p,g;const h=yield c.join(o,a,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof d.adaptiveStream=="object"?!0:d.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},u.signal);let y=h.serverInfo;if(y||(y={version:h.serverVersion,region:h.serverRegion}),this.serverInfo=y,this.log.debug("connected to Livekit Server ".concat(Object.entries(y).map(b=>{let[w,C]=b;return"".concat(w,": ").concat(C)}).join(", ")),{room:(f=h.room)===null||f===void 0?void 0:f.name,roomSid:(p=h.room)===null||p===void 0?void 0:p.sid,identity:(g=h.participant)===null||g===void 0?void 0:g.identity}),!y.version)throw new Vk("unknown server version");return y.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),d.dynacast=!1),h}),this.applyJoinResponse=o=>{const a=o.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([a,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,a,c,l)=>A(this,void 0,void 0,function*(){var d,u;this.state===ge.Reconnecting||this.isResuming||!((d=this.engine)===null||d===void 0)&&d.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((u=this.regionUrlProvider)===null||u===void 0)&&u.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Lu),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(o,a,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(U.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const p=new Ue("could not establish signal connection",Te.ServerUnreachable);throw f instanceof Error&&(p.message="".concat(p.message,": ").concat(f.message)),f instanceof Ue&&(p.reason=f.reason,p.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),p}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Ue("Connection attempt aborted",Te.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}Ot()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ot()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ge.Connected),this.emit(U.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return A(n,[...a],void 0,function(){var l=this;let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var u,f,p,g;const h=yield l.disconnectLock.lock();try{if(l.state===ge.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===ge.Connecting||l.state===ge.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(u=l.abortController)===null||u===void 0||u.abort(),(p=(f=l.connectFuture)===null||f===void 0?void 0:f.reject)===null||p===void 0||p.call(f,new Ue("Client initiated disconnect",Te.Cancelled)),l.connectFuture=void 0),!((g=l.engine)===null||g===void 0)&&g.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(d,dn.CLIENT_INITIATED),l.engine=void 0}finally{h()}}()})},this.onPageLeave=()=>A(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>A(this,void 0,void 0,function*(){const o=[],a=$t();if(a&&a.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const d=Bc();d.enabled=!0;const u=new MediaStream([d]);l.srcObject=u,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:u,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(U.Disconnected,()=>{l==null||l.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(d=>{o.push(d)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>A(this,void 0,void 0,function*(){const o=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.attachedElements.forEach(d=>{o.includes(d)||o.push(d)})});yield Promise.all(o.map(a=>a.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(a=>{a.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(ge.Reconnecting)&&this.emit(U.Reconnecting)},this.handleSignalRestarted=o=>A(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(a){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:a}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(ge.Connected),this.emit(U.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(a=>{var c;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(c=this.sidToIdentity.get(a.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(a.identity);a.state===_r.DISCONNECTED?this.handleParticipantDisconnected(a.identity,l):l=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=o=>{const a=[],c={};o.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const d=this.getRemoteParticipantBySid(l.sid);d&&(d.audioLevel=l.level,d.setIsSpeaking(!0),a.push(d))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(U.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=o=>{const a=new Map;this.activeSpeakers.forEach(l=>{const d=this.remoteParticipants.get(l.identity);d&&d.sid!==l.sid||a.set(l.sid,l)}),o.forEach(l=>{let d=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(d=this.localParticipant),d&&(d.audioLevel=l.level,d.setIsSpeaking(l.active),l.active?a.set(l.sid,d):a.delete(l.sid))});const c=Array.from(a.values());c.sort((l,d)=>d.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(U.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);if(!l||!l.track)return;const d=V.streamStateFromProto(a.state);d!==l.track.streamState&&(l.track.streamState=d,c.emit(Z.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(U.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const a=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setSubscriptionError(o.err)},this.handleDataPacket=o=>{const a=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(a,o.value.value,o.kind);else if(o.value.case==="transcription")this.handleTranscription(a,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(a,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(a,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,a);else if(o.value.case==="streamHeader")this.handleStreamHeader(o.value.value,o.participantIdentity);else if(o.value.case==="streamChunk")this.handleStreamChunk(o.value.value);else if(o.value.case==="streamTrailer")this.handleStreamTrailer(o.value.value);else if(o.value.case==="rpcRequest"){const c=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(o,a,c)=>{this.emit(U.DataReceived,a.payload,o,c,a.topic),o==null||o.emit(Z.DataReceived,a.payload,c)},this.handleSipDtmf=(o,a)=>{this.emit(U.SipDTMFReceived,a,o),o==null||o.emit(Z.SipDTMFReceived,a)},this.bufferedSegments=new Map,this.handleTranscription=(o,a)=>{const c=a.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(a.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(a.trackId),d=lT(a,this.transcriptionReceivedTimes);l==null||l.emit(re.TranscriptionReceived,d),c==null||c.emit(Z.TranscriptionReceived,d,l),this.emit(U.TranscriptionReceived,d,c,l)},this.handleChatMessage=(o,a)=>{const c=dT(a);this.emit(U.ChatMessage,c,o)},this.handleMetrics=(o,a)=>{this.emit(U.MetricsReceived,o,a)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(U.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(U.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(U.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(U.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>A(this,void 0,void 0,function*(){var o;((o=$t())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(U.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const a=this.roomInfo;this.roomInfo=o,a&&a.metadata!==o.metadata&&this.emitWhenConnected(U.RoomMetadataChanged,o.metadata),(a==null?void 0:a.activeRecording)!==o.activeRecording&&this.emitWhenConnected(U.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const c=this.getRemoteParticipantBySid(a.participantSid);c&&c.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(U.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(U.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(U.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(U.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(U.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var a;(a=o==null?void 0:o.onPublish)===null||a===void 0||a.call(o,this)},this.onLocalTrackPublished=o=>A(this,void 0,void 0,function*(){var a,c,l,d,u,f;(a=o.track)===null||a===void 0||a.on(re.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.on(re.Restarted,this.onLocalTrackRestarted),(u=(d=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||d===void 0?void 0:d.onPublish)===null||u===void 0||u.call(d,this),this.emit(U.LocalTrackPublished,o,this.localParticipant),Un(o.track)&&(yield o.track.checkForSilence())&&this.emit(U.LocalAudioSilenceDetected,o);const p=yield(f=o.track)===null||f===void 0?void 0:f.getDeviceId(!1),g=pd(o.source);g&&p&&p!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,p),this.emit(U.ActiveDeviceChanged,g,p))}),this.onLocalTrackUnpublished=o=>{var a,c;(a=o.track)===null||a===void 0||a.off(re.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.off(re.Restarted,this.onLocalTrackRestarted),this.emit(U.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>A(this,void 0,void 0,function*(){const a=yield o.getDeviceId(!1),c=pd(o.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(a," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,a),this.emit(U.ActiveDeviceChanged,c,a))}),this.onLocalConnectionQualityChanged=o=>{this.emit(U.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,a)=>{this.emit(U.MediaDevicesError,o,a)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(U.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(U.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},jT),e),this.log=Gn((i=this.options.loggerName)!==null&&i!==void 0?i:fn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},sy),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},oy),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},DT),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Nt,this.localParticipant=new y2("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",fi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",fi(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",fi(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Ot()){const o=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),pi.cleanupRegistry&&pi.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,n){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,n){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,n){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,n,i,r,s,o){return A(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,n),o!==1){yield this.engine.publishRpcResponse(e,n,null,Qe.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(i);if(!a){yield this.engine.publishRpcResponse(e,n,null,Qe.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield a({requestId:n,callerIdentity:e,payload:r,responseTimeout:s});Vu(d)>ay?(c=Qe.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=d}catch(d){d instanceof Qe?c=d:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),c=Qe.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,n,l,c)})}setE2EEEnabled(e){return A(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new xT(this.options.e2ee),this.e2eeManager.on(di.ParticipantEncryptionStatusChanged,(n,i)=>{fT(i)&&(this.isE2EEEnabled=n),this.emit(U.ParticipantEncryptionStatusChanged,n,i)}),this.e2eeManager.on(di.EncryptionError,n=>this.emit(U.EncryptionError,n)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&n!==void 0?n:!1}getSid(){return A(this,void 0,void 0,function*(){return this.state===ge.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(ae.RoomUpdate,i),e(r.sid))};this.engine.on(ae.RoomUpdate,i),this.once(U.Disconnected,()=>{this.engine.off(ae.RoomUpdate,i),n("Room disconnected before room server id was available")})})})}get name(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&n!==void 0?n:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&n!==void 0?n:0}get numPublishers(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&n!==void 0?n:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new r2(this.options),this.engine.on(ae.ParticipantUpdate,this.handleParticipantUpdates).on(ae.RoomUpdate,this.handleRoomUpdate).on(ae.SpeakersChanged,this.handleSpeakersChanged).on(ae.StreamStateChanged,this.handleStreamStateUpdate).on(ae.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(ae.SubscriptionError,this.handleSubscriptionError).on(ae.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(ae.MediaTrackAdded,(e,n,i)=>{this.onTrackAdded(e,n,i)}).on(ae.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(ae.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(ae.DataPacketReceived,this.handleDataPacket).on(ae.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ge.SignalReconnecting)&&this.emit(U.SignalReconnecting)}).on(ae.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ge.Connected)&&this.emit(U.Reconnected)}).on(ae.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ge.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(ae.Restarting,this.handleRestarting).on(ae.SignalRestarted,this.handleSignalRestarted).on(ae.Offline,()=>{this.setAndEmitConnectionState(ge.Reconnecting)&&this.emit(U.Reconnecting)}).on(ae.DCBufferStatusChanged,(e,n)=>{this.emit(U.DCBufferStatusChanged,e,n)}).on(ae.LocalTrackSubscribed,e=>{const n=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!n){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(Z.LocalTrackSubscribed,n),this.emitWhenConnected(U.LocalTrackSubscribed,n,this.localParticipant)}).on(ae.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((n,i)=>{this.handleParticipantDisconnected(i,n)}),this.emit(U.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return gt.getInstance().getDevices(e,n)}prepareConnection(e,n){return A(this,void 0,void 0,function*(){if(this.state===ge.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(ud(new URL(e))&&n){this.regionUrlProvider=new bd(e,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ge.Disconnected&&(this.regionUrl=i,yield fetch(fd(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(fd(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,n){return A(this,void 0,void 0,function*(){let i=()=>{},r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new bn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new bn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new bn({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new bn({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>A(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new bn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>A(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new bn({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new bn({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>A(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new Ya({reason:dn.CLIENT_INITIATED,action:Nr.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new bn({scenario:{case:"subscriberBandwidth",value:Li(n)}});break;case"leave-full-reconnect":r=new bn({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,n){return A(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var a,c,l,d,u,f,p;let g=!0,h=!1;const y=o?{exact:r}:r;if(i==="audioinput"){h=s.localParticipant.audioTrackPublications.size===0;const b=(a=s.getActiveDevice(i))!==null&&a!==void 0?a:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=y;const w=Array.from(s.localParticipant.audioTrackPublications.values()).filter(S=>S.source===V.Source.Microphone);try{g=(yield Promise.all(w.map(S=>{var x;return(x=S.audioTrack)===null||x===void 0?void 0:x.setDeviceId(y)}))).every(S=>S===!0)}catch(S){throw s.options.audioCaptureDefaults.deviceId=b,S}const C=w.some(S=>{var x,T;return(T=(x=S.track)===null||x===void 0?void 0:x.isMuted)!==null&&T!==void 0?T:!1});g&&C&&(h=!0)}else if(i==="videoinput"){h=s.localParticipant.videoTrackPublications.size===0;const b=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=y;const w=Array.from(s.localParticipant.videoTrackPublications.values()).filter(C=>C.source===V.Source.Camera);try{g=(yield Promise.all(w.map(C=>{var S;return(S=C.videoTrack)===null||S===void 0?void 0:S.setDeviceId(y)}))).every(C=>C===!0)}catch(C){throw s.options.videoCaptureDefaults.deviceId=b,C}}else if(i==="audiooutput"){if(h=!0,!dd()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");s.options.webAudioMix&&(r=(l=yield gt.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(d=(p=s.options).audioOutput)!==null&&d!==void 0||(p.audioOutput={});const b=(u=s.getActiveDevice(i))!==null&&u!==void 0?u:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((f=s.audioContext)===null||f===void 0||f.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(w=>w.setAudioOutput({deviceId:r})))}catch(w){throw s.options.audioOutput.deviceId=b,w}}return h&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(U.ActiveDeviceChanged,i,r)),g}()})}setupLocalParticipantEvents(){this.localParticipant.on(Z.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(Z.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(Z.AttributesChanged,this.onLocalAttributesChanged).on(Z.TrackMuted,this.onLocalTrackMuted).on(Z.TrackUnmuted,this.onLocalTrackUnmuted).on(Z.LocalTrackPublished,this.onLocalTrackPublished).on(Z.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(Z.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(Z.MediaDevicesError,this.onMediaDevicesError).on(Z.AudioStreamAcquired,this.startAudio).on(Z.ChatMessage,this.onLocalChatMessageSent).on(Z.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,n,i){if(this.state===ge.Connecting||this.state===ge.Reconnecting){const d=()=>{this.onTrackAdded(e,n,i),u()},u=()=>{this.off(U.Reconnected,d),this.off(U.Connected,d),this.off(U.Disconnected,u)};this.once(U.Reconnected,d),this.once(U.Connected,d),this.once(U.Disconnected,u);return}if(this.state===ge.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=Yk(n.id),s=r[0];let o=r[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(d=>d.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={}),c.addSubscribedMediaTrack(e,a,n,i,l)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==ge.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,o,a;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((s=r.track)===null||s===void 0||s.detach(),(o=r.track)===null||o===void 0||o.stop()):(a=r.track)===null||a===void 0||a.stopMonitor()}),this.localParticipant.off(Z.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(Z.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(Z.AttributesChanged,this.onLocalAttributesChanged).off(Z.TrackMuted,this.onLocalTrackMuted).off(Z.TrackUnmuted,this.onLocalTrackUnmuted).off(Z.LocalTrackPublished,this.onLocalTrackPublished).off(Z.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(Z.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(Z.MediaDevicesError,this.onMediaDevicesError).off(Z.AudioStreamAcquired,this.startAudio).off(Z.ChatMessage,this.onLocalChatMessageSent).off(Z.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),Ot()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ge.Disconnected),this.emit(U.Disconnected,n)}}}handleParticipantDisconnected(e,n){var i;this.remoteParticipants.delete(e),n&&(n.trackPublications.forEach(r=>{n.unpublishTrack(r.trackSid,!0)}),this.emit(U.ParticipantDisconnected,n),n.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(n.identity))}handleStreamHeader(e,n){return A(this,void 0,void 0,function*(){var i;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s;const o={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ra(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:c=>{s=c,this.byteStreamControllers.set(e.streamId,{info:o,controller:s,startTime:Date.now()})}});r(new c2(o,a,ra(e.totalLength)),{identity:n})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let s;const o={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:c=>{s=c,this.textStreamControllers.set(e.streamId,{info:o,controller:s,startTime:Date.now()})}});r(new l2(o,a,ra(e.totalLength)),{identity:n})}})}handleStreamChunk(e){const n=this.byteStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}selectDefaultDevices(){return A(this,void 0,void 0,function*(){var e,n,i;const r=gt.getInstance().previousDevices,s=yield gt.getInstance().getDevices(void 0,!1),o=$t();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of s){const l=r.find(d=>d.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(U.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const l=mT(c),d=this.localParticipant.getTrackPublication(l);if(d&&(!((e=d.track)===null||e===void 0)&&e.isUserProvided))continue;const u=s.filter(p=>p.kind===c),f=this.getActiveDevice(c);if(f===((n=r.filter(p=>p.kind===c)[0])===null||n===void 0?void 0:n.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==f){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Qh()||c==="videoinput"||u.length>0&&!u.find(p=>p.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Qh())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return A(this,void 0,void 0,function*(){var e,n;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Nu())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),jt(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((n=this.audioContext)===null||n===void 0?void 0:n.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(U.AudioPlaybackStatusChanged,i))})}createParticipant(e,n){var i;let r;return n?r=Ra.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new Ra(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(e,n){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return n&&r.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity),r}const i=this.createParticipant(e,n);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(U.ParticipantConnected,i),i.on(Z.TrackPublished,r=>{this.emitWhenConnected(U.TrackPublished,r,i)}).on(Z.TrackSubscribed,(r,s)=>{r.kind===V.Kind.Audio?(r.on(re.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(re.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===V.Kind.Video&&(r.on(re.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(re.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(U.TrackSubscribed,r,s,i)}).on(Z.TrackUnpublished,r=>{this.emit(U.TrackUnpublished,r,i)}).on(Z.TrackUnsubscribed,(r,s)=>{this.emit(U.TrackUnsubscribed,r,s,i)}).on(Z.TrackMuted,r=>{this.emitWhenConnected(U.TrackMuted,r,i)}).on(Z.TrackUnmuted,r=>{this.emitWhenConnected(U.TrackUnmuted,r,i)}).on(Z.ParticipantMetadataChanged,r=>{this.emitWhenConnected(U.ParticipantMetadataChanged,r,i)}).on(Z.ParticipantNameChanged,r=>{this.emitWhenConnected(U.ParticipantNameChanged,r,i)}).on(Z.AttributesChanged,r=>{this.emitWhenConnected(U.ParticipantAttributesChanged,r,i)}).on(Z.ConnectionQualityChanged,r=>{this.emitWhenConnected(U.ConnectionQualityChanged,r,i)}).on(Z.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(U.ParticipantPermissionsChanged,r,i)}).on(Z.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(U.TrackSubscriptionStatusChanged,r,s,i)}).on(Z.TrackSubscriptionFailed,(r,s)=>{this.emit(U.TrackSubscriptionFailed,r,i,s)}).on(Z.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(U.TrackSubscriptionPermissionChanged,r,s,i)}).on(Z.Active,()=>{this.emitWhenConnected(U.ParticipantActive,i),i.kind===Yi.AGENT&&this.localParticipant.setActiveAgent(i)}),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),n=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const n of e.videoTrackPublications.values())n.isSubscribed&&uT(n)&&n.emitTrackUpdate()}getRemoteParticipantBySid(e){const n=this.sidToIdentity.get(e);if(n)return this.remoteParticipants.get(n)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=bt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,dn.STATE_MISMATCH))):e=0},b2)}clearConnectionReconcile(){this.connectionReconcileInterval&&bt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(U.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[n,i]=e;this.emit(n,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===ge.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ge.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return A(this,void 0,void 0,function*(){var n,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ga({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ze.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Zi({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(U.SignalConnected),this.emit(U.Connected),this.setAndEmitConnectionState(ge.Connected),r.video){const o=new Sd(V.Kind.Video,new Cr({source:lt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:cn.AUDIO,name:"video-dummy"}),new Ea(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:im(160*((n=s.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(Z.LocalTrackPublished,o)}if(r.audio){const o=new Sd(V.Kind.Audio,new Cr({source:lt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:cn.AUDIO}),new Ta(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Bc(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(Z.LocalTrackPublished,o)}for(let o=0;o<s.count-1;o+=1){let a=new Zi({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:_r.ACTIVE,tracks:[],joinedAt:ze.parse(Date.now())});const c=this.getOrCreateParticipant(a.identity,a);if(s.video){const l=im(160*((i=s.aspectRatios[o%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),d=new Cr({source:lt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:cn.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,d]}if(s.audio){const l=Bc(),d=new Cr({source:lt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:cn.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,d]}c.updateInfo(a)}})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(e!==U.ActiveSpeakersChanged&&e!==U.TranscriptionReceived){const s=gy(i).filter(o=>o!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s}))}return super.emit(e,...i)}}pi.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function gy(t){return t.map(e=>{if(e)return Array.isArray(e)?gy(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var an;(function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"})(an||(an={}));class Ti extends Nn.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=an.IDLE,this.logs=[],this.options={},this.url=e,this.token=n,this.name=this.constructor.name,this.room=new pi(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return A(this,void 0,void 0,function*(){if(this.status!==an.IDLE)throw Error("check is running already");this.setStatus(an.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise(n=>setTimeout(n,500)),this.status!==an.SKIPPED&&this.setStatus(this.isSuccess()?an.SUCCESS:an.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return A(this,void 0,void 0,function*(){return this.room.state===ge.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return A(this,void 0,void 0,function*(){this.room&&this.room.state!==ge.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(an.SKIPPED)}switchProtocol(e){return A(this,void 0,void 0,function*(){let n=!1,i=!1;if(this.room.on(U.Reconnecting,()=>{n=!0}),this.room.once(U.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield jt(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class x2 extends Ti{get description(){return"Cloud regions"}perform(){return A(this,void 0,void 0,function*(){const e=new bd(this.url,this.token);if(!e.isCloud()){this.skip();return}const n=[],i=new Set;for(let s=0;s<3;s++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),n.push(a)}n.sort((s,o)=>(s.duration-o.duration)*.5+(s.rtt-o.rtt)*.5);const r=n[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return A(this,void 0,void 0,function*(){var n,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(n=this.room.serverInfo)===null||n===void 0?void 0:n.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,l="A".repeat(o),d=Date.now();for(let g=0;g<c;g++)yield s.write(l);yield s.close();const u=Date.now(),f=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),p={region:r,rtt:1e4,duration:u-d};return f==null||f.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(p.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const Yc=1e4;class S2 extends Ti{get description(){return"Connection via UDP vs TCP"}perform(){return A(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),n=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-n.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-n.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=n):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(Yc/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Yc/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return A(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const n=document.createElement("canvas");n.width=1280,n.height=720;const i=n.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,n.width,n.height),requestAnimationFrame(s)};s();const a=n.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,d={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>A(this,void 0,void 0,function*(){const f=yield l.getRTCStatsReport();f==null||f.forEach(p=>{p.type==="outbound-rtp"?(d.packetsSent=p.packetsSent,d.qualityLimitationDurations=p.qualityLimitationDurations,d.bitrateTotal+=p.targetBitrate,d.count++):p.type==="remote-inbound-rtp"&&(d.packetsLost=p.packetsLost,d.rttTotal+=p.roundTripTime,d.jitterTotal+=p.jitter)})}),1e3);return yield new Promise(f=>setTimeout(f,Yc)),clearInterval(u),a.stop(),n.remove(),yield this.disconnect(),d})}}class w2 extends Ti{get description(){return"Can publish audio"}perform(){return A(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield p2();if(yield ny(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),n.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let o=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class C2 extends Ti{get description(){return"Can publish video"}perform(){return A(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield m2();yield this.checkForVideo(i.mediaStreamTrack),n.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(s+=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return A(this,void 0,void 0,function*(){const n=new MediaStream;n.addTrack(e.clone());const i=document.createElement("video");i.srcObject=n,i.muted=!0,yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,o,a,c;const l=document.createElement("canvas"),d=e.getSettings(),u=(o=(s=d.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&o!==void 0?o:1280,f=(c=(a=d.height)!==null&&a!==void 0?a:i.videoHeight)!==null&&c!==void 0?c:720;l.width=u,l.height=f;const p=l.getContext("2d");p.drawImage(i,0,0);const h=p.getImageData(0,0,l.width,l.height).data;let y=!0;for(let b=0;b<h.length;b+=4)if(h[b]!==0||h[b+1]!==0||h[b+2]!==0){y=!1;break}y?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),n.getTracks().forEach(r=>r.stop()),i.remove()})}}class k2 extends Ti{get description(){return"Resuming connection after interruption"}perform(){return A(this,void 0,void 0,function*(){var e;const n=yield this.connect();let i=!1,r=!1,s;const o=new Promise(l=>{setTimeout(l,5e3),s=l}),a=()=>{i=!0};n.on(U.SignalReconnecting,a).on(U.Reconnecting,a).on(U.Reconnected,()=>{r=!0,s(!0)}),(e=n.engine.client.ws)===null||e===void 0||e.close();const c=n.engine.client.onClose;if(c&&c(""),yield o,i){if(!r||n.state!==ge.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class T2 extends Ti{get description(){return"Can connect via TURN"}perform(){return A(this,void 0,void 0,function*(){var e,n;const i=new Ou,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,o=!1,a=!1;for(let c of r.iceServers)for(let l of c.urls)l.startsWith("turn:")?(o=!0,a=!0):l.startsWith("turns:")&&(o=!0,a=!0,s=!0),l.startsWith("stun:")&&(a=!0);a?o&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((n=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||n===void 0)&&n.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class E2 extends Ti{get description(){return"Establishing WebRTC connection"}perform(){return A(this,void 0,void 0,function*(){let e=!1,n=!1;this.room.on(U.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const o=new RTCIceCandidate(r);let a="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(P2(o.address)?a+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,a+=" (passive)"):o.protocol==="udp"&&(n=!0)),this.appendMessage(a)}i&&i(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),Ce.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function P2(t){const e=t.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const n=parseInt(e[1],10);if(n>=16&&n<=31)return!0}}return!1}class R2 extends Ti{get description(){return"Connecting to signal connection via WebSocket"}perform(){return A(this,void 0,void 0,function*(){var e,n,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Ou;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===iv.Cloud&&(!((n=s.serverInfo)===null||n===void 0)&&n.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region)),yield r.close()})}}class OL extends Nn.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=n,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:an.IDLE,name:"",description:""}),e}updateCheck(e,n){this.checkResults.set(e,n),this.emit("checkUpdate",e,n)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==an.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return A(this,void 0,void 0,function*(){const n=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=o=>{this.updateCheck(n,o)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(R2)})}checkWebRTC(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(E2)})}checkTURN(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(T2)})}checkReconnect(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(k2)})}checkPublishAudio(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(w2)})}checkPublishVideo(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(C2)})}checkConnectionProtocol(){return A(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(S2);if(e.data&&"protocol"in e.data){const n=e.data;this.options.protocol=n.protocol}return e})}checkCloudRegion(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(x2)})}}const Bu=R.createContext({});function $u(t){const e=R.useRef(null);return e.current===null&&(e.current=t()),e.current}const Hu=typeof window<"u",vy=Hu?R.useLayoutEffect:R.useEffect,ec=R.createContext(null);function zu(t,e){t.indexOf(e)===-1&&t.push(e)}function Wu(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const Zn=(t,e,n)=>n>e?e:n<t?t:n;function wd(t,e){return e?`${t}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${e}`:t}let is=()=>{},Yn=()=>{};process.env.NODE_ENV!=="production"&&(is=(t,e,n)=>{!t&&typeof console<"u"&&console.warn(wd(e,n))},Yn=(t,e,n)=>{if(!t)throw new Error(wd(e,n))});const Jn={},yy=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function by(t){return typeof t=="object"&&t!==null}const xy=t=>/^0[^.\s]+$/u.test(t);function qu(t){let e;return()=>(e===void 0&&(e=t()),e)}const Xt=t=>t,A2=(t,e)=>n=>e(t(n)),ao=(...t)=>t.reduce(A2),Ws=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class Ku{constructor(){this.subscriptions=[]}add(e){return zu(this.subscriptions,e),()=>Wu(this.subscriptions,e)}notify(e,n,i){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](e,n,i);else for(let s=0;s<r;s++){const o=this.subscriptions[s];o&&o(e,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const un=t=>t*1e3,En=t=>t/1e3;function Sy(t,e){return e?t*(1e3/e):0}const wm=new Set;function Gu(t,e,n){t||wm.has(e)||(console.warn(wd(e,n)),wm.add(e))}const wy=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,I2=1e-7,M2=12;function _2(t,e,n,i,r){let s,o,a=0;do o=e+(n-e)/2,s=wy(o,i,r)-t,s>0?n=o:e=o;while(Math.abs(s)>I2&&++a<M2);return o}function co(t,e,n,i){if(t===e&&n===i)return Xt;const r=s=>_2(s,0,1,t,n);return s=>s===0||s===1?s:wy(r(s),e,i)}const Cy=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,ky=t=>e=>1-t(1-e),Ty=co(.33,1.53,.69,.99),Zu=ky(Ty),Ey=Cy(Zu),Py=t=>(t*=2)<1?.5*Zu(t):.5*(2-Math.pow(2,-10*(t-1))),Yu=t=>1-Math.sin(Math.acos(t)),Ry=ky(Yu),Ay=Cy(Yu),N2=co(.42,0,1,1),O2=co(0,0,.58,1),Iy=co(.42,0,.58,1),D2=t=>Array.isArray(t)&&typeof t[0]!="number",My=t=>Array.isArray(t)&&typeof t[0]=="number",Cm={linear:Xt,easeIn:N2,easeInOut:Iy,easeOut:O2,circIn:Yu,circInOut:Ay,circOut:Ry,backIn:Zu,backInOut:Ey,backOut:Ty,anticipate:Py},j2=t=>typeof t=="string",km=t=>{if(My(t)){Yn(t.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[e,n,i,r]=t;return co(e,n,i,r)}else if(j2(t))return Yn(Cm[t]!==void 0,`Invalid easing type '${t}'`,"invalid-easing-type"),Cm[t];return t},ko=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function L2(t,e){let n=new Set,i=new Set,r=!1,s=!1;const o=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function c(d){o.has(d)&&(l.schedule(d),t()),d(a)}const l={schedule:(d,u=!1,f=!1)=>{const g=f&&r?n:i;return u&&o.add(d),g.has(d)||g.add(d),d},cancel:d=>{i.delete(d),o.delete(d)},process:d=>{if(a=d,r){s=!0;return}r=!0,[n,i]=[i,n],n.forEach(c),n.clear(),r=!1,s&&(s=!1,l.process(d))}};return l}const V2=40;function _y(t,e){let n=!1,i=!0;const r={delta:0,timestamp:0,isProcessing:!1},s=()=>n=!0,o=ko.reduce((C,S)=>(C[S]=L2(s),C),{}),{setup:a,read:c,resolveKeyframes:l,preUpdate:d,update:u,preRender:f,render:p,postRender:g}=o,h=()=>{const C=Jn.useManualTiming?r.timestamp:performance.now();n=!1,Jn.useManualTiming||(r.delta=i?1e3/60:Math.max(Math.min(C-r.timestamp,V2),1)),r.timestamp=C,r.isProcessing=!0,a.process(r),c.process(r),l.process(r),d.process(r),u.process(r),f.process(r),p.process(r),g.process(r),r.isProcessing=!1,n&&e&&(i=!1,t(h))},y=()=>{n=!0,i=!0,r.isProcessing||t(h)};return{schedule:ko.reduce((C,S)=>{const x=o[S];return C[S]=(T,E=!1,P=!1)=>(n||y(),x.schedule(T,E,P)),C},{}),cancel:C=>{for(let S=0;S<ko.length;S++)o[ko[S]].cancel(C)},state:r,steps:o}}const{schedule:We,cancel:gi,state:vt,steps:Jc}=_y(typeof requestAnimationFrame<"u"?requestAnimationFrame:Xt,!0);let oa;function F2(){oa=void 0}const Dt={now:()=>(oa===void 0&&Dt.set(vt.isProcessing||Jn.useManualTiming?vt.timestamp:performance.now()),oa),set:t=>{oa=t,queueMicrotask(F2)}},Ny=t=>e=>typeof e=="string"&&e.startsWith(t),Ju=Ny("--"),U2=Ny("var(--"),Xu=t=>U2(t)?B2.test(t.split("/*")[0].trim()):!1,B2=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,rs={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},qs={...rs,transform:t=>Zn(0,1,t)},To={...rs,default:1},Vs=t=>Math.round(t*1e5)/1e5,Qu=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function $2(t){return t==null}const H2=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ef=(t,e)=>n=>!!(typeof n=="string"&&H2.test(n)&&n.startsWith(t)||e&&!$2(n)&&Object.prototype.hasOwnProperty.call(n,e)),Oy=(t,e,n)=>i=>{if(typeof i!="string")return i;const[r,s,o,a]=i.match(Qu);return{[t]:parseFloat(r),[e]:parseFloat(s),[n]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},z2=t=>Zn(0,255,t),Xc={...rs,transform:t=>Math.round(z2(t))},Ui={test:ef("rgb","red"),parse:Oy("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Xc.transform(t)+", "+Xc.transform(e)+", "+Xc.transform(n)+", "+Vs(qs.transform(i))+")"};function W2(t){let e="",n="",i="",r="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),i=t.substring(5,7),r=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),i=t.substring(3,4),r=t.substring(4,5),e+=e,n+=n,i+=i,r+=r),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:r?parseInt(r,16)/255:1}}const Cd={test:ef("#"),parse:W2,transform:Ui.transform},lo=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),oi=lo("deg"),Pn=lo("%"),he=lo("px"),q2=lo("vh"),K2=lo("vw"),Tm={...Pn,parse:t=>Pn.parse(t)/100,transform:t=>Pn.transform(t*100)},Er={test:ef("hsl","hue"),parse:Oy("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+Pn.transform(Vs(e))+", "+Pn.transform(Vs(n))+", "+Vs(qs.transform(i))+")"},ct={test:t=>Ui.test(t)||Cd.test(t)||Er.test(t),parse:t=>Ui.test(t)?Ui.parse(t):Er.test(t)?Er.parse(t):Cd.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ui.transform(t):Er.transform(t),getAnimatableNone:t=>{const e=ct.parse(t);return e.alpha=0,ct.transform(e)}},G2=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Z2(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Qu))==null?void 0:e.length)||0)+(((n=t.match(G2))==null?void 0:n.length)||0)>0}const Dy="number",jy="color",Y2="var",J2="var(",Em="${}",X2=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Ks(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},r=[];let s=0;const a=e.replace(X2,c=>(ct.test(c)?(i.color.push(s),r.push(jy),n.push(ct.parse(c))):c.startsWith(J2)?(i.var.push(s),r.push(Y2),n.push(c)):(i.number.push(s),r.push(Dy),n.push(parseFloat(c))),++s,Em)).split(Em);return{values:n,split:a,indexes:i,types:r}}function Ly(t){return Ks(t).values}function Vy(t){const{split:e,types:n}=Ks(t),i=e.length;return r=>{let s="";for(let o=0;o<i;o++)if(s+=e[o],r[o]!==void 0){const a=n[o];a===Dy?s+=Vs(r[o]):a===jy?s+=ct.transform(r[o]):s+=r[o]}return s}}const Q2=t=>typeof t=="number"?0:ct.test(t)?ct.getAnimatableNone(t):t;function eE(t){const e=Ly(t);return Vy(t)(e.map(Q2))}const vi={test:Z2,parse:Ly,createTransformer:Vy,getAnimatableNone:eE};function Qc(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function tE({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,e/=100,n/=100;let r=0,s=0,o=0;if(!e)r=s=o=n;else{const a=n<.5?n*(1+e):n+e-n*e,c=2*n-a;r=Qc(c,a,t+1/3),s=Qc(c,a,t),o=Qc(c,a,t-1/3)}return{red:Math.round(r*255),green:Math.round(s*255),blue:Math.round(o*255),alpha:i}}function Aa(t,e){return n=>n>0?e:t}const Ge=(t,e,n)=>t+(e-t)*n,el=(t,e,n)=>{const i=t*t,r=n*(e*e-i)+i;return r<0?0:Math.sqrt(r)},nE=[Cd,Ui,Er],iE=t=>nE.find(e=>e.test(t));function Pm(t){const e=iE(t);if(is(!!e,`'${t}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!e)return!1;let n=e.parse(t);return e===Er&&(n=tE(n)),n}const Rm=(t,e)=>{const n=Pm(t),i=Pm(e);if(!n||!i)return Aa(t,e);const r={...n};return s=>(r.red=el(n.red,i.red,s),r.green=el(n.green,i.green,s),r.blue=el(n.blue,i.blue,s),r.alpha=Ge(n.alpha,i.alpha,s),Ui.transform(r))},kd=new Set(["none","hidden"]);function rE(t,e){return kd.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function sE(t,e){return n=>Ge(t,e,n)}function tf(t){return typeof t=="number"?sE:typeof t=="string"?Xu(t)?Aa:ct.test(t)?Rm:cE:Array.isArray(t)?Fy:typeof t=="object"?ct.test(t)?Rm:oE:Aa}function Fy(t,e){const n=[...t],i=n.length,r=t.map((s,o)=>tf(s)(s,e[o]));return s=>{for(let o=0;o<i;o++)n[o]=r[o](s);return n}}function oE(t,e){const n={...t,...e},i={};for(const r in n)t[r]!==void 0&&e[r]!==void 0&&(i[r]=tf(t[r])(t[r],e[r]));return r=>{for(const s in i)n[s]=i[s](r);return n}}function aE(t,e){const n=[],i={color:0,var:0,number:0};for(let r=0;r<e.values.length;r++){const s=e.types[r],o=t.indexes[s][i[s]],a=t.values[o]??0;n[r]=a,i[s]++}return n}const cE=(t,e)=>{const n=vi.createTransformer(e),i=Ks(t),r=Ks(e);return i.indexes.var.length===r.indexes.var.length&&i.indexes.color.length===r.indexes.color.length&&i.indexes.number.length>=r.indexes.number.length?kd.has(t)&&!r.values.length||kd.has(e)&&!i.values.length?rE(t,e):ao(Fy(aE(i,r),r.values),n):(is(!0,`Complex values '${t}' and '${e}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),Aa(t,e))};function Uy(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?Ge(t,e,n):tf(t)(t,e)}const lE=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>We.update(e,n),stop:()=>gi(e),now:()=>vt.isProcessing?vt.timestamp:Dt.now()}},By=(t,e,n=10)=>{let i="";const r=Math.max(Math.round(e/n),2);for(let s=0;s<r;s++)i+=Math.round(t(s/(r-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},Ia=2e4;function nf(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<Ia;)e+=n,i=t.next(e);return e>=Ia?1/0:e}function dE(t,e=100,n){const i=n({...t,keyframes:[0,e]}),r=Math.min(nf(i),Ia);return{type:"keyframes",ease:s=>i.next(r*s).value/e,duration:En(r)}}const uE=5;function $y(t,e,n){const i=Math.max(e-uE,0);return Sy(n-t(i),e-i)}const Ke={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},tl=.001;function fE({duration:t=Ke.duration,bounce:e=Ke.bounce,velocity:n=Ke.velocity,mass:i=Ke.mass}){let r,s;is(t<=un(Ke.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let o=1-e;o=Zn(Ke.minDamping,Ke.maxDamping,o),t=Zn(Ke.minDuration,Ke.maxDuration,En(t)),o<1?(r=l=>{const d=l*o,u=d*t,f=d-n,p=Td(l,o),g=Math.exp(-u);return tl-f/p*g},s=l=>{const u=l*o*t,f=u*n+n,p=Math.pow(o,2)*Math.pow(l,2)*t,g=Math.exp(-u),h=Td(Math.pow(l,2),o);return(-r(l)+tl>0?-1:1)*((f-p)*g)/h}):(r=l=>{const d=Math.exp(-l*t),u=(l-n)*t+1;return-tl+d*u},s=l=>{const d=Math.exp(-l*t),u=(n-l)*(t*t);return d*u});const a=5/t,c=mE(r,s,a);if(t=un(t),isNaN(c))return{stiffness:Ke.stiffness,damping:Ke.damping,duration:t};{const l=Math.pow(c,2)*i;return{stiffness:l,damping:o*2*Math.sqrt(i*l),duration:t}}}const hE=12;function mE(t,e,n){let i=n;for(let r=1;r<hE;r++)i=i-t(i)/e(i);return i}function Td(t,e){return t*Math.sqrt(1-e*e)}const pE=["duration","bounce"],gE=["stiffness","damping","mass"];function Am(t,e){return e.some(n=>t[n]!==void 0)}function vE(t){let e={velocity:Ke.velocity,stiffness:Ke.stiffness,damping:Ke.damping,mass:Ke.mass,isResolvedFromDuration:!1,...t};if(!Am(t,gE)&&Am(t,pE))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),r=i*i,s=2*Zn(.05,1,1-(t.bounce||0))*Math.sqrt(r);e={...e,mass:Ke.mass,stiffness:r,damping:s}}else{const n=fE(t);e={...e,...n,mass:Ke.mass},e.isResolvedFromDuration=!0}return e}function Ma(t=Ke.visualDuration,e=Ke.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:r}=n;const s=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],a={done:!1,value:s},{stiffness:c,damping:l,mass:d,duration:u,velocity:f,isResolvedFromDuration:p}=vE({...n,velocity:-En(n.velocity||0)}),g=f||0,h=l/(2*Math.sqrt(c*d)),y=o-s,b=En(Math.sqrt(c/d)),w=Math.abs(y)<5;i||(i=w?Ke.restSpeed.granular:Ke.restSpeed.default),r||(r=w?Ke.restDelta.granular:Ke.restDelta.default);let C;if(h<1){const x=Td(b,h);C=T=>{const E=Math.exp(-h*b*T);return o-E*((g+h*b*y)/x*Math.sin(x*T)+y*Math.cos(x*T))}}else if(h===1)C=x=>o-Math.exp(-b*x)*(y+(g+b*y)*x);else{const x=b*Math.sqrt(h*h-1);C=T=>{const E=Math.exp(-h*b*T),P=Math.min(x*T,300);return o-E*((g+h*b*y)*Math.sinh(P)+x*y*Math.cosh(P))/x}}const S={calculatedDuration:p&&u||null,next:x=>{const T=C(x);if(p)a.done=x>=u;else{let E=x===0?g:0;h<1&&(E=x===0?un(g):$y(C,x,T));const P=Math.abs(E)<=i,_=Math.abs(o-T)<=r;a.done=P&&_}return a.value=a.done?o:T,a},toString:()=>{const x=Math.min(nf(S),Ia),T=By(E=>S.next(x*E).value,x,30);return x+"ms "+T},toTransition:()=>{}};return S}Ma.applyToOptions=t=>{const e=dE(t,100,Ma);return t.ease=e.ease,t.duration=un(e.duration),t.type="keyframes",t};function Ed({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:r=10,bounceStiffness:s=500,modifyTarget:o,min:a,max:c,restDelta:l=.5,restSpeed:d}){const u=t[0],f={done:!1,value:u},p=P=>a!==void 0&&P<a||c!==void 0&&P>c,g=P=>a===void 0?c:c===void 0||Math.abs(a-P)<Math.abs(c-P)?a:c;let h=n*e;const y=u+h,b=o===void 0?y:o(y);b!==y&&(h=b-u);const w=P=>-h*Math.exp(-P/i),C=P=>b+w(P),S=P=>{const _=w(P),k=C(P);f.done=Math.abs(_)<=l,f.value=f.done?b:k};let x,T;const E=P=>{p(f.value)&&(x=P,T=Ma({keyframes:[f.value,g(f.value)],velocity:$y(C,P,f.value),damping:r,stiffness:s,restDelta:l,restSpeed:d}))};return E(0),{calculatedDuration:null,next:P=>{let _=!1;return!T&&x===void 0&&(_=!0,S(P),E(P)),x!==void 0&&P>=x?T.next(P-x):(!_&&S(P),f)}}}function yE(t,e,n){const i=[],r=n||Jn.mix||Uy,s=t.length-1;for(let o=0;o<s;o++){let a=r(t[o],t[o+1]);if(e){const c=Array.isArray(e)?e[o]||Xt:e;a=ao(c,a)}i.push(a)}return i}function bE(t,e,{clamp:n=!0,ease:i,mixer:r}={}){const s=t.length;if(Yn(s===e.length,"Both input and output ranges must be the same length","range-length"),s===1)return()=>e[0];if(s===2&&e[0]===e[1])return()=>e[1];const o=t[0]===t[1];t[0]>t[s-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=yE(e,i,r),c=a.length,l=d=>{if(o&&d<t[0])return e[0];let u=0;if(c>1)for(;u<t.length-2&&!(d<t[u+1]);u++);const f=Ws(t[u],t[u+1],d);return a[u](f)};return n?d=>l(Zn(t[0],t[s-1],d)):l}function xE(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const r=Ws(0,e,i);t.push(Ge(n,1,r))}}function SE(t){const e=[0];return xE(e,t.length-1),e}function wE(t,e){return t.map(n=>n*e)}function CE(t,e){return t.map(()=>e||Iy).splice(0,t.length-1)}function Pr({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const r=D2(i)?i.map(km):km(i),s={done:!1,value:e[0]},o=wE(n&&n.length===e.length?n:SE(e),t),a=bE(o,e,{ease:Array.isArray(r)?r:CE(e,r)});return{calculatedDuration:t,next:c=>(s.value=a(c),s.done=c>=t,s)}}const kE=t=>t!==null;function rf(t,{repeat:e,repeatType:n="loop"},i,r=1){const s=t.filter(kE),a=r<0||e&&n!=="loop"&&e%2===1?0:s.length-1;return!a||i===void 0?s[a]:i}const TE={decay:Ed,inertia:Ed,tween:Pr,keyframes:Pr,spring:Ma};function Hy(t){typeof t.type=="string"&&(t.type=TE[t.type])}class sf{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,n){return this.finished.then(e,n)}}const EE=t=>t/100;class of extends sf{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var i,r;const{motionValue:n}=this.options;n&&n.updatedAt!==Dt.now()&&this.tick(Dt.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(r=(i=this.options).onStop)==null||r.call(i))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;Hy(e);const{type:n=Pr,repeat:i=0,repeatDelay:r=0,repeatType:s,velocity:o=0}=e;let{keyframes:a}=e;const c=n||Pr;process.env.NODE_ENV!=="production"&&c!==Pr&&Yn(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Pr&&typeof a[0]!="number"&&(this.mixKeyframes=ao(EE,Uy(a[0],a[1])),a=[0,100]);const l=c({...e,keyframes:a});s==="mirror"&&(this.mirroredGenerator=c({...e,keyframes:[...a].reverse(),velocity:-o})),l.calculatedDuration===null&&(l.calculatedDuration=nf(l));const{calculatedDuration:d}=l;this.calculatedDuration=d,this.resolvedDuration=d+r,this.totalDuration=this.resolvedDuration*(i+1)-r,this.generator=l}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:i,totalDuration:r,mixKeyframes:s,mirroredGenerator:o,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return i.next(0);const{delay:l=0,keyframes:d,repeat:u,repeatType:f,repeatDelay:p,type:g,onUpdate:h,finalKeyframe:y}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const b=this.currentTime-l*(this.playbackSpeed>=0?1:-1),w=this.playbackSpeed>=0?b<0:b>r;this.currentTime=Math.max(b,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let C=this.currentTime,S=i;if(u){const P=Math.min(this.currentTime,r)/a;let _=Math.floor(P),k=P%1;!k&&P>=1&&(k=1),k===1&&_--,_=Math.min(_,u+1),!!(_%2)&&(f==="reverse"?(k=1-k,p&&(k-=p/a)):f==="mirror"&&(S=o)),C=Zn(0,1,k)*a}const x=w?{done:!1,value:d[0]}:S.next(C);s&&(x.value=s(x.value));let{done:T}=x;!w&&c!==null&&(T=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const E=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&T);return E&&g!==Ed&&(x.value=rf(d,this.options,y,this.speed)),h&&h(x.value),E&&this.finish(),x}then(e,n){return this.finished.then(e,n)}get duration(){return En(this.calculatedDuration)}get time(){return En(this.currentTime)}set time(e){var n;e=un(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),(n=this.driver)==null||n.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(Dt.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=En(this.currentTime))}play(){var r,s;if(this.isStopped)return;const{driver:e=lE,startTime:n}=this.options;this.driver||(this.driver=e(o=>this.tick(o))),(s=(r=this.options).onPlay)==null||s.call(r);const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=n??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Dt.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(e=this.options).onComplete)==null||n.call(e)}cancel(){var e,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(e=this.options).onCancel)==null||n.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),e.observe(this)}}function PE(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Bi=t=>t*180/Math.PI,Pd=t=>{const e=Bi(Math.atan2(t[1],t[0]));return Rd(e)},RE={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Pd,rotateZ:Pd,skewX:t=>Bi(Math.atan(t[1])),skewY:t=>Bi(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Rd=t=>(t=t%360,t<0&&(t+=360),t),Im=Pd,Mm=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),_m=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),AE={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Mm,scaleY:_m,scale:t=>(Mm(t)+_m(t))/2,rotateX:t=>Rd(Bi(Math.atan2(t[6],t[5]))),rotateY:t=>Rd(Bi(Math.atan2(-t[2],t[0]))),rotateZ:Im,rotate:Im,skewX:t=>Bi(Math.atan(t[4])),skewY:t=>Bi(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Ad(t){return t.includes("scale")?1:0}function Id(t,e){if(!t||t==="none")return Ad(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,r;if(n)i=AE,r=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=RE,r=a}if(!r)return Ad(e);const s=i[e],o=r[1].split(",").map(ME);return typeof s=="function"?s(o):o[s]}const IE=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return Id(n,e)};function ME(t){return parseFloat(t.trim())}const ss=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],os=new Set(ss),Nm=t=>t===rs||t===he,_E=new Set(["x","y","z"]),NE=ss.filter(t=>!_E.has(t));function OE(t){const e=[];return NE.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const zi={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Id(e,"x"),y:(t,{transform:e})=>Id(e,"y")};zi.translateX=zi.x;zi.translateY=zi.y;const Wi=new Set;let Md=!1,_d=!1,Nd=!1;function zy(){if(_d){const t=Array.from(Wi).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const r=OE(i);r.length&&(n.set(i,r),i.render())}),t.forEach(i=>i.measureInitialState()),e.forEach(i=>{i.render();const r=n.get(i);r&&r.forEach(([s,o])=>{var a;(a=i.getValue(s))==null||a.set(o)})}),t.forEach(i=>i.measureEndState()),t.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}_d=!1,Md=!1,Wi.forEach(t=>t.complete(Nd)),Wi.clear()}function Wy(){Wi.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(_d=!0)})}function DE(){Nd=!0,Wy(),zy(),Nd=!1}class af{constructor(e,n,i,r,s,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=i,this.motionValue=r,this.element=s,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(Wi.add(this),Md||(Md=!0,We.read(Wy),We.resolveKeyframes(zy))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:i,motionValue:r}=this;if(e[0]===null){const s=r==null?void 0:r.get(),o=e[e.length-1];if(s!==void 0)e[0]=s;else if(i&&n){const a=i.readValue(n,o);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=o),r&&s===void 0&&r.set(e[0])}PE(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Wi.delete(this)}cancel(){this.state==="scheduled"&&(Wi.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const jE=t=>t.startsWith("--");function LE(t,e,n){jE(e)?t.style.setProperty(e,n):t.style[e]=n}const VE=qu(()=>window.ScrollTimeline!==void 0),FE={};function UE(t,e){const n=qu(t);return()=>FE[e]??n()}const qy=UE(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Ms=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,Om={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Ms([0,.65,.55,1]),circOut:Ms([.55,0,1,.45]),backIn:Ms([.31,.01,.66,-.59]),backOut:Ms([.33,1.53,.69,.99])};function Ky(t,e){if(t)return typeof t=="function"?qy()?By(t,e):"ease-out":My(t)?Ms(t):Array.isArray(t)?t.map(n=>Ky(n,e)||Om.easeOut):Om[t]}function BE(t,e,n,{delay:i=0,duration:r=300,repeat:s=0,repeatType:o="loop",ease:a="easeOut",times:c}={},l=void 0){const d={[e]:n};c&&(d.offset=c);const u=Ky(a,r);Array.isArray(u)&&(d.easing=u);const f={delay:i,duration:r,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:s+1,direction:o==="reverse"?"alternate":"normal"};return l&&(f.pseudoElement=l),t.animate(d,f)}function Gy(t){return typeof t=="function"&&"applyToOptions"in t}function $E({type:t,...e}){return Gy(t)&&qy()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class HE extends sf{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:i,keyframes:r,pseudoElement:s,allowFlatten:o=!1,finalKeyframe:a,onComplete:c}=e;this.isPseudoElement=!!s,this.allowFlatten=o,this.options=e,Yn(typeof e.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const l=$E(e);this.animation=BE(n,i,r,l,s),l.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!s){const d=rf(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):LE(n,i,d),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,n;(n=(e=this.animation).finish)==null||n.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var e,n;this.isPseudoElement||(n=(e=this.animation).commitStyles)==null||n.call(e)}get duration(){var n,i;const e=((i=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:i.call(n).duration)||0;return En(Number(e))}get time(){return En(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=un(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:n}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&VE()?(this.animation.timeline=e,Xt):n(this)}}const Zy={anticipate:Py,backInOut:Ey,circInOut:Ay};function zE(t){return t in Zy}function WE(t){typeof t.ease=="string"&&zE(t.ease)&&(t.ease=Zy[t.ease])}const Dm=10;class qE extends HE{constructor(e){WE(e),Hy(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:i,onComplete:r,element:s,...o}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const a=new of({...o,autoplay:!1}),c=un(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-Dm).value,a.sample(c).value,Dm),a.stop()}}const jm=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(vi.test(t)||t==="0")&&!t.startsWith("url("));function KE(t){const e=t[0];if(t.length===1)return!0;for(let n=0;n<t.length;n++)if(t[n]!==e)return!0}function GE(t,e,n,i){const r=t[0];if(r===null)return!1;if(e==="display"||e==="visibility")return!0;const s=t[t.length-1],o=jm(r,e),a=jm(s,e);return is(o===a,`You are trying to animate ${e} from "${r}" to "${s}". "${o?s:r}" is not an animatable value.`,"value-not-animatable"),!o||!a?!1:KE(t)||(n==="spring"||Gy(n))&&i}function Od(t){t.duration=0,t.type}const ZE=new Set(["opacity","clipPath","filter","transform"]),YE=qu(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function JE(t){var d;const{motionValue:e,name:n,repeatDelay:i,repeatType:r,damping:s,type:o}=t;if(!(((d=e==null?void 0:e.owner)==null?void 0:d.current)instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:l}=e.owner.getProps();return YE()&&n&&ZE.has(n)&&(n!=="transform"||!l)&&!c&&!i&&r!=="mirror"&&s!==0&&o!=="inertia"}const XE=40;class QE extends sf{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:r=0,repeatDelay:s=0,repeatType:o="loop",keyframes:a,name:c,motionValue:l,element:d,...u}){var g;super(),this.stop=()=>{var h,y;this._animation&&(this._animation.stop(),(h=this.stopTimeline)==null||h.call(this)),(y=this.keyframeResolver)==null||y.cancel()},this.createdAt=Dt.now();const f={autoplay:e,delay:n,type:i,repeat:r,repeatDelay:s,repeatType:o,name:c,motionValue:l,element:d,...u},p=(d==null?void 0:d.KeyframeResolver)||af;this.keyframeResolver=new p(a,(h,y,b)=>this.onKeyframesResolved(h,y,f,!b),c,l,d),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(e,n,i,r){this.keyframeResolver=void 0;const{name:s,type:o,velocity:a,delay:c,isHandoff:l,onUpdate:d}=i;this.resolvedAt=Dt.now(),GE(e,s,o,a)||((Jn.instantAnimations||!c)&&(d==null||d(rf(e,i,n))),e[0]=e[e.length-1],Od(i),i.repeat=0);const f={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>XE?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},p=!l&&JE(f)?new qE({...f,element:f.motionValue.owner.current}):new of(f);p.finished.then(()=>this.notifyFinished()).catch(Xt),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),DE()),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var e;this._animation&&this.animation.cancel(),(e=this.keyframeResolver)==null||e.cancel()}}const eP=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function tP(t){const e=eP.exec(t);if(!e)return[,];const[,n,i,r]=e;return[`--${n??i}`,r]}const nP=4;function Yy(t,e,n=1){Yn(n<=nP,`Max CSS variable fallback depth detected in property "${t}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[i,r]=tP(t);if(!i)return;const s=window.getComputedStyle(e).getPropertyValue(i);if(s){const o=s.trim();return yy(o)?parseFloat(o):o}return Xu(r)?Yy(r,e,n+1):r}function cf(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Jy=new Set(["width","height","top","left","right","bottom",...ss]),iP={test:t=>t==="auto",parse:t=>t},Xy=t=>e=>e.test(t),Qy=[rs,he,Pn,oi,K2,q2,iP],Lm=t=>Qy.find(Xy(t));function rP(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||xy(t):!0}const sP=new Set(["brightness","contrast","saturate","opacity"]);function oP(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Qu)||[];if(!i)return t;const r=n.replace(i,"");let s=sP.has(e)?1:0;return i!==n&&(s*=100),e+"("+s+r+")"}const aP=/\b([a-z-]*)\(.*?\)/gu,Dd={...vi,getAnimatableNone:t=>{const e=t.match(aP);return e?e.map(oP).join(" "):t}},Vm={...rs,transform:Math.round},cP={rotate:oi,rotateX:oi,rotateY:oi,rotateZ:oi,scale:To,scaleX:To,scaleY:To,scaleZ:To,skew:oi,skewX:oi,skewY:oi,distance:he,translateX:he,translateY:he,translateZ:he,x:he,y:he,z:he,perspective:he,transformPerspective:he,opacity:qs,originX:Tm,originY:Tm,originZ:he},lf={borderWidth:he,borderTopWidth:he,borderRightWidth:he,borderBottomWidth:he,borderLeftWidth:he,borderRadius:he,radius:he,borderTopLeftRadius:he,borderTopRightRadius:he,borderBottomRightRadius:he,borderBottomLeftRadius:he,width:he,maxWidth:he,height:he,maxHeight:he,top:he,right:he,bottom:he,left:he,padding:he,paddingTop:he,paddingRight:he,paddingBottom:he,paddingLeft:he,margin:he,marginTop:he,marginRight:he,marginBottom:he,marginLeft:he,backgroundPositionX:he,backgroundPositionY:he,...cP,zIndex:Vm,fillOpacity:qs,strokeOpacity:qs,numOctaves:Vm},lP={...lf,color:ct,backgroundColor:ct,outlineColor:ct,fill:ct,stroke:ct,borderColor:ct,borderTopColor:ct,borderRightColor:ct,borderBottomColor:ct,borderLeftColor:ct,filter:Dd,WebkitFilter:Dd},eb=t=>lP[t];function tb(t,e){let n=eb(t);return n!==Dd&&(n=vi),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const dP=new Set(["auto","none","0"]);function uP(t,e,n){let i=0,r;for(;i<t.length&&!r;){const s=t[i];typeof s=="string"&&!dP.has(s)&&Ks(s).values.length&&(r=t[i]),i++}if(r&&n)for(const s of e)t[s]=tb(n,r)}class fP extends af{constructor(e,n,i,r,s){super(e,n,i,r,s,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<e.length;c++){let l=e[c];if(typeof l=="string"&&(l=l.trim(),Xu(l))){const d=Yy(l,n.current);d!==void 0&&(e[c]=d),c===e.length-1&&(this.finalKeyframe=l)}}if(this.resolveNoneKeyframes(),!Jy.has(i)||e.length!==2)return;const[r,s]=e,o=Lm(r),a=Lm(s);if(o!==a)if(Nm(o)&&Nm(a))for(let c=0;c<e.length;c++){const l=e[c];typeof l=="string"&&(e[c]=parseFloat(l))}else zi[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let r=0;r<e.length;r++)(e[r]===null||rP(e[r]))&&i.push(r);i.length&&uP(e,i,n)}measureInitialState(){const{element:e,unresolvedKeyframes:n,name:i}=this;if(!e||!e.current)return;i==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=zi[i](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&e.getValue(i,r).jump(r,!1)}measureEndState(){var a;const{element:e,name:n,unresolvedKeyframes:i}=this;if(!e||!e.current)return;const r=e.getValue(n);r&&r.jump(this.measuredOrigin,!1);const s=i.length-1,o=i[s];i[s]=zi[n](e.measureViewportBox(),window.getComputedStyle(e.current)),o!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=o),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([c,l])=>{e.getValue(c).set(l)}),this.resolveNoneKeyframes()}}function hP(t,e,n){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let i=document;const r=(n==null?void 0:n[t])??i.querySelectorAll(t);return r?Array.from(r):[]}return Array.from(t)}const nb=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function ib(t){return by(t)&&"offsetHeight"in t}const Fm=30,mP=t=>!isNaN(parseFloat(t));class pP{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=i=>{var s;const r=Dt.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((s=this.events.change)==null||s.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=Dt.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=mP(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!=="production"&&Gu(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",e)}on(e,n){this.events[e]||(this.events[e]=new Ku);const i=this.events[e].add(n);return e==="change"?()=>{i(),We.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,n){this.passiveEffect=e,this.stopPassiveEffect=n}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,n,i){this.set(n),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-i}jump(e,n=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=Dt.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Fm)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Fm);return Sy(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(e){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=e(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var e,n;(e=this.dependents)==null||e.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Kr(t,e){return new pP(t,e)}const{schedule:df}=_y(queueMicrotask,!1),sn={x:!1,y:!1};function rb(){return sn.x||sn.y}function gP(t){return t==="x"||t==="y"?sn[t]?null:(sn[t]=!0,()=>{sn[t]=!1}):sn.x||sn.y?null:(sn.x=sn.y=!0,()=>{sn.x=sn.y=!1})}function sb(t,e){const n=hP(t),i=new AbortController,r={passive:!0,...e,signal:i.signal};return[n,r,()=>i.abort()]}function Um(t){return!(t.pointerType==="touch"||rb())}function vP(t,e,n={}){const[i,r,s]=sb(t,n),o=a=>{if(!Um(a))return;const{target:c}=a,l=e(c,a);if(typeof l!="function"||!c)return;const d=u=>{Um(u)&&(l(u),c.removeEventListener("pointerleave",d))};c.addEventListener("pointerleave",d,r)};return i.forEach(a=>{a.addEventListener("pointerenter",o,r)}),s}const ob=(t,e)=>e?t===e?!0:ob(t,e.parentElement):!1,uf=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,yP=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function bP(t){return yP.has(t.tagName)||t.tabIndex!==-1}const aa=new WeakSet;function Bm(t){return e=>{e.key==="Enter"&&t(e)}}function nl(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const xP=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=Bm(()=>{if(aa.has(n))return;nl(n,"down");const r=Bm(()=>{nl(n,"up")}),s=()=>nl(n,"cancel");n.addEventListener("keyup",r,e),n.addEventListener("blur",s,e)});n.addEventListener("keydown",i,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),e)};function $m(t){return uf(t)&&!rb()}function SP(t,e,n={}){const[i,r,s]=sb(t,n),o=a=>{const c=a.currentTarget;if(!$m(a))return;aa.add(c);const l=e(c,a),d=(p,g)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",f),aa.has(c)&&aa.delete(c),$m(p)&&typeof l=="function"&&l(p,{success:g})},u=p=>{d(p,c===window||c===document||n.useGlobalTarget||ob(c,p.target))},f=p=>{d(p,!1)};window.addEventListener("pointerup",u,r),window.addEventListener("pointercancel",f,r)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",o,r),ib(a)&&(a.addEventListener("focus",l=>xP(l,r)),!bP(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),s}function ab(t){return by(t)&&"ownerSVGElement"in t}function wP(t){return ab(t)&&t.tagName==="svg"}const Tt=t=>!!(t&&t.getVelocity),CP=[...Qy,ct,vi],kP=t=>CP.find(Xy(t)),ff=R.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class TP extends v.Component{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,r=ib(i)&&i.offsetWidth||0,s=this.props.sizeRef.current;s.height=n.offsetHeight||0,s.width=n.offsetWidth||0,s.top=n.offsetTop,s.left=n.offsetLeft,s.right=r-s.width-s.left}return null}componentDidUpdate(){}render(){return this.props.children}}function EP({children:t,isPresent:e,anchorX:n,root:i}){const r=R.useId(),s=R.useRef(null),o=R.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=R.useContext(ff);return R.useInsertionEffect(()=>{const{width:c,height:l,top:d,left:u,right:f}=o.current;if(e||!s.current||!c||!l)return;const p=n==="left"?`left: ${u}`:`right: ${f}`;s.current.dataset.motionPopId=r;const g=document.createElement("style");a&&(g.nonce=a);const h=i??document.head;return h.appendChild(g),g.sheet&&g.sheet.insertRule(`
67
+ `},qc}var dm;function MT(){if(dm)return nn;dm=1;var t=AT(),e=IT(),n=Du();return nn.grammar=n,nn.write=e,nn.parse=t.parse,nn.parseParams=t.parseParams,nn.parseFmtpConfig=t.parseFmtpConfig,nn.parsePayloads=t.parsePayloads,nn.parseRemoteCandidates=t.parseRemoteCandidates,nn.parseImageAttributes=t.parseImageAttributes,nn.parseSimulcastStreamList=t.parseSimulcastStreamList,nn}var si=MT();function ju(t,e,n){var i,r,s;e===void 0&&(e=50),n===void 0&&(n={});var o=(i=n.isImmediate)!=null&&i,a=(r=n.callback)!=null&&r,c=n.maxWait,l=Date.now(),d=[];function u(){if(c!==void 0){var p=Date.now()-l;if(p+e>=c)return c-p}return e}var f=function(){var p=[].slice.call(arguments),g=this;return new Promise(function(h,y){var b=o&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!o){var C=t.apply(g,p);a&&a(C),d.forEach(function(S){return(0,S.resolve)(C)}),d=[]}},u()),b){var w=t.apply(g,p);return a&&a(w),h(w)}d.push({resolve:h,reject:y})})};return f.cancel=function(p){s!==void 0&&clearTimeout(s),d.forEach(function(g){return(0,g.reject)(p)}),d=[]},f}const _T=.7,NT=20,Lr={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class um extends Nn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=Ce,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=ju(r=>A(this,void 0,void 0,function*(){this.emit(Lr.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),NT),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Gn((i=n.loggerName)!==null&&i!==void 0?i:fn.PCTransport),this.loggerOptions=n,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=n=>{var i;n.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,n.candidate))},e.onicecandidateerror=n=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,n)},e.oniceconnectionstatechange=()=>{var n;(n=this.onIceConnectionStateChange)===null||n===void 0||n.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var n;(n=this.onSignalingStatechange)===null||n===void 0||n.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var n;(n=this.onConnectionStateChange)===null||n===void 0||n.call(this,e.connectionState)},e.ondatachannel=n=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,n)},e.ontrack=n=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,n)},e}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return A(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,n){return A(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&n>0&&n!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:n,latestOfferId:this.latestOfferId})),!1;let r;if(e.type==="offer"){let{stereoMids:s,nackMids:o}=OT(e);this.remoteStereoMids=s,this.remoteNackMids=o}else if(e.type==="answer"){const s=si.parse((i=e.sdp)!==null&&i!==void 0?i:"");s.media.forEach(o=>{o.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||o.mid!=a.transceiver.mid)return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(c=d.payload,!0):!1),c===0)return!0;let l=!1;for(const d of o.fmtp)if(d.payload===c){d.config=d.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),l=!0;break}return l||a.maxbr>0&&o.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),r=si.write(s)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Lr.NegotiationComplete),e.sdp&&si.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Lr.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return A(this,void 0,void 0,function*(){var n;const i=this.latestOfferId+1;if(this.latestOfferId=i,this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const s=si.parse((n=r.sdp)!==null&&n!==void 0?n:"");if(s.media.forEach(o=>{hm(o),o.type==="audio"?fm(o,[],[]):o.type==="video"&&this.trackBitrates.some(a=>{if(!o.msid||!a.cid||!o.msid.includes(a.cid))return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(c=d.payload,!0):!1),c===0||(Kn(a.codec)&&this.ensureVideoDDExtensionForSVC(o,s),a.codec!=="av1"))return!0;const l=Math.round(a.maxbr*_T);for(const d of o.fmtp)if(d.payload===c){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>i){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));return}yield this.setMungedSDP(r,si.write(s)),this.onOffer(r,this.latestOfferId)})}createAndSetAnswer(){return A(this,void 0,void 0,function*(){var e;const n=yield this.pc.createAnswer(),i=si.parse((e=n.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{hm(r),r.type==="audio"&&fm(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,si.write(i)),n})}createDataChannel(e,n){return this.pc.createDataChannel(e,n)}addTransceiver(e,n){return this.pc.addTransceiver(e,n)}addTrack(e){if(!this._pc)throw new ht("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var n;if(!this._pc)throw new ht("PC closed, cannot configure");return(n=this._pc)===null||n===void 0?void 0:n.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var n;return(n=this._pc)===null||n===void 0?void 0:n.removeTrack(e)}getConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&n!==void 0?n:"closed"}getICEConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&n!==void 0?n:"closed"}getSignallingState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&n!==void 0?n:"closed"}getTransceivers(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&n!==void 0?n:[]}getSenders(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&n!==void 0?n:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return A(this,void 0,void 0,function*(){var e;if(!this._pc)return;let n="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":n=a.selectedCandidatePairId;break;case"candidate-pair":n===""&&a.selected&&(n=a.id),i.set(a.id,a);break;case"remote-candidate":r.set(a.id,"".concat(a.address,":").concat(a.port));break}}),n==="")return;const o=(e=i.get(n))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return r.get(o)})}setMungedSDP(e,n,i){return A(this,void 0,void 0,function*(){if(n){const r=e.sdp;e.sdp=n;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:n})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const o={error:s,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new sd(s)}})}ensureVideoDDExtensionForSVC(e,n){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===Xh))){if(this.ddExtID===0){let o=0;n.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:Xh})}}}function fm(t,e,n){let i=0;t.rtp.some(r=>r.codec==="opus"?(i=r.payload,!0):!1),i>0&&(t.rtcpFb||(t.rtcpFb=[]),n.includes(t.mid)&&!t.rtcpFb.some(r=>r.payload===i&&r.type==="nack")&&t.rtcpFb.push({payload:i,type:"nack"}),e.includes(t.mid)&&t.fmtp.some(r=>r.payload===i?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function OT(t){var e;const n=[],i=[],r=si.parse((e=t.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(o=>{var a;o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(c=>c.payload===s&&c.type==="nack")&&i.push(o.mid),o.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&n.push(o.mid),!0):!1))}),{stereoMids:n,nackMids:i}}function hm(t){if(t.connection){const e=t.connection.ip.indexOf(":")>=0;(t.connection.version===4&&e||t.connection.version===6&&!e)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}const gd="vp8",DT={audioPreset:od.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Mu.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:gd,backupCodec:!0,preConnectBuffer:!1},sy={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},oy={deviceId:{ideal:"default"},resolution:zs.h720.resolution},jT={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new wk,disconnectOnPageLeave:!0,webAudioMix:!1},Lu={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Je;(function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"})(Je||(Je={}));class LT{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,n,i){var r;this.peerConnectionTimeout=Lu.peerConnectionTimeout,this.log=Ce,this.updateState=()=>{var s;const o=this.state,a=this.requiredTransports.map(c=>c.getConnectionState());a.every(c=>c==="connected")?this.state=Je.CONNECTED:a.some(c=>c==="failed")?this.state=Je.FAILED:a.some(c=>c==="connecting")?this.state=Je.CONNECTING:a.every(c=>c==="closed")?this.state=Je.CLOSED:a.some(c=>c==="closed")?this.state=Je.CLOSING:a.every(c=>c==="new")&&(this.state=Je.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(Je[o]," to ").concat(Je[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Gn((r=i.loggerName)!==null&&r!==void 0?r:fn.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!n,this.isSubscriberConnectionRequired=n,this.publisher=new um(e,i),this.subscriber=new um(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,ln.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,ln.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,s)},this.subscriber.onTrack=s=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,s)},this.publisher.onOffer=(s,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s,o)},this.state=Je.NEW,this.connectionLock=new Nt,this.remoteOfferLock=new Nt}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,n){return this.publisher.setRemoteDescription(e,n)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return A(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const n of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(n)}catch(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return A(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,n){return A(this,void 0,void 0,function*(){n===ln.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,n){return A(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const i=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(e,n))?yield this.subscriber.createAndSetAnswer():void 0}finally{i()}})}updateConfiguration(e,n){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),n&&this.triggerIceRestart()}ensurePCTransportConnection(e,n){return A(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,n)))}finally{r()}})}negotiate(e){return A(this,void 0,void 0,function*(){return new Promise((n,i)=>A(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",s),this.publisher.once(Lr.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Lr.NegotiationComplete,()=>{clearTimeout(r),n()})}),yield this.publisher.negotiate(o=>{clearTimeout(r),i(o)})}))})}addPublisherTransceiver(e,n){return this.publisher.addTransceiver(e,n)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,n){return this.publisher.createDataChannel(e,n)}getConnectedAddress(e){return e===ln.PUBLISHER?this.publisher.getConnectedAddress():e===ln.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,n){return A(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((c,l)=>A(s,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection",this.logContext),bt.clearTimeout(u),l(new Ue("room connection has been cancelled",Te.Cancelled))};r!=null&&r.signal.aborted&&d(),r==null||r.signal.addEventListener("abort",d);const u=bt.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",d),l(new Ue("could not establish pc connection",Te.InternalError))},o);for(;this.state!==Je.CONNECTED;)if(yield jt(50),r!=null&&r.signal.aborted){l(new Ue("room connection has been cancelled",Te.Cancelled));return}bt.clearTimeout(u),r==null||r.signal.removeEventListener("abort",d),c()}))}()})}}class Qe extends Error{constructor(e,n,i){super(n),this.code=e,this.message=mm(n,Qe.MAX_MESSAGE_BYTES),this.data=i?mm(i,Qe.MAX_DATA_BYTES):void 0}static fromProto(e){return new Qe(e.code,e.message,e.data)}toProto(){return new ev({code:this.code,message:this.message,data:this.data})}static builtIn(e,n){return new Qe(Qe.ErrorCode[e],Qe.ErrorMessage[e],n)}}Qe.MAX_MESSAGE_BYTES=256;Qe.MAX_DATA_BYTES=15360;Qe.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404};Qe.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const ay=15360;function Vu(t){return new TextEncoder().encode(t).length}function mm(t,e){if(Vu(t)<=e)return t;let n=0,i=t.length;const r=new TextEncoder;for(;n<i;){const s=Math.floor((n+i+1)/2);r.encode(t.slice(0,s)).length<=e?n=s:i=s-1}return t.slice(0,n)}const Fu=2e3;function Xa(t,e){if(!e)return 0;let n,i;return"bytesReceived"in t?(n=t.bytesReceived,i=e.bytesReceived):"bytesSent"in t&&(n=t.bytesSent,i=e.bytesSent),n===void 0||i===void 0||t.timestamp===void 0||e.timestamp===void 0?0:(n-i)*8*1e3/(t.timestamp-e.timestamp)}const Uu=typeof MediaRecorder<"u";class VT{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const FT=Uu?MediaRecorder:VT;class UT extends FT{constructor(e,n){if(!Uu)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),n);let i,r;const s=()=>r===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r==null||r.close(),r=void 0},a=c=>{r==null||r.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r=void 0};this.byteStream=new ReadableStream({start:c=>{r=c,i=l=>A(this,void 0,void 0,function*(){const d=yield l.data.arrayBuffer();s()||c.enqueue(new Uint8Array(d))}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function BT(){return Uu}const $T=1e3,HT=1e4;class cy extends V{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,n,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,n,s),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=ju(()=>A(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>A(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(re.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Nt,this.pauseUpstreamLock=new Nt,this.processorLock=new Nt,this.restartLock=new Nt,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==V.Kind.Video)return;const{width:e,height:n}=this._mediaStreamTrack.getSettings();if(e&&n)return{width:e,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,n;return(n=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&n!==void 0?n:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,n){return A(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!n)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Dr(this._mediaStreamTrack,s)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){const s=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(kr(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}finally{s()}}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{kr(r??e,s)}))})}waitForDimensions(){return A(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:$T;return function*(){var i;if(e.kind===V.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=$t())===null||i===void 0?void 0:i.os)==="iOS"&&(yield jt(10));const r=Date.now();for(;Date.now()-r<n;){const s=e.dimensions;if(s)return s;yield jt(50)}throw new Wn("unable to get track dimensions after timeout")}()})}setDeviceId(e){return A(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===fi(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),fi(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return A(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===V.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===V.Kind.Audio?"audioinput":"videoinput";return n?gt.getInstance().normalizeDeviceId(s,i,r):i}()})}mute(){return A(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return A(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,n){return A(this,void 0,void 0,function*(){if(!this.sender)throw new Wn("unable to replace an unpublished track");let i,r;return typeof n=="boolean"?i=n:n!==void 0&&(i=n.userProvidedTrack,r=n.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return A(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,s=Ck(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===V.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(l=>{Dr(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(re.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?re.Muted:re.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return A(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xv()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return A(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(re.UpstreamPaused,this);const i=$t();if((i==null?void 0:i.name)==="Safari"&&mi(i.version,"12.0")<0)throw new Iu("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{n()}})}resumeUpstream(){return A(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(re.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}})}getRTCStatsReport(){return A(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return A(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;const o=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const a=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:a,audioContext:i.audioContext};if(yield n.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(kr(i._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))),i.processor=n,i.processorElement=a,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(Dr(i._mediaStreamTrack,l),kr(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(re.TrackProcessorUpdate,i.processor)}finally{o()}}()})}getProcessor(){return this.processor}stopProcessor(){return A(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,n||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(re.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!BT()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(!this.localTrackRecorder)this.localTrackRecorder=new UT(this,{mimeType:"audio/webm;codecs=opus"});else{this.log.warn("preconnect buffer already started");return}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},HT)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}}class Ta extends cy{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,V.Kind.Audio,n,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>A(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=Xa(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(re.AudioTrackFeatureUpdate,this,pt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(re.AudioTrackFeatureUpdate,this,pt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return A(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===V.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return A(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==fi(this._constraints.deviceId);return this.source===V.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{n()}})}restartTrack(e){return A(this,void 0,void 0,function*(){let n;if(e){const i=_u({audio:e});typeof i.audio!="boolean"&&(n=i.audio)}yield this.restart(n)})}restart(e){const n=Object.create(null,{restart:{get:()=>super.restart}});return A(this,void 0,void 0,function*(){const i=yield n.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){Ot()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Fu)))}setProcessor(e){return A(this,void 0,void 0,function*(){var n;const i=yield this.processorLock.lock();try{if(!In()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(n=this.sender)===null||n===void 0?void 0:n.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(re.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return A(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const n=yield this.sender.getStats();let i;return n.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return A(this,void 0,void 0,function*(){const e=yield ny(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(re.AudioSilenceDetected)),e})}}function zT(t,e,n){switch(t.kind){case"audio":return new Ta(t,e,!1,void 0,n);case"video":return new Ea(t,e,!1,n);default:throw new Wn("unsupported track type: ".concat(t.kind))}}const WT=Object.values(zs),qT=Object.values(ad),KT=Object.values(Mu),GT=[zs.h180,zs.h360],ZT=[ad.h180,ad.h360],YT=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(n=>{var i,r;return new je(Math.floor(t.width/n.scaleResolutionDownBy),Math.floor(t.height/n.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(n.scaleResolutionDownBy,2)*(((i=t.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=n.fps)!==null&&r!==void 0?r:30))))),n.fps,t.encoding.priority)}),vd=["q","h","f"];function yd(t,e,n,i){var r,s;let o=i==null?void 0:i.videoEncoding;t&&(o=i==null?void 0:i.screenShareEncoding);const a=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!o&&!a&&!c||!e||!n)return[{}];o||(o=XT(t,e,n,l),Ce.debug("using video encoding",o));const d=o.maxFramerate,u=new je(e,n,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Kn(l)){const g=new ly(c),h=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const y=$t();if(Xi()||In()||(y==null?void 0:y.name)==="Chrome"&&mi(y==null?void 0:y.version,"113")<0){const b=g.suffix=="h"?2:3,w=tT(y);for(let C=0;C<g.spatial;C+=1)h.push({rid:vd[2-C],maxBitrate:o.maxBitrate/Math.pow(b,C),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:w?Math.pow(2,C):void 0});h[0].scalabilityMode=c}else h.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(h[0].priority=u.encoding.priority,h[0].networkPriority=u.encoding.priority),Ce.debug("using svc encoding",{encodings:h}),h}if(!a)return[o];let f=[];t?f=(r=gm(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:pm(t,u):f=(s=gm(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:pm(t,u);let p;if(f.length>0){const g=f[0];f.length>1&&([,p]=f);const h=Math.max(e,n);if(h>=960&&p)return Kc(e,n,[g,p,u],d);if(h>=480)return Kc(e,n,[g,u],d)}return Kc(e,n,[u])}function JT(t,e,n){var i,r,s,o;if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;e!==n.backupCodec.codec&&Ce.warn("requested a different codec than specified as backup",{serverRequested:e,backup:n.backupCodec.codec}),n.videoCodec=e,n.videoEncoding=n.backupCodec.encoding;const a=t.mediaStreamTrack.getSettings(),c=(i=a.width)!==null&&i!==void 0?i:(r=t.dimensions)===null||r===void 0?void 0:r.width,l=(s=a.height)!==null&&s!==void 0?s:(o=t.dimensions)===null||o===void 0?void 0:o.height;return t.source===V.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),yd(t.source===V.Source.ScreenShare,c,l,n)}function XT(t,e,n,i){const r=QT(t,e,n);let{encoding:s}=r[0];const o=Math.max(e,n);for(let a=0;a<r.length;a+=1){const c=r[a];if(s=c.encoding,c.width>=o)break}if(i)switch(i){case"av1":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function QT(t,e,n){if(t)return KT;const i=e>n?e/n:n/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?WT:qT}function pm(t,e){if(t)return YT(e);const{width:n,height:i}=e,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?GT:ZT}function Kc(t,e,n,i){const r=[];if(n.forEach((s,o)=>{if(o>=vd.length)return;const a=Math.min(t,e),l={rid:vd[o],scaleResolutionDownBy:Math.max(1,a/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},d=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;d&&(l.maxFramerate=d);const u=qr()||o===0;s.encoding.priority&&u&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),In()&&ey()==="ios"){let s;r.forEach(a=>{s?a.maxFramerate&&a.maxFramerate>s&&(s=a.maxFramerate):s=a.maxFramerate});let o=!0;r.forEach(a=>{var c;a.maxFramerate!=s&&(o&&(o=!1,Ce.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Ce.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),a.maxFramerate=s)})}return r}function gm(t){if(t)return t.sort((e,n)=>{const{encoding:i}=e,{encoding:r}=n;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class ly{constructor(e){const n=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!n)throw new Error("invalid scalability mode");if(this.spatial=parseInt(n[1]),this.temporal=parseInt(n[2]),n.length>3)switch(n[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=n[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function e2(t){return t.source===V.Source.ScreenShare||t.constraints.height&&fi(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const t2=5e3;class Ea extends cy{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,V.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>A(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}const o=new Map(s.map(a=>[a.rid,a]));if(this.prevStats){let a=0;o.forEach((c,l)=>{var d;const u=(d=this.prevStats)===null||d===void 0?void 0:d.get(l);a+=Xa(c,u)}),this._currentBitrate=a}this.prevStats=o}),this.senderLock=new Nt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var n;if(this.signalClient=e,!Ot())return;const i=(n=this.sender)===null||n===void 0?void 0:n.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Fu))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return A(this,void 0,void 0,function*(){var n,i,r,s,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=zn(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0)s=l.value,a=!1,yield(o=s.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(d){i={error:d}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return A(this,void 0,void 0,function*(){var n,i,r,s,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=zn(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0){s=l.value,a=!1;const d=s;yield(o=d.sender)===null||o===void 0?void 0:o.replaceTrack(d.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return A(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===V.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return A(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.source===V.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{n()}})}setTrackMuted(e){super.setTrackMuted(e);for(const n of this.simulcastCodecs.values())n.mediaStreamTrack.enabled=!e}getSenderStats(){return A(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const n=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const o={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},a=i.get(r.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),n.push(o)}}),n.sort((r,s)=>{var o,a;return((o=s.frameWidth)!==null&&o!==void 0?o:0)-((a=r.frameWidth)!==null&&a!==void 0?a:0)}),n})}setPublishingQuality(e){const n=[];for(let i=Jt.LOW;i<=Jt.HIGH;i+=1)n.push(new Pu({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Kn(this.codec),n)}restartTrack(e){return A(this,void 0,void 0,function*(){var n,i,r,s,o;let a;if(e){const u=_u({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a);try{for(var c=!0,l=zn(this.simulcastCodecs.values()),d;d=yield l.next(),n=d.done,!n;c=!0){s=d.value,c=!1;const u=s;u.sender&&((o=u.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}setProcessor(e){const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return A(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var o,a,c,l,d,u;if(yield n.setProcessor.call(r,i,s),!((d=r.processor)===null||d===void 0)&&d.processedTrack)try{for(var f=!0,p=zn(r.simulcastCodecs.values()),g;g=yield p.next(),o=g.done,!o;f=!0)l=g.value,f=!1,yield(u=l.sender)===null||u===void 0?void 0:u.replaceTrack(r.processor.processedTrack)}catch(h){a={error:h}}finally{try{!f&&!o&&(c=p.return)&&(yield c.call(p))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return A(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const n=this.sender.getParameters();n.degradationPreference=e,this.sender.setParameters(n)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},this.logContext))}})}addSimulcastTrack(e,n){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:n};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,n){const i=this.simulcastCodecs.get(e);i&&(i.sender=n,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},t2))}setPublishingCodecs(e){return A(this,void 0,void 0,function*(){var n,i,r,s,o,a,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Kn(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(n=!0,i=zn(e);r=yield i.next(),s=r.done,!s;n=!0){c=r.value,n=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(Kn(d.codec),d.qualities);else{const u=this.simulcastCodecs.get(d.codec);if(this.log.debug("try setPublishingCodec for ".concat(d.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const f of d.qualities)if(f.enabled){l.push(d.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(d.codec),this.logContext),yield vm(u.sender,u.encodings,d.qualities,this.senderLock,Kn(d.codec),this.log,this.logContext))}}}catch(d){o={error:d}}finally{try{!n&&!s&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return l})}setPublishingLayers(e,n){return A(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:n})),!(!this.sender||!this.encodings)&&(yield vm(this.sender,this.encodings,n,this.senderLock,e,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return A(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xv()&&this.isInBackground&&this.source===V.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function vm(t,e,n,i,r,s,o){return A(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:t,qualities:n,senderEncodings:e}));try{const c=t.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:e}));return}let d=!1;!1&&l[0].scalabilityMode||(r&&n.some(p=>p.enabled)&&n.forEach(p=>p.enabled=!0),l.forEach((f,p)=>{var g;let h=(g=f.rid)!==null&&g!==void 0?g:"";h===""&&(h="q");const y=dy(h),b=n.find(w=>w.quality===y);b&&f.active!==b.enabled&&(d=!0,f.active=b.enabled,s.debug("setting layer ".concat(b.quality," to ").concat(f.active?"enabled":"disabled"),o),qr()&&(b.enabled?(f.scaleResolutionDownBy=e[p].scaleResolutionDownBy,f.maxBitrate=e[p].maxBitrate,f.maxFrameRate=e[p].maxFrameRate):(f.scaleResolutionDownBy=4,f.maxBitrate=10,f.maxFrameRate=2)))})),d&&(c.encodings=l,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield t.setParameters(c))}finally{a()}})}function dy(t){switch(t){case"f":return Jt.HIGH;case"h":return Jt.MEDIUM;case"q":return Jt.LOW;default:return Jt.HIGH}}function ym(t,e,n,i){if(!n)return[new Hi({quality:Jt.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,s=new ly(r),o=[],a=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)o.push(new Hi({quality:Math.min(Jt.HIGH,s.spatial-1)-l,width:Math.ceil(t/Math.pow(a,l)),height:Math.ceil(e/Math.pow(a,l)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return o}return n.map(r=>{var s,o,a;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=dy((o=r.rid)!==null&&o!==void 0?o:"");return new Hi({quality:l,width:Math.ceil(t/c),height:Math.ceil(e/c),bitrate:(a=r.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const bm="_lossy",xm="_reliable",n2=2*1e3,Gc="leave-reconnect",i2=3e4;var rn;(function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"})(rn||(rn={}));class r2 extends Nn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var n;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Lu.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=rn.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Ce,this.reliableDataSequence=1,this.reliableMessageBuffer=new om,this.reliableReceivedState=new RT(i2),this.handleDataChannel=i=>A(this,[i],void 0,function(r){var s=this;let{channel:o}=r;return function*(){if(o){if(o.label===xm)s.reliableDCSub=o;else if(o.label===bm)s.lossyDCSub=o;else return;s.log.debug("on data channel ".concat(o.id,", ").concat(o.label),s.logContext),o.onmessage=s.handleDataMessage}}()}),this.handleDataMessage=i=>A(this,void 0,void 0,function*(){var r,s;const o=yield this.dataProcessLock.lock();try{let a;if(i.data instanceof ArrayBuffer)a=i.data;else if(i.data instanceof Blob)a=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=Mt.fromBinary(new Uint8Array(a));if(c.sequence>0&&c.participantSid!==""){const l=this.reliableReceivedState.get(c.participantSid);if(l&&c.sequence<=l)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(ae.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&o2(c,c.value.value),this.emit(ae.DataPacketReceived,c))}finally{o()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?be.LOSSY:be.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(ae.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){s(o);return}i===Gc&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=bt.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===rn.Connected&&i();const s=()=>{this.off(ae.Disconnected,o),i()},o=()=>{this.off(ae.Restarted,s),r()};this.once(ae.Restarted,s),this.once(ae.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(ae.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return i===be.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount),r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Be.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(dr.RR_SIGNAL_DISCONNECTED))},this.log=Gn((n=e.loggerName)!==null&&n!==void 0?n:fn.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Ou(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Nt,this.dataProcessLock=new Nt,this.dcBufferStatus=new Map([[be.LOSSY,!0],[be.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(ae.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(ae.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(ae.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(ae.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(ae.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(ae.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(ae.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(ae.SignalRequestResponse,i)}get logContext(){var e,n,i,r,s,o;return{room:(n=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||n===void 0?void 0:n.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(o=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,n,i,r){return A(this,void 0,void 0,function*(){this.url=e,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,n,i,r);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),(!this.subscriberPrimary||s.fastPublish)&&this.negotiate(),this.clientConfiguration=s.clientConfiguration,this.emit(ae.SignalConnected,s),s}catch(s){if(s instanceof Ue&&s.reason===Te.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,n,i,r);throw s}})}close(){return A(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(ae.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return A(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const n=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};n(this.lossyDC),n(this.lossyDCSub),n(this.reliableDC),n(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new om,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return A(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Wn("a track with the same ID has already been published");return new Promise((n,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new Ue("publication of local track timed out, no response from server",Te.Timeout))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),n(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:n}=this.pendingTrackResolvers[e.track.id];n&&n(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(n){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:n}))}return!1}updateMuteStatus(e,n){this.client.sendMuteTrack(e,n)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return A(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return A(this,void 0,void 0,function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==Je.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new LT(r,e.subscriberPrimary,this.loggerOptions),this.emit(ae.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,o)=>{this.client.sendIceCandidate(s,o)},this.pcManager.onPublisherOffer=(s,o)=>{this.client.sendOffer(s,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,o,a)=>A(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),s===Je.CONNECTED){const d=this.pcState===rn.New;this.pcState=rn.Connected,d&&this.emit(ae.Connected,e)}else s===Je.FAILED&&this.pcState===rn.Connected&&(this.pcState=rn.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?dr.RR_SUBSCRIBER_FAILED:dr.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===Be.RECONNECTING,l=[Je.FAILED,Je.CLOSING,Je.CLOSED].includes(s);c&&l&&!this._isClosed&&this.emit(ae.Offline)}),this.pcManager.onTrack=s=>{this.emit(ae.MediaTrackAdded,s.track,s.streams[0],s.receiver)},s2((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,n)=>A(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,n))}),this.client.onTrickle=(e,n)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:n})),this.pcManager.addIceCandidate(e,n))},this.client.onOffer=(e,n)=>A(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=n,!this.pcManager)return;const i=yield this.pcManager.createSubscriberAnswerFromOffer(e,n);i&&this.client.sendAnswer(i,n)}),this.client.onLocalTrackPublished=e=>{var n;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(n=e.track)===null||n===void 0?void 0:n.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(ae.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(ae.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,n)=>{this.emit(ae.RemoteMute,e,n)},this.client.onSubscribedQualityUpdate=e=>{this.emit(ae.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var n;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(ae.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",dr.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Nr.DISCONNECT:this.emit(ae.Disconnected,e==null?void 0:e.reason),this.close();break;case Nr.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Gc);break;case Nr.RESUME:this.handleDisconnect(Gc)}}}makeRTCConfiguration(e){var n;const i=Object.assign({},this.rtcConfig);if(!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(s=>{const o={urls:s.urls};s.username&&(o.username=s.username),s.credential&&(o.credential=s.credential),r.push(o)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Hs.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(bm,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(xm,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,n,i){return A(this,void 0,void 0,function*(){if(cd())return yield this.createTransceiverRTCRtpSender(e,n,i);if(ld())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ht("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,n,i,r){return A(this,void 0,void 0,function*(){if(cd())return this.createSimulcastTransceiverSender(e,n,i,r);if(ld())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ht("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,n,i){return A(this,void 0,void 0,function*(){if(!this.pcManager)throw new ht("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),ns(e)&&(e.codec=n.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,n,i,r){return A(this,void 0,void 0,function*(){if(!this.pcManager)throw new ht("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const o=yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return A(this,void 0,void 0,function*(){if(!this.pcManager)throw new ht("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return A(this,void 0,void 0,function*(){var n,i,r;if(!this._isClosed){if(this.attemptingReconnect){Ce.warn("already attempting reconnect, returning early",this.logContext);return}(((n=this.clientConfiguration)===null||n===void 0?void 0:n.resumeConnection)===Hs.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Je.NEW)===Je.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let o=!0;s instanceof ht?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),o=!1):s instanceof ur||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",dr.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(ae.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(n){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:n}))}return null}restartConnection(e){return A(this,void 0,void 0,function*(){var n,i,r;try{if(!this.url||!this.token)throw new ht("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(ae.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new ur;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof Ue&&o.reason===Te.NotAllowed?new ht("could not reconnect, token might be expired"):new ur}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(ae.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==Be.CONNECTED)throw new ur("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(ae.Restarted)}catch(s){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return A(this,void 0,void 0,function*(){var n;if(!this.url||!this.token)throw new ht("could not reconnect, url or token not saved");if(!this.pcManager)throw new ht("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(ae.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof Ue&&r.reason===Te.NotAllowed?new ht("could not reconnect, token might be expired"):r instanceof Ue&&r.reason===Te.LeaveRequest?r:new ur(s)}if(this.emit(ae.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Be.CONNECTED)throw new ur("Signal connection got severed during reconnect");this.client.setReconnected(),((n=this.reliableDC)===null||n===void 0?void 0:n.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(ae.Resumed)})}waitForPCInitialConnection(e,n){return A(this,void 0,void 0,function*(){if(!this.pcManager)throw new ht("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,e)})}waitForPCReconnected(){return A(this,void 0,void 0,function*(){this.pcState=rn.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield jt(n2),!this.pcManager)throw new ht("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=rn.Connected}catch(e){throw this.pcState=rn.Disconnected,new Ue("could not establish PC connection, ".concat(e.message),Te.InternalError)}})}publishRpcResponse(e,n,i,r){return A(this,void 0,void 0,function*(){const s=new Mt({destinationIdentities:[e],kind:be.RELIABLE,value:{case:"rpcResponse",value:new Q0({requestId:n,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,be.RELIABLE)})}publishRpcAck(e,n){return A(this,void 0,void 0,function*(){const i=new Mt({destinationIdentities:[e],kind:be.RELIABLE,value:{case:"rpcAck",value:new X0({requestId:n})}});yield this.sendDataPacket(i,be.RELIABLE)})}sendDataPacket(e,n){return A(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(n),n===be.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),r=this.dataChannelForKind(n);if(r){if(n===be.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;r.send(i)}this.updateAndEmitDCBufferStatus(n)})}resendReliableMessagesForResume(e){return A(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(be.RELIABLE);const n=this.dataChannelForKind(be.RELIABLE);n&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{n.send(i.data)})),this.updateAndEmitDCBufferStatus(be.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((n,i)=>A(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))n();else{const r=()=>i("Engine closed");for(this.once(ae.Closing,r);!this.dcBufferStatus.get(e);)yield jt(10);this.off(ae.Closing,r),n()}}))}ensureDataTransportConnected(e){return A(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!i.pcManager)throw new ht("PC manager is closed");const o=r?i.pcManager.subscriber:i.pcManager.publisher,a=r?"Subscriber":"Publisher";if(!o)throw new Ue("".concat(a," connection not set"),Te.InternalError);let c=!1;!r&&!i.dataChannelForKind(n,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const l=i.dataChannelForKind(n,r);if((l==null?void 0:l.readyState)==="open")return;const d=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<d;){if(o.isICEConnected&&((s=i.dataChannelForKind(n,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield jt(50)}throw new Ue("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()),Te.InternalError)}()})}ensurePublisherConnected(e){return A(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Je.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return A(this,void 0,void 0,function*(){return new Promise((e,n)=>A(this,void 0,void 0,function*(){if(!this.pcManager){n(new sd("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(ae.Closing,r),this.pcManager.publisher.once(Lr.RTPVideoPayloadTypes,s=>{const o=new Map;s.forEach(a=>{const c=a.codec.toLowerCase();aT(c)&&o.set(a.payload,c)}),this.emit(ae.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof sd&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",dr.RR_UNKNOWN),n(s)}finally{this.off(ae.Closing,r)}}))})}dataChannelForKind(e,n){if(n){if(e===be.LOSSY)return this.lossyDCSub;if(e===be.RELIABLE)return this.reliableDCSub}else{if(e===be.LOSSY)return this.lossyDC;if(e===be.RELIABLE)return this.reliableDC}}sendSyncState(e,n){var i,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),a=(r=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&r!==void 0?r:!0,c=new Array,l=new Array;e.forEach(d=>{d.isDesired!==a&&c.push(d.trackSid),d.isEnabled||l.push(d.trackSid)}),this.client.sendSyncState(new gv({answer:s?ka({sdp:s.sdp,type:s.type}):void 0,offer:o?ka({sdp:o.sdp,type:o.type}):void 0,subscription:new Za({trackSids:c,subscribe:!a,participantTracks:[]}),publishTracks:gT(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((d,u)=>new vv({publisherSid:u,lastSeq:d}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new yv({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(be.LOSSY),ln.PUBLISHER),n(this.dataChannelForKind(be.RELIABLE),ln.PUBLISHER),n(this.dataChannelForKind(be.LOSSY,!0),ln.SUBSCRIBER),n(this.dataChannelForKind(be.RELIABLE,!0),ln.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&bt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ot()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Ot()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class ur extends Error{}function s2(t){return t!==void 0&&t>13}function o2(t,e){const n=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=n,e.participantIdentity=n;const i=t.destinationIdentities.length!==0?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=i,e.destinationIdentities=i}class bd{constructor(e,n){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=n}updateToken(e){this.token=e}isCloud(){return ud(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return A(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const n=this.regionSettings.regions.filter(i=>!this.attemptedRegions.find(r=>r.url===i.url));if(n.length>0){const i=n[0];return this.attemptedRegions.push(i),Ce.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return A(this,void 0,void 0,function*(){const n=yield fetch("".concat(a2(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(n.ok){const i=yield n.json();return this.lastUpdateAt=Date.now(),i}else throw new Ue("Could not fetch region settings: ".concat(n.statusText),n.status===401?Te.NotAllowed:Te.InternalError,n.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function a2(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class uy{get info(){return this._info}constructor(e,n,i){this.reader=n,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class c2 extends uy{handleChunkReceived(e){var n;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>A(this,void 0,void 0,function*(){try{const{done:n,value:i}=yield e.read();return n?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch{return{done:!0,value:void 0}}}),return(){return A(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return A(this,void 0,void 0,function*(){var e,n,i,r;let s=new Set;try{for(var o=!0,a=zn(this),c;c=yield a.next(),e=c.done,!e;o=!0){r=c.value,o=!1;const l=r;s.add(l)}}catch(l){n={error:l}}finally{try{!o&&!e&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}return Array.from(s)})}}class l2 extends uy{constructor(e,n,i){super(e,n,i),this.receivedChunks=new Map}handleChunkReceived(e){var n;const i=ra(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),n=new TextDecoder;return{next:()=>A(this,void 0,void 0,function*(){try{const{done:i,value:r}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:n.decode(r.content)})}catch{return{done:!0,value:void 0}}}),return(){return A(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return A(this,void 0,void 0,function*(){var e,n,i,r;let s="";try{for(var o=!0,a=zn(this),c;c=yield a.next(),e=c.done,!e;o=!0)r=c.value,o=!1,s+=r}catch(l){n={error:l}}finally{try{!o&&!e&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}return s})}}class fy{constructor(e,n,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=n}write(e){return this.defaultWriter.write(e)}close(){return A(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class d2 extends fy{}class u2 extends fy{}class hy extends V{constructor(e,n,i,r,s){super(e,i,s),this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?re.Muted:re.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const n=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(re.Ended,this))};e.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return A(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Fu)),vT()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var n;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(n=this.receiver)===null||n===void 0?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(re.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class my extends hy{constructor(e,n,i,r,s,o){super(e,n,V.Kind.Audio,i,o),this.monitorReceiver=()=>A(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Xa(a,this.prevStats)),this.prevStats=a}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var n;for(const i of this.attachedElements)this.audioContext?(n=this.gainNode)===null||n===void 0||n.gain.setTargetAtTime(e,0,.1):i.volume=e;In()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(In())return 1;let e=0;return this.attachedElements.forEach(n=>{n.volume>e&&(e=n.volume)}),e}setSinkId(e){return A(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(n=>{if(dd(n))return n.setSinkId(e)}))})}attach(e){const n=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&dd(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&n&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let n;return e?(n=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(n=super.detach(),this.disconnectWebAudio()),n}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,n){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(re.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(re.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,n;(e=this.gainNode)===null||e===void 0||e.disconnect(),(n=this.sourceNode)===null||n===void 0||n.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return A(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n;return e.forEach(i=>{i.type==="inbound-rtp"&&(n={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),n})}}const Zc=100;class f2 extends hy{constructor(e,n,i,r,s){super(e,n,V.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>A(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=Xa(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=ju(()=>{this.updateDimensions()},Zc),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(n=>{e?Dr(this._mediaStreamTrack,n):kr(this._mediaStreamTrack,n)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(n=>n.element===e)===void 0){const n=new h2(e);this.observeElementInfo(n)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(n=>n===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const n=this.elementInfos.filter(i=>i===e);for(const i of n)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let n=[];if(e)return this.stopObservingElement(e),super.detach(e);n=super.detach();for(const i of n)this.stopObservingElement(i);return n}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return A(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,n={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),n&&i!==""&&r.get(i)&&(n.mimeType=r.get(i).mimeType),n})}stopObservingElement(e){const n=this.elementInfos.filter(i=>i.element===e);for(const i of n)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return A(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,n;const i=this.elementInfos.reduce((a,c)=>Math.max(a,c.visibilityChangedAt||0),0),r=!((n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,s=this.elementInfos.some(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!r||s;if(this.lastVisible!==o){if(!o&&Date.now()-i<Zc){bt.setTimeout(()=>{this.updateVisibility()},Zc);return}this.lastVisible=o,this.emit(re.VisibilityChanged,o,this)}}updateDimensions(){var e,n;let i=0,r=0;const s=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*s,c=o.height()*s;a+c>i+r&&(i=a,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((n=this.lastDimensions)===null||n===void 0?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(re.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return n==="screen"?em():n||(em()>2?2:1)}}class h2{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,n){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:o}=i;s===this.element&&(this.isIntersecting=o,this.isPiP=ks(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ks(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=ks(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=n??xd(e),this.isPiP=Ot()&&ks(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,n,i;this.isIntersecting=xd(this.element),this.isPiP=ks(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,nm().observe(this.element),tm().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,n,i,r,s;(e=nm())===null||e===void 0||e.unobserve(this.element),(n=tm())===null||n===void 0||n.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function ks(t){var e,n;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?xd(t,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function xd(t,e){const n=e||window;let i=t.offsetTop,r=t.offsetLeft;const s=t.offsetWidth,o=t.offsetHeight,{hidden:a}=t,{display:c}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,i+=t.offsetTop,r+=t.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+s>n.pageXOffset&&!a&&c!=="none"}class Bn extends Nn.EventEmitter{constructor(e,n,i,r){var s;super(),this.metadataMuted=!1,this.encryption=Ft.NONE,this.log=Ce,this.handleMuted=()=>{this.emit(re.Muted)},this.handleUnmuted=()=>{this.emit(re.Unmuted)},this.log=Gn((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:fn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=n,this.trackName=i,this.source=V.Source.Unknown}setTrack(e){this.track&&(this.track.off(re.Muted,this.handleMuted),this.track.off(re.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(re.Muted,this.handleMuted),e.on(re.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),we(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Ft.NONE}get audioTrack(){if(Tn(this.track))return this.track}get videoTrack(){if(ns(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=V.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===V.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(t){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(t.SubscriptionStatus||(t.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(t.PermissionStatus||(t.PermissionStatus={}))})(Bn||(Bn={}));class Sd extends Bn{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(re.Ended)},this.updateInfo(n),this.setTrack(i)}setTrack(e){this.track&&this.track.off(re.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(re.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return A(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return A(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return A(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return A(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Tn(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(pt.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(pt.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(pt.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(pt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(pt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(pt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Qa(t,e){return A(this,void 0,void 0,function*(){t??(t={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=iy(t);let o=s.audio,a=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),t.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const u=s.audio.deviceId;s.audio.deviceId={exact:u},n=!0,o=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:u}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const u=s.video.deviceId;s.video.deviceId={exact:u},n=!0,a=Object.assign(Object.assign({},s.video),{deviceId:{ideal:u}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const c=ty(s,sy,oy),l=_u(c),d=navigator.mediaDevices.getUserMedia(l);s.audio&&(gt.userMediaPromiseMap.set("audioinput",d),d.catch(()=>gt.userMediaPromiseMap.delete("audioinput"))),s.video&&(gt.userMediaPromiseMap.set("videoinput",d),d.catch(()=>gt.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(f=>A(this,void 0,void 0,function*(){const p=f.kind==="audio";let g=p?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let h;const y=p?l.audio:l.video;typeof y!="boolean"&&(h=y);const b=f.getSettings().deviceId;h!=null&&h.deviceId&&fi(h.deviceId)!==b?h.deviceId=b:h||(h={deviceId:b});const w=zT(f,h,e);return w.kind===V.Kind.Video?w.source=V.Source.Camera:w.kind===V.Kind.Audio&&(w.source=V.Source.Microphone),w.mediaStream=u,Tn(w)&&i?yield w.setProcessor(i):ns(w)&&r&&(yield w.setProcessor(r)),w})))}catch(u){if(!n)throw u;return Qa(Object.assign(Object.assign({},t),{audio:o,video:a}),e)}})}function m2(t){return A(this,void 0,void 0,function*(){return(yield Qa({audio:!1,video:!0}))[0]})}function p2(t){return A(this,void 0,void 0,function*(){return(yield Qa({audio:!0,video:!1}))[0]})}var ci;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(ci||(ci={}));function g2(t){switch(t){case As.EXCELLENT:return ci.Excellent;case As.GOOD:return ci.Good;case As.POOR:return ci.Poor;case As.LOST:return ci.Lost;default:return ci.Unknown}}class py extends Nn.EventEmitter{get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Yi.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===_r.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,n,i,r,s,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Yi.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=ci.Unknown,this.log=Ce,this.log=Gn((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:fn.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,n]of this.trackPublications)if(n.source===e)return n}getTrackPublicationByName(e){for(const[,n]of this.trackPublications)if(n.trackName===e)return n}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Tr,this.once(Z.Active,()=>{var e,n;(n=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||n===void 0||n.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const n=this.getTrackPublication(V.Source.Camera);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const n=this.getTrackPublication(V.Source.Microphone);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(V.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var n;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===_r.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==_r.ACTIVE&&this.emit(Z.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const n=this.metadata!==e,i=this.metadata;this.metadata=e,n&&this.emit(Z.ParticipantMetadataChanged,i)}_setName(e){const n=this.name!==e;this.name=e,n&&this.emit(Z.ParticipantNameChanged,e)}_setAttributes(e){const n=yT(this.attributes,e);this._attributes=e,Object.keys(n).length>0&&this.emit(Z.AttributesChanged,n)}setPermissions(e){var n,i,r,s,o,a;const c=this.permissions,l=e.canPublish!==((n=this.permissions)===null||n===void 0?void 0:n.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((d,u)=>{var f;return d!==((f=this.permissions)===null||f===void 0?void 0:f.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,l&&this.emit(Z.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(Z.IsSpeakingChanged,e))}setConnectionQuality(e){const n=this._connectionQuality;this._connectionQuality=g2(e),n!==this._connectionQuality&&this.emit(Z.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,n;this.activeFuture&&((n=(e=this.activeFuture).reject)===null||n===void 0||n.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(n=>Tn(n.track)&&n.track.setAudioContext(e))}addTrackPublication(e){e.on(re.Muted,()=>{this.emit(Z.TrackMuted,e)}),e.on(re.Unmuted,()=>{this.emit(Z.TrackUnmuted,e)});const n=e;switch(n.track&&(n.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case V.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case V.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function v2(t){var e,n,i;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new mv({participantIdentity:(e=t.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(n=t.participantSid)!==null&&n!==void 0?n:"",allTracks:(i=t.allowAll)!==null&&i!==void 0?i:!1,trackSids:t.allowedTrackSids||[]})}const Sm=15e3;class y2 extends py{constructor(e,n,i,r,s){super(e,n,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Ft.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Tr)},this.handleReconnected=()=>{var o,a;(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||a===void 0||a.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var o,a,c,l,d,u;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||a===void 0||a.call(o,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((l=(c=this.signalConnectedFuture).reject)===null||l===void 0||l.call(c,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(u=(d=this.activeAgentFuture)===null||d===void 0?void 0:d.reject)===null||u===void 0||u.call(d,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var a,c;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Tr),(c=(a=this.signalConnectedFuture).resolve)===null||c===void 0||c.call(a)},this.handleSignalRequestResponse=o=>{const{requestId:a,reason:c,message:l}=o,d=this.pendingSignalRequests.get(a);d&&(c!==Ru.OK&&d.reject(new Zh(l,c)),this.pendingSignalRequests.delete(a))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let a=o.value.value,c=null,l=null;a.value.case==="payload"?c=a.value.value:a.value.case==="error"&&(l=Qe.fromProto(a.value.value)),this.handleIncomingRpcResponse(a.requestId,c,l);break;case"rpcAck":let d=o.value.value;this.handleIncomingRpcAck(d.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(o=>v2(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,a)=>{if(a===void 0&&(a=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),we(o)));return}this.engine.updateMuteStatus(o.sid,a)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),we(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),we(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const a=this.audioTrackPublications.get(o.sid);if(!a){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(a.trackSid,a.getTrackFeatures())},this.handleSubscribedQualityUpdate=o=>A(this,void 0,void 0,function*(){var a,c,l,d,u;if(!(!((u=this.roomOptions)===null||u===void 0)&&u.dynacast))return;const f=this.videoTrackPublications.get(o.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!f.videoTrack)return;const p=yield f.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var g=!0,h=zn(p),y;y=yield h.next(),a=y.done,!a;g=!0){d=y.value,g=!1;const b=d;Gk(b)&&(this.log.debug("publish ".concat(b," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),we(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,b,f.options))}}catch(b){c={error:b}}finally{try{!g&&!a&&(l=h.return)&&(yield l.call(h))}finally{if(c)throw c.error}}}),this.handleLocalTrackUnpublished=o=>{const a=this.trackPublications.get(o.trackSid);if(!a){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(a.track)},this.handleTrackEnded=o=>A(this,void 0,void 0,function*(){if(o.source===V.Source.ScreenShare||o.source===V.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),we(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(Un(o)||ii(o))try{if(Ot())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:o.source===V.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),we(o))),a.onchange=()=>{a.state!=="denied"&&(o.isMuted||o.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),we(o))),Un(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),we(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Ft.NONE}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setupEngine(e){this.engine=e,this.engine.on(ae.RemoteMute,(n,i)=>{const r=this.trackPublications.get(n);!r||!r.track||(i?r.mute():r.unmute())}),this.engine.on(ae.Connected,this.handleReconnected).on(ae.SignalConnected,this.handleSignalConnected).on(ae.SignalRestarted,this.handleReconnected).on(ae.SignalResumed,this.handleReconnected).on(ae.Restarting,this.handleReconnecting).on(ae.Resuming,this.handleReconnecting).on(ae.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(ae.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(ae.Disconnected,this.handleDisconnected).on(ae.SignalRequestResponse,this.handleSignalRequestResponse).on(ae.DataPacketReceived,this.handleDataPacket),this.signalConnectedFuture=void 0}setMetadata(e){return A(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return A(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return A(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return A(this,arguments,void 0,function(n){var i=this;let{metadata:r,name:s,attributes:o}=n;return function*(){return new Promise((a,c)=>A(i,void 0,void 0,function*(){var l,d;try{let u=!1;const f=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(d=s??this.name)!==null&&d!==void 0?d:"",o),p=performance.now();for(this.pendingSignalRequests.set(f,{resolve:a,reject:g=>{c(g),u=!0},values:{name:s,metadata:r,attributes:o}});performance.now()-p<5e3&&!u;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!o||Object.entries(o).every(g=>{let[h,y]=g;return this.attributes[h]===y||y===""&&!this.attributes[h]}))){this.pendingSignalRequests.delete(f),a();return}yield jt(50)}c(new Zh("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))}()})}setCameraEnabled(e,n,i){return this.setTrackEnabled(V.Source.Camera,e,n,i)}setMicrophoneEnabled(e,n,i){return this.setTrackEnabled(V.Source.Microphone,e,n,i)}setScreenShareEnabled(e,n,i){return this.setTrackEnabled(V.Source.ScreenShare,e,n,i)}setPermissions(e){const n=this.permissions,i=super.setPermissions(e);return i&&n&&this.emit(Z.ParticipantPermissionsChanged,n),i}setE2EEEnabled(e){return A(this,void 0,void 0,function*(){this.encryptionType=e?Ft.GCM:Ft.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,n,i,r){return A(this,void 0,void 0,function*(){var s,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:n})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(n)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case V.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case V.Source.Microphone:c=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case V.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Wn(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(Z.MediaDevicesError,l,pd(e)),this.pendingPublishing.delete(e),l}for(const l of c)e===V.Source.Microphone&&Tn(l)&&(r!=null&&r.preConnectBuffer)&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer());try{const l=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),we(u))),l.push(this.publishTrack(u,r));[a]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(a!=null&&a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===V.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(V.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return A(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(V.Source.Camera)||this.pendingPublishing.has(V.Source.Microphone))){this.pendingPublishing.add(V.Source.Camera),this.pendingPublishing.add(V.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(n=>this.publishTrack(n)))}finally{this.pendingPublishing.delete(V.Source.Camera),this.pendingPublishing.delete(V.Source.Microphone)}}})}createTracks(e){return A(this,void 0,void 0,function*(){var n,i;e??(e={});const r=ty(e,(n=this.roomOptions)===null||n===void 0?void 0:n.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Qa(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(Tn(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=V.Source.Microphone,this.emit(Z.AudioStreamAcquired)),ns(a)&&(this.cameraError=void 0,a.source=V.Source.Camera),a))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return A(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Iu("getDisplayMedia not supported");e.resolution===void 0&&!eT()&&(e.resolution=Mu.h1080fps30.resolution);const n=pT(e),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new Wn("no video track found");const s=new Ea(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=V.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const o=[s];if(i.getAudioTracks().length>0){this.emit(Z.AudioStreamAcquired);const a=new Ta(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=V.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,n){return A(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,n)})}publishOrRepublishTrack(e,n){return A(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var a,c,l,d;Un(i)&&i.setAudioContext(s.audioContext),yield(a=s.reconnectFuture)===null||a===void 0?void 0:a.promise,s.republishPromise&&!o&&(yield s.republishPromise),jr(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let b;switch(i.source){case V.Source.Microphone:b="audioinput";break;case V.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(u=Object.assign(Object.assign({},u),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Ta(i,u,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Ea(i,u,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Wn("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let f;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(f=b)}),f)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),we(f))),f;const p="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,g=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:p;g&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),we(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=r.dtx)!==null&&l!==void 0||(r.dtx=!1),(d=r.red)!==null&&d!==void 0||(r.red=!1));const h=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!nT()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},s.logContext)),h.simulcast=!1),h.source&&(i.source=h.source);const y=new Promise((b,w)=>A(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Be.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:we(i)}));const C=setTimeout(()=>{w(new Gh("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(C);const S=yield this.publish(i,h,g);b(S)}else try{const C=yield this.publish(i,h,g);b(C)}catch(C){w(C)}}catch(C){w(C)}}));s.pendingPublishPromises.set(i,y);try{return yield y}catch(b){throw b}finally{s.pendingPublishPromises.delete(i)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Tr),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),we(e))),!1;const{canPublish:n,canPublishSources:i}=this.permissions;return n&&(i.length===0||i.map(r=>bT(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),we(e))),!1)}publish(e,n,i){return A(this,void 0,void 0,function*(){var r,s,o,a,c,l,d,u,f,p;if(!this.hasPermissionsToPublish(e))throw new Gh("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(_=>jr(e)&&_.source===e.source)&&e.source!==V.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),we(e))),n.stopMicTrackOnMute&&Tn(e)&&(e.stopOnMute=!0),e.source===V.Source.ScreenShare&&qr()&&(n.simulcast=!1),n.videoCodec==="av1"&&!Jk()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!Xk()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=gd),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(_=>n.videoCodec===sa(_.mime))||(n.videoCodec=sa(this.enabledPublishVideoCodecs[0].mime)));const h=n.videoCodec;e.on(re.Muted,this.onTrackMuted),e.on(re.Unmuted,this.onTrackUnmuted),e.on(re.Ended,this.handleTrackEnded),e.on(re.UpstreamPaused,this.onTrackUpstreamPaused),e.on(re.UpstreamResumed,this.onTrackUpstreamResumed),e.on(re.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const y=[],b=!(!((r=n.dtx)!==null&&r!==void 0)||r),w=e.getSourceTrackSettings();w.autoGainControl&&y.push(pt.TF_AUTO_GAIN_CONTROL),w.echoCancellation&&y.push(pt.TF_ECHO_CANCELLATION),w.noiseSuppression&&y.push(pt.TF_NOISE_SUPPRESSION),w.channelCount&&w.channelCount>1&&y.push(pt.TF_STEREO),b&&y.push(pt.TF_NO_DTX),Un(e)&&e.hasPreConnectBuffer&&y.push(pt.TF_PRECONNECT_BUFFER);const C=new Yl({cid:e.mediaStreamTrack.id,name:n.name,type:V.kindToProto(e.kind),muted:e.isMuted,source:V.sourceToProto(e.source),disableDtx:b,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=n.red)!==null&&s!==void 0)||s),stream:n==null?void 0:n.stream,backupCodecPolicy:n==null?void 0:n.backupCodecPolicy,audioFeatures:y});let S;if(e.kind===V.Kind.Video){let _={width:0,height:0};try{_=yield e.waitForDimensions()}catch{const I=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:zs.h720.resolution;_={width:I.width,height:I.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),we(e)),{dims:_}))}C.width=_.width,C.height=_.height,ii(e)&&(Kn(h)&&(e.source===V.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),we(e))))),n.scalabilityMode=(c=n.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),C.simulcastCodecs=[new Zl({codec:h,cid:e.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:gd}),n.backupCodec&&h!==n.backupCodec.codec&&C.encryption===Ft.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),C.simulcastCodecs.push(new Zl({codec:n.backupCodec.codec,cid:""})))),S=yd(e.source===V.Source.ScreenShare,C.width,C.height,n),C.layers=ym(C.width,C.height,S,Kn(n.videoCodec))}else e.kind===V.Kind.Audio&&(S=[{maxBitrate:(l=n.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(u=(d=n.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&u!==void 0?u:"high",networkPriority:(p=(f=n.audioPreset)===null||f===void 0?void 0:f.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new ht("cannot publish track when not connected");const x=()=>A(this,void 0,void 0,function*(){var _,k,I;if(!this.engine.pcManager)throw new ht("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,n,S),ii(e)&&((_=n.degradationPreference)!==null&&_!==void 0||(n.degradationPreference=e2(e)),e.setDegradationPreference(n.degradationPreference)),S)if(qr()&&e.kind===V.Kind.Audio){let N;for(const K of this.engine.pcManager.publisher.getTransceivers())if(K.sender===e.sender){N=K;break}N&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:N,codec:"opus",maxbr:!((k=S[0])===null||k===void 0)&&k.maxBitrate?S[0].maxBitrate/1e3:0})}else e.codec&&Kn(e.codec)&&(!((I=S[0])===null||I===void 0)&&I.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:C.cid,codec:e.codec,maxbr:S[0].maxBitrate/1e3});yield this.engine.negotiate()});let T;const E=new Promise((_,k)=>A(this,void 0,void 0,function*(){var I;try{T=yield this.engine.addTrack(C),_(T)}catch(N){e.sender&&(!((I=this.engine.pcManager)===null||I===void 0)&&I.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(K=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),we(e)),{error:K}))})),k(N)}}));if(this.enabledPublishVideoCodecs.length>0)T=(yield Promise.all([E,x()]))[0];else{T=yield E;let _;if(T.codecs.forEach(k=>{_===void 0&&(_=k.mimeType)}),_&&e.kind===V.Kind.Video){const k=sa(_);k!==h&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),we(e)),{codec:k})),n.videoCodec=k,S=yd(e.source===V.Source.ScreenShare,C.width,C.height,n))}yield x()}const P=new Sd(e.kind,T,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(P.options=n,e.sid=T.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:S,trackInfo:T})),ii(e)?e.startMonitor(this.engine.client):Un(e)&&e.startMonitor(),this.addTrackPublication(P),this.emit(Z.LocalTrackPublished,P),Un(e)&&T.audioFeatures.includes(pt.TF_PRECONNECT_BUFFER)){const _=e.getPreConnectBuffer();this.on(Z.LocalTrackSubscribed,k=>{if(k.trackSid===T.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),we(e))),e.stopPreConnectBuffer()}}),_&&new Promise((I,N)=>A(this,void 0,void 0,function*(){var K,J,se,ie,X,O;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),we(e)));const te=setTimeout(()=>{N(new Error("agent not active within 10 seconds"))},1e4),j=yield this.waitUntilActiveAgentPresent();clearTimeout(te),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),we(e)));const q=yield this.streamBytes({name:"preconnect-buffer",mimeType:"audio/opus",topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[j.identity],attributes:{trackId:P.trackSid,sampleRate:String((X=w.sampleRate)!==null&&X!==void 0?X:"48000"),channels:String((O=w.channelCount)!==null&&O!==void 0?O:"1")}});try{for(var oe=!0,L=zn(_),F;F=yield L.next(),K=F.done,!K;oe=!0){ie=F.value,oe=!1;const ee=ie;yield q.write(ee)}}catch(ee){J={error:ee}}finally{try{!oe&&!K&&(se=L.return)&&(yield se.call(L))}finally{if(J)throw J.error}}yield q.close(),I()}catch(te){N(te)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),we(e)))}).catch(I=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),we(e)),{error:I}))})}return P})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,n,i){return A(this,void 0,void 0,function*(){var r;if(this.encryptionType!==Ft.NONE)return;let s;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(s=p)}),!s)throw new Wn("track is not published");if(!ii(e))throw new Wn("track is not a video track");const o=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),a=JT(e,n,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),we(e)));return}const c=e.addSimulcastTrack(n,a);if(!c)return;const l=new Yl({cid:c.mediaStreamTrack.id,type:V.kindToProto(e.kind),muted:e.isMuted,source:V.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=ym(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new ht("cannot publish track when not connected");const d=()=>A(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate()}),f=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(n," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:f}))})}unpublishTrack(e,n){return A(this,void 0,void 0,function*(){var i,r;if(jr(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),we(e))),yield l)}const s=this.getPublicationForTrack(e),o=s?we(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=s.track,e.off(re.Muted,this.onTrackMuted),e.off(re.Unmuted,this.onTrackUnmuted),e.off(re.Ended,this.handleTrackEnded),e.off(re.UpstreamPaused,this.onTrackUpstreamPaused),e.off(re.UpstreamResumed,this.onTrackUpstreamResumed),e.off(re.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),n===void 0&&(n=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),n?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Je.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),ii(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case V.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case V.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(Z.LocalTrackUnpublished,s),s.setTrack(void 0),a&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return A(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return A(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((s,o)=>A(i,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(n&&(c.options=Object.assign(Object.assign({},c.options),n)),a.push(c))}),yield Promise.all(a.map(c=>A(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==V.Source.ScreenShare&&l.source!==V.Source.ScreenShareAudio&&(Un(l)||ii(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(a){o(a)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return A(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const s=r.reliable?be.RELIABLE:be.LOSSY,o=r.destinationIdentities,a=r.topic,c=new Mt({kind:s,value:{case:"user",value:new Z0({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:a})}});yield i.engine.sendDataPacket(c,s)}()})}publishDtmf(e,n){return A(this,void 0,void 0,function*(){const i=new Mt({kind:be.RELIABLE,value:{case:"sipDtmf",value:new Y0({code:e,digit:n})}});yield this.engine.sendDataPacket(i,be.RELIABLE)})}sendChatMessage(e,n){return A(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:n==null?void 0:n.attachments},r=new Mt({value:{case:"chatMessage",value:new Hl(Object.assign(Object.assign({},i),{timestamp:ze.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,be.RELIABLE),this.emit(Z.ChatMessage,i),i})}editChatMessage(e,n){return A(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},n),{message:e,editTimestamp:Date.now()}),r=new Mt({value:{case:"chatMessage",value:new Hl(Object.assign(Object.assign({},i),{timestamp:ze.parse(i.timestamp),editTimestamp:ze.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,be.RELIABLE),this.emit(Z.ChatMessage,i),i})}sendText(e,n){return A(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(i=n==null?void 0:n.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),l=(u,f)=>{var p;c[f]=u;const g=c.reduce((h,y)=>h+y,0);(p=n==null?void 0:n.onProgress)===null||p===void 0||p.call(n,g)},d=yield this.streamText({streamId:r,totalSize:o,destinationIdentities:n==null?void 0:n.destinationIdentities,topic:n==null?void 0:n.topic,attachedStreamIds:a,attributes:n==null?void 0:n.attributes});return yield d.write(e),l(1,0),yield d.close(),n!=null&&n.attachments&&a&&(yield Promise.all(n.attachments.map((u,f)=>A(this,void 0,void 0,function*(){return this._sendFile(a[f],u,{topic:n.topic,mimeType:u.type,onProgress:p=>{l(p,f+1)}})})))),d.info})}streamText(e){return A(this,void 0,void 0,function*(){var n,i;const r=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},o=new Wl({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:Li(s.timestamp),totalLength:Li(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new av({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?zl.UPDATE:zl.CREATE})}}),a=e==null?void 0:e.destinationIdentities,c=new Mt({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,be.RELIABLE);let l=0;const d=this,u=new WritableStream({write(g){return A(this,void 0,void 0,function*(){for(const h of hT(g,Sm)){yield d.engine.waitForBufferStatusLow(be.RELIABLE);const y=new ql({content:h,streamId:r,chunkIndex:Li(l)}),b=new Mt({destinationIdentities:a,value:{case:"streamChunk",value:y}});yield d.engine.sendDataPacket(b,be.RELIABLE),l+=1}})},close(){return A(this,void 0,void 0,function*(){const g=new Kl({streamId:r}),h=new Mt({destinationIdentities:a,value:{case:"streamTrailer",value:g}});yield d.engine.sendDataPacket(h,be.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let f=()=>A(this,void 0,void 0,function*(){yield p.close()});d.engine.once(ae.Closing,f);const p=new d2(u,s,()=>this.engine.off(ae.Closing,f));return p})}sendFile(e,n){return A(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,n),{id:i}})}_sendFile(e,n,i){return A(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:n.size,name:n.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:n.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=n.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return A(this,void 0,void 0,function*(){var n,i,r,s,o;const a=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,l={id:a,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown"},d=new Wl({totalLength:Li((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:a,topic:l.topic,timestamp:Li(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new cv({name:l.name})}}),u=new Mt({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(u,be.RELIABLE);let f=0;const p=new Nt,g=this.engine,h=this.log,y=new WritableStream({write(w){return A(this,void 0,void 0,function*(){const C=yield p.lock();let S=0;try{for(;S<w.byteLength;){const x=w.slice(S,S+Sm);yield g.waitForBufferStatusLow(be.RELIABLE);const T=new Mt({destinationIdentities:c,value:{case:"streamChunk",value:new ql({content:x,streamId:a,chunkIndex:Li(f)})}});yield g.sendDataPacket(T,be.RELIABLE),f+=1,S+=x.byteLength}}finally{C()}})},close(){return A(this,void 0,void 0,function*(){const w=new Kl({streamId:a}),C=new Mt({destinationIdentities:c,value:{case:"streamTrailer",value:w}});yield g.sendDataPacket(C,be.RELIABLE)})},abort(w){h.error("Sink error:",w)}});return new u2(y,l)})}performRpc(e){return A(this,arguments,void 0,function(n){var i=this;let{destinationIdentity:r,method:s,payload:o,responseTimeout:a=1e4}=n;return function*(){return new Promise((l,d)=>A(i,void 0,void 0,function*(){var u,f,p,g;if(Vu(o)>ay){d(Qe.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((f=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||f===void 0)&&f.version&&mi((g=(p=this.engine.latestJoinResponse)===null||p===void 0?void 0:p.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){d(Qe.builtIn("UNSUPPORTED_SERVER"));return}const h=crypto.randomUUID();yield this.publishRpcRequest(r,h,s,o,a-2e3);const y=setTimeout(()=>{this.pendingAcks.delete(h),d(Qe.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(h),clearTimeout(b)},2e3);this.pendingAcks.set(h,{resolve:()=>{clearTimeout(y)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(h),d(Qe.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(h,{resolve:(w,C)=>{clearTimeout(b),this.pendingAcks.has(h)&&(console.warn("RPC response received before ack",h),this.pendingAcks.delete(h),clearTimeout(y)),C?d(C):l(w??"")},participantIdentity:r})}))}()})}registerRpcMethod(e,n){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=n,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const n=this.pendingAcks.get(e);n?(n.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,n,i){const r=this.pendingResponses.get(e);r?(r.resolve(n,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,n,i,r,s){return A(this,void 0,void 0,function*(){const o=new Mt({destinationIdentities:[e],kind:be.RELIABLE,value:{case:"rpcRequest",value:new J0({id:n,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,be.RELIABLE)})}handleParticipantDisconnected(e){for(const[n,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(n);for(const[n,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,Qe.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(n=>n.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(n=>{var i,r;const s=this.trackPublications.get(n.sid);if(s){const o=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);o!==n.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),we(s)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(n.sid,o))}}),!0):!1}setActiveAgent(e){var n,i,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.resolve)===null||i===void 0||i.call(n,e):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Tr),this.activeAgentFuture.promise)}getPublicationForTrack(e){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(Un(r)||ii(r))&&r.mediaStreamTrack===e&&(n=i):e===r&&(n=i))}),n}waitForPendingPublicationOfSource(e){return A(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[o]=s;return o.source===e});if(r)return r[1];yield jt(20)}})}}class Pa extends Bn{constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Jt.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(re.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.disabled=!s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensions=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new Za({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new tv({participantSid:"",trackSids:[this.trackSid]})]});this.emit(re.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Bn.SubscriptionStatus.Unsubscribed:super.isSubscribed?Bn.SubscriptionStatus.Subscribed:Bn.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Bn.PermissionStatus.Allowed:Bn.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var n,i;this.isManualOperationAllowed()&&(((n=this.videoDimensions)===null||n===void 0?void 0:n.width)===e.width&&((i=this.videoDimensions)===null||i===void 0?void 0:i.height)===e.height||($c(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&$c(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(re.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(re.VisibilityChanged,this.handleVisibilityChange),r.off(re.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(re.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(re.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(re.VisibilityChanged,this.handleVisibilityChange),e.on(re.Ended,this.handleEnded),this.emit(re.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n)}setSubscriptionError(e){this.emit(re.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const n=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):n!==e.muted&&this.emit(e.muted?re.Muted:re.Unmuted)}emitSubscriptionUpdateIfChanged(e){const n=this.subscriptionStatus;e!==n&&this.emit(re.SubscriptionStatusChanged,n,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(re.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===V.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return $c(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new lv({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=Jt.HIGH,this.emit(re.UpdateSettings,e)}}class Ra extends py{static fromParticipantInfo(e,n,i){return new Ra(e,n.sid,n.identity,n.name,n.metadata,n.attributes,i,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,n,i,r,s,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Yi.STANDARD;super(n,i||"",r,s,o,a,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(re.UpdateSettings,n=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),we(e))),this.signalClient.sendUpdateTrackSettings(n)}),e.on(re.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),e.on(re.SubscriptionPermissionChanged,n=>{this.emit(Z.TrackSubscriptionPermissionChanged,e,n)}),e.on(re.SubscriptionStatusChanged,n=>{this.emit(Z.TrackSubscriptionStatusChanged,e,n)}),e.on(re.Subscribed,n=>{this.emit(Z.TrackSubscribed,n,e)}),e.on(re.Unsubscribed,n=>{this.emit(Z.TrackUnsubscribed,n,e)}),e.on(re.SubscriptionFailed,n=>{this.emit(Z.TrackSubscriptionFailed,e.trackSid,n)})}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setVolume(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:V.Source.Microphone;this.volumeMap.set(n,e);const i=this.getTrackPublication(n);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:V.Source.Microphone;const n=this.getTrackPublication(e);return n&&n.track?n.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,n,i,r,s,o){let a=this.getTrackPublicationBySid(n);if(a||n.startsWith("TR")||this.trackPublications.forEach(d=>{!a&&e.kind===d.kind.toString()&&(a=d)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),this.emit(Z.TrackSubscriptionFailed,n);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,n,i,r,s,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),we(a))),this.emit(Z.TrackSubscriptionFailed,n);return}const c=e.kind==="video";let l;return c?l=new f2(e,n,r,s):l=new my(e,n,r,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(i),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&hd(l)&&Tn(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const n=new Map,i=new Map;return e.tracks.forEach(r=>{var s,o;let a=this.getTrackPublicationBySid(r.sid);if(a)a.updateInfo(r);else{const c=V.kindFromProto(r.type);if(!c)return;a=new Pa(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(r),i.set(r.sid,a);const l=Array.from(this.trackPublications.values()).find(d=>d.source===(a==null?void 0:a.source));l&&a.source!==V.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:we(l),newTrack:we(a)})),this.addTrackPublication(a)}n.set(r.sid,a)}),this.trackPublications.forEach(r=>{n.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),we(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(Z.TrackPublished,r)}),!0}unpublishTrack(e,n){const i=this.trackPublications.get(e);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case V.Kind.Audio:this.audioTrackPublications.delete(e);break;case V.Kind.Video:this.videoTrackPublications.delete(e);break}n&&this.emit(Z.TrackUnpublished,i)}setAudioOutput(e){return A(this,void 0,void 0,function*(){this.audioOutput=e;const n=[];this.audioTrackPublications.forEach(i=>{var r;Tn(i.track)&&hd(i.track)&&n.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(n)})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var ge;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(ge||(ge={}));const b2=4*1e3;class pi extends Nn.EventEmitter{constructor(e){var n,i,r,s;if(super(),n=this,this.state=ge.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Ce,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(o,a,c)=>A(this,void 0,void 0,function*(){var l;if(!Qk())throw In()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const d=yield this.disconnectLock.lock();if(this.state===ge.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),d(),Promise.resolve();if(this.connectFuture)return d(),this.connectFuture.promise;this.setAndEmitConnectionState(ge.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==o&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ud(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new bd(o,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().then(p=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(p)}).catch(p=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:p}))}));const u=(p,g,h)=>A(this,void 0,void 0,function*(){var y,b;this.abortController&&this.abortController.abort();const w=new AbortController;this.abortController=w,d==null||d();try{yield this.attemptConnection(h??o,a,c,w),this.abortController=void 0,p()}catch(C){if(this.regionUrlProvider&&C instanceof Ue&&C.reason!==Te.Cancelled&&C.reason!==Te.NotAllowed){let S=null;try{S=yield this.regionUrlProvider.getNextBestRegionUrl((y=this.abortController)===null||y===void 0?void 0:y.signal)}catch(x){if(x instanceof Ue&&(x.status===401||x.reason===Te.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(x);return}}S&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(C.message,". Retrying with another region: ").concat(S),this.logContext),this.recreateEngine(),yield u(p,g,S)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,rm(C)),g(C))}else{let S=dn.UNKNOWN_REASON;C instanceof Ue&&(S=rm(C)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,S),g(C)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Tr((p,g)=>{u(p,g,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,a,c,l,d,u)=>A(this,void 0,void 0,function*(){var f,p,g;const h=yield c.join(o,a,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof d.adaptiveStream=="object"?!0:d.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},u.signal);let y=h.serverInfo;if(y||(y={version:h.serverVersion,region:h.serverRegion}),this.serverInfo=y,this.log.debug("connected to Livekit Server ".concat(Object.entries(y).map(b=>{let[w,C]=b;return"".concat(w,": ").concat(C)}).join(", ")),{room:(f=h.room)===null||f===void 0?void 0:f.name,roomSid:(p=h.room)===null||p===void 0?void 0:p.sid,identity:(g=h.participant)===null||g===void 0?void 0:g.identity}),!y.version)throw new Vk("unknown server version");return y.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),d.dynacast=!1),h}),this.applyJoinResponse=o=>{const a=o.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([a,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,a,c,l)=>A(this,void 0,void 0,function*(){var d,u;this.state===ge.Reconnecting||this.isResuming||!((d=this.engine)===null||d===void 0)&&d.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((u=this.regionUrlProvider)===null||u===void 0)&&u.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Lu),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(o,a,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(U.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const p=new Ue("could not establish signal connection",Te.ServerUnreachable);throw f instanceof Error&&(p.message="".concat(p.message,": ").concat(f.message)),f instanceof Ue&&(p.reason=f.reason,p.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),p}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Ue("Connection attempt aborted",Te.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}Ot()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ot()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ge.Connected),this.emit(U.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return A(n,[...a],void 0,function(){var l=this;let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var u,f,p,g;const h=yield l.disconnectLock.lock();try{if(l.state===ge.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===ge.Connecting||l.state===ge.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(u=l.abortController)===null||u===void 0||u.abort(),(p=(f=l.connectFuture)===null||f===void 0?void 0:f.reject)===null||p===void 0||p.call(f,new Ue("Client initiated disconnect",Te.Cancelled)),l.connectFuture=void 0),!((g=l.engine)===null||g===void 0)&&g.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(d,dn.CLIENT_INITIATED),l.engine=void 0}finally{h()}}()})},this.onPageLeave=()=>A(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>A(this,void 0,void 0,function*(){const o=[],a=$t();if(a&&a.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const d=Bc();d.enabled=!0;const u=new MediaStream([d]);l.srcObject=u,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:u,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(U.Disconnected,()=>{l==null||l.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(d=>{o.push(d)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>A(this,void 0,void 0,function*(){const o=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.attachedElements.forEach(d=>{o.includes(d)||o.push(d)})});yield Promise.all(o.map(a=>a.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(a=>{a.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(ge.Reconnecting)&&this.emit(U.Reconnecting)},this.handleSignalRestarted=o=>A(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(a){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:a}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(ge.Connected),this.emit(U.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(a=>{var c;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(c=this.sidToIdentity.get(a.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(a.identity);a.state===_r.DISCONNECTED?this.handleParticipantDisconnected(a.identity,l):l=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=o=>{const a=[],c={};o.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const d=this.getRemoteParticipantBySid(l.sid);d&&(d.audioLevel=l.level,d.setIsSpeaking(!0),a.push(d))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(U.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=o=>{const a=new Map;this.activeSpeakers.forEach(l=>{const d=this.remoteParticipants.get(l.identity);d&&d.sid!==l.sid||a.set(l.sid,l)}),o.forEach(l=>{let d=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(d=this.localParticipant),d&&(d.audioLevel=l.level,d.setIsSpeaking(l.active),l.active?a.set(l.sid,d):a.delete(l.sid))});const c=Array.from(a.values());c.sort((l,d)=>d.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(U.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);if(!l||!l.track)return;const d=V.streamStateFromProto(a.state);d!==l.track.streamState&&(l.track.streamState=d,c.emit(Z.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(U.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const a=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setSubscriptionError(o.err)},this.handleDataPacket=o=>{const a=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(a,o.value.value,o.kind);else if(o.value.case==="transcription")this.handleTranscription(a,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(a,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(a,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,a);else if(o.value.case==="streamHeader")this.handleStreamHeader(o.value.value,o.participantIdentity);else if(o.value.case==="streamChunk")this.handleStreamChunk(o.value.value);else if(o.value.case==="streamTrailer")this.handleStreamTrailer(o.value.value);else if(o.value.case==="rpcRequest"){const c=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(o,a,c)=>{this.emit(U.DataReceived,a.payload,o,c,a.topic),o==null||o.emit(Z.DataReceived,a.payload,c)},this.handleSipDtmf=(o,a)=>{this.emit(U.SipDTMFReceived,a,o),o==null||o.emit(Z.SipDTMFReceived,a)},this.bufferedSegments=new Map,this.handleTranscription=(o,a)=>{const c=a.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(a.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(a.trackId),d=lT(a,this.transcriptionReceivedTimes);l==null||l.emit(re.TranscriptionReceived,d),c==null||c.emit(Z.TranscriptionReceived,d,l),this.emit(U.TranscriptionReceived,d,c,l)},this.handleChatMessage=(o,a)=>{const c=dT(a);this.emit(U.ChatMessage,c,o)},this.handleMetrics=(o,a)=>{this.emit(U.MetricsReceived,o,a)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(U.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(U.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(U.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(U.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>A(this,void 0,void 0,function*(){var o;((o=$t())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(U.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const a=this.roomInfo;this.roomInfo=o,a&&a.metadata!==o.metadata&&this.emitWhenConnected(U.RoomMetadataChanged,o.metadata),(a==null?void 0:a.activeRecording)!==o.activeRecording&&this.emitWhenConnected(U.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const c=this.getRemoteParticipantBySid(a.participantSid);c&&c.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(U.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(U.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(U.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(U.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(U.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var a;(a=o==null?void 0:o.onPublish)===null||a===void 0||a.call(o,this)},this.onLocalTrackPublished=o=>A(this,void 0,void 0,function*(){var a,c,l,d,u,f;(a=o.track)===null||a===void 0||a.on(re.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.on(re.Restarted,this.onLocalTrackRestarted),(u=(d=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||d===void 0?void 0:d.onPublish)===null||u===void 0||u.call(d,this),this.emit(U.LocalTrackPublished,o,this.localParticipant),Un(o.track)&&(yield o.track.checkForSilence())&&this.emit(U.LocalAudioSilenceDetected,o);const p=yield(f=o.track)===null||f===void 0?void 0:f.getDeviceId(!1),g=pd(o.source);g&&p&&p!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,p),this.emit(U.ActiveDeviceChanged,g,p))}),this.onLocalTrackUnpublished=o=>{var a,c;(a=o.track)===null||a===void 0||a.off(re.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.off(re.Restarted,this.onLocalTrackRestarted),this.emit(U.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>A(this,void 0,void 0,function*(){const a=yield o.getDeviceId(!1),c=pd(o.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(a," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,a),this.emit(U.ActiveDeviceChanged,c,a))}),this.onLocalConnectionQualityChanged=o=>{this.emit(U.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,a)=>{this.emit(U.MediaDevicesError,o,a)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(U.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(U.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},jT),e),this.log=Gn((i=this.options.loggerName)!==null&&i!==void 0?i:fn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},sy),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},oy),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},DT),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Nt,this.localParticipant=new y2("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",fi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",fi(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",fi(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Ot()){const o=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),pi.cleanupRegistry&&pi.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,n){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,n){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,n){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,n,i,r,s,o){return A(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,n),o!==1){yield this.engine.publishRpcResponse(e,n,null,Qe.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(i);if(!a){yield this.engine.publishRpcResponse(e,n,null,Qe.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield a({requestId:n,callerIdentity:e,payload:r,responseTimeout:s});Vu(d)>ay?(c=Qe.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=d}catch(d){d instanceof Qe?c=d:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),c=Qe.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,n,l,c)})}setE2EEEnabled(e){return A(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new xT(this.options.e2ee),this.e2eeManager.on(di.ParticipantEncryptionStatusChanged,(n,i)=>{fT(i)&&(this.isE2EEEnabled=n),this.emit(U.ParticipantEncryptionStatusChanged,n,i)}),this.e2eeManager.on(di.EncryptionError,n=>this.emit(U.EncryptionError,n)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&n!==void 0?n:!1}getSid(){return A(this,void 0,void 0,function*(){return this.state===ge.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(ae.RoomUpdate,i),e(r.sid))};this.engine.on(ae.RoomUpdate,i),this.once(U.Disconnected,()=>{this.engine.off(ae.RoomUpdate,i),n("Room disconnected before room server id was available")})})})}get name(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&n!==void 0?n:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&n!==void 0?n:0}get numPublishers(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&n!==void 0?n:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new r2(this.options),this.engine.on(ae.ParticipantUpdate,this.handleParticipantUpdates).on(ae.RoomUpdate,this.handleRoomUpdate).on(ae.SpeakersChanged,this.handleSpeakersChanged).on(ae.StreamStateChanged,this.handleStreamStateUpdate).on(ae.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(ae.SubscriptionError,this.handleSubscriptionError).on(ae.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(ae.MediaTrackAdded,(e,n,i)=>{this.onTrackAdded(e,n,i)}).on(ae.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(ae.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(ae.DataPacketReceived,this.handleDataPacket).on(ae.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ge.SignalReconnecting)&&this.emit(U.SignalReconnecting)}).on(ae.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ge.Connected)&&this.emit(U.Reconnected)}).on(ae.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ge.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(ae.Restarting,this.handleRestarting).on(ae.SignalRestarted,this.handleSignalRestarted).on(ae.Offline,()=>{this.setAndEmitConnectionState(ge.Reconnecting)&&this.emit(U.Reconnecting)}).on(ae.DCBufferStatusChanged,(e,n)=>{this.emit(U.DCBufferStatusChanged,e,n)}).on(ae.LocalTrackSubscribed,e=>{const n=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!n){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(Z.LocalTrackSubscribed,n),this.emitWhenConnected(U.LocalTrackSubscribed,n,this.localParticipant)}).on(ae.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((n,i)=>{this.handleParticipantDisconnected(i,n)}),this.emit(U.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return gt.getInstance().getDevices(e,n)}prepareConnection(e,n){return A(this,void 0,void 0,function*(){if(this.state===ge.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(ud(new URL(e))&&n){this.regionUrlProvider=new bd(e,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ge.Disconnected&&(this.regionUrl=i,yield fetch(fd(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(fd(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,n){return A(this,void 0,void 0,function*(){let i=()=>{},r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new bn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new bn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new bn({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new bn({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>A(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new bn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>A(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new bn({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new bn({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>A(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new Ya({reason:dn.CLIENT_INITIATED,action:Nr.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new bn({scenario:{case:"subscriberBandwidth",value:Li(n)}});break;case"leave-full-reconnect":r=new bn({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,n){return A(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var a,c,l,d,u,f,p;let g=!0,h=!1;const y=o?{exact:r}:r;if(i==="audioinput"){h=s.localParticipant.audioTrackPublications.size===0;const b=(a=s.getActiveDevice(i))!==null&&a!==void 0?a:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=y;const w=Array.from(s.localParticipant.audioTrackPublications.values()).filter(S=>S.source===V.Source.Microphone);try{g=(yield Promise.all(w.map(S=>{var x;return(x=S.audioTrack)===null||x===void 0?void 0:x.setDeviceId(y)}))).every(S=>S===!0)}catch(S){throw s.options.audioCaptureDefaults.deviceId=b,S}const C=w.some(S=>{var x,T;return(T=(x=S.track)===null||x===void 0?void 0:x.isMuted)!==null&&T!==void 0?T:!1});g&&C&&(h=!0)}else if(i==="videoinput"){h=s.localParticipant.videoTrackPublications.size===0;const b=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=y;const w=Array.from(s.localParticipant.videoTrackPublications.values()).filter(C=>C.source===V.Source.Camera);try{g=(yield Promise.all(w.map(C=>{var S;return(S=C.videoTrack)===null||S===void 0?void 0:S.setDeviceId(y)}))).every(C=>C===!0)}catch(C){throw s.options.videoCaptureDefaults.deviceId=b,C}}else if(i==="audiooutput"){if(h=!0,!dd()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");s.options.webAudioMix&&(r=(l=yield gt.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(d=(p=s.options).audioOutput)!==null&&d!==void 0||(p.audioOutput={});const b=(u=s.getActiveDevice(i))!==null&&u!==void 0?u:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((f=s.audioContext)===null||f===void 0||f.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(w=>w.setAudioOutput({deviceId:r})))}catch(w){throw s.options.audioOutput.deviceId=b,w}}return h&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(U.ActiveDeviceChanged,i,r)),g}()})}setupLocalParticipantEvents(){this.localParticipant.on(Z.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(Z.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(Z.AttributesChanged,this.onLocalAttributesChanged).on(Z.TrackMuted,this.onLocalTrackMuted).on(Z.TrackUnmuted,this.onLocalTrackUnmuted).on(Z.LocalTrackPublished,this.onLocalTrackPublished).on(Z.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(Z.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(Z.MediaDevicesError,this.onMediaDevicesError).on(Z.AudioStreamAcquired,this.startAudio).on(Z.ChatMessage,this.onLocalChatMessageSent).on(Z.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,n,i){if(this.state===ge.Connecting||this.state===ge.Reconnecting){const d=()=>{this.onTrackAdded(e,n,i),u()},u=()=>{this.off(U.Reconnected,d),this.off(U.Connected,d),this.off(U.Disconnected,u)};this.once(U.Reconnected,d),this.once(U.Connected,d),this.once(U.Disconnected,u);return}if(this.state===ge.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=Yk(n.id),s=r[0];let o=r[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(d=>d.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={}),c.addSubscribedMediaTrack(e,a,n,i,l)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==ge.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,o,a;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((s=r.track)===null||s===void 0||s.detach(),(o=r.track)===null||o===void 0||o.stop()):(a=r.track)===null||a===void 0||a.stopMonitor()}),this.localParticipant.off(Z.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(Z.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(Z.AttributesChanged,this.onLocalAttributesChanged).off(Z.TrackMuted,this.onLocalTrackMuted).off(Z.TrackUnmuted,this.onLocalTrackUnmuted).off(Z.LocalTrackPublished,this.onLocalTrackPublished).off(Z.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(Z.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(Z.MediaDevicesError,this.onMediaDevicesError).off(Z.AudioStreamAcquired,this.startAudio).off(Z.ChatMessage,this.onLocalChatMessageSent).off(Z.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),Ot()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ge.Disconnected),this.emit(U.Disconnected,n)}}}handleParticipantDisconnected(e,n){var i;this.remoteParticipants.delete(e),n&&(n.trackPublications.forEach(r=>{n.unpublishTrack(r.trackSid,!0)}),this.emit(U.ParticipantDisconnected,n),n.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(n.identity))}handleStreamHeader(e,n){return A(this,void 0,void 0,function*(){var i;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s;const o={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ra(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:c=>{s=c,this.byteStreamControllers.set(e.streamId,{info:o,controller:s,startTime:Date.now()})}});r(new c2(o,a,ra(e.totalLength)),{identity:n})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let s;const o={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:c=>{s=c,this.textStreamControllers.set(e.streamId,{info:o,controller:s,startTime:Date.now()})}});r(new l2(o,a,ra(e.totalLength)),{identity:n})}})}handleStreamChunk(e){const n=this.byteStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}selectDefaultDevices(){return A(this,void 0,void 0,function*(){var e,n,i;const r=gt.getInstance().previousDevices,s=yield gt.getInstance().getDevices(void 0,!1),o=$t();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of s){const l=r.find(d=>d.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(U.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const l=mT(c),d=this.localParticipant.getTrackPublication(l);if(d&&(!((e=d.track)===null||e===void 0)&&e.isUserProvided))continue;const u=s.filter(p=>p.kind===c),f=this.getActiveDevice(c);if(f===((n=r.filter(p=>p.kind===c)[0])===null||n===void 0?void 0:n.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==f){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Qh()||c==="videoinput"||u.length>0&&!u.find(p=>p.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Qh())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return A(this,void 0,void 0,function*(){var e,n;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Nu())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),jt(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((n=this.audioContext)===null||n===void 0?void 0:n.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(U.AudioPlaybackStatusChanged,i))})}createParticipant(e,n){var i;let r;return n?r=Ra.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new Ra(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(e,n){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return n&&r.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity),r}const i=this.createParticipant(e,n);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(U.ParticipantConnected,i),i.on(Z.TrackPublished,r=>{this.emitWhenConnected(U.TrackPublished,r,i)}).on(Z.TrackSubscribed,(r,s)=>{r.kind===V.Kind.Audio?(r.on(re.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(re.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===V.Kind.Video&&(r.on(re.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(re.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(U.TrackSubscribed,r,s,i)}).on(Z.TrackUnpublished,r=>{this.emit(U.TrackUnpublished,r,i)}).on(Z.TrackUnsubscribed,(r,s)=>{this.emit(U.TrackUnsubscribed,r,s,i)}).on(Z.TrackMuted,r=>{this.emitWhenConnected(U.TrackMuted,r,i)}).on(Z.TrackUnmuted,r=>{this.emitWhenConnected(U.TrackUnmuted,r,i)}).on(Z.ParticipantMetadataChanged,r=>{this.emitWhenConnected(U.ParticipantMetadataChanged,r,i)}).on(Z.ParticipantNameChanged,r=>{this.emitWhenConnected(U.ParticipantNameChanged,r,i)}).on(Z.AttributesChanged,r=>{this.emitWhenConnected(U.ParticipantAttributesChanged,r,i)}).on(Z.ConnectionQualityChanged,r=>{this.emitWhenConnected(U.ConnectionQualityChanged,r,i)}).on(Z.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(U.ParticipantPermissionsChanged,r,i)}).on(Z.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(U.TrackSubscriptionStatusChanged,r,s,i)}).on(Z.TrackSubscriptionFailed,(r,s)=>{this.emit(U.TrackSubscriptionFailed,r,i,s)}).on(Z.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(U.TrackSubscriptionPermissionChanged,r,s,i)}).on(Z.Active,()=>{this.emitWhenConnected(U.ParticipantActive,i),i.kind===Yi.AGENT&&this.localParticipant.setActiveAgent(i)}),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),n=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const n of e.videoTrackPublications.values())n.isSubscribed&&uT(n)&&n.emitTrackUpdate()}getRemoteParticipantBySid(e){const n=this.sidToIdentity.get(e);if(n)return this.remoteParticipants.get(n)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=bt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,dn.STATE_MISMATCH))):e=0},b2)}clearConnectionReconcile(){this.connectionReconcileInterval&&bt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(U.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[n,i]=e;this.emit(n,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===ge.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ge.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return A(this,void 0,void 0,function*(){var n,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ga({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ze.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Zi({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(U.SignalConnected),this.emit(U.Connected),this.setAndEmitConnectionState(ge.Connected),r.video){const o=new Sd(V.Kind.Video,new Cr({source:lt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:cn.AUDIO,name:"video-dummy"}),new Ea(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:im(160*((n=s.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(Z.LocalTrackPublished,o)}if(r.audio){const o=new Sd(V.Kind.Audio,new Cr({source:lt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:cn.AUDIO}),new Ta(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Bc(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(Z.LocalTrackPublished,o)}for(let o=0;o<s.count-1;o+=1){let a=new Zi({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:_r.ACTIVE,tracks:[],joinedAt:ze.parse(Date.now())});const c=this.getOrCreateParticipant(a.identity,a);if(s.video){const l=im(160*((i=s.aspectRatios[o%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),d=new Cr({source:lt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:cn.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,d]}if(s.audio){const l=Bc(),d=new Cr({source:lt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:cn.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,d]}c.updateInfo(a)}})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(e!==U.ActiveSpeakersChanged&&e!==U.TranscriptionReceived){const s=gy(i).filter(o=>o!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s}))}return super.emit(e,...i)}}pi.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function gy(t){return t.map(e=>{if(e)return Array.isArray(e)?gy(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var an;(function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"})(an||(an={}));class Ti extends Nn.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=an.IDLE,this.logs=[],this.options={},this.url=e,this.token=n,this.name=this.constructor.name,this.room=new pi(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return A(this,void 0,void 0,function*(){if(this.status!==an.IDLE)throw Error("check is running already");this.setStatus(an.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise(n=>setTimeout(n,500)),this.status!==an.SKIPPED&&this.setStatus(this.isSuccess()?an.SUCCESS:an.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return A(this,void 0,void 0,function*(){return this.room.state===ge.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return A(this,void 0,void 0,function*(){this.room&&this.room.state!==ge.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(an.SKIPPED)}switchProtocol(e){return A(this,void 0,void 0,function*(){let n=!1,i=!1;if(this.room.on(U.Reconnecting,()=>{n=!0}),this.room.once(U.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield jt(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class x2 extends Ti{get description(){return"Cloud regions"}perform(){return A(this,void 0,void 0,function*(){const e=new bd(this.url,this.token);if(!e.isCloud()){this.skip();return}const n=[],i=new Set;for(let s=0;s<3;s++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),n.push(a)}n.sort((s,o)=>(s.duration-o.duration)*.5+(s.rtt-o.rtt)*.5);const r=n[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return A(this,void 0,void 0,function*(){var n,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(n=this.room.serverInfo)===null||n===void 0?void 0:n.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,l="A".repeat(o),d=Date.now();for(let g=0;g<c;g++)yield s.write(l);yield s.close();const u=Date.now(),f=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),p={region:r,rtt:1e4,duration:u-d};return f==null||f.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(p.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const Yc=1e4;class S2 extends Ti{get description(){return"Connection via UDP vs TCP"}perform(){return A(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),n=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-n.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-n.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=n):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(Yc/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Yc/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return A(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const n=document.createElement("canvas");n.width=1280,n.height=720;const i=n.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,n.width,n.height),requestAnimationFrame(s)};s();const a=n.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,d={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>A(this,void 0,void 0,function*(){const f=yield l.getRTCStatsReport();f==null||f.forEach(p=>{p.type==="outbound-rtp"?(d.packetsSent=p.packetsSent,d.qualityLimitationDurations=p.qualityLimitationDurations,d.bitrateTotal+=p.targetBitrate,d.count++):p.type==="remote-inbound-rtp"&&(d.packetsLost=p.packetsLost,d.rttTotal+=p.roundTripTime,d.jitterTotal+=p.jitter)})}),1e3);return yield new Promise(f=>setTimeout(f,Yc)),clearInterval(u),a.stop(),n.remove(),yield this.disconnect(),d})}}class w2 extends Ti{get description(){return"Can publish audio"}perform(){return A(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield p2();if(yield ny(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),n.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let o=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class C2 extends Ti{get description(){return"Can publish video"}perform(){return A(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield m2();yield this.checkForVideo(i.mediaStreamTrack),n.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(s+=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return A(this,void 0,void 0,function*(){const n=new MediaStream;n.addTrack(e.clone());const i=document.createElement("video");i.srcObject=n,i.muted=!0,yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,o,a,c;const l=document.createElement("canvas"),d=e.getSettings(),u=(o=(s=d.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&o!==void 0?o:1280,f=(c=(a=d.height)!==null&&a!==void 0?a:i.videoHeight)!==null&&c!==void 0?c:720;l.width=u,l.height=f;const p=l.getContext("2d");p.drawImage(i,0,0);const h=p.getImageData(0,0,l.width,l.height).data;let y=!0;for(let b=0;b<h.length;b+=4)if(h[b]!==0||h[b+1]!==0||h[b+2]!==0){y=!1;break}y?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),n.getTracks().forEach(r=>r.stop()),i.remove()})}}class k2 extends Ti{get description(){return"Resuming connection after interruption"}perform(){return A(this,void 0,void 0,function*(){var e;const n=yield this.connect();let i=!1,r=!1,s;const o=new Promise(l=>{setTimeout(l,5e3),s=l}),a=()=>{i=!0};n.on(U.SignalReconnecting,a).on(U.Reconnecting,a).on(U.Reconnected,()=>{r=!0,s(!0)}),(e=n.engine.client.ws)===null||e===void 0||e.close();const c=n.engine.client.onClose;if(c&&c(""),yield o,i){if(!r||n.state!==ge.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class T2 extends Ti{get description(){return"Can connect via TURN"}perform(){return A(this,void 0,void 0,function*(){var e,n;const i=new Ou,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,o=!1,a=!1;for(let c of r.iceServers)for(let l of c.urls)l.startsWith("turn:")?(o=!0,a=!0):l.startsWith("turns:")&&(o=!0,a=!0,s=!0),l.startsWith("stun:")&&(a=!0);a?o&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((n=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||n===void 0)&&n.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class E2 extends Ti{get description(){return"Establishing WebRTC connection"}perform(){return A(this,void 0,void 0,function*(){let e=!1,n=!1;this.room.on(U.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const o=new RTCIceCandidate(r);let a="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(P2(o.address)?a+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,a+=" (passive)"):o.protocol==="udp"&&(n=!0)),this.appendMessage(a)}i&&i(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),Ce.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function P2(t){const e=t.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const n=parseInt(e[1],10);if(n>=16&&n<=31)return!0}}return!1}class R2 extends Ti{get description(){return"Connecting to signal connection via WebSocket"}perform(){return A(this,void 0,void 0,function*(){var e,n,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Ou;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===iv.Cloud&&(!((n=s.serverInfo)===null||n===void 0)&&n.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region)),yield r.close()})}}class NL extends Nn.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=n,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:an.IDLE,name:"",description:""}),e}updateCheck(e,n){this.checkResults.set(e,n),this.emit("checkUpdate",e,n)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==an.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return A(this,void 0,void 0,function*(){const n=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=o=>{this.updateCheck(n,o)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(R2)})}checkWebRTC(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(E2)})}checkTURN(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(T2)})}checkReconnect(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(k2)})}checkPublishAudio(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(w2)})}checkPublishVideo(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(C2)})}checkConnectionProtocol(){return A(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(S2);if(e.data&&"protocol"in e.data){const n=e.data;this.options.protocol=n.protocol}return e})}checkCloudRegion(){return A(this,void 0,void 0,function*(){return this.createAndRunCheck(x2)})}}const Bu=R.createContext({});function $u(t){const e=R.useRef(null);return e.current===null&&(e.current=t()),e.current}const Hu=typeof window<"u",vy=Hu?R.useLayoutEffect:R.useEffect,ec=R.createContext(null);function zu(t,e){t.indexOf(e)===-1&&t.push(e)}function Wu(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const Zn=(t,e,n)=>n>e?e:n<t?t:n;function wd(t,e){return e?`${t}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${e}`:t}let is=()=>{},Yn=()=>{};process.env.NODE_ENV!=="production"&&(is=(t,e,n)=>{!t&&typeof console<"u"&&console.warn(wd(e,n))},Yn=(t,e,n)=>{if(!t)throw new Error(wd(e,n))});const Jn={},yy=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function by(t){return typeof t=="object"&&t!==null}const xy=t=>/^0[^.\s]+$/u.test(t);function qu(t){let e;return()=>(e===void 0&&(e=t()),e)}const Xt=t=>t,A2=(t,e)=>n=>e(t(n)),ao=(...t)=>t.reduce(A2),Ws=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class Ku{constructor(){this.subscriptions=[]}add(e){return zu(this.subscriptions,e),()=>Wu(this.subscriptions,e)}notify(e,n,i){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](e,n,i);else for(let s=0;s<r;s++){const o=this.subscriptions[s];o&&o(e,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const un=t=>t*1e3,En=t=>t/1e3;function Sy(t,e){return e?t*(1e3/e):0}const wm=new Set;function Gu(t,e,n){t||wm.has(e)||(console.warn(wd(e,n)),wm.add(e))}const wy=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,I2=1e-7,M2=12;function _2(t,e,n,i,r){let s,o,a=0;do o=e+(n-e)/2,s=wy(o,i,r)-t,s>0?n=o:e=o;while(Math.abs(s)>I2&&++a<M2);return o}function co(t,e,n,i){if(t===e&&n===i)return Xt;const r=s=>_2(s,0,1,t,n);return s=>s===0||s===1?s:wy(r(s),e,i)}const Cy=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,ky=t=>e=>1-t(1-e),Ty=co(.33,1.53,.69,.99),Zu=ky(Ty),Ey=Cy(Zu),Py=t=>(t*=2)<1?.5*Zu(t):.5*(2-Math.pow(2,-10*(t-1))),Yu=t=>1-Math.sin(Math.acos(t)),Ry=ky(Yu),Ay=Cy(Yu),N2=co(.42,0,1,1),O2=co(0,0,.58,1),Iy=co(.42,0,.58,1),D2=t=>Array.isArray(t)&&typeof t[0]!="number",My=t=>Array.isArray(t)&&typeof t[0]=="number",Cm={linear:Xt,easeIn:N2,easeInOut:Iy,easeOut:O2,circIn:Yu,circInOut:Ay,circOut:Ry,backIn:Zu,backInOut:Ey,backOut:Ty,anticipate:Py},j2=t=>typeof t=="string",km=t=>{if(My(t)){Yn(t.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[e,n,i,r]=t;return co(e,n,i,r)}else if(j2(t))return Yn(Cm[t]!==void 0,`Invalid easing type '${t}'`,"invalid-easing-type"),Cm[t];return t},ko=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function L2(t,e){let n=new Set,i=new Set,r=!1,s=!1;const o=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function c(d){o.has(d)&&(l.schedule(d),t()),d(a)}const l={schedule:(d,u=!1,f=!1)=>{const g=f&&r?n:i;return u&&o.add(d),g.has(d)||g.add(d),d},cancel:d=>{i.delete(d),o.delete(d)},process:d=>{if(a=d,r){s=!0;return}r=!0,[n,i]=[i,n],n.forEach(c),n.clear(),r=!1,s&&(s=!1,l.process(d))}};return l}const V2=40;function _y(t,e){let n=!1,i=!0;const r={delta:0,timestamp:0,isProcessing:!1},s=()=>n=!0,o=ko.reduce((C,S)=>(C[S]=L2(s),C),{}),{setup:a,read:c,resolveKeyframes:l,preUpdate:d,update:u,preRender:f,render:p,postRender:g}=o,h=()=>{const C=Jn.useManualTiming?r.timestamp:performance.now();n=!1,Jn.useManualTiming||(r.delta=i?1e3/60:Math.max(Math.min(C-r.timestamp,V2),1)),r.timestamp=C,r.isProcessing=!0,a.process(r),c.process(r),l.process(r),d.process(r),u.process(r),f.process(r),p.process(r),g.process(r),r.isProcessing=!1,n&&e&&(i=!1,t(h))},y=()=>{n=!0,i=!0,r.isProcessing||t(h)};return{schedule:ko.reduce((C,S)=>{const x=o[S];return C[S]=(T,E=!1,P=!1)=>(n||y(),x.schedule(T,E,P)),C},{}),cancel:C=>{for(let S=0;S<ko.length;S++)o[ko[S]].cancel(C)},state:r,steps:o}}const{schedule:We,cancel:gi,state:vt,steps:Jc}=_y(typeof requestAnimationFrame<"u"?requestAnimationFrame:Xt,!0);let oa;function F2(){oa=void 0}const Dt={now:()=>(oa===void 0&&Dt.set(vt.isProcessing||Jn.useManualTiming?vt.timestamp:performance.now()),oa),set:t=>{oa=t,queueMicrotask(F2)}},Ny=t=>e=>typeof e=="string"&&e.startsWith(t),Ju=Ny("--"),U2=Ny("var(--"),Xu=t=>U2(t)?B2.test(t.split("/*")[0].trim()):!1,B2=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,rs={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},qs={...rs,transform:t=>Zn(0,1,t)},To={...rs,default:1},Vs=t=>Math.round(t*1e5)/1e5,Qu=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function $2(t){return t==null}const H2=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ef=(t,e)=>n=>!!(typeof n=="string"&&H2.test(n)&&n.startsWith(t)||e&&!$2(n)&&Object.prototype.hasOwnProperty.call(n,e)),Oy=(t,e,n)=>i=>{if(typeof i!="string")return i;const[r,s,o,a]=i.match(Qu);return{[t]:parseFloat(r),[e]:parseFloat(s),[n]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},z2=t=>Zn(0,255,t),Xc={...rs,transform:t=>Math.round(z2(t))},Ui={test:ef("rgb","red"),parse:Oy("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Xc.transform(t)+", "+Xc.transform(e)+", "+Xc.transform(n)+", "+Vs(qs.transform(i))+")"};function W2(t){let e="",n="",i="",r="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),i=t.substring(5,7),r=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),i=t.substring(3,4),r=t.substring(4,5),e+=e,n+=n,i+=i,r+=r),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:r?parseInt(r,16)/255:1}}const Cd={test:ef("#"),parse:W2,transform:Ui.transform},lo=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),oi=lo("deg"),Pn=lo("%"),he=lo("px"),q2=lo("vh"),K2=lo("vw"),Tm={...Pn,parse:t=>Pn.parse(t)/100,transform:t=>Pn.transform(t*100)},Er={test:ef("hsl","hue"),parse:Oy("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+Pn.transform(Vs(e))+", "+Pn.transform(Vs(n))+", "+Vs(qs.transform(i))+")"},ct={test:t=>Ui.test(t)||Cd.test(t)||Er.test(t),parse:t=>Ui.test(t)?Ui.parse(t):Er.test(t)?Er.parse(t):Cd.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ui.transform(t):Er.transform(t),getAnimatableNone:t=>{const e=ct.parse(t);return e.alpha=0,ct.transform(e)}},G2=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Z2(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Qu))==null?void 0:e.length)||0)+(((n=t.match(G2))==null?void 0:n.length)||0)>0}const Dy="number",jy="color",Y2="var",J2="var(",Em="${}",X2=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Ks(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},r=[];let s=0;const a=e.replace(X2,c=>(ct.test(c)?(i.color.push(s),r.push(jy),n.push(ct.parse(c))):c.startsWith(J2)?(i.var.push(s),r.push(Y2),n.push(c)):(i.number.push(s),r.push(Dy),n.push(parseFloat(c))),++s,Em)).split(Em);return{values:n,split:a,indexes:i,types:r}}function Ly(t){return Ks(t).values}function Vy(t){const{split:e,types:n}=Ks(t),i=e.length;return r=>{let s="";for(let o=0;o<i;o++)if(s+=e[o],r[o]!==void 0){const a=n[o];a===Dy?s+=Vs(r[o]):a===jy?s+=ct.transform(r[o]):s+=r[o]}return s}}const Q2=t=>typeof t=="number"?0:ct.test(t)?ct.getAnimatableNone(t):t;function eE(t){const e=Ly(t);return Vy(t)(e.map(Q2))}const vi={test:Z2,parse:Ly,createTransformer:Vy,getAnimatableNone:eE};function Qc(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function tE({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,e/=100,n/=100;let r=0,s=0,o=0;if(!e)r=s=o=n;else{const a=n<.5?n*(1+e):n+e-n*e,c=2*n-a;r=Qc(c,a,t+1/3),s=Qc(c,a,t),o=Qc(c,a,t-1/3)}return{red:Math.round(r*255),green:Math.round(s*255),blue:Math.round(o*255),alpha:i}}function Aa(t,e){return n=>n>0?e:t}const Ge=(t,e,n)=>t+(e-t)*n,el=(t,e,n)=>{const i=t*t,r=n*(e*e-i)+i;return r<0?0:Math.sqrt(r)},nE=[Cd,Ui,Er],iE=t=>nE.find(e=>e.test(t));function Pm(t){const e=iE(t);if(is(!!e,`'${t}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!e)return!1;let n=e.parse(t);return e===Er&&(n=tE(n)),n}const Rm=(t,e)=>{const n=Pm(t),i=Pm(e);if(!n||!i)return Aa(t,e);const r={...n};return s=>(r.red=el(n.red,i.red,s),r.green=el(n.green,i.green,s),r.blue=el(n.blue,i.blue,s),r.alpha=Ge(n.alpha,i.alpha,s),Ui.transform(r))},kd=new Set(["none","hidden"]);function rE(t,e){return kd.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function sE(t,e){return n=>Ge(t,e,n)}function tf(t){return typeof t=="number"?sE:typeof t=="string"?Xu(t)?Aa:ct.test(t)?Rm:cE:Array.isArray(t)?Fy:typeof t=="object"?ct.test(t)?Rm:oE:Aa}function Fy(t,e){const n=[...t],i=n.length,r=t.map((s,o)=>tf(s)(s,e[o]));return s=>{for(let o=0;o<i;o++)n[o]=r[o](s);return n}}function oE(t,e){const n={...t,...e},i={};for(const r in n)t[r]!==void 0&&e[r]!==void 0&&(i[r]=tf(t[r])(t[r],e[r]));return r=>{for(const s in i)n[s]=i[s](r);return n}}function aE(t,e){const n=[],i={color:0,var:0,number:0};for(let r=0;r<e.values.length;r++){const s=e.types[r],o=t.indexes[s][i[s]],a=t.values[o]??0;n[r]=a,i[s]++}return n}const cE=(t,e)=>{const n=vi.createTransformer(e),i=Ks(t),r=Ks(e);return i.indexes.var.length===r.indexes.var.length&&i.indexes.color.length===r.indexes.color.length&&i.indexes.number.length>=r.indexes.number.length?kd.has(t)&&!r.values.length||kd.has(e)&&!i.values.length?rE(t,e):ao(Fy(aE(i,r),r.values),n):(is(!0,`Complex values '${t}' and '${e}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),Aa(t,e))};function Uy(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?Ge(t,e,n):tf(t)(t,e)}const lE=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>We.update(e,n),stop:()=>gi(e),now:()=>vt.isProcessing?vt.timestamp:Dt.now()}},By=(t,e,n=10)=>{let i="";const r=Math.max(Math.round(e/n),2);for(let s=0;s<r;s++)i+=Math.round(t(s/(r-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},Ia=2e4;function nf(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<Ia;)e+=n,i=t.next(e);return e>=Ia?1/0:e}function dE(t,e=100,n){const i=n({...t,keyframes:[0,e]}),r=Math.min(nf(i),Ia);return{type:"keyframes",ease:s=>i.next(r*s).value/e,duration:En(r)}}const uE=5;function $y(t,e,n){const i=Math.max(e-uE,0);return Sy(n-t(i),e-i)}const Ke={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},tl=.001;function fE({duration:t=Ke.duration,bounce:e=Ke.bounce,velocity:n=Ke.velocity,mass:i=Ke.mass}){let r,s;is(t<=un(Ke.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let o=1-e;o=Zn(Ke.minDamping,Ke.maxDamping,o),t=Zn(Ke.minDuration,Ke.maxDuration,En(t)),o<1?(r=l=>{const d=l*o,u=d*t,f=d-n,p=Td(l,o),g=Math.exp(-u);return tl-f/p*g},s=l=>{const u=l*o*t,f=u*n+n,p=Math.pow(o,2)*Math.pow(l,2)*t,g=Math.exp(-u),h=Td(Math.pow(l,2),o);return(-r(l)+tl>0?-1:1)*((f-p)*g)/h}):(r=l=>{const d=Math.exp(-l*t),u=(l-n)*t+1;return-tl+d*u},s=l=>{const d=Math.exp(-l*t),u=(n-l)*(t*t);return d*u});const a=5/t,c=mE(r,s,a);if(t=un(t),isNaN(c))return{stiffness:Ke.stiffness,damping:Ke.damping,duration:t};{const l=Math.pow(c,2)*i;return{stiffness:l,damping:o*2*Math.sqrt(i*l),duration:t}}}const hE=12;function mE(t,e,n){let i=n;for(let r=1;r<hE;r++)i=i-t(i)/e(i);return i}function Td(t,e){return t*Math.sqrt(1-e*e)}const pE=["duration","bounce"],gE=["stiffness","damping","mass"];function Am(t,e){return e.some(n=>t[n]!==void 0)}function vE(t){let e={velocity:Ke.velocity,stiffness:Ke.stiffness,damping:Ke.damping,mass:Ke.mass,isResolvedFromDuration:!1,...t};if(!Am(t,gE)&&Am(t,pE))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),r=i*i,s=2*Zn(.05,1,1-(t.bounce||0))*Math.sqrt(r);e={...e,mass:Ke.mass,stiffness:r,damping:s}}else{const n=fE(t);e={...e,...n,mass:Ke.mass},e.isResolvedFromDuration=!0}return e}function Ma(t=Ke.visualDuration,e=Ke.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:r}=n;const s=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],a={done:!1,value:s},{stiffness:c,damping:l,mass:d,duration:u,velocity:f,isResolvedFromDuration:p}=vE({...n,velocity:-En(n.velocity||0)}),g=f||0,h=l/(2*Math.sqrt(c*d)),y=o-s,b=En(Math.sqrt(c/d)),w=Math.abs(y)<5;i||(i=w?Ke.restSpeed.granular:Ke.restSpeed.default),r||(r=w?Ke.restDelta.granular:Ke.restDelta.default);let C;if(h<1){const x=Td(b,h);C=T=>{const E=Math.exp(-h*b*T);return o-E*((g+h*b*y)/x*Math.sin(x*T)+y*Math.cos(x*T))}}else if(h===1)C=x=>o-Math.exp(-b*x)*(y+(g+b*y)*x);else{const x=b*Math.sqrt(h*h-1);C=T=>{const E=Math.exp(-h*b*T),P=Math.min(x*T,300);return o-E*((g+h*b*y)*Math.sinh(P)+x*y*Math.cosh(P))/x}}const S={calculatedDuration:p&&u||null,next:x=>{const T=C(x);if(p)a.done=x>=u;else{let E=x===0?g:0;h<1&&(E=x===0?un(g):$y(C,x,T));const P=Math.abs(E)<=i,_=Math.abs(o-T)<=r;a.done=P&&_}return a.value=a.done?o:T,a},toString:()=>{const x=Math.min(nf(S),Ia),T=By(E=>S.next(x*E).value,x,30);return x+"ms "+T},toTransition:()=>{}};return S}Ma.applyToOptions=t=>{const e=dE(t,100,Ma);return t.ease=e.ease,t.duration=un(e.duration),t.type="keyframes",t};function Ed({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:r=10,bounceStiffness:s=500,modifyTarget:o,min:a,max:c,restDelta:l=.5,restSpeed:d}){const u=t[0],f={done:!1,value:u},p=P=>a!==void 0&&P<a||c!==void 0&&P>c,g=P=>a===void 0?c:c===void 0||Math.abs(a-P)<Math.abs(c-P)?a:c;let h=n*e;const y=u+h,b=o===void 0?y:o(y);b!==y&&(h=b-u);const w=P=>-h*Math.exp(-P/i),C=P=>b+w(P),S=P=>{const _=w(P),k=C(P);f.done=Math.abs(_)<=l,f.value=f.done?b:k};let x,T;const E=P=>{p(f.value)&&(x=P,T=Ma({keyframes:[f.value,g(f.value)],velocity:$y(C,P,f.value),damping:r,stiffness:s,restDelta:l,restSpeed:d}))};return E(0),{calculatedDuration:null,next:P=>{let _=!1;return!T&&x===void 0&&(_=!0,S(P),E(P)),x!==void 0&&P>=x?T.next(P-x):(!_&&S(P),f)}}}function yE(t,e,n){const i=[],r=n||Jn.mix||Uy,s=t.length-1;for(let o=0;o<s;o++){let a=r(t[o],t[o+1]);if(e){const c=Array.isArray(e)?e[o]||Xt:e;a=ao(c,a)}i.push(a)}return i}function bE(t,e,{clamp:n=!0,ease:i,mixer:r}={}){const s=t.length;if(Yn(s===e.length,"Both input and output ranges must be the same length","range-length"),s===1)return()=>e[0];if(s===2&&e[0]===e[1])return()=>e[1];const o=t[0]===t[1];t[0]>t[s-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=yE(e,i,r),c=a.length,l=d=>{if(o&&d<t[0])return e[0];let u=0;if(c>1)for(;u<t.length-2&&!(d<t[u+1]);u++);const f=Ws(t[u],t[u+1],d);return a[u](f)};return n?d=>l(Zn(t[0],t[s-1],d)):l}function xE(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const r=Ws(0,e,i);t.push(Ge(n,1,r))}}function SE(t){const e=[0];return xE(e,t.length-1),e}function wE(t,e){return t.map(n=>n*e)}function CE(t,e){return t.map(()=>e||Iy).splice(0,t.length-1)}function Pr({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const r=D2(i)?i.map(km):km(i),s={done:!1,value:e[0]},o=wE(n&&n.length===e.length?n:SE(e),t),a=bE(o,e,{ease:Array.isArray(r)?r:CE(e,r)});return{calculatedDuration:t,next:c=>(s.value=a(c),s.done=c>=t,s)}}const kE=t=>t!==null;function rf(t,{repeat:e,repeatType:n="loop"},i,r=1){const s=t.filter(kE),a=r<0||e&&n!=="loop"&&e%2===1?0:s.length-1;return!a||i===void 0?s[a]:i}const TE={decay:Ed,inertia:Ed,tween:Pr,keyframes:Pr,spring:Ma};function Hy(t){typeof t.type=="string"&&(t.type=TE[t.type])}class sf{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,n){return this.finished.then(e,n)}}const EE=t=>t/100;class of extends sf{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var i,r;const{motionValue:n}=this.options;n&&n.updatedAt!==Dt.now()&&this.tick(Dt.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(r=(i=this.options).onStop)==null||r.call(i))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;Hy(e);const{type:n=Pr,repeat:i=0,repeatDelay:r=0,repeatType:s,velocity:o=0}=e;let{keyframes:a}=e;const c=n||Pr;process.env.NODE_ENV!=="production"&&c!==Pr&&Yn(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Pr&&typeof a[0]!="number"&&(this.mixKeyframes=ao(EE,Uy(a[0],a[1])),a=[0,100]);const l=c({...e,keyframes:a});s==="mirror"&&(this.mirroredGenerator=c({...e,keyframes:[...a].reverse(),velocity:-o})),l.calculatedDuration===null&&(l.calculatedDuration=nf(l));const{calculatedDuration:d}=l;this.calculatedDuration=d,this.resolvedDuration=d+r,this.totalDuration=this.resolvedDuration*(i+1)-r,this.generator=l}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:i,totalDuration:r,mixKeyframes:s,mirroredGenerator:o,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return i.next(0);const{delay:l=0,keyframes:d,repeat:u,repeatType:f,repeatDelay:p,type:g,onUpdate:h,finalKeyframe:y}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const b=this.currentTime-l*(this.playbackSpeed>=0?1:-1),w=this.playbackSpeed>=0?b<0:b>r;this.currentTime=Math.max(b,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let C=this.currentTime,S=i;if(u){const P=Math.min(this.currentTime,r)/a;let _=Math.floor(P),k=P%1;!k&&P>=1&&(k=1),k===1&&_--,_=Math.min(_,u+1),!!(_%2)&&(f==="reverse"?(k=1-k,p&&(k-=p/a)):f==="mirror"&&(S=o)),C=Zn(0,1,k)*a}const x=w?{done:!1,value:d[0]}:S.next(C);s&&(x.value=s(x.value));let{done:T}=x;!w&&c!==null&&(T=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const E=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&T);return E&&g!==Ed&&(x.value=rf(d,this.options,y,this.speed)),h&&h(x.value),E&&this.finish(),x}then(e,n){return this.finished.then(e,n)}get duration(){return En(this.calculatedDuration)}get time(){return En(this.currentTime)}set time(e){var n;e=un(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),(n=this.driver)==null||n.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(Dt.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=En(this.currentTime))}play(){var r,s;if(this.isStopped)return;const{driver:e=lE,startTime:n}=this.options;this.driver||(this.driver=e(o=>this.tick(o))),(s=(r=this.options).onPlay)==null||s.call(r);const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=n??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Dt.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(e=this.options).onComplete)==null||n.call(e)}cancel(){var e,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(e=this.options).onCancel)==null||n.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),e.observe(this)}}function PE(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Bi=t=>t*180/Math.PI,Pd=t=>{const e=Bi(Math.atan2(t[1],t[0]));return Rd(e)},RE={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Pd,rotateZ:Pd,skewX:t=>Bi(Math.atan(t[1])),skewY:t=>Bi(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Rd=t=>(t=t%360,t<0&&(t+=360),t),Im=Pd,Mm=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),_m=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),AE={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Mm,scaleY:_m,scale:t=>(Mm(t)+_m(t))/2,rotateX:t=>Rd(Bi(Math.atan2(t[6],t[5]))),rotateY:t=>Rd(Bi(Math.atan2(-t[2],t[0]))),rotateZ:Im,rotate:Im,skewX:t=>Bi(Math.atan(t[4])),skewY:t=>Bi(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Ad(t){return t.includes("scale")?1:0}function Id(t,e){if(!t||t==="none")return Ad(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,r;if(n)i=AE,r=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=RE,r=a}if(!r)return Ad(e);const s=i[e],o=r[1].split(",").map(ME);return typeof s=="function"?s(o):o[s]}const IE=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return Id(n,e)};function ME(t){return parseFloat(t.trim())}const ss=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],os=new Set(ss),Nm=t=>t===rs||t===he,_E=new Set(["x","y","z"]),NE=ss.filter(t=>!_E.has(t));function OE(t){const e=[];return NE.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const zi={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Id(e,"x"),y:(t,{transform:e})=>Id(e,"y")};zi.translateX=zi.x;zi.translateY=zi.y;const Wi=new Set;let Md=!1,_d=!1,Nd=!1;function zy(){if(_d){const t=Array.from(Wi).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const r=OE(i);r.length&&(n.set(i,r),i.render())}),t.forEach(i=>i.measureInitialState()),e.forEach(i=>{i.render();const r=n.get(i);r&&r.forEach(([s,o])=>{var a;(a=i.getValue(s))==null||a.set(o)})}),t.forEach(i=>i.measureEndState()),t.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}_d=!1,Md=!1,Wi.forEach(t=>t.complete(Nd)),Wi.clear()}function Wy(){Wi.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(_d=!0)})}function DE(){Nd=!0,Wy(),zy(),Nd=!1}class af{constructor(e,n,i,r,s,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=i,this.motionValue=r,this.element=s,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(Wi.add(this),Md||(Md=!0,We.read(Wy),We.resolveKeyframes(zy))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:i,motionValue:r}=this;if(e[0]===null){const s=r==null?void 0:r.get(),o=e[e.length-1];if(s!==void 0)e[0]=s;else if(i&&n){const a=i.readValue(n,o);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=o),r&&s===void 0&&r.set(e[0])}PE(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Wi.delete(this)}cancel(){this.state==="scheduled"&&(Wi.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const jE=t=>t.startsWith("--");function LE(t,e,n){jE(e)?t.style.setProperty(e,n):t.style[e]=n}const VE=qu(()=>window.ScrollTimeline!==void 0),FE={};function UE(t,e){const n=qu(t);return()=>FE[e]??n()}const qy=UE(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Ms=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,Om={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Ms([0,.65,.55,1]),circOut:Ms([.55,0,1,.45]),backIn:Ms([.31,.01,.66,-.59]),backOut:Ms([.33,1.53,.69,.99])};function Ky(t,e){if(t)return typeof t=="function"?qy()?By(t,e):"ease-out":My(t)?Ms(t):Array.isArray(t)?t.map(n=>Ky(n,e)||Om.easeOut):Om[t]}function BE(t,e,n,{delay:i=0,duration:r=300,repeat:s=0,repeatType:o="loop",ease:a="easeOut",times:c}={},l=void 0){const d={[e]:n};c&&(d.offset=c);const u=Ky(a,r);Array.isArray(u)&&(d.easing=u);const f={delay:i,duration:r,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:s+1,direction:o==="reverse"?"alternate":"normal"};return l&&(f.pseudoElement=l),t.animate(d,f)}function Gy(t){return typeof t=="function"&&"applyToOptions"in t}function $E({type:t,...e}){return Gy(t)&&qy()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class HE extends sf{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:i,keyframes:r,pseudoElement:s,allowFlatten:o=!1,finalKeyframe:a,onComplete:c}=e;this.isPseudoElement=!!s,this.allowFlatten=o,this.options=e,Yn(typeof e.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const l=$E(e);this.animation=BE(n,i,r,l,s),l.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!s){const d=rf(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):LE(n,i,d),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,n;(n=(e=this.animation).finish)==null||n.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var e,n;this.isPseudoElement||(n=(e=this.animation).commitStyles)==null||n.call(e)}get duration(){var n,i;const e=((i=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:i.call(n).duration)||0;return En(Number(e))}get time(){return En(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=un(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:n}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&VE()?(this.animation.timeline=e,Xt):n(this)}}const Zy={anticipate:Py,backInOut:Ey,circInOut:Ay};function zE(t){return t in Zy}function WE(t){typeof t.ease=="string"&&zE(t.ease)&&(t.ease=Zy[t.ease])}const Dm=10;class qE extends HE{constructor(e){WE(e),Hy(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:i,onComplete:r,element:s,...o}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const a=new of({...o,autoplay:!1}),c=un(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-Dm).value,a.sample(c).value,Dm),a.stop()}}const jm=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(vi.test(t)||t==="0")&&!t.startsWith("url("));function KE(t){const e=t[0];if(t.length===1)return!0;for(let n=0;n<t.length;n++)if(t[n]!==e)return!0}function GE(t,e,n,i){const r=t[0];if(r===null)return!1;if(e==="display"||e==="visibility")return!0;const s=t[t.length-1],o=jm(r,e),a=jm(s,e);return is(o===a,`You are trying to animate ${e} from "${r}" to "${s}". "${o?s:r}" is not an animatable value.`,"value-not-animatable"),!o||!a?!1:KE(t)||(n==="spring"||Gy(n))&&i}function Od(t){t.duration=0,t.type}const ZE=new Set(["opacity","clipPath","filter","transform"]),YE=qu(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function JE(t){var d;const{motionValue:e,name:n,repeatDelay:i,repeatType:r,damping:s,type:o}=t;if(!(((d=e==null?void 0:e.owner)==null?void 0:d.current)instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:l}=e.owner.getProps();return YE()&&n&&ZE.has(n)&&(n!=="transform"||!l)&&!c&&!i&&r!=="mirror"&&s!==0&&o!=="inertia"}const XE=40;class QE extends sf{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:r=0,repeatDelay:s=0,repeatType:o="loop",keyframes:a,name:c,motionValue:l,element:d,...u}){var g;super(),this.stop=()=>{var h,y;this._animation&&(this._animation.stop(),(h=this.stopTimeline)==null||h.call(this)),(y=this.keyframeResolver)==null||y.cancel()},this.createdAt=Dt.now();const f={autoplay:e,delay:n,type:i,repeat:r,repeatDelay:s,repeatType:o,name:c,motionValue:l,element:d,...u},p=(d==null?void 0:d.KeyframeResolver)||af;this.keyframeResolver=new p(a,(h,y,b)=>this.onKeyframesResolved(h,y,f,!b),c,l,d),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(e,n,i,r){this.keyframeResolver=void 0;const{name:s,type:o,velocity:a,delay:c,isHandoff:l,onUpdate:d}=i;this.resolvedAt=Dt.now(),GE(e,s,o,a)||((Jn.instantAnimations||!c)&&(d==null||d(rf(e,i,n))),e[0]=e[e.length-1],Od(i),i.repeat=0);const f={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>XE?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},p=!l&&JE(f)?new qE({...f,element:f.motionValue.owner.current}):new of(f);p.finished.then(()=>this.notifyFinished()).catch(Xt),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),DE()),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var e;this._animation&&this.animation.cancel(),(e=this.keyframeResolver)==null||e.cancel()}}const eP=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function tP(t){const e=eP.exec(t);if(!e)return[,];const[,n,i,r]=e;return[`--${n??i}`,r]}const nP=4;function Yy(t,e,n=1){Yn(n<=nP,`Max CSS variable fallback depth detected in property "${t}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[i,r]=tP(t);if(!i)return;const s=window.getComputedStyle(e).getPropertyValue(i);if(s){const o=s.trim();return yy(o)?parseFloat(o):o}return Xu(r)?Yy(r,e,n+1):r}function cf(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Jy=new Set(["width","height","top","left","right","bottom",...ss]),iP={test:t=>t==="auto",parse:t=>t},Xy=t=>e=>e.test(t),Qy=[rs,he,Pn,oi,K2,q2,iP],Lm=t=>Qy.find(Xy(t));function rP(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||xy(t):!0}const sP=new Set(["brightness","contrast","saturate","opacity"]);function oP(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Qu)||[];if(!i)return t;const r=n.replace(i,"");let s=sP.has(e)?1:0;return i!==n&&(s*=100),e+"("+s+r+")"}const aP=/\b([a-z-]*)\(.*?\)/gu,Dd={...vi,getAnimatableNone:t=>{const e=t.match(aP);return e?e.map(oP).join(" "):t}},Vm={...rs,transform:Math.round},cP={rotate:oi,rotateX:oi,rotateY:oi,rotateZ:oi,scale:To,scaleX:To,scaleY:To,scaleZ:To,skew:oi,skewX:oi,skewY:oi,distance:he,translateX:he,translateY:he,translateZ:he,x:he,y:he,z:he,perspective:he,transformPerspective:he,opacity:qs,originX:Tm,originY:Tm,originZ:he},lf={borderWidth:he,borderTopWidth:he,borderRightWidth:he,borderBottomWidth:he,borderLeftWidth:he,borderRadius:he,radius:he,borderTopLeftRadius:he,borderTopRightRadius:he,borderBottomRightRadius:he,borderBottomLeftRadius:he,width:he,maxWidth:he,height:he,maxHeight:he,top:he,right:he,bottom:he,left:he,padding:he,paddingTop:he,paddingRight:he,paddingBottom:he,paddingLeft:he,margin:he,marginTop:he,marginRight:he,marginBottom:he,marginLeft:he,backgroundPositionX:he,backgroundPositionY:he,...cP,zIndex:Vm,fillOpacity:qs,strokeOpacity:qs,numOctaves:Vm},lP={...lf,color:ct,backgroundColor:ct,outlineColor:ct,fill:ct,stroke:ct,borderColor:ct,borderTopColor:ct,borderRightColor:ct,borderBottomColor:ct,borderLeftColor:ct,filter:Dd,WebkitFilter:Dd},eb=t=>lP[t];function tb(t,e){let n=eb(t);return n!==Dd&&(n=vi),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const dP=new Set(["auto","none","0"]);function uP(t,e,n){let i=0,r;for(;i<t.length&&!r;){const s=t[i];typeof s=="string"&&!dP.has(s)&&Ks(s).values.length&&(r=t[i]),i++}if(r&&n)for(const s of e)t[s]=tb(n,r)}class fP extends af{constructor(e,n,i,r,s){super(e,n,i,r,s,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<e.length;c++){let l=e[c];if(typeof l=="string"&&(l=l.trim(),Xu(l))){const d=Yy(l,n.current);d!==void 0&&(e[c]=d),c===e.length-1&&(this.finalKeyframe=l)}}if(this.resolveNoneKeyframes(),!Jy.has(i)||e.length!==2)return;const[r,s]=e,o=Lm(r),a=Lm(s);if(o!==a)if(Nm(o)&&Nm(a))for(let c=0;c<e.length;c++){const l=e[c];typeof l=="string"&&(e[c]=parseFloat(l))}else zi[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let r=0;r<e.length;r++)(e[r]===null||rP(e[r]))&&i.push(r);i.length&&uP(e,i,n)}measureInitialState(){const{element:e,unresolvedKeyframes:n,name:i}=this;if(!e||!e.current)return;i==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=zi[i](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&e.getValue(i,r).jump(r,!1)}measureEndState(){var a;const{element:e,name:n,unresolvedKeyframes:i}=this;if(!e||!e.current)return;const r=e.getValue(n);r&&r.jump(this.measuredOrigin,!1);const s=i.length-1,o=i[s];i[s]=zi[n](e.measureViewportBox(),window.getComputedStyle(e.current)),o!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=o),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([c,l])=>{e.getValue(c).set(l)}),this.resolveNoneKeyframes()}}function hP(t,e,n){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let i=document;const r=(n==null?void 0:n[t])??i.querySelectorAll(t);return r?Array.from(r):[]}return Array.from(t)}const nb=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function ib(t){return by(t)&&"offsetHeight"in t}const Fm=30,mP=t=>!isNaN(parseFloat(t));class pP{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=i=>{var s;const r=Dt.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((s=this.events.change)==null||s.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=Dt.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=mP(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!=="production"&&Gu(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",e)}on(e,n){this.events[e]||(this.events[e]=new Ku);const i=this.events[e].add(n);return e==="change"?()=>{i(),We.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,n){this.passiveEffect=e,this.stopPassiveEffect=n}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,n,i){this.set(n),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-i}jump(e,n=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=Dt.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Fm)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Fm);return Sy(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(e){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=e(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var e,n;(e=this.dependents)==null||e.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Kr(t,e){return new pP(t,e)}const{schedule:df}=_y(queueMicrotask,!1),sn={x:!1,y:!1};function rb(){return sn.x||sn.y}function gP(t){return t==="x"||t==="y"?sn[t]?null:(sn[t]=!0,()=>{sn[t]=!1}):sn.x||sn.y?null:(sn.x=sn.y=!0,()=>{sn.x=sn.y=!1})}function sb(t,e){const n=hP(t),i=new AbortController,r={passive:!0,...e,signal:i.signal};return[n,r,()=>i.abort()]}function Um(t){return!(t.pointerType==="touch"||rb())}function vP(t,e,n={}){const[i,r,s]=sb(t,n),o=a=>{if(!Um(a))return;const{target:c}=a,l=e(c,a);if(typeof l!="function"||!c)return;const d=u=>{Um(u)&&(l(u),c.removeEventListener("pointerleave",d))};c.addEventListener("pointerleave",d,r)};return i.forEach(a=>{a.addEventListener("pointerenter",o,r)}),s}const ob=(t,e)=>e?t===e?!0:ob(t,e.parentElement):!1,uf=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,yP=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function bP(t){return yP.has(t.tagName)||t.tabIndex!==-1}const aa=new WeakSet;function Bm(t){return e=>{e.key==="Enter"&&t(e)}}function nl(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const xP=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=Bm(()=>{if(aa.has(n))return;nl(n,"down");const r=Bm(()=>{nl(n,"up")}),s=()=>nl(n,"cancel");n.addEventListener("keyup",r,e),n.addEventListener("blur",s,e)});n.addEventListener("keydown",i,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),e)};function $m(t){return uf(t)&&!rb()}function SP(t,e,n={}){const[i,r,s]=sb(t,n),o=a=>{const c=a.currentTarget;if(!$m(a))return;aa.add(c);const l=e(c,a),d=(p,g)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",f),aa.has(c)&&aa.delete(c),$m(p)&&typeof l=="function"&&l(p,{success:g})},u=p=>{d(p,c===window||c===document||n.useGlobalTarget||ob(c,p.target))},f=p=>{d(p,!1)};window.addEventListener("pointerup",u,r),window.addEventListener("pointercancel",f,r)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",o,r),ib(a)&&(a.addEventListener("focus",l=>xP(l,r)),!bP(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),s}function ab(t){return by(t)&&"ownerSVGElement"in t}function wP(t){return ab(t)&&t.tagName==="svg"}const Tt=t=>!!(t&&t.getVelocity),CP=[...Qy,ct,vi],kP=t=>CP.find(Xy(t)),ff=R.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class TP extends v.Component{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,r=ib(i)&&i.offsetWidth||0,s=this.props.sizeRef.current;s.height=n.offsetHeight||0,s.width=n.offsetWidth||0,s.top=n.offsetTop,s.left=n.offsetLeft,s.right=r-s.width-s.left}return null}componentDidUpdate(){}render(){return this.props.children}}function EP({children:t,isPresent:e,anchorX:n,root:i}){const r=R.useId(),s=R.useRef(null),o=R.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=R.useContext(ff);return R.useInsertionEffect(()=>{const{width:c,height:l,top:d,left:u,right:f}=o.current;if(e||!s.current||!c||!l)return;const p=n==="left"?`left: ${u}`:`right: ${f}`;s.current.dataset.motionPopId=r;const g=document.createElement("style");a&&(g.nonce=a);const h=i??document.head;return h.appendChild(g),g.sheet&&g.sheet.insertRule(`
79
68
  [data-motion-pop-id="${r}"] {
80
69
  position: absolute !important;
81
70
  width: ${c}px !important;
@@ -125,7 +114,7 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
125
114
  `)},Pg=function(){var t=parseInt(document.body.getAttribute($r)||"0",10);return isFinite(t)?t:0},e8=function(){v.useEffect(function(){return document.body.setAttribute($r,(Pg()+1).toString()),function(){var t=Pg()-1;t<=0?document.body.removeAttribute($r):document.body.setAttribute($r,t.toString())}},[])},t8=function(t){var e=t.noRelative,n=t.noImportant,i=t.gapMode,r=i===void 0?"margin":i;e8();var s=v.useMemo(function(){return JO(r)},[r]);return v.createElement(XO,{styles:QO(s,!e,r,n?"":"!important")})},ru=!1;if(typeof window<"u")try{var Lo=Object.defineProperty({},"passive",{get:function(){return ru=!0,!0}});window.addEventListener("test",Lo,Lo),window.removeEventListener("test",Lo,Lo)}catch{ru=!1}var mr=ru?{passive:!1}:!1,n8=function(t){return t.tagName==="TEXTAREA"},zx=function(t,e){if(!(t instanceof Element))return!1;var n=window.getComputedStyle(t);return n[e]!=="hidden"&&!(n.overflowY===n.overflowX&&!n8(t)&&n[e]==="visible")},i8=function(t){return zx(t,"overflowY")},r8=function(t){return zx(t,"overflowX")},Rg=function(t,e){var n=e.ownerDocument,i=e;do{typeof ShadowRoot<"u"&&i instanceof ShadowRoot&&(i=i.host);var r=Wx(t,i);if(r){var s=qx(t,i),o=s[1],a=s[2];if(o>a)return!0}i=i.parentNode}while(i&&i!==n.body);return!1},s8=function(t){var e=t.scrollTop,n=t.scrollHeight,i=t.clientHeight;return[e,n,i]},o8=function(t){var e=t.scrollLeft,n=t.scrollWidth,i=t.clientWidth;return[e,n,i]},Wx=function(t,e){return t==="v"?i8(e):r8(e)},qx=function(t,e){return t==="v"?s8(e):o8(e)},a8=function(t,e){return t==="h"&&e==="rtl"?-1:1},c8=function(t,e,n,i,r){var s=a8(t,window.getComputedStyle(e).direction),o=s*i,a=n.target,c=e.contains(a),l=!1,d=o>0,u=0,f=0;do{if(!a)break;var p=qx(t,a),g=p[0],h=p[1],y=p[2],b=h-y-s*g;(g||b)&&Wx(t,a)&&(u+=b,f+=g);var w=a.parentNode;a=w&&w.nodeType===Node.DOCUMENT_FRAGMENT_NODE?w.host:w}while(!c&&a!==document.body||c&&(e.contains(a)||e===a));return(d&&Math.abs(u)<1||!d&&Math.abs(f)<1)&&(l=!0),l},Vo=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},Ag=function(t){return[t.deltaX,t.deltaY]},Ig=function(t){return t&&"current"in t?t.current:t},l8=function(t,e){return t[0]===e[0]&&t[1]===e[1]},d8=function(t){return`
126
115
  .block-interactivity-`.concat(t,` {pointer-events: none;}
127
116
  .allow-interactivity-`).concat(t,` {pointer-events: all;}
128
- `)},u8=0,pr=[];function f8(t){var e=v.useRef([]),n=v.useRef([0,0]),i=v.useRef(),r=v.useState(u8++)[0],s=v.useState(Hx)[0],o=v.useRef(t);v.useEffect(function(){o.current=t},[t]),v.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(r));var h=NO([t.lockRef.current],(t.shards||[]).map(Ig),!0).filter(Boolean);return h.forEach(function(y){return y.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),h.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(r))})}}},[t.inert,t.lockRef.current,t.shards]);var a=v.useCallback(function(h,y){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!o.current.allowPinchZoom;var b=Vo(h),w=n.current,C="deltaX"in h?h.deltaX:w[0]-b[0],S="deltaY"in h?h.deltaY:w[1]-b[1],x,T=h.target,E=Math.abs(C)>Math.abs(S)?"h":"v";if("touches"in h&&E==="h"&&T.type==="range")return!1;var P=Rg(E,T);if(!P)return!0;if(P?x=E:(x=E==="v"?"h":"v",P=Rg(E,T)),!P)return!1;if(!i.current&&"changedTouches"in h&&(C||S)&&(i.current=x),!x)return!0;var _=i.current||x;return c8(_,y,h,_==="h"?C:S)},[]),c=v.useCallback(function(h){var y=h;if(!(!pr.length||pr[pr.length-1]!==s)){var b="deltaY"in y?Ag(y):Vo(y),w=e.current.filter(function(x){return x.name===y.type&&(x.target===y.target||y.target===x.shadowParent)&&l8(x.delta,b)})[0];if(w&&w.should){y.cancelable&&y.preventDefault();return}if(!w){var C=(o.current.shards||[]).map(Ig).filter(Boolean).filter(function(x){return x.contains(y.target)}),S=C.length>0?a(y,C[0]):!o.current.noIsolation;S&&y.cancelable&&y.preventDefault()}}},[]),l=v.useCallback(function(h,y,b,w){var C={name:h,delta:y,target:b,should:w,shadowParent:h8(b)};e.current.push(C),setTimeout(function(){e.current=e.current.filter(function(S){return S!==C})},1)},[]),d=v.useCallback(function(h){n.current=Vo(h),i.current=void 0},[]),u=v.useCallback(function(h){l(h.type,Ag(h),h.target,a(h,t.lockRef.current))},[]),f=v.useCallback(function(h){l(h.type,Vo(h),h.target,a(h,t.lockRef.current))},[]);v.useEffect(function(){return pr.push(s),t.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:f}),document.addEventListener("wheel",c,mr),document.addEventListener("touchmove",c,mr),document.addEventListener("touchstart",d,mr),function(){pr=pr.filter(function(h){return h!==s}),document.removeEventListener("wheel",c,mr),document.removeEventListener("touchmove",c,mr),document.removeEventListener("touchstart",d,mr)}},[]);var p=t.removeScrollBar,g=t.inert;return v.createElement(v.Fragment,null,g?v.createElement(s,{styles:d8(r)}):null,p?v.createElement(t8,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function h8(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const m8=$O($x,f8);var Kx=v.forwardRef(function(t,e){return v.createElement(ac,Cn({},t,{ref:e,sideCar:m8}))});Kx.classNames=ac.classNames;var p8=[" ","Enter","ArrowUp","ArrowDown"],g8=[" ","Enter"],tr="Select",[cc,lc,v8]=D_(tr),[us,jL]=Df(tr,[v8,Rx]),dc=Rx(),[y8,Ai]=us(tr),[b8,x8]=us(tr),Gx=t=>{const{__scopeSelect:e,children:n,open:i,defaultOpen:r,onOpenChange:s,value:o,defaultValue:a,onValueChange:c,dir:l,name:d,autoComplete:u,disabled:f,required:p,form:g}=t,h=dc(e),[y,b]=v.useState(null),[w,C]=v.useState(null),[S,x]=v.useState(!1),T=L_(l),[E,P]=Qd({prop:i,defaultProp:r??!1,onChange:s,caller:tr}),[_,k]=Qd({prop:o,defaultProp:a,onChange:c,caller:tr}),I=v.useRef(null),N=y?g||!!y.closest("form"):!0,[K,J]=v.useState(new Set),se=Array.from(K).map(ie=>ie.props.value).join(";");return m.jsx(SO,{...h,children:m.jsxs(y8,{required:p,scope:e,trigger:y,onTriggerChange:b,valueNode:w,onValueNodeChange:C,valueNodeHasChildren:S,onValueNodeHasChildrenChange:x,contentId:jf(),value:_,onValueChange:k,open:E,onOpenChange:P,dir:T,triggerPointerDownPosRef:I,disabled:f,children:[m.jsx(cc.Provider,{scope:e,children:m.jsx(b8,{scope:t.__scopeSelect,onNativeOptionAdd:v.useCallback(ie=>{J(X=>new Set(X).add(ie))},[]),onNativeOptionRemove:v.useCallback(ie=>{J(X=>{const O=new Set(X);return O.delete(ie),O})},[]),children:n})}),N?m.jsxs(gS,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:u,value:_,onChange:ie=>k(ie.target.value),disabled:f,form:g,children:[_===void 0?m.jsx("option",{value:""}):null,Array.from(K)]},se):null]})})};Gx.displayName=tr;var Zx="SelectTrigger",Yx=v.forwardRef((t,e)=>{const{__scopeSelect:n,disabled:i=!1,...r}=t,s=dc(n),o=Ai(Zx,n),a=o.disabled||i,c=xt(e,o.onTriggerChange),l=lc(n),d=v.useRef("touch"),[u,f,p]=yS(h=>{const y=l().filter(C=>!C.disabled),b=y.find(C=>C.value===o.value),w=bS(y,h,b);w!==void 0&&o.onValueChange(w.value)}),g=h=>{a||(o.onOpenChange(!0),p()),h&&(o.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})};return m.jsx(wO,{asChild:!0,...s,children:m.jsx(et.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":vS(o.value)?"":void 0,...r,ref:c,onClick:it(r.onClick,h=>{h.currentTarget.focus(),d.current!=="mouse"&&g(h)}),onPointerDown:it(r.onPointerDown,h=>{d.current=h.pointerType;const y=h.target;y.hasPointerCapture(h.pointerId)&&y.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(g(h),h.preventDefault())}),onKeyDown:it(r.onKeyDown,h=>{const y=u.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&f(h.key),!(y&&h.key===" ")&&p8.includes(h.key)&&(g(),h.preventDefault())})})})});Yx.displayName=Zx;var Jx="SelectValue",Xx=v.forwardRef((t,e)=>{const{__scopeSelect:n,className:i,style:r,children:s,placeholder:o="",...a}=t,c=Ai(Jx,n),{onValueNodeHasChildrenChange:l}=c,d=s!==void 0,u=xt(e,c.onValueNodeChange);return Lt(()=>{l(d)},[l,d]),m.jsx(et.span,{...a,ref:u,style:{pointerEvents:"none"},children:vS(c.value)?m.jsx(m.Fragment,{children:o}):s})});Xx.displayName=Jx;var S8="SelectIcon",Qx=v.forwardRef((t,e)=>{const{__scopeSelect:n,children:i,...r}=t;return m.jsx(et.span,{"aria-hidden":!0,...r,ref:e,children:i||"▼"})});Qx.displayName=S8;var w8="SelectPortal",eS=t=>m.jsx(Lx,{asChild:!0,...t});eS.displayName=w8;var nr="SelectContent",tS=v.forwardRef((t,e)=>{const n=Ai(nr,t.__scopeSelect),[i,r]=v.useState();if(Lt(()=>{r(new DocumentFragment)},[]),!n.open){const s=i;return s?qa.createPortal(m.jsx(nS,{scope:t.__scopeSelect,children:m.jsx(cc.Slot,{scope:t.__scopeSelect,children:m.jsx("div",{children:t.children})})}),s):null}return m.jsx(iS,{...t,ref:e})});tS.displayName=nr;var on=10,[nS,Ii]=us(nr),C8="SelectContentImpl",k8=eo("SelectContent.RemoveScroll"),iS=v.forwardRef((t,e)=>{const{__scopeSelect:n,position:i="item-aligned",onCloseAutoFocus:r,onEscapeKeyDown:s,onPointerDownOutside:o,side:a,sideOffset:c,align:l,alignOffset:d,arrowPadding:u,collisionBoundary:f,collisionPadding:p,sticky:g,hideWhenDetached:h,avoidCollisions:y,...b}=t,w=Ai(nr,n),[C,S]=v.useState(null),[x,T]=v.useState(null),E=xt(e,D=>S(D)),[P,_]=v.useState(null),[k,I]=v.useState(null),N=lc(n),[K,J]=v.useState(!1),se=v.useRef(!1);v.useEffect(()=>{if(C)return _O(C)},[C]),q_();const ie=v.useCallback(D=>{const[$,...Q]=N().map(z=>z.ref.current),[W]=Q.slice(-1),ce=document.activeElement;for(const z of D)if(z===ce||(z==null||z.scrollIntoView({block:"nearest"}),z===$&&x&&(x.scrollTop=0),z===W&&x&&(x.scrollTop=x.scrollHeight),z==null||z.focus(),document.activeElement!==ce))return},[N,x]),X=v.useCallback(()=>ie([P,C]),[ie,P,C]);v.useEffect(()=>{K&&X()},[K,X]);const{onOpenChange:O,triggerPointerDownPosRef:oe}=w;v.useEffect(()=>{if(C){let D={x:0,y:0};const $=W=>{var ce,z;D={x:Math.abs(Math.round(W.pageX)-(((ce=oe.current)==null?void 0:ce.x)??0)),y:Math.abs(Math.round(W.pageY)-(((z=oe.current)==null?void 0:z.y)??0))}},Q=W=>{D.x<=10&&D.y<=10?W.preventDefault():C.contains(W.target)||O(!1),document.removeEventListener("pointermove",$),oe.current=null};return oe.current!==null&&(document.addEventListener("pointermove",$),document.addEventListener("pointerup",Q,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",Q,{capture:!0})}}},[C,O,oe]),v.useEffect(()=>{const D=()=>O(!1);return window.addEventListener("blur",D),window.addEventListener("resize",D),()=>{window.removeEventListener("blur",D),window.removeEventListener("resize",D)}},[O]);const[L,F]=yS(D=>{const $=N().filter(ce=>!ce.disabled),Q=$.find(ce=>ce.ref.current===document.activeElement),W=bS($,D,Q);W&&setTimeout(()=>W.ref.current.focus())}),te=v.useCallback((D,$,Q)=>{const W=!se.current&&!Q;(w.value!==void 0&&w.value===$||W)&&(_(D),W&&(se.current=!0))},[w.value]),j=v.useCallback(()=>C==null?void 0:C.focus(),[C]),q=v.useCallback((D,$,Q)=>{const W=!se.current&&!Q;(w.value!==void 0&&w.value===$||W)&&I(D)},[w.value]),ee=i==="popper"?su:rS,G=ee===su?{side:a,sideOffset:c,align:l,alignOffset:d,arrowPadding:u,collisionBoundary:f,collisionPadding:p,sticky:g,hideWhenDetached:h,avoidCollisions:y}:{};return m.jsx(nS,{scope:n,content:C,viewport:x,onViewportChange:T,itemRefCallback:te,selectedItem:P,onItemLeave:j,itemTextRefCallback:q,focusSelectedItem:X,selectedItemText:k,position:i,isPositioned:K,searchRef:L,children:m.jsx(Kx,{as:k8,allowPinchZoom:!0,children:m.jsx(hx,{asChild:!0,trapped:w.open,onMountAutoFocus:D=>{D.preventDefault()},onUnmountAutoFocus:it(r,D=>{var $;($=w.trigger)==null||$.focus({preventScroll:!0}),D.preventDefault()}),children:m.jsx(ux,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:D=>D.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:m.jsx(ee,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:D=>D.preventDefault(),...b,...G,onPlaced:()=>J(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:it(b.onKeyDown,D=>{const $=D.ctrlKey||D.altKey||D.metaKey;if(D.key==="Tab"&&D.preventDefault(),!$&&D.key.length===1&&F(D.key),["ArrowUp","ArrowDown","Home","End"].includes(D.key)){let W=N().filter(ce=>!ce.disabled).map(ce=>ce.ref.current);if(["ArrowUp","End"].includes(D.key)&&(W=W.slice().reverse()),["ArrowUp","ArrowDown"].includes(D.key)){const ce=D.target,z=W.indexOf(ce);W=W.slice(z+1)}setTimeout(()=>ie(W)),D.preventDefault()}})})})})})})});iS.displayName=C8;var T8="SelectItemAlignedPosition",rS=v.forwardRef((t,e)=>{const{__scopeSelect:n,onPlaced:i,...r}=t,s=Ai(nr,n),o=Ii(nr,n),[a,c]=v.useState(null),[l,d]=v.useState(null),u=xt(e,E=>d(E)),f=lc(n),p=v.useRef(!1),g=v.useRef(!0),{viewport:h,selectedItem:y,selectedItemText:b,focusSelectedItem:w}=o,C=v.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&l&&h&&y&&b){const E=s.trigger.getBoundingClientRect(),P=l.getBoundingClientRect(),_=s.valueNode.getBoundingClientRect(),k=b.getBoundingClientRect();if(s.dir!=="rtl"){const ce=k.left-P.left,z=_.left-ce,me=E.left-z,Ee=E.width+me,qe=Math.max(Ee,P.width),Ct=window.innerWidth-on,gn=cg(z,[on,Math.max(on,Ct-qe)]);a.style.minWidth=Ee+"px",a.style.left=gn+"px"}else{const ce=P.right-k.right,z=window.innerWidth-_.right-ce,me=window.innerWidth-E.right-z,Ee=E.width+me,qe=Math.max(Ee,P.width),Ct=window.innerWidth-on,gn=cg(z,[on,Math.max(on,Ct-qe)]);a.style.minWidth=Ee+"px",a.style.right=gn+"px"}const I=f(),N=window.innerHeight-on*2,K=h.scrollHeight,J=window.getComputedStyle(l),se=parseInt(J.borderTopWidth,10),ie=parseInt(J.paddingTop,10),X=parseInt(J.borderBottomWidth,10),O=parseInt(J.paddingBottom,10),oe=se+ie+K+O+X,L=Math.min(y.offsetHeight*5,oe),F=window.getComputedStyle(h),te=parseInt(F.paddingTop,10),j=parseInt(F.paddingBottom,10),q=E.top+E.height/2-on,ee=N-q,G=y.offsetHeight/2,D=y.offsetTop+G,$=se+ie+D,Q=oe-$;if($<=q){const ce=I.length>0&&y===I[I.length-1].ref.current;a.style.bottom="0px";const z=l.clientHeight-h.offsetTop-h.offsetHeight,me=Math.max(ee,G+(ce?j:0)+z+X),Ee=$+me;a.style.height=Ee+"px"}else{const ce=I.length>0&&y===I[0].ref.current;a.style.top="0px";const me=Math.max(q,se+h.offsetTop+(ce?te:0)+G)+Q;a.style.height=me+"px",h.scrollTop=$-q+h.offsetTop}a.style.margin=`${on}px 0`,a.style.minHeight=L+"px",a.style.maxHeight=N+"px",i==null||i(),requestAnimationFrame(()=>p.current=!0)}},[f,s.trigger,s.valueNode,a,l,h,y,b,s.dir,i]);Lt(()=>C(),[C]);const[S,x]=v.useState();Lt(()=>{l&&x(window.getComputedStyle(l).zIndex)},[l]);const T=v.useCallback(E=>{E&&g.current===!0&&(C(),w==null||w(),g.current=!1)},[C,w]);return m.jsx(P8,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:T,children:m.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:m.jsx(et.div,{...r,ref:u,style:{boxSizing:"border-box",maxHeight:"100%",...r.style}})})})});rS.displayName=T8;var E8="SelectPopperPosition",su=v.forwardRef((t,e)=>{const{__scopeSelect:n,align:i="start",collisionPadding:r=on,...s}=t,o=dc(n);return m.jsx(CO,{...o,...s,ref:e,align:i,collisionPadding:r,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});su.displayName=E8;var[P8,qf]=us(nr,{}),ou="SelectViewport",sS=v.forwardRef((t,e)=>{const{__scopeSelect:n,nonce:i,...r}=t,s=Ii(ou,n),o=qf(ou,n),a=xt(e,s.onViewportChange),c=v.useRef(0);return m.jsxs(m.Fragment,{children:[m.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:i}),m.jsx(cc.Slot,{scope:n,children:m.jsx(et.div,{"data-radix-select-viewport":"",role:"presentation",...r,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...r.style},onScroll:it(r.onScroll,l=>{const d=l.currentTarget,{contentWrapper:u,shouldExpandOnScrollRef:f}=o;if(f!=null&&f.current&&u){const p=Math.abs(c.current-d.scrollTop);if(p>0){const g=window.innerHeight-on*2,h=parseFloat(u.style.minHeight),y=parseFloat(u.style.height),b=Math.max(h,y);if(b<g){const w=b+p,C=Math.min(g,w),S=w-C;u.style.height=C+"px",u.style.bottom==="0px"&&(d.scrollTop=S>0?S:0,u.style.justifyContent="flex-end")}}}c.current=d.scrollTop})})})]})});sS.displayName=ou;var oS="SelectGroup",[R8,A8]=us(oS),I8=v.forwardRef((t,e)=>{const{__scopeSelect:n,...i}=t,r=jf();return m.jsx(R8,{scope:n,id:r,children:m.jsx(et.div,{role:"group","aria-labelledby":r,...i,ref:e})})});I8.displayName=oS;var aS="SelectLabel",M8=v.forwardRef((t,e)=>{const{__scopeSelect:n,...i}=t,r=A8(aS,n);return m.jsx(et.div,{id:r.id,...i,ref:e})});M8.displayName=aS;var Ua="SelectItem",[_8,cS]=us(Ua),lS=v.forwardRef((t,e)=>{const{__scopeSelect:n,value:i,disabled:r=!1,textValue:s,...o}=t,a=Ai(Ua,n),c=Ii(Ua,n),l=a.value===i,[d,u]=v.useState(s??""),[f,p]=v.useState(!1),g=xt(e,w=>{var C;return(C=c.itemRefCallback)==null?void 0:C.call(c,w,i,r)}),h=jf(),y=v.useRef("touch"),b=()=>{r||(a.onValueChange(i),a.onOpenChange(!1))};if(i==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return m.jsx(_8,{scope:n,value:i,disabled:r,textId:h,isSelected:l,onItemTextChange:v.useCallback(w=>{u(C=>C||((w==null?void 0:w.textContent)??"").trim())},[]),children:m.jsx(cc.ItemSlot,{scope:n,value:i,disabled:r,textValue:d,children:m.jsx(et.div,{role:"option","aria-labelledby":h,"data-highlighted":f?"":void 0,"aria-selected":l&&f,"data-state":l?"checked":"unchecked","aria-disabled":r||void 0,"data-disabled":r?"":void 0,tabIndex:r?void 0:-1,...o,ref:g,onFocus:it(o.onFocus,()=>p(!0)),onBlur:it(o.onBlur,()=>p(!1)),onClick:it(o.onClick,()=>{y.current!=="mouse"&&b()}),onPointerUp:it(o.onPointerUp,()=>{y.current==="mouse"&&b()}),onPointerDown:it(o.onPointerDown,w=>{y.current=w.pointerType}),onPointerMove:it(o.onPointerMove,w=>{var C;y.current=w.pointerType,r?(C=c.onItemLeave)==null||C.call(c):y.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:it(o.onPointerLeave,w=>{var C;w.currentTarget===document.activeElement&&((C=c.onItemLeave)==null||C.call(c))}),onKeyDown:it(o.onKeyDown,w=>{var S;((S=c.searchRef)==null?void 0:S.current)!==""&&w.key===" "||(g8.includes(w.key)&&b(),w.key===" "&&w.preventDefault())})})})})});lS.displayName=Ua;var _s="SelectItemText",dS=v.forwardRef((t,e)=>{const{__scopeSelect:n,className:i,style:r,...s}=t,o=Ai(_s,n),a=Ii(_s,n),c=cS(_s,n),l=x8(_s,n),[d,u]=v.useState(null),f=xt(e,b=>u(b),c.onItemTextChange,b=>{var w;return(w=a.itemTextRefCallback)==null?void 0:w.call(a,b,c.value,c.disabled)}),p=d==null?void 0:d.textContent,g=v.useMemo(()=>m.jsx("option",{value:c.value,disabled:c.disabled,children:p},c.value),[c.disabled,c.value,p]),{onNativeOptionAdd:h,onNativeOptionRemove:y}=l;return Lt(()=>(h(g),()=>y(g)),[h,y,g]),m.jsxs(m.Fragment,{children:[m.jsx(et.span,{id:c.textId,...s,ref:f}),c.isSelected&&o.valueNode&&!o.valueNodeHasChildren?qa.createPortal(s.children,o.valueNode):null]})});dS.displayName=_s;var uS="SelectItemIndicator",fS=v.forwardRef((t,e)=>{const{__scopeSelect:n,...i}=t;return cS(uS,n).isSelected?m.jsx(et.span,{"aria-hidden":!0,...i,ref:e}):null});fS.displayName=uS;var au="SelectScrollUpButton",hS=v.forwardRef((t,e)=>{const n=Ii(au,t.__scopeSelect),i=qf(au,t.__scopeSelect),[r,s]=v.useState(!1),o=xt(e,i.onScrollButtonChange);return Lt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const l=c.scrollTop>0;s(l)};const c=n.viewport;return a(),c.addEventListener("scroll",a),()=>c.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),r?m.jsx(pS,{...t,ref:o,onAutoScroll:()=>{const{viewport:a,selectedItem:c}=n;a&&c&&(a.scrollTop=a.scrollTop-c.offsetHeight)}}):null});hS.displayName=au;var cu="SelectScrollDownButton",mS=v.forwardRef((t,e)=>{const n=Ii(cu,t.__scopeSelect),i=qf(cu,t.__scopeSelect),[r,s]=v.useState(!1),o=xt(e,i.onScrollButtonChange);return Lt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const l=c.scrollHeight-c.clientHeight,d=Math.ceil(c.scrollTop)<l;s(d)};const c=n.viewport;return a(),c.addEventListener("scroll",a),()=>c.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),r?m.jsx(pS,{...t,ref:o,onAutoScroll:()=>{const{viewport:a,selectedItem:c}=n;a&&c&&(a.scrollTop=a.scrollTop+c.offsetHeight)}}):null});mS.displayName=cu;var pS=v.forwardRef((t,e)=>{const{__scopeSelect:n,onAutoScroll:i,...r}=t,s=Ii("SelectScrollButton",n),o=v.useRef(null),a=lc(n),c=v.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return v.useEffect(()=>()=>c(),[c]),Lt(()=>{var d;const l=a().find(u=>u.ref.current===document.activeElement);(d=l==null?void 0:l.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),m.jsx(et.div,{"aria-hidden":!0,...r,ref:e,style:{flexShrink:0,...r.style},onPointerDown:it(r.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(i,50))}),onPointerMove:it(r.onPointerMove,()=>{var l;(l=s.onItemLeave)==null||l.call(s),o.current===null&&(o.current=window.setInterval(i,50))}),onPointerLeave:it(r.onPointerLeave,()=>{c()})})}),N8="SelectSeparator",O8=v.forwardRef((t,e)=>{const{__scopeSelect:n,...i}=t;return m.jsx(et.div,{"aria-hidden":!0,...i,ref:e})});O8.displayName=N8;var lu="SelectArrow",D8=v.forwardRef((t,e)=>{const{__scopeSelect:n,...i}=t,r=dc(n),s=Ai(lu,n),o=Ii(lu,n);return s.open&&o.position==="popper"?m.jsx(kO,{...r,...i,ref:e}):null});D8.displayName=lu;var j8="SelectBubbleInput",gS=v.forwardRef(({__scopeSelect:t,value:e,...n},i)=>{const r=v.useRef(null),s=xt(i,r),o=EO(e);return v.useEffect(()=>{const a=r.current;if(!a)return;const c=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(o!==e&&d){const u=new Event("change",{bubbles:!0});d.call(a,e),a.dispatchEvent(u)}},[o,e]),m.jsx(et.select,{...n,style:{...Vx,...n.style},ref:s,defaultValue:e})});gS.displayName=j8;function vS(t){return t===""||t===void 0}function yS(t){const e=Qi(t),n=v.useRef(""),i=v.useRef(0),r=v.useCallback(o=>{const a=n.current+o;e(a),function c(l){n.current=l,window.clearTimeout(i.current),l!==""&&(i.current=window.setTimeout(()=>c(""),1e3))}(a)},[e]),s=v.useCallback(()=>{n.current="",window.clearTimeout(i.current)},[]);return v.useEffect(()=>()=>window.clearTimeout(i.current),[]),[n,r,s]}function bS(t,e,n){const r=e.length>1&&Array.from(e).every(l=>l===e[0])?e[0]:e,s=n?t.indexOf(n):-1;let o=L8(t,Math.max(s,0));r.length===1&&(o=o.filter(l=>l!==n));const c=o.find(l=>l.textValue.toLowerCase().startsWith(r.toLowerCase()));return c!==n?c:void 0}function L8(t,e){return t.map((n,i)=>t[(e+i)%t.length])}var V8=Gx,F8=Yx,U8=Xx,B8=Qx,$8=eS,H8=tS,z8=sS,W8=lS,q8=dS,K8=fS,G8=hS,Z8=mS;function Mg({...t}){return m.jsx(V8,{"data-slot":"select",...t})}function _g({...t}){return m.jsx(U8,{"data-slot":"select-value",...t})}function Ng({className:t,size:e="default",children:n,...i}){return m.jsxs(F8,{"data-slot":"select-trigger","data-size":e,className:fe(["flex w-fit cursor-pointer items-center justify-between gap-2","rounded-full px-3 py-2 text-sm whitespace-nowrap","bg-button transition-[color,border,background-color]","disabled:cursor-not-allowed disabled:opacity-50","hover:bg-muted hover:text-muted-foreground","!focus:ring-0 !focus-visible:ring-0 !focus:border-none !focus-visible:border-none !ring-0 !border-none !outline-none","aria-invalid:ring-0 dark:aria-invalid:ring-0","data-[placeholder]:text-muted-foreground","data-[size=default]:h-9 data-[size=sm]:h-8","*:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2","[&:not([class*='text-'])_svg:not([class*='text-'])]:text-muted-foreground","[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"],t),...i,children:[n,m.jsx(B8,{asChild:!0,children:m.jsx(_f,{weight:"bold",className:"size-4 transition-colors"})})]})}function Og({className:t,children:e,position:n="popper",...i}){return m.jsx($8,{children:m.jsxs(H8,{"data-slot":"select-content",className:fe(["bg-[#18182a]/90 backdrop-blur-md text-white border border-[#23233a] shadow-2xl","relative z-50 overflow-x-hidden overflow-y-auto rounded-xl","max-h-(--radix-select-content-available-height) min-w-[8rem]","origin-(--radix-select-content-transform-origin)","data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=top]:slide-in-from-bottom-2","data-[side=right]:slide-in-from-left-2","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2"],n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,...i,children:[m.jsx(Y8,{}),m.jsx(z8,{className:fe("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:e}),m.jsx(J8,{})]})})}function Dg({className:t,children:e,...n}){return m.jsxs(W8,{"data-slot":"select-item",className:fe(["relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none","cursor-pointer disabled:cursor-not-allowed","focus:bg-accent focus:text-accent-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50","*:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2","[&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"],t),...n,children:[m.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:m.jsx(K8,{children:m.jsx($1,{className:"size-4",weight:"bold"})})}),m.jsx(q8,{children:e})]})}function Y8({className:t,...e}){return m.jsx(G8,{"data-slot":"select-scroll-up-button",className:fe("flex cursor-default items-center justify-center py-1",t),...e,children:m.jsx(U1,{className:"size-4",weight:"bold"})})}function J8({className:t,...e}){return m.jsx(Z8,{"data-slot":"select-scroll-down-button",className:fe("flex cursor-default items-center justify-center py-1",t),...e,children:m.jsx(_f,{className:"size-4",weight:"bold"})})}const jg=Wa.cva(["w-full rounded-full px-3 py-2 text-sm cursor-pointer","disabled:not-allowed hover:bg-button-hover focus:bg-button-hover"],{variants:{size:{default:"w-[180px]",sm:"w-auto"}},defaultVariants:{size:"default"}});function Lg({kind:t,track:e,requestPermissions:n,onError:i,client:r,...s}){const o=s.size||"default";if(!r)return m.jsxs(Mg,{disabled:!0,children:[m.jsx(Ng,{className:fe(jg({size:o}),s.className),children:m.jsx(_g,{placeholder:`Select a ${t}`})}),m.jsx(Og,{children:m.jsx(Dg,{value:"none",children:"No devices available"})})]});const{devices:a,activeDeviceId:c,setActiveMediaDevice:l}=__(r,t==="audioinput"?"audioinput":"videoinput");return m.jsxs(Mg,{value:c,onValueChange:l,children:[m.jsx(Ng,{className:fe(jg({size:o}),s.className,"hover:bg"),children:o!=="sm"&&m.jsx(_g,{className:"font-mono text-sm",placeholder:`Select a ${t}`})}),m.jsx(Og,{children:a.map(d=>m.jsx(Dg,{value:d.deviceId,className:"font-mono text-xs",children:d.label},d.deviceId))})]})}function X8(t,e,n=!1){if(n)return Nf;switch(t){case V.Source.Microphone:return e?H1:z1;case V.Source.Camera:return e?q1:K1;case V.Source.ScreenShare:return W1;default:return v.Fragment}}function Al({source:t,pressed:e,pending:n,className:i,...r}){const s=X8(t,e??!1,n),o=t===V.Source.Microphone&&!(e??!1)&&!n,a=t===V.Source.Camera&&!(e??!1)&&!n;return v.useEffect(()=>{console.log(`TrackToggle for ${t} changed: pressed=${e}, pending=${n}, actualState=${e?"enabled":"disabled"}`)},[t,e,n]),m.jsxs(lx,{pressed:e,"aria-label":`Toggle ${t}`,className:fe(i),...r,children:[m.jsx(s,{weight:"bold",className:fe(n&&"animate-spin",o||a?"text-red-500":void 0)}),r.children]})}function Q8(t){return t?A_(t):{camera:!0,microphone:!0,screenShare:!0,data:!0}}function e6(t={}){const{controls:e,saveUserChoices:n=!0,client:i}=t,r={leave:!0,...e};if(!i)return{micTrackRef:{participant:void 0,source:V.Source.Microphone,publication:void 0},visibleControls:r,microphoneToggle:{enabled:!1,pending:!1,toggle:async()=>{}},cameraToggle:{enabled:!1,pending:!1,toggle:async()=>{}},screenShareToggle:{enabled:!1,pending:!1,toggle:async()=>{}},handleDisconnect:()=>{},handleAudioDeviceChange:()=>{},handleVideoDeviceChange:()=>{}};const{microphoneTrack:s,localParticipant:o}=I_(i),a=Q8(i);M_(i);const c=bl(i,"microphone",{onDeviceError:T=>{var E;return(E=t.onDeviceError)==null?void 0:E.call(t,{source:V.Source.Microphone,error:T})}}),l=bl(i,"camera",{onDeviceError:T=>{var E;return(E=t.onDeviceError)==null?void 0:E.call(t,{source:V.Source.Camera,error:T})}}),d=bl(i,"screenShare",{onDeviceError:T=>{var E;return(E=t.onDeviceError)==null?void 0:E.call(t,{source:V.Source.ScreenShare,error:T})}}),u=v.useMemo(()=>{let T;if(o){for(const[,E]of o.trackPublications)if(E.source===V.Source.Microphone){T=E;break}}return console.log("🎤 Creating micTrackRef:",{hasParticipant:!!o,hasPublication:!!T,isTrackSubscribed:T==null?void 0:T.isSubscribed,isMuted:T==null?void 0:T.isMuted,trackSid:T==null?void 0:T.trackSid}),{participant:o??void 0,source:V.Source.Microphone,publication:T}},[o,s]);r.microphone??(r.microphone=a.microphone),r.screenShare??(r.screenShare=a.screenShare),r.camera??(r.camera=a.camera),r.chat??(r.chat=a.data);const{saveAudioInputEnabled:f,saveAudioInputDeviceId:p,saveVideoInputEnabled:g,saveVideoInputDeviceId:h}=N_({preventSave:!n}),y=v.useCallback(()=>{i&&i.disconnect()},[i]),b=v.useCallback(T=>{p(T??"default"),i&&i.setAudioInputDevice(T)},[p,i]),w=v.useCallback(T=>{h(T??"default"),i&&i.setVideoInputDevice(T)},[h,i]),C=v.useCallback(async T=>{d.enabled&&await d.toggle(!1),await l.toggle(T),g(!l.enabled)},[l,g,d]),S=v.useCallback(async T=>{await c.toggle(T),f(!c.enabled)},[c,f]),x=v.useCallback(async T=>{l.enabled&&await l.toggle(!1),await d.toggle(T)},[l,d]);return{micTrackRef:u,visibleControls:r,cameraToggle:{...l,toggle:C},microphoneToggle:{...c,toggle:S},screenShareToggle:{...d,toggle:x},handleDisconnect:y,handleAudioDeviceChange:b,handleVideoDeviceChange:w}}const t6={card:" bg-gradient-to-br from-black to-gray-900 border border-gray-900 w-full h-full flex flex-col justify-between overflow-hidden mx-auto my-auto rounded-2xl shadow-lg",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-10 z-10 bg-gradient-to-b from-black/90 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-gray-800/20 via-transparent to-transparent",cardPurpleBlur:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-gray-600/10 to-transparent rounded-full blur-2xl",cardPinkBlur:"absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-gray-500/8 to-transparent rounded-full blur-xl",cardPulse1:"absolute -top-2 -left-2 w-6 h-6 bg-gradient-to-br from-gray-400 to-gray-500 rounded-full blur-sm opacity-20 animate-pulse",cardPulse2:"absolute -bottom-2 -right-2 w-4 h-4 bg-gradient-to-br from-gray-500 to-gray-600 rounded-full blur-sm opacity-15 animate-pulse",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-br from-black to-gray-900 rounded-2xl shadow-xl p-0 overflow-hidden h-full",text:{primary:"text-white",secondary:"text-gray-300",muted:"text-gray-400",accent:"bg-clip-text text-transparent bg-gradient-to-r from-white via-gray-200 to-gray-300"},micButton:"absolute w-20 h-20 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 mic-glow shadow-2xl group",chatButton:"absolute w-20 h-20 bg-gradient-to-br from-[#10B981] to-[#059669] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",videoButton:"absolute w-20 h-20 bg-gradient-to-br from-[#8B5CF6] to-[#EC4899] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",popupTrigger:"bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] text-white font-medium hover:from-[#2563EB] hover:to-[#7C3AED] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900",promptSlider:"absolute w-full py-3 px-2 bg-gray-900 rounded-xl text-center text-white text-sm transition-opacity duration-700 ease-in-out border border-gray-600",statusIndicator:"w-2 h-2 bg-gray-400 rounded-full animate-pulse",pulseRings:{ring1:"w-32 h-32 rounded-full border-2 border-gray-600/30 pulse-ring",ring2:"absolute w-28 h-28 rounded-full border-2 border-gray-500/20 pulse-ring",ring3:"absolute w-24 h-24 rounded-full border-2 border-gray-400/15 pulse-ring"},controlBar:"border border-gray-600 rounded-3xl py-4 flex flex-col justify-end h-full bg-gray-900/50 backdrop-blur-sm",chatInput:{container:"bg-gray-900 w-full border-gray-600",textarea:"bg-gray-800 border-none text-white placeholder-gray-400",sendButton:"bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:opacity-50 text-white",attachButton:"text-gray-400 hover:text-gray-300 hover:bg-gray-700",endButton:"bg-red-900/20 hover:bg-red-800/30 text-red-400 border-red-800"},chatMessage:{own:"bg-gray-600 text-white",other:"bg-gray-700 text-white"},chatHeader:{container:"bg-gray-900 border-gray-600",backButton:"text-gray-400 hover:text-white hover:bg-gray-700"},spinner:"w-10 h-10 animate-spin text-gray-400 mb-2",suggestedResponse:{container:"bg-gray-800 text-blue-300 border-gray-700 hover:bg-gray-700 hover:text-white"},video:{container:"bg-gradient-to-br from-black to-gray-900 text-white",header:"border-gray-700 bg-gray-900/50",headerButton:"bg-gray-800 hover:bg-gray-700 text-gray-300",statusDot:"bg-green-500 animate-pulse",controlsBackground:"bg-gray-900/80 backdrop-blur-sm border-t border-gray-700",controlEnabled:"bg-blue-600 hover:bg-blue-700 text-white",controlDisabled:"bg-gray-700 hover:bg-gray-600 text-gray-300",endCall:"bg-red-600 hover:bg-red-700 text-white",tile:"bg-gray-800 border border-gray-700 shadow-lg",placeholder:"bg-gray-800 text-gray-300",avatar:"bg-gray-700 text-gray-300",nameOverlay:"bg-black/70 text-white",mutedIndicator:"bg-red-600/80 text-white"}},n6={card:" bg-gradient-to-br from-white to-gray-50 border border-gray-200 w-full h-full flex flex-col justify-between overflow-hidden mx-auto my-auto shadow-lg",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-10 z-10 bg-gradient-to-b from-white/90 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-blue-500/5 via-transparent to-transparent",cardPurpleBlur:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-purple-500/10 to-transparent rounded-full blur-2xl",cardPinkBlur:"absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-pink-500/8 to-transparent rounded-full blur-xl",cardPulse1:"absolute -top-2 -left-2 w-6 h-6 bg-gradient-to-br from-blue-500 to-purple-500 rounded-full blur-sm opacity-30 animate-pulse",cardPulse2:"absolute -bottom-2 -right-2 w-4 h-4 bg-gradient-to-br from-pink-500 to-purple-500 rounded-full blur-sm opacity-20 animate-pulse",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-br from-white to-gray-50 rounded-2xl shadow-xl p-0 overflow-hidden h-full",text:{primary:"text-gray-900",secondary:"text-gray-700",muted:"text-gray-500",accent:"bg-clip-text text-transparent bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600"},micButton:"absolute text-white w-20 h-20 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 mic-glow shadow-2xl group",chatButton:"absolute text-white w-20 h-20 bg-gradient-to-br from-[#10B981] to-[#059669] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",videoButton:"absolute text-white w-20 h-20 bg-gradient-to-br from-[#8B5CF6] to-[#EC4899] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",popupTrigger:"bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] text-white font-medium hover:from-[#2563EB] hover:to-[#7C3AED] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-white",promptSlider:"absolute w-full py-3 px-2 bg-gray-100 rounded-xl text-center text-gray-700 text-sm transition-opacity duration-700 ease-in-out border border-gray-200",statusIndicator:"w-2 h-2 bg-green-500 rounded-full animate-pulse",pulseRings:{ring1:"w-32 h-32 rounded-full border-2 border-blue-500/20 pulse-ring",ring2:"absolute w-28 h-28 rounded-full border-2 border-purple-500/15 pulse-ring",ring3:"absolute w-24 h-24 rounded-full border-2 border-pink-500/10 pulse-ring"},controlBar:"border border-gray-200 rounded-3xl py-4 flex flex-col justify-end h-full bg-white/80 backdrop-blur-sm",chatInput:{container:"bg-white/90 border-gray-200 shadow-sm",textarea:"bg-white border-none text-gray-900 placeholder-gray-500 ",sendButton:"bg-blue-600 hover:bg-blue-700 disabled:bg-gray-300 disabled:opacity-50 text-white",attachButton:"text-gray-500 hover:text-gray-700 hover:bg-gray-100 bg-blue-50",endButton:"bg-red-50 hover:bg-red-100 text-red-600 border-red-200"},chatMessage:{own:"bg-blue-50 text-gray-900 border border-blue-100",other:"bg-gray-50 text-gray-900 border border-gray-200"},chatHeader:{container:"bg-white border-gray-200",backButton:"text-gray-500 hover:text-gray-700 hover:bg-gray-100"},spinner:"w-10 h-10 animate-spin text-blue-500 mb-2",suggestedResponse:{container:"bg-white text-blue-700 border-blue-200 hover:bg-blue-50 hover:text-blue-900"},video:{container:"bg-gradient-to-br from-white to-gray-50 text-gray-900",header:"border-gray-200 bg-white/80",headerButton:"bg-gray-100 hover:bg-gray-200 text-gray-600",statusDot:"bg-green-500 animate-pulse",controlsBackground:"bg-white/90 backdrop-blur-sm border-t border-gray-200",controlEnabled:"bg-blue-600 hover:bg-blue-700 text-white",controlDisabled:"bg-gray-200 hover:bg-gray-300 text-gray-600",endCall:"bg-red-600 hover:bg-red-700 text-white",tile:"bg-white border border-gray-200 shadow-sm",placeholder:"bg-gray-50 text-gray-600",avatar:"bg-gray-200 text-gray-600",nameOverlay:"bg-black/70 text-white",mutedIndicator:"bg-red-600/80 text-white"}},i6={card:" text-white bg-gradient-to-br from-[#171727] to-[#12121F] border border-gray-800 w-full h-full flex flex-col justify-between overflow-hidden mx-auto my-auto",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-10 z-10 bg-gradient-to-b from-[#171727]/90 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-[#3B82F6]/15 via-transparent to-transparent",cardPurpleBlur:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-[#8B5CF6]/25 to-transparent rounded-full blur-2xl",cardPinkBlur:"absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-[#EC4899]/20 to-transparent rounded-full blur-xl",cardPulse1:"absolute -top-2 -left-2 w-6 h-6 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full blur-sm opacity-50 animate-pulse",cardPulse2:"absolute -bottom-2 -right-2 w-4 h-4 bg-gradient-to-br from-[#EC4899] to-[#8B5CF6] rounded-full blur-sm opacity-40 animate-pulse",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-br from-[#171727] to-[#12121F] rounded-2xl shadow-xl p-0 overflow-hidden h-full",text:{primary:"text-white",secondary:"text-gray-300",muted:"text-gray-400",accent:"bg-clip-text text-transparent bg-gradient-to-r from-[#3B82F6] via-[#8B5CF6] to-[#EC4899]"},micButton:"absolute w-20 h-20 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 mic-glow shadow-2xl group",chatButton:"absolute w-20 h-20 bg-gradient-to-br from-[#10B981] to-[#059669] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",videoButton:"absolute w-20 h-20 bg-gradient-to-br from-[#8B5CF6] to-[#EC4899] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",popupTrigger:"bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] text-white font-medium hover:from-[#2563EB] hover:to-[#7C3AED] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900 shadow-xl",promptSlider:"absolute w-full py-3 px-2 bg-[#1E1E2E] rounded-xl text-center text-gray-200 text-sm transition-opacity duration-700 ease-in-out border border-gray-700",statusIndicator:"w-2 h-2 bg-[#10B981] rounded-full animate-pulse",pulseRings:{ring1:"w-32 h-32 rounded-full border-2 border-[#3B82F6]/40 pulse-ring",ring2:"absolute w-28 h-28 rounded-full border-2 border-[#8B5CF6]/30 pulse-ring",ring3:"absolute w-24 h-24 rounded-full border-2 border-[#EC4899]/20 pulse-ring"},controlBar:"border border-border rounded-3xl py-4 flex flex-col justify-end h-full",chatInput:{container:"bg-[#1E1E2E] border-gray-700",textarea:"bg-[#1E1E2E] border-none text-white placeholder-gray-400",sendButton:"bg-[#3B82F6] hover:bg-[#2563EB] disabled:bg-gray-600 disabled:opacity-50 text-white",attachButton:"text-gray-400 hover:text-gray-300 hover:bg-gray-700",endButton:"bg-red-900/20 hover:bg-red-800/30 text-red-400 border-red-800"},chatMessage:{own:"bg-[#1E1E2E]/80 text-white",other:"bg-[#1E1E2E] text-white border border-gray-700"},chatHeader:{container:"bg-[#1E1E2E] border-gray-700",backButton:"text-gray-400 hover:text-white hover:bg-gray-700"},spinner:"w-10 h-10 animate-spin text-blue-400 mb-2",suggestedResponse:{container:"bg-[#221f3f] text-white border-none"},video:{container:"bg-gradient-to-br from-[#171727] to-[#12121F] text-white",header:"border-gray-700 bg-[#1E1E2E]/80",headerButton:"bg-[#1E1E2E] hover:bg-gray-700 text-gray-300",statusDot:"bg-[#10B981] animate-pulse",controlsBackground:"bg-[#1E1E2E]/90 backdrop-blur-sm border-t border-gray-700",controlEnabled:"bg-[#3B82F6] hover:bg-[#2563EB] text-white",controlDisabled:"bg-gray-700 hover:bg-gray-600 text-gray-300",endCall:"bg-red-600 hover:bg-red-700 text-white",tile:"bg-[#1E1E2E] border border-gray-700 shadow-xl",placeholder:"bg-[#1E1E2E] text-gray-300",avatar:"bg-gray-700 text-gray-300",nameOverlay:"bg-black/70 text-white",mutedIndicator:"bg-red-600/80 text-white"}},Vg={dark:t6,light:n6,vox:i6};function St(t){return Vg[t]||Vg.vox}function r6({controls:t,saveUserChoices:e=!0,capabilities:n,className:i,onSendMessage:r,onChatOpenChange:s,onDisconnect:o,onDeviceError:a,theme:c="vox",client:l,...d}){const[u,f]=v.useState(!1),[p,g]=v.useState(!1),h=St(c),{micTrackRef:y,visibleControls:b,cameraToggle:w,microphoneToggle:C,screenShareToggle:S,handleAudioDeviceChange:x,handleVideoDeviceChange:T,handleDisconnect:E}=e6({controls:t,saveUserChoices:e,client:l}),P=async _=>{g(!0);try{await(r==null?void 0:r(_))}finally{g(!1)}};return v.useEffect(()=>{s==null||s(u)},[u,s]),v.useEffect(()=>{var _,k,I,N;console.log("🎤 AgentControlBar: micTrackRef changed:",{hasParticipant:!!y.participant,hasPublication:!!y.publication,source:y.source,isSubscribed:(_=y.publication)==null?void 0:_.isSubscribed,isMuted:(k=y.publication)==null?void 0:k.isMuted,trackSid:(I=y.publication)==null?void 0:I.trackSid,hasTrack:!!((N=y.publication)!=null&&N.track)})},[y]),m.jsxs("div",{"aria-label":"Voice assistant controls",className:fe(h.controlBar,i),...d,children:[n.suportsChatInput&&m.jsxs("div",{inert:!u,className:fe("overflow-hidden transition-[height] relative duration-300 ease-in-out",u?"h-[64px] mb-3":"h-0"),children:[m.jsx("div",{className:"flex h-9 px-4 w-full",children:m.jsx(S_,{onSend:P,disabled:p,className:fe("w-full",h.chatInput)})}),m.jsx("hr",{className:"border-border my-2 mx-5"})]}),m.jsxs("div",{className:fe("flex flex-row items-center gap-2 rounded-2xl mx-auto border-none backdrop-blur-lg px-2 py-2",c==="light"?"bg-white/80":"bg-[#18182a]/80"),children:[m.jsxs("div",{className:"flex gap-y-2 justify-start",children:[b.microphone&&m.jsxs("div",{className:"flex gap-y-2 items-center rounded-full overflow-hidden border-none ",children:[m.jsx(Al,{variant:"primary",source:V.Source.Microphone,pressed:C.enabled,disabled:C.pending,onPressedChange:C.toggle,className:"w-auto py-2 rounded-none border-none bg-transparent text-inherit focus:bg-primary/80 hover:bg-primary/80 transition-colors"}),m.jsx(V1,{barCount:3,trackRef:y,options:{minHeight:5},className:"flex h-full w-auto items-center justify-center gap-x-0.5",children:m.jsx("span",{className:fe(["h-full w-0.5 origin-center rounded-2xl","bg-white","group-data-[state=on]/track:bg-white group-data-[state=off]/track:bg-white","data-lk-muted:bg-muted"])})}),m.jsx(Lg,{size:"sm",kind:"audioinput",client:l,onError:a?_=>_ instanceof Error?a({source:V.Source.Microphone,error:_}):void 0:void 0,onActiveDeviceChange:x,className:fe(["h-full py-2 rounded-none border-none bg-transparent text-inherit focus:bg-primary/80 hover:bg-primary/30 transition-colors","min-w-[2.5rem]"])})]}),n.suportsVideoInput&&b.camera&&m.jsxs("div",{className:"flex items-center rounded-full overflow-hidden border-none ",children:[m.jsx(Al,{variant:"primary",source:V.Source.Camera,pressed:w.enabled,pending:w.pending,disabled:w.pending,onPressedChange:w.toggle,className:"w-auto py-2 rounded-none border-none bg-transparent text-inherit focus:bg-primary/80 hover:bg-primary/80 transition-colors"}),m.jsx(Lg,{size:"sm",kind:"videoinput",client:l,onError:a?_=>_ instanceof Error?a({source:V.Source.Camera,error:_}):void 0:void 0,onActiveDeviceChange:T,className:fe(["h-full py-2 rounded-none border-none bg-transparent text-inherit focus:bg-primary/80 hover:bg-primary/80 transition-colors","min-w-[2.5rem]"])})]}),n.suportsScreenShare&&b.screenShare&&m.jsx("div",{className:"flex items-center rounded-full overflow-hidden border-none ",children:m.jsx(Al,{variant:"secondary",source:V.Source.ScreenShare,pressed:S.enabled,disabled:S.pending,onPressedChange:S.toggle,className:"w-auto py-2 disabled:opacity-70 rounded-none border-none bg-transparent text-inherit focus:bg-primary/80 hover:bg-primary/80 transition-colors"})})]}),b.chat&&m.jsx("div",{className:"flex items-center rounded-full overflow-hidden bg-secondary text-secondary-foreground border-none ",children:m.jsx(lx,{variant:"secondary","aria-label":"Toggle chat",pressed:u,onPressedChange:_=>{f(_)},className:"aspect-square h-full py-3 rounded-none border-none bg-transparent text-inherit focus:bg-secondary/80 hover:bg-secondary/80 transition-colors flex items-center",children:m.jsx(B1,{weight:"bold",className:"h-5 w-5"})})})]})]})}const s6=(t,e)=>{var a,c;const n=v.useMemo(()=>e?e(t.message):t.message,[t.message,e]),i=!!t.editTimestamp,r=new Date(t.timestamp),s=typeof navigator<"u"?navigator.language:"en-US",o=(a=t.from)!=null&&a.name&&t.from.name!==""?t.from.name:(c=t.from)==null?void 0:c.identity;return{message:n,hasBeenEdited:i,time:r,locale:s,name:o}},o6=({entry:t,messageFormatter:e,className:n,participantName:i,...r})=>{var d,u;const{message:s,time:o,locale:a}=s6(t,e),c=((d=t.from)==null?void 0:d.isLocal)??!1;fe("w-full px-3 py-2 rounded-2xl text-xs break-words whitespace-pre-line",c?" text-end border border-[#5078F2]/30":"bg-muted text-foreground border border-[#813aa7]/30","text-left");const l=fe("inline-flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold flex-shrink-0",c?"bg-[#5078F2] text-white":"bg-[#813aa7] ml-1 text-white");return m.jsx("li",{title:o.toLocaleTimeString(a,{timeStyle:"full"}),className:fe("group flex mb-2",c?"justify-end":"justify-start",n),...r,children:m.jsxs("div",{className:fe("flex w-fit max-w-full rounded-2xl border",c?"flex-row-reverse items-center border-[#5078F2]/30":"flex-row items-center border-[#813aa7]/30 bg-muted text-foreground"),children:[m.jsx("span",{className:l,children:c?((u=i==null?void 0:i[0])==null?void 0:u.toUpperCase())||"U":"A"}),m.jsx("span",{className:fe("flex items-center text-xs break-words whitespace-pre-line",c?"ml-auto justify-end text-right":"justify-start text-left","px-3 py-2"),children:s})]})})};function a6(t){R.useEffect(()=>{function e(){const n=t.current;n&&(n.scrollTop=n.scrollHeight)}if(t.current){const n=new ResizeObserver(e);return n.observe(t.current),e(),()=>n.disconnect()}},[t])}const c6=({className:t,children:e,...n})=>{const i=R.useRef(null);return a6(i),m.jsx("div",{ref:i,className:fe("flex flex-col justify-end",t),...n,children:e})},l6=({state:t,audioTrack:e,className:n,ref:i})=>m.jsx("div",{ref:i,className:fe("",n),children:m.jsx(V1,{barCount:5,state:t,options:{minHeight:5},trackRef:e,className:fe("flex aspect-video w-40 items-center justify-center gap-1"),children:m.jsx("span",{className:fe(["bg-[#6721a4] min-h-2 w-2 rounded-full","origin-center transition-colors duration-250 ease-linear","data-[lk-highlighted=true]:bg-[#5c64f6]","data-[lk-muted=true]:bg-[#222222]"])})})}),d6=({videoTrack:t,className:e,ref:n})=>{var i,r;return m.jsx("div",{ref:n,className:fe(e),children:m.jsx(Mf,{trackRef:t,width:((i=t==null?void 0:t.publication.dimensions)==null?void 0:i.width)??0,height:((r=t==null?void 0:t.publication.dimensions)==null?void 0:r.height)??0,className:"rounded-md"})})},u6=xe.create(Mf),f6=({trackRef:t,className:e,ref:n})=>{var i,r;return m.jsx("div",{className:fe("bg-muted overflow-hidden rounded-md",e),children:m.jsx(u6,{ref:n,trackRef:t,width:((i=t==null?void 0:t.publication.dimensions)==null?void 0:i.width)??0,height:((r=t==null?void 0:t.publication.dimensions)==null?void 0:r.height)??0,className:fe("h-full w-auto")})})},Fg=xe.create(f6),h6=xe.create(l6),m6=xe.create(d6),Vn={initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},exit:{opacity:0,scale:0},transition:{type:"spring",stiffness:675,damping:75,mass:1}},gr={grid:["h-full w-full","grid gap-x-2 place-content-center","grid-cols-[1fr_1fr] grid-rows-[90px_1fr_90px]"],agentChatOpenWithSecondTile:["col-start-1 row-start-1","self-center justify-self-end"],agentChatOpenWithoutSecondTile:["col-start-1 row-start-1","col-span-2","place-content-center"],agentChatClosed:["col-start-1 row-start-1","col-span-2 row-span-3","place-content-center"],secondTileChatOpen:["col-start-2 row-start-1","self-center justify-self-start"],secondTileChatClosed:["col-start-2 row-start-3","place-content-end"]};function p6(t){const{localParticipant:e}=LM(),n=e.getTrackPublication(t);return R.useMemo(()=>n?{source:t,participant:e,publication:n}:void 0,[t,n,e])}function g6({chatOpen:t}){const{state:e,audioTrack:n,videoTrack:i,agent:{isActive:r=!1}={}}=j1(),[s]=If([V.Source.ScreenShare]),o=p6(V.Source.Camera),a=o&&!o.publication.isMuted,c=s&&!s.publication.isMuted,l=a||c,d={...Vn.transition,delay:t?0:.15},u={...Vn.animate,scale:t?1:3,transition:d},f={...Vn.animate,transition:d},p=d,g=d,h=i!==void 0;return m.jsx("div",{className:"relative w-full h-full z-10 flex items-center justify-center",children:m.jsx("div",{className:"relative w-full h-full max-w-2xl px-4 md:px-0",children:m.jsxs("div",{className:fe(gr.grid),children:[r&&m.jsx("div",{className:fe(["grid",!t&&gr.agentChatClosed,t&&l&&gr.agentChatOpenWithSecondTile,t&&!l&&gr.agentChatOpenWithoutSecondTile]),children:m.jsxs("div",{className:"h-full flex items-center justify-center",children:[!h&&m.jsx(h6,{layoutId:"agent",...Vn,animate:u,transition:p,state:e,audioTrack:n,className:fe(t?"h-[90px]":"h-auto w-full")},"agent"),h&&m.jsx(m6,{layoutId:"avatar",...Vn,animate:f,transition:g,videoTrack:i,className:fe(t?"h-[90px] [&>video]:h-[90px] [&>video]:w-auto":"h-auto w-full")},"avatar")]})}),m.jsx("div",{className:fe(["grid",t&&gr.secondTileChatOpen,!t&&gr.secondTileChatClosed]),children:m.jsxs("div",{className:"w-full px-10 flex items-center shadow-2xl justify-between",children:[o&&a&&m.jsx(Fg,{layout:"position",layoutId:"camera",...Vn,trackRef:o,transition:{...Vn.transition,delay:t?0:.15},className:"h-[60px] order-1"},"camera"),c&&m.jsx(Fg,{layout:"position",layoutId:"screen",...Vn,trackRef:s,transition:{...Vn.transition,delay:t?0:.15},className:"h-[70px] order-2"},"screen")]})})]})})})}/**
117
+ `)},u8=0,pr=[];function f8(t){var e=v.useRef([]),n=v.useRef([0,0]),i=v.useRef(),r=v.useState(u8++)[0],s=v.useState(Hx)[0],o=v.useRef(t);v.useEffect(function(){o.current=t},[t]),v.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(r));var h=NO([t.lockRef.current],(t.shards||[]).map(Ig),!0).filter(Boolean);return h.forEach(function(y){return y.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),h.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(r))})}}},[t.inert,t.lockRef.current,t.shards]);var a=v.useCallback(function(h,y){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!o.current.allowPinchZoom;var b=Vo(h),w=n.current,C="deltaX"in h?h.deltaX:w[0]-b[0],S="deltaY"in h?h.deltaY:w[1]-b[1],x,T=h.target,E=Math.abs(C)>Math.abs(S)?"h":"v";if("touches"in h&&E==="h"&&T.type==="range")return!1;var P=Rg(E,T);if(!P)return!0;if(P?x=E:(x=E==="v"?"h":"v",P=Rg(E,T)),!P)return!1;if(!i.current&&"changedTouches"in h&&(C||S)&&(i.current=x),!x)return!0;var _=i.current||x;return c8(_,y,h,_==="h"?C:S)},[]),c=v.useCallback(function(h){var y=h;if(!(!pr.length||pr[pr.length-1]!==s)){var b="deltaY"in y?Ag(y):Vo(y),w=e.current.filter(function(x){return x.name===y.type&&(x.target===y.target||y.target===x.shadowParent)&&l8(x.delta,b)})[0];if(w&&w.should){y.cancelable&&y.preventDefault();return}if(!w){var C=(o.current.shards||[]).map(Ig).filter(Boolean).filter(function(x){return x.contains(y.target)}),S=C.length>0?a(y,C[0]):!o.current.noIsolation;S&&y.cancelable&&y.preventDefault()}}},[]),l=v.useCallback(function(h,y,b,w){var C={name:h,delta:y,target:b,should:w,shadowParent:h8(b)};e.current.push(C),setTimeout(function(){e.current=e.current.filter(function(S){return S!==C})},1)},[]),d=v.useCallback(function(h){n.current=Vo(h),i.current=void 0},[]),u=v.useCallback(function(h){l(h.type,Ag(h),h.target,a(h,t.lockRef.current))},[]),f=v.useCallback(function(h){l(h.type,Vo(h),h.target,a(h,t.lockRef.current))},[]);v.useEffect(function(){return pr.push(s),t.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:f}),document.addEventListener("wheel",c,mr),document.addEventListener("touchmove",c,mr),document.addEventListener("touchstart",d,mr),function(){pr=pr.filter(function(h){return h!==s}),document.removeEventListener("wheel",c,mr),document.removeEventListener("touchmove",c,mr),document.removeEventListener("touchstart",d,mr)}},[]);var p=t.removeScrollBar,g=t.inert;return v.createElement(v.Fragment,null,g?v.createElement(s,{styles:d8(r)}):null,p?v.createElement(t8,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function h8(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const m8=$O($x,f8);var Kx=v.forwardRef(function(t,e){return v.createElement(ac,Cn({},t,{ref:e,sideCar:m8}))});Kx.classNames=ac.classNames;var p8=[" ","Enter","ArrowUp","ArrowDown"],g8=[" ","Enter"],tr="Select",[cc,lc,v8]=D_(tr),[us,DL]=Df(tr,[v8,Rx]),dc=Rx(),[y8,Ai]=us(tr),[b8,x8]=us(tr),Gx=t=>{const{__scopeSelect:e,children:n,open:i,defaultOpen:r,onOpenChange:s,value:o,defaultValue:a,onValueChange:c,dir:l,name:d,autoComplete:u,disabled:f,required:p,form:g}=t,h=dc(e),[y,b]=v.useState(null),[w,C]=v.useState(null),[S,x]=v.useState(!1),T=L_(l),[E,P]=Qd({prop:i,defaultProp:r??!1,onChange:s,caller:tr}),[_,k]=Qd({prop:o,defaultProp:a,onChange:c,caller:tr}),I=v.useRef(null),N=y?g||!!y.closest("form"):!0,[K,J]=v.useState(new Set),se=Array.from(K).map(ie=>ie.props.value).join(";");return m.jsx(SO,{...h,children:m.jsxs(y8,{required:p,scope:e,trigger:y,onTriggerChange:b,valueNode:w,onValueNodeChange:C,valueNodeHasChildren:S,onValueNodeHasChildrenChange:x,contentId:jf(),value:_,onValueChange:k,open:E,onOpenChange:P,dir:T,triggerPointerDownPosRef:I,disabled:f,children:[m.jsx(cc.Provider,{scope:e,children:m.jsx(b8,{scope:t.__scopeSelect,onNativeOptionAdd:v.useCallback(ie=>{J(X=>new Set(X).add(ie))},[]),onNativeOptionRemove:v.useCallback(ie=>{J(X=>{const O=new Set(X);return O.delete(ie),O})},[]),children:n})}),N?m.jsxs(gS,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:u,value:_,onChange:ie=>k(ie.target.value),disabled:f,form:g,children:[_===void 0?m.jsx("option",{value:""}):null,Array.from(K)]},se):null]})})};Gx.displayName=tr;var Zx="SelectTrigger",Yx=v.forwardRef((t,e)=>{const{__scopeSelect:n,disabled:i=!1,...r}=t,s=dc(n),o=Ai(Zx,n),a=o.disabled||i,c=xt(e,o.onTriggerChange),l=lc(n),d=v.useRef("touch"),[u,f,p]=yS(h=>{const y=l().filter(C=>!C.disabled),b=y.find(C=>C.value===o.value),w=bS(y,h,b);w!==void 0&&o.onValueChange(w.value)}),g=h=>{a||(o.onOpenChange(!0),p()),h&&(o.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})};return m.jsx(wO,{asChild:!0,...s,children:m.jsx(et.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":vS(o.value)?"":void 0,...r,ref:c,onClick:it(r.onClick,h=>{h.currentTarget.focus(),d.current!=="mouse"&&g(h)}),onPointerDown:it(r.onPointerDown,h=>{d.current=h.pointerType;const y=h.target;y.hasPointerCapture(h.pointerId)&&y.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(g(h),h.preventDefault())}),onKeyDown:it(r.onKeyDown,h=>{const y=u.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&f(h.key),!(y&&h.key===" ")&&p8.includes(h.key)&&(g(),h.preventDefault())})})})});Yx.displayName=Zx;var Jx="SelectValue",Xx=v.forwardRef((t,e)=>{const{__scopeSelect:n,className:i,style:r,children:s,placeholder:o="",...a}=t,c=Ai(Jx,n),{onValueNodeHasChildrenChange:l}=c,d=s!==void 0,u=xt(e,c.onValueNodeChange);return Lt(()=>{l(d)},[l,d]),m.jsx(et.span,{...a,ref:u,style:{pointerEvents:"none"},children:vS(c.value)?m.jsx(m.Fragment,{children:o}):s})});Xx.displayName=Jx;var S8="SelectIcon",Qx=v.forwardRef((t,e)=>{const{__scopeSelect:n,children:i,...r}=t;return m.jsx(et.span,{"aria-hidden":!0,...r,ref:e,children:i||"▼"})});Qx.displayName=S8;var w8="SelectPortal",eS=t=>m.jsx(Lx,{asChild:!0,...t});eS.displayName=w8;var nr="SelectContent",tS=v.forwardRef((t,e)=>{const n=Ai(nr,t.__scopeSelect),[i,r]=v.useState();if(Lt(()=>{r(new DocumentFragment)},[]),!n.open){const s=i;return s?qa.createPortal(m.jsx(nS,{scope:t.__scopeSelect,children:m.jsx(cc.Slot,{scope:t.__scopeSelect,children:m.jsx("div",{children:t.children})})}),s):null}return m.jsx(iS,{...t,ref:e})});tS.displayName=nr;var on=10,[nS,Ii]=us(nr),C8="SelectContentImpl",k8=eo("SelectContent.RemoveScroll"),iS=v.forwardRef((t,e)=>{const{__scopeSelect:n,position:i="item-aligned",onCloseAutoFocus:r,onEscapeKeyDown:s,onPointerDownOutside:o,side:a,sideOffset:c,align:l,alignOffset:d,arrowPadding:u,collisionBoundary:f,collisionPadding:p,sticky:g,hideWhenDetached:h,avoidCollisions:y,...b}=t,w=Ai(nr,n),[C,S]=v.useState(null),[x,T]=v.useState(null),E=xt(e,D=>S(D)),[P,_]=v.useState(null),[k,I]=v.useState(null),N=lc(n),[K,J]=v.useState(!1),se=v.useRef(!1);v.useEffect(()=>{if(C)return _O(C)},[C]),q_();const ie=v.useCallback(D=>{const[$,...Q]=N().map(z=>z.ref.current),[W]=Q.slice(-1),ce=document.activeElement;for(const z of D)if(z===ce||(z==null||z.scrollIntoView({block:"nearest"}),z===$&&x&&(x.scrollTop=0),z===W&&x&&(x.scrollTop=x.scrollHeight),z==null||z.focus(),document.activeElement!==ce))return},[N,x]),X=v.useCallback(()=>ie([P,C]),[ie,P,C]);v.useEffect(()=>{K&&X()},[K,X]);const{onOpenChange:O,triggerPointerDownPosRef:oe}=w;v.useEffect(()=>{if(C){let D={x:0,y:0};const $=W=>{var ce,z;D={x:Math.abs(Math.round(W.pageX)-(((ce=oe.current)==null?void 0:ce.x)??0)),y:Math.abs(Math.round(W.pageY)-(((z=oe.current)==null?void 0:z.y)??0))}},Q=W=>{D.x<=10&&D.y<=10?W.preventDefault():C.contains(W.target)||O(!1),document.removeEventListener("pointermove",$),oe.current=null};return oe.current!==null&&(document.addEventListener("pointermove",$),document.addEventListener("pointerup",Q,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",Q,{capture:!0})}}},[C,O,oe]),v.useEffect(()=>{const D=()=>O(!1);return window.addEventListener("blur",D),window.addEventListener("resize",D),()=>{window.removeEventListener("blur",D),window.removeEventListener("resize",D)}},[O]);const[L,F]=yS(D=>{const $=N().filter(ce=>!ce.disabled),Q=$.find(ce=>ce.ref.current===document.activeElement),W=bS($,D,Q);W&&setTimeout(()=>W.ref.current.focus())}),te=v.useCallback((D,$,Q)=>{const W=!se.current&&!Q;(w.value!==void 0&&w.value===$||W)&&(_(D),W&&(se.current=!0))},[w.value]),j=v.useCallback(()=>C==null?void 0:C.focus(),[C]),q=v.useCallback((D,$,Q)=>{const W=!se.current&&!Q;(w.value!==void 0&&w.value===$||W)&&I(D)},[w.value]),ee=i==="popper"?su:rS,G=ee===su?{side:a,sideOffset:c,align:l,alignOffset:d,arrowPadding:u,collisionBoundary:f,collisionPadding:p,sticky:g,hideWhenDetached:h,avoidCollisions:y}:{};return m.jsx(nS,{scope:n,content:C,viewport:x,onViewportChange:T,itemRefCallback:te,selectedItem:P,onItemLeave:j,itemTextRefCallback:q,focusSelectedItem:X,selectedItemText:k,position:i,isPositioned:K,searchRef:L,children:m.jsx(Kx,{as:k8,allowPinchZoom:!0,children:m.jsx(hx,{asChild:!0,trapped:w.open,onMountAutoFocus:D=>{D.preventDefault()},onUnmountAutoFocus:it(r,D=>{var $;($=w.trigger)==null||$.focus({preventScroll:!0}),D.preventDefault()}),children:m.jsx(ux,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:D=>D.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:m.jsx(ee,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:D=>D.preventDefault(),...b,...G,onPlaced:()=>J(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:it(b.onKeyDown,D=>{const $=D.ctrlKey||D.altKey||D.metaKey;if(D.key==="Tab"&&D.preventDefault(),!$&&D.key.length===1&&F(D.key),["ArrowUp","ArrowDown","Home","End"].includes(D.key)){let W=N().filter(ce=>!ce.disabled).map(ce=>ce.ref.current);if(["ArrowUp","End"].includes(D.key)&&(W=W.slice().reverse()),["ArrowUp","ArrowDown"].includes(D.key)){const ce=D.target,z=W.indexOf(ce);W=W.slice(z+1)}setTimeout(()=>ie(W)),D.preventDefault()}})})})})})})});iS.displayName=C8;var T8="SelectItemAlignedPosition",rS=v.forwardRef((t,e)=>{const{__scopeSelect:n,onPlaced:i,...r}=t,s=Ai(nr,n),o=Ii(nr,n),[a,c]=v.useState(null),[l,d]=v.useState(null),u=xt(e,E=>d(E)),f=lc(n),p=v.useRef(!1),g=v.useRef(!0),{viewport:h,selectedItem:y,selectedItemText:b,focusSelectedItem:w}=o,C=v.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&l&&h&&y&&b){const E=s.trigger.getBoundingClientRect(),P=l.getBoundingClientRect(),_=s.valueNode.getBoundingClientRect(),k=b.getBoundingClientRect();if(s.dir!=="rtl"){const ce=k.left-P.left,z=_.left-ce,me=E.left-z,Ee=E.width+me,qe=Math.max(Ee,P.width),Ct=window.innerWidth-on,gn=cg(z,[on,Math.max(on,Ct-qe)]);a.style.minWidth=Ee+"px",a.style.left=gn+"px"}else{const ce=P.right-k.right,z=window.innerWidth-_.right-ce,me=window.innerWidth-E.right-z,Ee=E.width+me,qe=Math.max(Ee,P.width),Ct=window.innerWidth-on,gn=cg(z,[on,Math.max(on,Ct-qe)]);a.style.minWidth=Ee+"px",a.style.right=gn+"px"}const I=f(),N=window.innerHeight-on*2,K=h.scrollHeight,J=window.getComputedStyle(l),se=parseInt(J.borderTopWidth,10),ie=parseInt(J.paddingTop,10),X=parseInt(J.borderBottomWidth,10),O=parseInt(J.paddingBottom,10),oe=se+ie+K+O+X,L=Math.min(y.offsetHeight*5,oe),F=window.getComputedStyle(h),te=parseInt(F.paddingTop,10),j=parseInt(F.paddingBottom,10),q=E.top+E.height/2-on,ee=N-q,G=y.offsetHeight/2,D=y.offsetTop+G,$=se+ie+D,Q=oe-$;if($<=q){const ce=I.length>0&&y===I[I.length-1].ref.current;a.style.bottom="0px";const z=l.clientHeight-h.offsetTop-h.offsetHeight,me=Math.max(ee,G+(ce?j:0)+z+X),Ee=$+me;a.style.height=Ee+"px"}else{const ce=I.length>0&&y===I[0].ref.current;a.style.top="0px";const me=Math.max(q,se+h.offsetTop+(ce?te:0)+G)+Q;a.style.height=me+"px",h.scrollTop=$-q+h.offsetTop}a.style.margin=`${on}px 0`,a.style.minHeight=L+"px",a.style.maxHeight=N+"px",i==null||i(),requestAnimationFrame(()=>p.current=!0)}},[f,s.trigger,s.valueNode,a,l,h,y,b,s.dir,i]);Lt(()=>C(),[C]);const[S,x]=v.useState();Lt(()=>{l&&x(window.getComputedStyle(l).zIndex)},[l]);const T=v.useCallback(E=>{E&&g.current===!0&&(C(),w==null||w(),g.current=!1)},[C,w]);return m.jsx(P8,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:T,children:m.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:m.jsx(et.div,{...r,ref:u,style:{boxSizing:"border-box",maxHeight:"100%",...r.style}})})})});rS.displayName=T8;var E8="SelectPopperPosition",su=v.forwardRef((t,e)=>{const{__scopeSelect:n,align:i="start",collisionPadding:r=on,...s}=t,o=dc(n);return m.jsx(CO,{...o,...s,ref:e,align:i,collisionPadding:r,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});su.displayName=E8;var[P8,qf]=us(nr,{}),ou="SelectViewport",sS=v.forwardRef((t,e)=>{const{__scopeSelect:n,nonce:i,...r}=t,s=Ii(ou,n),o=qf(ou,n),a=xt(e,s.onViewportChange),c=v.useRef(0);return m.jsxs(m.Fragment,{children:[m.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:i}),m.jsx(cc.Slot,{scope:n,children:m.jsx(et.div,{"data-radix-select-viewport":"",role:"presentation",...r,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...r.style},onScroll:it(r.onScroll,l=>{const d=l.currentTarget,{contentWrapper:u,shouldExpandOnScrollRef:f}=o;if(f!=null&&f.current&&u){const p=Math.abs(c.current-d.scrollTop);if(p>0){const g=window.innerHeight-on*2,h=parseFloat(u.style.minHeight),y=parseFloat(u.style.height),b=Math.max(h,y);if(b<g){const w=b+p,C=Math.min(g,w),S=w-C;u.style.height=C+"px",u.style.bottom==="0px"&&(d.scrollTop=S>0?S:0,u.style.justifyContent="flex-end")}}}c.current=d.scrollTop})})})]})});sS.displayName=ou;var oS="SelectGroup",[R8,A8]=us(oS),I8=v.forwardRef((t,e)=>{const{__scopeSelect:n,...i}=t,r=jf();return m.jsx(R8,{scope:n,id:r,children:m.jsx(et.div,{role:"group","aria-labelledby":r,...i,ref:e})})});I8.displayName=oS;var aS="SelectLabel",M8=v.forwardRef((t,e)=>{const{__scopeSelect:n,...i}=t,r=A8(aS,n);return m.jsx(et.div,{id:r.id,...i,ref:e})});M8.displayName=aS;var Ua="SelectItem",[_8,cS]=us(Ua),lS=v.forwardRef((t,e)=>{const{__scopeSelect:n,value:i,disabled:r=!1,textValue:s,...o}=t,a=Ai(Ua,n),c=Ii(Ua,n),l=a.value===i,[d,u]=v.useState(s??""),[f,p]=v.useState(!1),g=xt(e,w=>{var C;return(C=c.itemRefCallback)==null?void 0:C.call(c,w,i,r)}),h=jf(),y=v.useRef("touch"),b=()=>{r||(a.onValueChange(i),a.onOpenChange(!1))};if(i==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return m.jsx(_8,{scope:n,value:i,disabled:r,textId:h,isSelected:l,onItemTextChange:v.useCallback(w=>{u(C=>C||((w==null?void 0:w.textContent)??"").trim())},[]),children:m.jsx(cc.ItemSlot,{scope:n,value:i,disabled:r,textValue:d,children:m.jsx(et.div,{role:"option","aria-labelledby":h,"data-highlighted":f?"":void 0,"aria-selected":l&&f,"data-state":l?"checked":"unchecked","aria-disabled":r||void 0,"data-disabled":r?"":void 0,tabIndex:r?void 0:-1,...o,ref:g,onFocus:it(o.onFocus,()=>p(!0)),onBlur:it(o.onBlur,()=>p(!1)),onClick:it(o.onClick,()=>{y.current!=="mouse"&&b()}),onPointerUp:it(o.onPointerUp,()=>{y.current==="mouse"&&b()}),onPointerDown:it(o.onPointerDown,w=>{y.current=w.pointerType}),onPointerMove:it(o.onPointerMove,w=>{var C;y.current=w.pointerType,r?(C=c.onItemLeave)==null||C.call(c):y.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:it(o.onPointerLeave,w=>{var C;w.currentTarget===document.activeElement&&((C=c.onItemLeave)==null||C.call(c))}),onKeyDown:it(o.onKeyDown,w=>{var S;((S=c.searchRef)==null?void 0:S.current)!==""&&w.key===" "||(g8.includes(w.key)&&b(),w.key===" "&&w.preventDefault())})})})})});lS.displayName=Ua;var _s="SelectItemText",dS=v.forwardRef((t,e)=>{const{__scopeSelect:n,className:i,style:r,...s}=t,o=Ai(_s,n),a=Ii(_s,n),c=cS(_s,n),l=x8(_s,n),[d,u]=v.useState(null),f=xt(e,b=>u(b),c.onItemTextChange,b=>{var w;return(w=a.itemTextRefCallback)==null?void 0:w.call(a,b,c.value,c.disabled)}),p=d==null?void 0:d.textContent,g=v.useMemo(()=>m.jsx("option",{value:c.value,disabled:c.disabled,children:p},c.value),[c.disabled,c.value,p]),{onNativeOptionAdd:h,onNativeOptionRemove:y}=l;return Lt(()=>(h(g),()=>y(g)),[h,y,g]),m.jsxs(m.Fragment,{children:[m.jsx(et.span,{id:c.textId,...s,ref:f}),c.isSelected&&o.valueNode&&!o.valueNodeHasChildren?qa.createPortal(s.children,o.valueNode):null]})});dS.displayName=_s;var uS="SelectItemIndicator",fS=v.forwardRef((t,e)=>{const{__scopeSelect:n,...i}=t;return cS(uS,n).isSelected?m.jsx(et.span,{"aria-hidden":!0,...i,ref:e}):null});fS.displayName=uS;var au="SelectScrollUpButton",hS=v.forwardRef((t,e)=>{const n=Ii(au,t.__scopeSelect),i=qf(au,t.__scopeSelect),[r,s]=v.useState(!1),o=xt(e,i.onScrollButtonChange);return Lt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const l=c.scrollTop>0;s(l)};const c=n.viewport;return a(),c.addEventListener("scroll",a),()=>c.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),r?m.jsx(pS,{...t,ref:o,onAutoScroll:()=>{const{viewport:a,selectedItem:c}=n;a&&c&&(a.scrollTop=a.scrollTop-c.offsetHeight)}}):null});hS.displayName=au;var cu="SelectScrollDownButton",mS=v.forwardRef((t,e)=>{const n=Ii(cu,t.__scopeSelect),i=qf(cu,t.__scopeSelect),[r,s]=v.useState(!1),o=xt(e,i.onScrollButtonChange);return Lt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const l=c.scrollHeight-c.clientHeight,d=Math.ceil(c.scrollTop)<l;s(d)};const c=n.viewport;return a(),c.addEventListener("scroll",a),()=>c.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),r?m.jsx(pS,{...t,ref:o,onAutoScroll:()=>{const{viewport:a,selectedItem:c}=n;a&&c&&(a.scrollTop=a.scrollTop+c.offsetHeight)}}):null});mS.displayName=cu;var pS=v.forwardRef((t,e)=>{const{__scopeSelect:n,onAutoScroll:i,...r}=t,s=Ii("SelectScrollButton",n),o=v.useRef(null),a=lc(n),c=v.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return v.useEffect(()=>()=>c(),[c]),Lt(()=>{var d;const l=a().find(u=>u.ref.current===document.activeElement);(d=l==null?void 0:l.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),m.jsx(et.div,{"aria-hidden":!0,...r,ref:e,style:{flexShrink:0,...r.style},onPointerDown:it(r.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(i,50))}),onPointerMove:it(r.onPointerMove,()=>{var l;(l=s.onItemLeave)==null||l.call(s),o.current===null&&(o.current=window.setInterval(i,50))}),onPointerLeave:it(r.onPointerLeave,()=>{c()})})}),N8="SelectSeparator",O8=v.forwardRef((t,e)=>{const{__scopeSelect:n,...i}=t;return m.jsx(et.div,{"aria-hidden":!0,...i,ref:e})});O8.displayName=N8;var lu="SelectArrow",D8=v.forwardRef((t,e)=>{const{__scopeSelect:n,...i}=t,r=dc(n),s=Ai(lu,n),o=Ii(lu,n);return s.open&&o.position==="popper"?m.jsx(kO,{...r,...i,ref:e}):null});D8.displayName=lu;var j8="SelectBubbleInput",gS=v.forwardRef(({__scopeSelect:t,value:e,...n},i)=>{const r=v.useRef(null),s=xt(i,r),o=EO(e);return v.useEffect(()=>{const a=r.current;if(!a)return;const c=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(o!==e&&d){const u=new Event("change",{bubbles:!0});d.call(a,e),a.dispatchEvent(u)}},[o,e]),m.jsx(et.select,{...n,style:{...Vx,...n.style},ref:s,defaultValue:e})});gS.displayName=j8;function vS(t){return t===""||t===void 0}function yS(t){const e=Qi(t),n=v.useRef(""),i=v.useRef(0),r=v.useCallback(o=>{const a=n.current+o;e(a),function c(l){n.current=l,window.clearTimeout(i.current),l!==""&&(i.current=window.setTimeout(()=>c(""),1e3))}(a)},[e]),s=v.useCallback(()=>{n.current="",window.clearTimeout(i.current)},[]);return v.useEffect(()=>()=>window.clearTimeout(i.current),[]),[n,r,s]}function bS(t,e,n){const r=e.length>1&&Array.from(e).every(l=>l===e[0])?e[0]:e,s=n?t.indexOf(n):-1;let o=L8(t,Math.max(s,0));r.length===1&&(o=o.filter(l=>l!==n));const c=o.find(l=>l.textValue.toLowerCase().startsWith(r.toLowerCase()));return c!==n?c:void 0}function L8(t,e){return t.map((n,i)=>t[(e+i)%t.length])}var V8=Gx,F8=Yx,U8=Xx,B8=Qx,$8=eS,H8=tS,z8=sS,W8=lS,q8=dS,K8=fS,G8=hS,Z8=mS;function Mg({...t}){return m.jsx(V8,{"data-slot":"select",...t})}function _g({...t}){return m.jsx(U8,{"data-slot":"select-value",...t})}function Ng({className:t,size:e="default",children:n,...i}){return m.jsxs(F8,{"data-slot":"select-trigger","data-size":e,className:fe(["flex w-fit cursor-pointer items-center justify-between gap-2","rounded-full px-3 py-2 text-sm whitespace-nowrap","bg-button transition-[color,border,background-color]","disabled:cursor-not-allowed disabled:opacity-50","hover:bg-muted hover:text-muted-foreground","!focus:ring-0 !focus-visible:ring-0 !focus:border-none !focus-visible:border-none !ring-0 !border-none !outline-none","aria-invalid:ring-0 dark:aria-invalid:ring-0","data-[placeholder]:text-muted-foreground","data-[size=default]:h-9 data-[size=sm]:h-8","*:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2","[&:not([class*='text-'])_svg:not([class*='text-'])]:text-muted-foreground","[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"],t),...i,children:[n,m.jsx(B8,{asChild:!0,children:m.jsx(_f,{weight:"bold",className:"size-4 transition-colors"})})]})}function Og({className:t,children:e,position:n="popper",...i}){return m.jsx($8,{children:m.jsxs(H8,{"data-slot":"select-content",className:fe(["bg-[#18182a]/90 backdrop-blur-md text-white border border-[#23233a] shadow-2xl","relative z-50 overflow-x-hidden overflow-y-auto rounded-xl","max-h-(--radix-select-content-available-height) min-w-[8rem]","origin-(--radix-select-content-transform-origin)","data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=top]:slide-in-from-bottom-2","data-[side=right]:slide-in-from-left-2","data-[side=bottom]:slide-in-from-top-2","data-[side=left]:slide-in-from-right-2"],n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,...i,children:[m.jsx(Y8,{}),m.jsx(z8,{className:fe("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:e}),m.jsx(J8,{})]})})}function Dg({className:t,children:e,...n}){return m.jsxs(W8,{"data-slot":"select-item",className:fe(["relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none","cursor-pointer disabled:cursor-not-allowed","focus:bg-accent focus:text-accent-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50","*:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2","[&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"],t),...n,children:[m.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:m.jsx(K8,{children:m.jsx($1,{className:"size-4",weight:"bold"})})}),m.jsx(q8,{children:e})]})}function Y8({className:t,...e}){return m.jsx(G8,{"data-slot":"select-scroll-up-button",className:fe("flex cursor-default items-center justify-center py-1",t),...e,children:m.jsx(U1,{className:"size-4",weight:"bold"})})}function J8({className:t,...e}){return m.jsx(Z8,{"data-slot":"select-scroll-down-button",className:fe("flex cursor-default items-center justify-center py-1",t),...e,children:m.jsx(_f,{className:"size-4",weight:"bold"})})}const jg=Wa.cva(["w-full rounded-full px-3 py-2 text-sm cursor-pointer","disabled:not-allowed hover:bg-button-hover focus:bg-button-hover"],{variants:{size:{default:"w-[180px]",sm:"w-auto"}},defaultVariants:{size:"default"}});function Lg({kind:t,track:e,requestPermissions:n,onError:i,client:r,...s}){const o=s.size||"default";if(!r)return m.jsxs(Mg,{disabled:!0,children:[m.jsx(Ng,{className:fe(jg({size:o}),s.className),children:m.jsx(_g,{placeholder:`Select a ${t}`})}),m.jsx(Og,{children:m.jsx(Dg,{value:"none",children:"No devices available"})})]});const{devices:a,activeDeviceId:c,setActiveMediaDevice:l}=__(r,t==="audioinput"?"audioinput":"videoinput");return m.jsxs(Mg,{value:c,onValueChange:l,children:[m.jsx(Ng,{className:fe(jg({size:o}),s.className,"hover:bg"),children:o!=="sm"&&m.jsx(_g,{className:"font-mono text-sm",placeholder:`Select a ${t}`})}),m.jsx(Og,{children:a.map(d=>m.jsx(Dg,{value:d.deviceId,className:"font-mono text-xs",children:d.label},d.deviceId))})]})}function X8(t,e,n=!1){if(n)return Nf;switch(t){case V.Source.Microphone:return e?H1:z1;case V.Source.Camera:return e?q1:K1;case V.Source.ScreenShare:return W1;default:return v.Fragment}}function Al({source:t,pressed:e,pending:n,className:i,...r}){const s=X8(t,e??!1,n),o=t===V.Source.Microphone&&!(e??!1)&&!n,a=t===V.Source.Camera&&!(e??!1)&&!n;return v.useEffect(()=>{console.log(`TrackToggle for ${t} changed: pressed=${e}, pending=${n}, actualState=${e?"enabled":"disabled"}`)},[t,e,n]),m.jsxs(lx,{pressed:e,"aria-label":`Toggle ${t}`,className:fe(i),...r,children:[m.jsx(s,{weight:"bold",className:fe(n&&"animate-spin",o||a?"text-red-500":void 0)}),r.children]})}function Q8(t){return t?A_(t):{camera:!0,microphone:!0,screenShare:!0,data:!0}}function e6(t={}){const{controls:e,saveUserChoices:n=!0,client:i}=t,r={leave:!0,...e};if(!i)return{micTrackRef:{participant:void 0,source:V.Source.Microphone,publication:void 0},visibleControls:r,microphoneToggle:{enabled:!1,pending:!1,toggle:async()=>{}},cameraToggle:{enabled:!1,pending:!1,toggle:async()=>{}},screenShareToggle:{enabled:!1,pending:!1,toggle:async()=>{}},handleDisconnect:()=>{},handleAudioDeviceChange:()=>{},handleVideoDeviceChange:()=>{}};const{microphoneTrack:s,localParticipant:o}=I_(i),a=Q8(i);M_(i);const c=bl(i,"microphone",{onDeviceError:T=>{var E;return(E=t.onDeviceError)==null?void 0:E.call(t,{source:V.Source.Microphone,error:T})}}),l=bl(i,"camera",{onDeviceError:T=>{var E;return(E=t.onDeviceError)==null?void 0:E.call(t,{source:V.Source.Camera,error:T})}}),d=bl(i,"screenShare",{onDeviceError:T=>{var E;return(E=t.onDeviceError)==null?void 0:E.call(t,{source:V.Source.ScreenShare,error:T})}}),u=v.useMemo(()=>{let T;if(o){for(const[,E]of o.trackPublications)if(E.source===V.Source.Microphone){T=E;break}}return console.log("🎤 Creating micTrackRef:",{hasParticipant:!!o,hasPublication:!!T,isTrackSubscribed:T==null?void 0:T.isSubscribed,isMuted:T==null?void 0:T.isMuted,trackSid:T==null?void 0:T.trackSid}),{participant:o??void 0,source:V.Source.Microphone,publication:T}},[o,s]);r.microphone??(r.microphone=a.microphone),r.screenShare??(r.screenShare=a.screenShare),r.camera??(r.camera=a.camera),r.chat??(r.chat=a.data);const{saveAudioInputEnabled:f,saveAudioInputDeviceId:p,saveVideoInputEnabled:g,saveVideoInputDeviceId:h}=N_({preventSave:!n}),y=v.useCallback(()=>{i&&i.disconnect()},[i]),b=v.useCallback(T=>{p(T??"default"),i&&i.setAudioInputDevice(T)},[p,i]),w=v.useCallback(T=>{h(T??"default"),i&&i.setVideoInputDevice(T)},[h,i]),C=v.useCallback(async T=>{d.enabled&&await d.toggle(!1),await l.toggle(T),g(!l.enabled)},[l,g,d]),S=v.useCallback(async T=>{await c.toggle(T),f(!c.enabled)},[c,f]),x=v.useCallback(async T=>{l.enabled&&await l.toggle(!1),await d.toggle(T)},[l,d]);return{micTrackRef:u,visibleControls:r,cameraToggle:{...l,toggle:C},microphoneToggle:{...c,toggle:S},screenShareToggle:{...d,toggle:x},handleDisconnect:y,handleAudioDeviceChange:b,handleVideoDeviceChange:w}}const t6={card:" bg-gradient-to-br from-black to-gray-900 border border-gray-900 w-full h-full flex flex-col justify-between overflow-hidden mx-auto my-auto rounded-2xl shadow-lg",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-10 z-10 bg-gradient-to-b from-black/90 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-gray-800/20 via-transparent to-transparent",cardPurpleBlur:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-gray-600/10 to-transparent rounded-full blur-2xl",cardPinkBlur:"absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-gray-500/8 to-transparent rounded-full blur-xl",cardPulse1:"absolute -top-2 -left-2 w-6 h-6 bg-gradient-to-br from-gray-400 to-gray-500 rounded-full blur-sm opacity-20 animate-pulse",cardPulse2:"absolute -bottom-2 -right-2 w-4 h-4 bg-gradient-to-br from-gray-500 to-gray-600 rounded-full blur-sm opacity-15 animate-pulse",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-br from-black to-gray-900 rounded-2xl shadow-xl p-0 overflow-hidden h-full",text:{primary:"text-white",secondary:"text-gray-300",muted:"text-gray-400",accent:"bg-clip-text text-transparent bg-gradient-to-r from-white via-gray-200 to-gray-300"},micButton:"absolute w-20 h-20 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 mic-glow shadow-2xl group",chatButton:"absolute w-20 h-20 bg-gradient-to-br from-[#10B981] to-[#059669] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",videoButton:"absolute w-20 h-20 bg-gradient-to-br from-[#8B5CF6] to-[#EC4899] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",popupTrigger:"bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] text-white font-medium hover:from-[#2563EB] hover:to-[#7C3AED] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900",promptSlider:"absolute w-full py-3 px-2 bg-gray-900 rounded-xl text-center text-white text-sm transition-opacity duration-700 ease-in-out border border-gray-600",statusIndicator:"w-2 h-2 bg-gray-400 rounded-full animate-pulse",pulseRings:{ring1:"w-32 h-32 rounded-full border-2 border-gray-600/30 pulse-ring",ring2:"absolute w-28 h-28 rounded-full border-2 border-gray-500/20 pulse-ring",ring3:"absolute w-24 h-24 rounded-full border-2 border-gray-400/15 pulse-ring"},controlBar:"border border-gray-600 rounded-3xl py-4 flex flex-col justify-end h-full bg-gray-900/50 backdrop-blur-sm",chatInput:{container:"bg-gray-900 w-full border-gray-600",textarea:"bg-gray-800 border-none text-white placeholder-gray-400",sendButton:"bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:opacity-50 text-white",attachButton:"text-gray-400 hover:text-gray-300 hover:bg-gray-700",endButton:"bg-red-900/20 hover:bg-red-800/30 text-red-400 border-red-800"},chatMessage:{own:"bg-gray-600 text-white",other:"bg-gray-700 text-white"},chatHeader:{container:"bg-gray-900 border-gray-600",backButton:"text-gray-400 hover:text-white hover:bg-gray-700"},spinner:"w-10 h-10 animate-spin text-gray-400 mb-2",suggestedResponse:{container:"bg-gray-800 text-blue-300 border-gray-700 hover:bg-gray-700 hover:text-white"},video:{container:"bg-gradient-to-br from-black to-gray-900 text-white",header:"border-gray-700 bg-gray-900/50",headerButton:"bg-gray-800 hover:bg-gray-700 text-gray-300",statusDot:"bg-green-500 animate-pulse",controlsBackground:"bg-gray-900/80 backdrop-blur-sm border-t border-gray-700",controlEnabled:"bg-blue-600 hover:bg-blue-700 text-white",controlDisabled:"bg-gray-700 hover:bg-gray-600 text-gray-300",endCall:"bg-red-600 hover:bg-red-700 text-white",tile:"bg-gray-800 border border-gray-700 shadow-lg",placeholder:"bg-gray-800 text-gray-300",avatar:"bg-gray-700 text-gray-300",nameOverlay:"bg-black/70 text-white",mutedIndicator:"bg-red-600/80 text-white"}},n6={card:" bg-gradient-to-br from-white to-gray-50 border border-gray-200 w-full h-full flex flex-col justify-between overflow-hidden mx-auto my-auto shadow-lg",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-10 z-10 bg-gradient-to-b from-white/90 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-blue-500/5 via-transparent to-transparent",cardPurpleBlur:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-purple-500/10 to-transparent rounded-full blur-2xl",cardPinkBlur:"absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-pink-500/8 to-transparent rounded-full blur-xl",cardPulse1:"absolute -top-2 -left-2 w-6 h-6 bg-gradient-to-br from-blue-500 to-purple-500 rounded-full blur-sm opacity-30 animate-pulse",cardPulse2:"absolute -bottom-2 -right-2 w-4 h-4 bg-gradient-to-br from-pink-500 to-purple-500 rounded-full blur-sm opacity-20 animate-pulse",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-br from-white to-gray-50 rounded-2xl shadow-xl p-0 overflow-hidden h-full",text:{primary:"text-gray-900",secondary:"text-gray-700",muted:"text-gray-500",accent:"bg-clip-text text-transparent bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600"},micButton:"absolute text-white w-20 h-20 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 mic-glow shadow-2xl group",chatButton:"absolute text-white w-20 h-20 bg-gradient-to-br from-[#10B981] to-[#059669] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",videoButton:"absolute text-white w-20 h-20 bg-gradient-to-br from-[#8B5CF6] to-[#EC4899] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",popupTrigger:"bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] text-white font-medium hover:from-[#2563EB] hover:to-[#7C3AED] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-white",promptSlider:"absolute w-full py-3 px-2 bg-gray-100 rounded-xl text-center text-gray-700 text-sm transition-opacity duration-700 ease-in-out border border-gray-200",statusIndicator:"w-2 h-2 bg-green-500 rounded-full animate-pulse",pulseRings:{ring1:"w-32 h-32 rounded-full border-2 border-blue-500/20 pulse-ring",ring2:"absolute w-28 h-28 rounded-full border-2 border-purple-500/15 pulse-ring",ring3:"absolute w-24 h-24 rounded-full border-2 border-pink-500/10 pulse-ring"},controlBar:"border border-gray-200 rounded-3xl py-4 flex flex-col justify-end h-full bg-white/80 backdrop-blur-sm",chatInput:{container:"bg-white/90 border-gray-200 shadow-sm",textarea:"bg-white border-none text-gray-900 placeholder-gray-500 ",sendButton:"bg-blue-600 hover:bg-blue-700 disabled:bg-gray-300 disabled:opacity-50 text-white",attachButton:"text-gray-500 hover:text-gray-700 hover:bg-gray-100 bg-blue-50",endButton:"bg-red-50 hover:bg-red-100 text-red-600 border-red-200"},chatMessage:{own:"bg-blue-50 text-gray-900 border border-blue-100",other:"bg-gray-50 text-gray-900 border border-gray-200"},chatHeader:{container:"bg-white border-gray-200",backButton:"text-gray-500 hover:text-gray-700 hover:bg-gray-100"},spinner:"w-10 h-10 animate-spin text-blue-500 mb-2",suggestedResponse:{container:"bg-white text-blue-700 border-blue-200 hover:bg-blue-50 hover:text-blue-900"},video:{container:"bg-gradient-to-br from-white to-gray-50 text-gray-900",header:"border-gray-200 bg-white/80",headerButton:"bg-gray-100 hover:bg-gray-200 text-gray-600",statusDot:"bg-green-500 animate-pulse",controlsBackground:"bg-white/90 backdrop-blur-sm border-t border-gray-200",controlEnabled:"bg-blue-600 hover:bg-blue-700 text-white",controlDisabled:"bg-gray-200 hover:bg-gray-300 text-gray-600",endCall:"bg-red-600 hover:bg-red-700 text-white",tile:"bg-white border border-gray-200 shadow-sm",placeholder:"bg-gray-50 text-gray-600",avatar:"bg-gray-200 text-gray-600",nameOverlay:"bg-black/70 text-white",mutedIndicator:"bg-red-600/80 text-white"}},i6={card:" text-white bg-gradient-to-br from-[#171727] to-[#12121F] border border-gray-800 w-full h-full flex flex-col justify-between overflow-hidden mx-auto my-auto",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-10 z-10 bg-gradient-to-b from-[#171727]/90 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-[#3B82F6]/15 via-transparent to-transparent",cardPurpleBlur:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-[#8B5CF6]/25 to-transparent rounded-full blur-2xl",cardPinkBlur:"absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-[#EC4899]/20 to-transparent rounded-full blur-xl",cardPulse1:"absolute -top-2 -left-2 w-6 h-6 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full blur-sm opacity-50 animate-pulse",cardPulse2:"absolute -bottom-2 -right-2 w-4 h-4 bg-gradient-to-br from-[#EC4899] to-[#8B5CF6] rounded-full blur-sm opacity-40 animate-pulse",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-br from-[#171727] to-[#12121F] rounded-2xl shadow-xl p-0 overflow-hidden h-full",text:{primary:"text-white",secondary:"text-gray-300",muted:"text-gray-400",accent:"bg-clip-text text-transparent bg-gradient-to-r from-[#3B82F6] via-[#8B5CF6] to-[#EC4899]"},micButton:"absolute w-20 h-20 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 mic-glow shadow-2xl group",chatButton:"absolute w-20 h-20 bg-gradient-to-br from-[#10B981] to-[#059669] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",videoButton:"absolute w-20 h-20 bg-gradient-to-br from-[#8B5CF6] to-[#EC4899] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",popupTrigger:"bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] text-white font-medium hover:from-[#2563EB] hover:to-[#7C3AED] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900 shadow-xl",promptSlider:"absolute w-full py-3 px-2 bg-[#1E1E2E] rounded-xl text-center text-gray-200 text-sm transition-opacity duration-700 ease-in-out border border-gray-700",statusIndicator:"w-2 h-2 bg-[#10B981] rounded-full animate-pulse",pulseRings:{ring1:"w-32 h-32 rounded-full border-2 border-[#3B82F6]/40 pulse-ring",ring2:"absolute w-28 h-28 rounded-full border-2 border-[#8B5CF6]/30 pulse-ring",ring3:"absolute w-24 h-24 rounded-full border-2 border-[#EC4899]/20 pulse-ring"},controlBar:"border border-border rounded-3xl py-4 flex flex-col justify-end h-full",chatInput:{container:"bg-[#1E1E2E] border-gray-700",textarea:"bg-[#1E1E2E] border-none text-white placeholder-gray-400",sendButton:"bg-[#3B82F6] hover:bg-[#2563EB] disabled:bg-gray-600 disabled:opacity-50 text-white",attachButton:"text-gray-400 hover:text-gray-300 hover:bg-gray-700",endButton:"bg-red-900/20 hover:bg-red-800/30 text-red-400 border-red-800"},chatMessage:{own:"bg-[#1E1E2E]/80 text-white",other:"bg-[#1E1E2E] text-white border border-gray-700"},chatHeader:{container:"bg-[#1E1E2E] border-gray-700",backButton:"text-gray-400 hover:text-white hover:bg-gray-700"},spinner:"w-10 h-10 animate-spin text-blue-400 mb-2",suggestedResponse:{container:"bg-[#221f3f] text-white border-none"},video:{container:"bg-gradient-to-br from-[#171727] to-[#12121F] text-white",header:"border-gray-700 bg-[#1E1E2E]/80",headerButton:"bg-[#1E1E2E] hover:bg-gray-700 text-gray-300",statusDot:"bg-[#10B981] animate-pulse",controlsBackground:"bg-[#1E1E2E]/90 backdrop-blur-sm border-t border-gray-700",controlEnabled:"bg-[#3B82F6] hover:bg-[#2563EB] text-white",controlDisabled:"bg-gray-700 hover:bg-gray-600 text-gray-300",endCall:"bg-red-600 hover:bg-red-700 text-white",tile:"bg-[#1E1E2E] border border-gray-700 shadow-xl",placeholder:"bg-[#1E1E2E] text-gray-300",avatar:"bg-gray-700 text-gray-300",nameOverlay:"bg-black/70 text-white",mutedIndicator:"bg-red-600/80 text-white"}},Vg={dark:t6,light:n6,vox:i6};function St(t){return Vg[t]||Vg.vox}function r6({controls:t,saveUserChoices:e=!0,capabilities:n,className:i,onSendMessage:r,onChatOpenChange:s,onDisconnect:o,onDeviceError:a,theme:c="vox",client:l,...d}){const[u,f]=v.useState(!1),[p,g]=v.useState(!1),h=St(c),{micTrackRef:y,visibleControls:b,cameraToggle:w,microphoneToggle:C,screenShareToggle:S,handleAudioDeviceChange:x,handleVideoDeviceChange:T,handleDisconnect:E}=e6({controls:t,saveUserChoices:e,client:l}),P=async _=>{g(!0);try{await(r==null?void 0:r(_))}finally{g(!1)}};return v.useEffect(()=>{s==null||s(u)},[u,s]),v.useEffect(()=>{var _,k,I,N;console.log("🎤 AgentControlBar: micTrackRef changed:",{hasParticipant:!!y.participant,hasPublication:!!y.publication,source:y.source,isSubscribed:(_=y.publication)==null?void 0:_.isSubscribed,isMuted:(k=y.publication)==null?void 0:k.isMuted,trackSid:(I=y.publication)==null?void 0:I.trackSid,hasTrack:!!((N=y.publication)!=null&&N.track)})},[y]),m.jsxs("div",{"aria-label":"Voice assistant controls",className:fe(h.controlBar,i),...d,children:[n.suportsChatInput&&m.jsxs("div",{inert:!u,className:fe("overflow-hidden transition-[height] relative duration-300 ease-in-out",u?"h-[64px] mb-3":"h-0"),children:[m.jsx("div",{className:"flex h-9 px-4 w-full",children:m.jsx(S_,{onSend:P,disabled:p,className:fe("w-full",h.chatInput)})}),m.jsx("hr",{className:"border-border my-2 mx-5"})]}),m.jsxs("div",{className:fe("flex flex-row items-center gap-2 rounded-2xl mx-auto border-none backdrop-blur-lg px-2 py-2",c==="light"?"bg-white/80":"bg-[#18182a]/80"),children:[m.jsxs("div",{className:"flex gap-y-2 justify-start",children:[b.microphone&&m.jsxs("div",{className:"flex gap-y-2 items-center rounded-full overflow-hidden border-none ",children:[m.jsx(Al,{variant:"primary",source:V.Source.Microphone,pressed:C.enabled,disabled:C.pending,onPressedChange:C.toggle,className:"w-auto py-2 rounded-none border-none bg-transparent text-inherit focus:bg-primary/80 hover:bg-primary/80 transition-colors"}),m.jsx(V1,{barCount:3,trackRef:y,options:{minHeight:5},className:"flex h-full w-auto items-center justify-center gap-x-0.5",children:m.jsx("span",{className:fe(["h-full w-0.5 origin-center rounded-2xl","bg-white","group-data-[state=on]/track:bg-white group-data-[state=off]/track:bg-white","data-lk-muted:bg-muted"])})}),m.jsx(Lg,{size:"sm",kind:"audioinput",client:l,onError:a?_=>_ instanceof Error?a({source:V.Source.Microphone,error:_}):void 0:void 0,onActiveDeviceChange:x,className:fe(["h-full py-2 rounded-none border-none bg-transparent text-inherit focus:bg-primary/80 hover:bg-primary/30 transition-colors","min-w-[2.5rem]"])})]}),n.suportsVideoInput&&b.camera&&m.jsxs("div",{className:"flex items-center rounded-full overflow-hidden border-none ",children:[m.jsx(Al,{variant:"primary",source:V.Source.Camera,pressed:w.enabled,pending:w.pending,disabled:w.pending,onPressedChange:w.toggle,className:"w-auto py-2 rounded-none border-none bg-transparent text-inherit focus:bg-primary/80 hover:bg-primary/80 transition-colors"}),m.jsx(Lg,{size:"sm",kind:"videoinput",client:l,onError:a?_=>_ instanceof Error?a({source:V.Source.Camera,error:_}):void 0:void 0,onActiveDeviceChange:T,className:fe(["h-full py-2 rounded-none border-none bg-transparent text-inherit focus:bg-primary/80 hover:bg-primary/80 transition-colors","min-w-[2.5rem]"])})]}),n.suportsScreenShare&&b.screenShare&&m.jsx("div",{className:"flex items-center rounded-full overflow-hidden border-none ",children:m.jsx(Al,{variant:"secondary",source:V.Source.ScreenShare,pressed:S.enabled,disabled:S.pending,onPressedChange:S.toggle,className:"w-auto py-2 disabled:opacity-70 rounded-none border-none bg-transparent text-inherit focus:bg-primary/80 hover:bg-primary/80 transition-colors"})})]}),b.chat&&m.jsx("div",{className:"flex items-center rounded-full overflow-hidden bg-secondary text-secondary-foreground border-none ",children:m.jsx(lx,{variant:"secondary","aria-label":"Toggle chat",pressed:u,onPressedChange:_=>{f(_)},className:"aspect-square h-full py-3 rounded-none border-none bg-transparent text-inherit focus:bg-secondary/80 hover:bg-secondary/80 transition-colors flex items-center",children:m.jsx(B1,{weight:"bold",className:"h-5 w-5"})})})]})]})}const s6=(t,e)=>{var a,c;const n=v.useMemo(()=>e?e(t.message):t.message,[t.message,e]),i=!!t.editTimestamp,r=new Date(t.timestamp),s=typeof navigator<"u"?navigator.language:"en-US",o=(a=t.from)!=null&&a.name&&t.from.name!==""?t.from.name:(c=t.from)==null?void 0:c.identity;return{message:n,hasBeenEdited:i,time:r,locale:s,name:o}},o6=({entry:t,messageFormatter:e,className:n,participantName:i,...r})=>{var d,u;const{message:s,time:o,locale:a}=s6(t,e),c=((d=t.from)==null?void 0:d.isLocal)??!1;fe("w-full px-3 py-2 rounded-2xl text-xs break-words whitespace-pre-line",c?" text-end border border-[#5078F2]/30":"bg-muted text-foreground border border-[#813aa7]/30","text-left");const l=fe("inline-flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold flex-shrink-0",c?"bg-[#5078F2] text-white":"bg-[#813aa7] ml-1 text-white");return m.jsx("li",{title:o.toLocaleTimeString(a,{timeStyle:"full"}),className:fe("group flex mb-2",c?"justify-end":"justify-start",n),...r,children:m.jsxs("div",{className:fe("flex w-fit max-w-full rounded-2xl border",c?"flex-row-reverse items-center border-[#5078F2]/30":"flex-row items-center border-[#813aa7]/30 bg-muted text-foreground"),children:[m.jsx("span",{className:l,children:c?((u=i==null?void 0:i[0])==null?void 0:u.toUpperCase())||"U":"A"}),m.jsx("span",{className:fe("flex items-center text-xs break-words whitespace-pre-line",c?"ml-auto justify-end text-right":"justify-start text-left","px-3 py-2"),children:s})]})})};function a6(t){R.useEffect(()=>{function e(){const n=t.current;n&&(n.scrollTop=n.scrollHeight)}if(t.current){const n=new ResizeObserver(e);return n.observe(t.current),e(),()=>n.disconnect()}},[t])}const c6=({className:t,children:e,...n})=>{const i=R.useRef(null);return a6(i),m.jsx("div",{ref:i,className:fe("flex flex-col justify-end",t),...n,children:e})},l6=({state:t,audioTrack:e,className:n,ref:i})=>m.jsx("div",{ref:i,className:fe("",n),children:m.jsx(V1,{barCount:5,state:t,options:{minHeight:5},trackRef:e,className:fe("flex aspect-video w-40 items-center justify-center gap-1"),children:m.jsx("span",{className:fe(["bg-[#6721a4] min-h-2 w-2 rounded-full","origin-center transition-colors duration-250 ease-linear","data-[lk-highlighted=true]:bg-[#5c64f6]","data-[lk-muted=true]:bg-[#222222]"])})})}),d6=({videoTrack:t,className:e,ref:n})=>{var i,r;return m.jsx("div",{ref:n,className:fe(e),children:m.jsx(Mf,{trackRef:t,width:((i=t==null?void 0:t.publication.dimensions)==null?void 0:i.width)??0,height:((r=t==null?void 0:t.publication.dimensions)==null?void 0:r.height)??0,className:"rounded-md"})})},u6=xe.create(Mf),f6=({trackRef:t,className:e,ref:n})=>{var i,r;return m.jsx("div",{className:fe("bg-muted overflow-hidden rounded-md",e),children:m.jsx(u6,{ref:n,trackRef:t,width:((i=t==null?void 0:t.publication.dimensions)==null?void 0:i.width)??0,height:((r=t==null?void 0:t.publication.dimensions)==null?void 0:r.height)??0,className:fe("h-full w-auto")})})},Fg=xe.create(f6),h6=xe.create(l6),m6=xe.create(d6),Vn={initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},exit:{opacity:0,scale:0},transition:{type:"spring",stiffness:675,damping:75,mass:1}},gr={grid:["h-full w-full","grid gap-x-2 place-content-center","grid-cols-[1fr_1fr] grid-rows-[90px_1fr_90px]"],agentChatOpenWithSecondTile:["col-start-1 row-start-1","self-center justify-self-end"],agentChatOpenWithoutSecondTile:["col-start-1 row-start-1","col-span-2","place-content-center"],agentChatClosed:["col-start-1 row-start-1","col-span-2 row-span-3","place-content-center"],secondTileChatOpen:["col-start-2 row-start-1","self-center justify-self-start"],secondTileChatClosed:["col-start-2 row-start-3","place-content-end"]};function p6(t){const{localParticipant:e}=LM(),n=e.getTrackPublication(t);return R.useMemo(()=>n?{source:t,participant:e,publication:n}:void 0,[t,n,e])}function g6({chatOpen:t}){const{state:e,audioTrack:n,videoTrack:i,agent:{isActive:r=!1}={}}=j1(),[s]=If([V.Source.ScreenShare]),o=p6(V.Source.Camera),a=o&&!o.publication.isMuted,c=s&&!s.publication.isMuted,l=a||c,d={...Vn.transition,delay:t?0:.15},u={...Vn.animate,scale:t?1:3,transition:d},f={...Vn.animate,transition:d},p=d,g=d,h=i!==void 0;return m.jsx("div",{className:"relative w-full h-full z-10 flex items-center justify-center",children:m.jsx("div",{className:"relative w-full h-full max-w-2xl px-4 md:px-0",children:m.jsxs("div",{className:fe(gr.grid),children:[r&&m.jsx("div",{className:fe(["grid",!t&&gr.agentChatClosed,t&&l&&gr.agentChatOpenWithSecondTile,t&&!l&&gr.agentChatOpenWithoutSecondTile]),children:m.jsxs("div",{className:"h-full flex items-center justify-center",children:[!h&&m.jsx(h6,{layoutId:"agent",...Vn,animate:u,transition:p,state:e,audioTrack:n,className:fe(t?"h-[90px]":"h-auto w-full")},"agent"),h&&m.jsx(m6,{layoutId:"avatar",...Vn,animate:f,transition:g,videoTrack:i,className:fe(t?"h-[90px] [&>video]:h-[90px] [&>video]:w-auto":"h-auto w-full")},"avatar")]})}),m.jsx("div",{className:fe(["grid",t&&gr.secondTileChatOpen,!t&&gr.secondTileChatClosed]),children:m.jsxs("div",{className:"w-full px-10 flex items-center shadow-2xl justify-between",children:[o&&a&&m.jsx(Fg,{layout:"position",layoutId:"camera",...Vn,trackRef:o,transition:{...Vn.transition,delay:t?0:.15},className:"h-[60px] order-1"},"camera"),c&&m.jsx(Fg,{layout:"position",layoutId:"screen",...Vn,trackRef:s,transition:{...Vn.transition,delay:t?0:.15},className:"h-[70px] order-2"},"screen")]})})]})})})}/**
129
118
  * @license lucide-react v0.522.0 - ISC
130
119
  *
131
120
  * This source code is licensed under the ISC license.
@@ -326,7 +315,7 @@ To suppress this warning, you need to explicitly provide the \`palette.${e}Chann
326
315
  ${n.promptSlider}
327
316
  ${o===i?"opacity-100":"opacity-0"}
328
317
  whitespace-pre-line break-words
329
- `,style:{minHeight:"2.5rem",display:o===i?"block":"none"},children:s},o))})}function Fj({statusMessage:t,theme:e}){const n=St(e);return m.jsxs("div",{className:"z-10 flex items-center space-x-2 mt-2 pb-2",children:[m.jsx("div",{className:n.statusIndicator}),m.jsx("span",{className:`text-xs ${n.text.muted}`,children:t})]})}const Uj=({disabled:t,onStartCall:e,onStartChat:n,onStartVideo:i,prompts:r=['"Book a meeting with the marketing team"',`"What's the status of project Alpha?"`,`"Summarize yesterday's sales report"`,'"Find a good Italian restaurant nearby"','"Remind me to call John tomorrow at 10 AM"'],statusMessage:s="Agent is ready",title:o="Choose how to interact",subTitle:a="Ask me anything or give me a task to complete",theme:c="vox",modalities:l=["voice","chat","video"]})=>{const d=St(c),u=l.includes("voice"),f=l.includes("chat"),p=l.includes("video"),g=[u,f,p].filter(Boolean).length;return console.log("🎯 Welcome component debug:",{modalities:l,hasVoice:u,hasChat:f,hasVideo:p,totalButtons:g,onStartVideo:!!i}),m.jsxs("div",{inert:t,className:"flex p-8 flex-col items-center h-full justify-center w-full",children:[m.jsxs("div",{className:"mt-1 relative flex items-center justify-center mb-8 w-full",style:{minHeight:"120px"},children:[m.jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[m.jsx("div",{className:d.pulseRings.ring1}),m.jsx("div",{className:d.pulseRings.ring2,style:{animationDelay:"0.5s"}}),m.jsx("div",{className:d.pulseRings.ring3,style:{animationDelay:"1s"}})]}),m.jsx("div",{className:"relative z-10 flex items-center justify-center",children:u&&f&&p?m.jsxs("div",{className:"flex gap-4 items-center justify-center",children:[m.jsx(Wo,{onClick:e,disabled:t,theme:c}),m.jsx(Ul,{onClick:n,disabled:t,theme:c}),m.jsx(Bl,{onClick:i||e,disabled:t,theme:c})]}):g>1?m.jsxs("div",{className:"flex gap-6 items-center justify-center",children:[u&&m.jsx(Wo,{onClick:e,disabled:t,theme:c}),f&&m.jsx(Ul,{onClick:n,disabled:t,theme:c}),p&&i&&m.jsx(Bl,{onClick:i,disabled:t,theme:c})]}):m.jsx("div",{className:"flex items-center justify-center",children:u?m.jsx(Wo,{onClick:e,disabled:t,theme:c}):f?m.jsx(Ul,{onClick:n,disabled:t,theme:c}):p&&i?m.jsx(Bl,{onClick:i,disabled:t,theme:c}):m.jsx(Wo,{onClick:e,disabled:t,theme:c})})})]}),m.jsxs("div",{className:"text-center flex flex-col items-center gap-y-2 mb-6 w-full",children:[m.jsx("h3",{className:`text-xl font-semibold mb-2 ${d.text.accent}`,children:o}),m.jsx("p",{className:`text-sm leading-relaxed px-4 ${d.text.secondary}`,children:a}),g>1&&m.jsxs("div",{className:"flex gap-6 mt-4 text-xs justify-center",children:[u&&m.jsxs("div",{className:"flex flex-col items-center gap-1",children:[m.jsx(QS,{className:"w-4 h-4"}),m.jsx("span",{className:d.text.muted,children:"Voice"})]}),f&&m.jsxs("div",{className:"flex flex-col items-center gap-1",children:[m.jsx(XS,{className:"w-4 h-4"}),m.jsx("span",{className:d.text.muted,children:"Chat"})]}),p&&m.jsxs("div",{className:"flex flex-col items-center gap-1",children:[m.jsx(ew,{className:"w-4 h-4"}),m.jsx("span",{className:d.text.muted,children:"Video"})]})]})]}),m.jsx(Vj,{prompts:r,theme:c}),m.jsx(Fj,{statusMessage:s,theme:c})]})};function tw({room:t,onSessionEnd:e,onSessionStart:n,enableConsoleLogging:i=!0,enableLocalStorage:r=!0,voxketSessionId:s}={}){const[o,a]=v.useState(null),[c,l]=v.useState([]),[d,u]=v.useState(null),[f,p]=v.useState([]),g=v.useCallback((w,C)=>{const S={timestamp:new Date,event:w,data:C,sessionId:o==null?void 0:o.sessionId,participantId:d==null?void 0:d.identity};if(l(x=>[...x,S]),r){const x=JSON.parse(localStorage.getItem("voxket-session-logs")||"[]");x.push(S),localStorage.setItem("voxket-session-logs",JSON.stringify(x))}return S},[o==null?void 0:o.sessionId,d==null?void 0:d.identity,i,r]);v.useEffect(()=>{if(!t)return;const w=()=>{const k=s||`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,I=new Date,N={sessionId:k,startTime:I,totalMessages:0,connectionIssues:0,participantCount:f.length,events:[]};a(N),g("SESSION_STARTED",{sessionId:k,startTime:I}),n==null||n(k)},C=()=>{if(o){const k=new Date,I=k.getTime()-o.startTime.getTime(),N={...o,endTime:k,duration:I,events:c};g("SESSION_ENDED",{sessionId:o.sessionId,duration:`${Math.round(I/1e3)}s`,totalMessages:o.totalMessages,connectionIssues:o.connectionIssues}),e==null||e(N),a(null),l([])}},S=k=>{g("CONNECTION_STATE_CHANGED",{state:k}),k===ge.Reconnecting&&o&&(a(I=>I?{...I,connectionIssues:I.connectionIssues+1}:null),g("CONNECTION_ISSUE",{type:"reconnecting"}))},x=k=>{g("TRACK_PUBLISHED",{trackKind:k.kind,trackSource:k.source})},T=k=>{g("TRACK_UNPUBLISHED",{trackKind:k.kind,trackSource:k.source})},E=(k,I)=>{o&&a(N=>N?{...N,totalMessages:N.totalMessages+1}:null),g("DATA_RECEIVED",{participantId:I==null?void 0:I.identity,dataSize:k.length})},P=k=>{g("PARTICIPANT_CONNECTED",{participantId:k.identity,participantName:k.name}),p(I=>[...I,k]),o&&a(I=>I?{...I,participantCount:I.participantCount+1}:null)},_=k=>{g("PARTICIPANT_DISCONNECTED",{participantId:k.identity,participantName:k.name}),p(I=>I.filter(N=>N.identity!==k.identity))};return t.localParticipant&&u(t.localParticipant),t.on(U.Connected,w),t.on(U.Disconnected,C),t.on(U.ConnectionStateChanged,S),t.on(U.TrackPublished,x),t.on(U.TrackUnpublished,T),t.on(U.DataReceived,E),t.on(U.ParticipantConnected,P),t.on(U.ParticipantDisconnected,_),()=>{t.off(U.Connected,w),t.off(U.Disconnected,C),t.off(U.ConnectionStateChanged,S),t.off(U.TrackPublished,x),t.off(U.TrackUnpublished,T),t.off(U.DataReceived,E),t.off(U.ParticipantConnected,P),t.off(U.ParticipantDisconnected,_)}},[t,o,c,f.length,g,e,n]);const h=v.useCallback(()=>r?JSON.parse(localStorage.getItem("voxket-session-logs")||"[]"):c,[c,r]),y=v.useCallback(()=>{r&&localStorage.removeItem("voxket-session-logs"),l([])},[r]),b=v.useCallback(()=>{const w=h(),C=JSON.stringify(w,null,2),S="data:application/json;charset=utf-8,"+encodeURIComponent(C),x=`voxket-session-logs-${new Date().toISOString().split("T")[0]}.json`,T=document.createElement("a");T.setAttribute("href",S),T.setAttribute("download",x),T.click()},[h]);return{sessionMetrics:o,sessionLogs:c,logEvent:g,getSessionLogs:h,clearSessionLogs:y,exportSessionLogs:b}}var wr={},E0;function Bj(){if(E0)return wr;E0=1;var t=bu;if(process.env.NODE_ENV==="production")wr.createRoot=t.createRoot,wr.hydrateRoot=t.hydrateRoot;else{var e=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;wr.createRoot=function(n,i){e.usingClientEntryPoint=!0;try{return t.createRoot(n,i)}finally{e.usingClientEntryPoint=!1}},wr.hydrateRoot=function(n,i,r){e.usingClientEntryPoint=!0;try{return t.hydrateRoot(n,i,r)}finally{e.usingClientEntryPoint=!1}}}return wr}var $j=Bj();class rh{constructor(){at(this,"listeners",{})}on(e,n){return this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(n),()=>this.off(e,n)}once(e,n){const i=(...r)=>{this.off(e,i),n(...r)};return this.on(e,i)}off(e,n){const i=this.listeners[e];if(!i)return;const r=i.indexOf(n);r>-1&&i.splice(r,1)}removeAllListeners(e){e?delete this.listeners[e]:this.listeners={}}emit(e,...n){const i=this.listeners[e];if(!i)return;const r=[...i];for(const s of r)try{s(...n)}catch(o){console.error(`Error in event listener for ${String(e)}:`,o)}}listenerCount(e){var n;return((n=this.listeners[e])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class nw{constructor(e){at(this,"plugins",new Map);at(this,"installedPlugins",new Set);at(this,"context");this.context={client:e,emit:e.emit.bind(e),on:e.on.bind(e),config:{}}}register(e){if(this.plugins.has(e.name))throw new Error(`Plugin '${e.name}' is already registered`);if(e.dependencies){for(const n of e.dependencies)if(!this.plugins.has(n))throw new Error(`Plugin '${e.name}' depends on '${n}' which is not registered`)}this.plugins.set(e.name,e)}async install(e,n){const i=this.plugins.get(e);if(!i)throw new Error(`Plugin '${e}' is not registered`);if(this.installedPlugins.has(e))throw new Error(`Plugin '${e}' is already installed`);if(i.dependencies)for(const s of i.dependencies)this.installedPlugins.has(s)||await this.install(s);const r={...this.context,config:{...i.config,...n}};i.install&&await i.install(r),this.installedPlugins.add(e),this.setupPluginEvents(i,r)}async uninstall(e){var i;const n=this.plugins.get(e);if(!n)throw new Error(`Plugin '${e}' is not registered`);if(this.installedPlugins.has(e)){for(const[r,s]of this.plugins)if(this.installedPlugins.has(r)&&((i=s.dependencies)!=null&&i.includes(e)))throw new Error(`Cannot uninstall '${e}' because '${r}' depends on it`);n.uninstall&&await n.uninstall(this.context),this.installedPlugins.delete(e)}}isInstalled(e){return this.installedPlugins.has(e)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(e){return this.plugins.get(e)}setupPluginEvents(e,n){e.onSessionStart&&n.on("session.started",i=>{e.onSessionStart(n,i.id)}),e.onSessionEnd&&n.on("session.ended",i=>{e.onSessionEnd(n,i.id)}),e.onAgentResponse&&n.on("agent.response",i=>{e.onAgentResponse(n,i)})}}function Hj(t){return t}function sh(t,e,n){return{name:t,version:"1.0.0",description:`${e} modality plugin`,install:async i=>{n.onActivate&&await n.onActivate(i)},uninstall:async i=>{n.onDeactivate&&await n.onDeactivate(i)},onAgentResponse:n.onMessage}}const zj={name:"analytics",version:"1.0.0",description:"Built-in analytics tracking",install:async t=>{console.log("Analytics plugin installed"),t.on("session.started",e=>{console.log("Analytics: Session started",e.id)}),t.on("session.ended",(e,n)=>{console.log("Analytics: Session ended",e.id,n)}),t.on("chat.message.sent",e=>{console.log("Analytics: User message sent",e.content.length)})}},Wj={name:"debug",version:"1.0.0",description:"Debug logging and development tools",install:async t=>{console.log("Debug plugin installed");const e=t.emit;t.emit=(n,...i)=>(console.log(`[Debug] Event: ${String(n)}`,i),e(n,...i))}},qj={name:"metrics",version:"1.0.0",description:"Advanced metrics collection",install:async t=>{console.log("Metrics plugin installed");const e=new Map;t.on("session.started",n=>{e.set(n.id,{startTime:Date.now(),events:[]})}),t.on("agent.response",n=>{console.log("Metrics: Agent response analyzed",{type:n.type,length:n.content.length,timestamp:n.timestamp})})}},iw=R.createContext(null);function rw({config:t,children:e,autoConnect:n=!1}){const[i,r]=R.useState(null),[s,o]=R.useState(!1),[a,c]=R.useState(!1),[l,d]=R.useState(null),[u,f]=R.useState(null),[p,g]=R.useState("idle"),[h,y]=R.useState(null),[b,w]=R.useState([]),[C,S]=R.useState([]),[x,T]=R.useState([]);R.useEffect(()=>{const O=new bo(t);return r(O),E(O),n&&P(O),()=>{O.disconnect().catch(console.error)}},[t,n]);const E=O=>{O.on("connection.connecting",()=>{c(!0),d(null)}),O.on("connection.connected",()=>{o(!0),c(!1),d(null)}),O.on("connection.disconnected",()=>{o(!1),c(!1),f(null),g("idle"),w([]),S([]),T([])}),O.on("connection.error",oe=>{d(oe),c(!1)}),O.on("session.created",oe=>{f(oe),g(oe.state)}),O.on("session.state.changed",oe=>{g(oe),u&&f({...u,state:oe})}),O.on("session.ended",(oe,L)=>{f(null),g("idle"),y(L),w([]),S([]),T([])}),O.on("participant.joined",oe=>{w(L=>[...L,oe])}),O.on("participant.left",oe=>{w(L=>L.filter(F=>F.id!==oe.id))}),O.on("chat.message.received",oe=>{S(L=>[...L,oe])}),O.on("chat.message.sent",oe=>{S(L=>[...L,oe])}),O.on("transcription.received",oe=>{T(L=>[...L,oe])})},P=async O=>{const oe=O||i;if(oe)try{await oe.connect()}catch(L){console.error("Failed to connect:",L)}},X={client:i,isConnected:s,isConnecting:a,connectionError:l,currentSession:u,sessionState:p,sessionMetrics:h,participants:b,chatMessages:C,transcriptions:x,connect:()=>P(),disconnect:async()=>{if(i)try{await i.disconnect()}catch(O){console.error("Failed to disconnect:",O)}},createSession:async(O,oe={})=>{if(!i)throw new Error("Client not initialized");const L={agentId:O,participantName:oe.participantName||"User",metadata:oe.metadata,modalities:oe.modalities||["voice"]};return await i.createSession(L)},endSession:async()=>i?await i.endSession():null,sendChatMessage:async O=>{if(!i)throw new Error("Client not initialized");await i.sendChatMessage(O)},setMicrophoneEnabled:async O=>{if(!i)throw new Error("Client not initialized");await i.setMicrophoneEnabled(O)},setCameraEnabled:async O=>{if(!i)throw new Error("Client not initialized");await i.setCameraEnabled(O)},startScreenShare:async()=>{if(!i)throw new Error("Client not initialized");await i.startScreenShare()},stopScreenShare:async()=>{if(!i)throw new Error("Client not initialized");await i.stopScreenShare()}};return m.jsx(iw.Provider,{value:X,children:e})}function jn(){const t=R.useContext(iw);if(!t)throw new Error("useVoxket must be used within a VoxketProvider");return t}class Kj extends rh{constructor(n){super();at(this,"room",null);at(this,"registeredMethods",new Map);at(this,"activeInteractions",new Map);at(this,"currentInteraction",null);n&&this.setRoom(n)}setRoom(n){this.room=n}async registerFrontendRPC(n,i,r="embedded"){if(console.log(`RpcManager: Starting registration for method '${n}'`),!this.room)throw console.error(`RpcManager: Cannot register '${n}' - no room instance`),new Error("Room not initialized. Cannot register RPC method.");if(!this.room.localParticipant)throw console.error(`RpcManager: Cannot register '${n}' - no local participant`),new Error("Local participant not available for RPC registration");console.log(`RpcManager: Room state: ${this.room.state}`),console.log(`RpcManager: Local participant: ${this.room.localParticipant.identity}`),console.log(`RpcManager: Registering frontend RPC method: ${n}`);const s={methodName:n,component:i,presentationMode:r};this.registeredMethods.set(n,s);try{this.room.registerRpcMethod(n,async o=>{console.log(`RpcManager: RPC method '${n}' called by ${o.callerIdentity}`),console.log("RpcManager: Payload:",o.payload),this.emit("rpc.method.called",{methodName:n,data:o});let a;console.log(`RpcManager: Current registration for '${n}':`,s);let c=o.responseTimeout||30;try{a=JSON.parse(o.payload)}catch{a=o.payload}try{const l=await this.awaitUserInteraction(n,i,r,a,c);return JSON.stringify(l)}catch(l){throw console.error(`RpcManager: Error in RPC method '${n}':`,l),l}}),this.emit("rpc.method.registered",{methodName:n}),console.log(`RpcManager: Successfully registered RPC method: ${n}`)}catch(o){throw console.error(`RpcManager: Failed to register RPC method '${n}':`,o),o}}async awaitUserInteraction(n,i,r,s,o){return new Promise((a,c)=>{const l=`${n}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${n}, timeout: ${o} seconds`);const d={didSuccess:(f,p)=>{console.log(`RpcManager: User interaction successful for method: ${n}`,f),this.clearInteraction(l),this.currentInteraction=null;const g={success:!0,message:"User interaction completed successfully",data:f,timestamp:new Date,...p?{successView:p}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:g}),a(g)},didFail:f=>{console.log(`RpcManager: User interaction failed for method: ${n}`,f),this.clearInteraction(l);const p={success:!1,message:"User interaction failed",error:f,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:p}),a(p)},dismissView:()=>{var p;console.log(`RpcManager: User dismissed interaction for method: ${n}`),console.log("RpcManager: Current interaction before dismiss:",(p=this.currentInteraction)==null?void 0:p.methodName),this.clearInteraction(l),this.currentInteraction=null,console.log("RpcManager: Current interaction after dismiss:",this.currentInteraction);const f={success:!0,data:{dismissed:!0,reason:"User dismissed the interaction"},message:"User interaction dismissed",timestamp:new Date};this.emit("rpc.interaction.dismissed",{methodName:n,response:f}),this.emit("rpc.interaction.completed",{methodName:n,response:f}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(f)},didTimeout:f=>{console.log(`RpcManager: User interaction timeout for method: ${n}`),this.clearInteraction(l),this.currentInteraction=null;const p={success:!0,message:`User interaction timed out after ${o} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...f?{timeoutView:f}:{}};this.emit("rpc.interaction.timeout",{methodName:n,response:p}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(p)}},u=setTimeout(()=>{d.didTimeout&&d.didTimeout()},o);this.activeInteractions.set(l,{resolve:f=>a(JSON.parse(f)),reject:c,timeoutId:u}),this.currentInteraction={isVisible:!0,methodName:n,component:i,presentationMode:r,timeout:o,data:s,handler:d},this.emit("rpc.interaction.started",{methodName:n,presentationMode:r}),setTimeout(async()=>{var f;if((f=this.currentInteraction)!=null&&f.handler)try{console.log(`RpcManager: Component created for method: ${n} with data:`,s)}catch(p){console.error("RpcManager: Error loading data into component:",p),d.didFail({error:"Failed to load data into component"})}},100)})}clearInteraction(n){const i=this.activeInteractions.get(n);i&&(console.log(`RpcManager: Clearing interaction: ${n}`),clearTimeout(i.timeoutId),this.activeInteractions.delete(n))}getCurrentInteraction(){return this.currentInteraction}dismissCurrentInteraction(){var n;this.currentInteraction&&(console.log(`RpcManager: Dismissing current interaction: ${this.currentInteraction.methodName}`),(n=this.currentInteraction.handler)==null||n.dismissView(),setTimeout(()=>{this.currentInteraction&&(console.log("RpcManager: Force clearing lingering interaction"),this.currentInteraction=null)},0))}getRegisteredMethods(){return Array.from(this.registeredMethods.keys())}unregisterMethod(n){this.registeredMethods.delete(n),console.log(`RpcManager: Unregistered RPC method: ${n}`)}clear(){for(const[n,i]of this.activeInteractions)clearTimeout(i.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null,console.log("RpcManager: Cleared all registrations and interactions")}}class De extends Error{constructor(e,n,i){super(e),this.code=n,this.details=i,this.name="VoxketError"}}class bo extends rh{constructor(n){super();at(this,"config");at(this,"room",null);at(this,"pluginManager");at(this,"rpcManager");at(this,"isConnected",!1);at(this,"currentSession",null);at(this,"connectionState",ge.Disconnected);at(this,"renderedComponents",new Map);at(this,"textStreamHandlersRegistered",!1);at(this,"currentAgentInfo",null);at(this,"chatMessages",[]);this.config=n,this.pluginManager=new nw(this),this.rpcManager=new Kj,this.setupEventListeners(),this.initializeClient()}setupEventListeners(){this.on("connection.connected",()=>{var n,i;this.isConnected=!0,(i=(n=this.config).onConnected)==null||i.call(n)}),this.on("connection.disconnected",n=>{var i,r;this.isConnected=!1,(r=(i=this.config).onDisconnected)==null||r.call(i,n)}),this.on("connection.error",n=>{var i,r;(r=(i=this.config).onError)==null||r.call(i,n)}),this.on("chat.message.received",n=>{var i,r;this.addChatMessage(n),(r=(i=this.config).onMessageReceived)==null||r.call(i,n)}),this.on("chat.message.updated",n=>{this.updateChatMessage(n)}),this.on("chat.message.sent",n=>{this.addChatMessage(n)}),this.on("transcription.received",n=>{var i,r;(r=(i=this.config).onTranscriptionReceived)==null||r.call(i,n)}),this.on("session.state.changed",n=>{var i,r;(r=(i=this.config).onSessionStateChanged)==null||r.call(i,n)}),this.on("session.created",n=>{var i,r;(r=(i=this.config).onSessionStart)==null||r.call(i,n.id)}),this.on("session.ended",(n,i)=>{var r,s;(s=(r=this.config).onSessionEnd)==null||s.call(r,i)}),this.on("participant.joined",n=>{var i,r;(r=(i=this.config).onUserJoined)==null||r.call(i,n.id)}),this.on("participant.left",n=>{var i,r;(r=(i=this.config).onUserLeft)==null||r.call(i,n.id)}),this.setupRpcEventForwarding()}setupRpcEventForwarding(){if(!this.rpcManager){console.warn("RpcManager not initialized, skipping event forwarding setup");return}this.rpcManager.on("rpc.method.registered",n=>this.emit("rpc.method.registered",n)),this.rpcManager.on("rpc.method.called",n=>this.emit("rpc.method.called",n)),this.rpcManager.on("rpc.interaction.started",n=>this.emit("rpc.interaction.started",n)),this.rpcManager.on("rpc.interaction.completed",n=>this.emit("rpc.interaction.completed",n)),this.rpcManager.on("rpc.interaction.timeout",n=>this.emit("rpc.interaction.timeout",n)),this.rpcManager.on("rpc.interaction.dismissed",n=>this.emit("rpc.interaction.dismissed",n))}initializeClient(){this.room=new pi,this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(U.Connected,()=>{var n,i;this.connectionState=ge.Connected,this.emit("connection.connected"),this.rpcManager.setRoom(this.room),(i=(n=this.currentSession)==null?void 0:n.activeModalities)!=null&&i.includes("voice")&&setTimeout(async()=>{var r;try{(r=this.room)!=null&&r.localParticipant&&(this.room.localParticipant.isMicrophoneEnabled?this.emit("track.unmuted",{source:"microphone",enabled:!0}):(await this.room.localParticipant.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0})))}catch(s){console.warn("VoxketClient: Failed to enable microphone after room connection:",s)}},1e3),this.textStreamHandlersRegistered||this.setupTextStreamHandlers()}),this.room.on(U.Disconnected,n=>{this.connectionState=ge.Disconnected,this.textStreamHandlersRegistered=!1,this.emit("connection.disconnected",n==null?void 0:n.toString())}),this.room.on(U.ConnectionStateChanged,n=>{this.connectionState=n,n===ge.Connecting&&this.emit("connection.connecting")}),this.room.on(U.ParticipantConnected,n=>{const i={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.joined",i)}),this.room.on(U.ParticipantDisconnected,n=>{const i={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.left",i)}))}setupTextStreamHandlers(){if(this.room){try{this.room.registerTextStreamHandler("lk.chat",async(n,i)=>{try{const r=await n.readAll(),s={id:`msg_${Date.now()}_${i.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:r,timestamp:new Date,sender:{id:i.identity||"user",name:i.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.emit("chat.message.received",s)}catch(r){console.error("VoxketClient: Failed to process lk.chat message:",r)}})}catch(n){console.warn("VoxketClient: lk.chat handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("lk.transcription",async(n,i)=>{var r,s;try{const o=`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`;let a="";const c=((r=this.currentAgentInfo)==null?void 0:r.name)||i.identity||"AI Assistant",l={id:o,content:"",timestamp:new Date,sender:{id:i.identity||"agent",name:c,type:"agent"},metadata:{topic:"lk.transcription",streaming:!0}};this.emit("chat.message.received",l);for await(const f of n){a+=f;const p=this.convertMarkdownToText(a),g={...l,content:p,metadata:{...l.metadata,streaming:!0}};this.emit("chat.message.updated",g)}const d=this.convertMarkdownToText(a),u={...l,content:d,metadata:{...l.metadata,streaming:!1}};this.emit("chat.message.updated",u)}catch(o){console.error("VoxketClient: Failed to process lk.transcription message:",o);try{const a=await n.readAll(),c=((s=this.currentAgentInfo)==null?void 0:s.name)||i.identity||"AI Assistant",l={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:a,timestamp:new Date,sender:{id:i.identity||"agent",name:c,type:"agent"},metadata:{topic:"lk.transcription"}};this.emit("chat.message.received",l)}catch(a){console.error("VoxketClient: Fallback failed for lk.transcription:",a)}}})}catch(n){console.warn("VoxketClient: lk.transcription handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("suggested_response",async n=>{const i=await n.readAll();let r=[];try{r=["tes","hello how are you","algebra make me learn that ","what is the meaning of life"]}catch(s){console.warn("VoxketClient: Failed to parse suggested_response:",s,i)}this.emit("suggested.response",r)})}catch(n){console.warn("VoxketClient: suggested_response handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("agent_state_changed",async(n,i)=>{const r=await n.readAll();let s={};try{s=typeof r=="string"?JSON.parse(r.replace(/'/g,'"')):r}catch(o){console.warn("VoxketClient: Failed to parse agent_state_changed:",o,r)}s.new_state==="speaking"?this.emit("agent.speaking",s):s.new_state==="thinking"&&this.emit("agent.thinking",s)})}catch(n){console.warn("VoxketClient: conversation_item_added handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("images",async(n,i)=>{try{const r=await n.readAll()}catch(r){console.error("VoxketClient: Error processing images stream:",r)}})}catch(n){console.warn("VoxketClient: images handler already registered, skipping:",n)}try{this.room.registerByteStreamHandler("images",async(n,i)=>{var r,s;try{const o=n.info,a={id:`img_${Date.now()}_${i.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`�️ ${o.name||"Image"}`,sender:{id:i.identity||"agent",name:i.identity||"Agent",type:i.identity===((s=(r=this.room)==null?void 0:r.localParticipant)==null?void 0:s.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:o.name,fileSize:o.size,mimeType:o.mimeType,streamId:o.id,downloading:!0}};this.emit("chat.message.received",a),n.onProgress&&(n.onProgress=f=>{const p={...a,metadata:{...a.metadata,downloadProgress:f||0}};this.emit("chat.message.updated",p)});const c=[];for await(const f of n)c.push(f);const l=new Blob(c,{type:o.mimeType||"application/octet-stream"}),d=URL.createObjectURL(l),u={...a,metadata:{...a.metadata,downloading:!1,downloadProgress:1,downloadUrl:d,blob:l}};this.emit("chat.message.updated",u)}catch(o){console.error("VoxketClient: Error processing image attachment:",o)}})}catch(n){console.warn("VoxketClient: image handler already registered, skipping:",n)}this.textStreamHandlersRegistered=!0}}async fetchConnectionDetails(n,i,r){const s=n||this.config.agentId||"default-agent",o=i||this.config.participantName||"User",a=r||this.config.modalities||["voice"];try{const c={agent_id:s,participant_name:o,participant_metadata:{user_id:""},modality:a[0]},l=await fetch(`${this.config.baseUrl}/api/live/agent/session`,{method:"POST",headers:{accept:"application/json","X-APP-ID":this.config.appId,"X-APP-SECRET":this.config.appSecret,"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){let f=`HTTP ${l.status}: Failed to fetch connection details`;try{const p=await l.json();p&&(p.error?f=`API Error: ${p.error}`:p.detail?f=`API Error: ${p.detail}`:p.message&&(f=`API Error: ${p.message}`))}catch{try{const g=await l.text();g&&(f=`API Error: ${g}`)}catch{}}throw new Error(f)}const d=await l.json();let u;return d.agent_info&&(u={id:d.agent_info.id||s,name:d.agent_info.name||"AI Assistant",avatar:d.agent_info.avatar,capabilities:d.agent_info.capabilities||["voice_interaction","text_chat"],metadata:d.agent_info.metadata||{}},this.currentAgentInfo=u),{serverUrl:d.wss_url,participantToken:d.token,voxketSessionId:d.session_id,agentInfo:u}}catch(c){console.error("VoxketClient: fetchConnectionDetails failed:",c);const l=new De(`Failed to fetch connection details: ${c instanceof Error?c.message:"Unknown error"}`,"CONNECTION_FAILED",c);throw this.emit("connection.error",l),l}}async connect(n,i,r){var s;try{this.emit("connection.connecting");const o=await this.fetchConnectionDetails(n,i,r);return await((s=this.room)==null?void 0:s.connect(o.serverUrl,o.participantToken)),this.isConnected=!0,o}catch(o){console.error("VoxketClient: Connection failed:",o);const a=new De(`Failed to connect to Voxket services: ${o instanceof Error?o.message:"Unknown error"}`,"CONNECTION_FAILED",o);throw this.emit("connection.error",a),a}}async disconnect(){var n;try{await((n=this.room)==null?void 0:n.disconnect()),this.isConnected=!1,this.currentSession=null,this.currentAgentInfo=null,this.textStreamHandlersRegistered=!1,this.clearChatMessages(),this.room=new pi,this.setupRoomEventListeners()}catch(i){const r=new De("Failed to disconnect properly","NETWORK_ERROR",i);throw this.emit("connection.error",r),r}}async createSession(n){var i,r;try{const s=await this.connect(n.agentId,n.participantName,n.modalities),o={id:s.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:s.agentInfo||this.currentAgentInfo};if(this.currentSession=o,this.emit("session.created",o),(i=n.modalities)!=null&&i.includes("voice"))try{await new Promise(a=>setTimeout(a,500)),(r=this.room)!=null&&r.localParticipant?(await this.room.localParticipant.setMicrophoneEnabled(!0,void 0,{preConnectBuffer:!0}),this.emit("track.unmuted",{source:"microphone",enabled:!0})):console.warn("VoxketClient: No local participant found, microphone not enabled")}catch(a){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",a)}return setTimeout(()=>{this.currentSession&&(this.currentSession.state="active",this.emit("session.state.changed","active",this.currentSession.state))},1e3),o}catch(s){throw console.error("VoxketClient: Failed to create session:",s),s instanceof De?s:s instanceof TypeError&&s.message.includes("fetch")?new De("Network connection failed","CONNECTION_FAILED",s):s instanceof Error&&s.message.includes("Failed to fetch connection details")?new De(`API connection failed: ${s.message}`,"CONNECTION_FAILED",s):new De(`Failed to create session: ${s instanceof Error?s.message:"Unknown error"}`,"SESSION_NOT_FOUND",s)}}async startSession(n,i){const r={agentId:n||this.config.agentId||"default-agent",participantName:(i==null?void 0:i.participantName)||this.config.participantName||"User",modalities:(i==null?void 0:i.modalities)||this.config.modalities||["voice","chat"],metadata:i==null?void 0:i.metadata};return this.createSession(r)}async endSession(){var n,i;if(!this.currentSession)return null;try{const r={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((i=this.room)==null?void 0:i.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]};return this.currentSession.endedAt=new Date,this.currentSession.state="disconnected",this.emit("session.ended",this.currentSession,r),await this.disconnect(),r}catch(r){throw new De("Failed to end session","SESSION_NOT_FOUND",r)}}getCurrentSession(){return this.currentSession}getCurrentAgentInfo(){return this.currentAgentInfo}getChatMessages(){return[...this.chatMessages]}addChatMessage(n){this.chatMessages.some(r=>r.id===n.id)||this.chatMessages.push(n)}updateChatMessage(n){const i=this.chatMessages.findIndex(r=>r.id===n.id);i!==-1&&(this.chatMessages[i]=n)}clearChatMessages(){this.chatMessages=[],this.dismissCurrentInteraction(),this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays(),this.emit("chat.history.cleared")}renderUI(n={}){var c,l,d;const i=this.resolveTarget(n.target||"body"),r=this.getTargetKey(i),s=this.renderedComponents.get(r);s&&s.target===i||this.removeUI(i);const o=(s==null?void 0:s.root)||$j.createRoot(i),a={agentId:n.agentId||this.config.agentId||"default-agent",participantName:n.participantName||this.config.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:n.className,theme:typeof n.theme=="string"?n.theme:void 0,modalities:n.modality||this.config.modalities||["voice"],suportsChatInput:((c=n.modality)==null?void 0:c.includes("chat"))!==!1,suportsVideoInput:((l=n.modality)==null?void 0:l.includes("video"))===!0,suportsScreenShare:((d=n.modality)==null?void 0:d.includes("screen_share"))===!0,autoStart:n.autoStart,displayType:n.displayType||"widget",popupPosition:n.popupPosition||"bottom-right",popupTriggerText:n.popupTriggerText||"Open Chat",width:n.width,height:n.height,onDisplayTypeChange:n.onDisplayTypeChange,prompts:n.prompts,statusMessage:n.statusMessage,welcomeTitle:n.welcomeTitle,welcomeSubTitle:n.welcomeSubTitle,loadingText:n.loadingText,voxketClient:this};o.render(R.createElement(rw,{config:this.config,autoConnect:n.autoStart||!1,children:R.createElement(sw,a)})),this.renderedComponents.set(r,{root:o,target:i})}removeUI(n){const i=n?this.resolveTarget(n):null;if(i){const r=this.getTargetKey(i),s=this.renderedComponents.get(r);s&&(s.root.unmount(),this.renderedComponents.delete(r),i.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(a=>{try{a.remove()}catch(c){console.warn("Failed to remove element:",c)}}),i===document.body&&i.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(c=>{if(c.classList.contains("bg-black")&&c.classList.contains("backdrop-blur-sm"))try{c.remove()}catch(l){console.warn("Failed to remove fixed element:",l)}}))}}removeAllUI(){for(const[n,i]of this.renderedComponents)i.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(i=>{if(i.classList.contains("bg-black")&&(i.classList.contains("backdrop-blur-sm")||i.classList.contains("bg-opacity-30")))try{i.remove()}catch(r){console.warn("Failed to remove overlay:",r)}})}resolveTarget(n){if(typeof n=="string"){const i=document.querySelector(n);if(!i)throw new Error(`Target element not found: ${n}`);return i}return n}getTargetKey(n){return n.id?n.id:n.className?n.tagName+"_"+n.className.replace(/\s+/g,"_"):n.tagName+"_"+n.outerHTML.length%1e3}async sendMessage(n,i){var r;if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new De("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new De("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new De("No local participant","CONNECTION_FAILED");this.dismissCurrentInteraction();try{const s={id:`msg_${Date.now()}`,content:n,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:i||{}},o=await((r=this.room)==null?void 0:r.localParticipant.sendText(n,{topic:"lk.chat",destinationIdentities:[]}));this.emit("chat.message.sent",s)}catch(s){throw console.error("VoxketClient: Failed to send chat message:",s),new De("Failed to send message","NETWORK_ERROR",s)}}async sendChatMessage(n,i){return this.sendMessage(n,i)}async sendAttachments(n,i){if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new De("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new De("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new De("No local participant","CONNECTION_FAILED");if(!n||n.length===0)throw new De("No files provided","INVALID_PARAMETER");this.dismissCurrentInteraction();const r=n.filter(s=>s.type.startsWith("image/"));if(r.length===0)throw new De("Only image files are allowed","INVALID_PARAMETER");r.length!==n.length&&console.warn("VoxketClient: Some non-image files were filtered out");try{const s=r.map(async(o,a)=>{const l={id:`att_${Date.now()}_${a}`,content:`📎 ${o.name}`,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:{...i,type:"attachment",fileName:o.name,fileSize:o.size,mimeType:o.type,uploading:!0}};this.emit("chat.message.sent",l);const d=await this.room.localParticipant.sendFile(o,{mimeType:o.type,topic:"images",onProgress:f=>{const p={...l,metadata:{...l.metadata,uploadProgress:f}};this.emit("chat.message.updated",p)}});try{const f=new FileReader,p=new Promise((y,b)=>{f.onload=()=>{typeof f.result=="string"?y(f.result):b(new Error("Failed to convert to base64"))},f.onerror=b});f.readAsDataURL(o);const h={type:"image",data:await p,filename:o.name,mimeType:o.type,size:o.size};await this.room.localParticipant.sendText(JSON.stringify(h),{topic:"images",destinationIdentities:[]})}catch(f){console.warn("VoxketClient: Failed to send image data to agent:",f);try{const p=`I've shared an image: ${o.name}`;await this.room.localParticipant.sendText(p,{topic:"lk.chat",destinationIdentities:[]})}catch(p){console.warn("VoxketClient: Failed to send image notification to agent:",p)}}const u={...l,metadata:{...l.metadata,uploading:!1,uploadProgress:1,streamId:d.id}};return this.emit("chat.message.updated",u),d});await Promise.all(s)}catch(s){throw console.error("VoxketClient: Failed to send attachments:",s),new De("Failed to send attachments","NETWORK_ERROR",s)}}async sendAttachment(n,i){return this.sendAttachments([n],i)}toggleMicrophone(n){return this.setMicrophoneEnabled(n!==!1)}async setMicrophoneEnabled(n){var i,r;try{const s=(i=this.room)==null?void 0:i.localParticipant.isMicrophoneEnabled,o=n??!s;await((r=this.room)==null?void 0:r.localParticipant.setMicrophoneEnabled(o)),o?this.emit("track.unmuted",{source:"microphone",enabled:!0}):this.emit("track.muted",{source:"microphone",enabled:!1})}catch(s){throw console.error("VoxketClient: Failed to toggle microphone:",s),new De("Failed to toggle microphone","PERMISSION_DENIED",s)}}toggleCamera(n){return this.setCameraEnabled(n!==!1)}async setCameraEnabled(n){var i,r;try{const s=(i=this.room)==null?void 0:i.localParticipant.isCameraEnabled,o=n??!s;await((r=this.room)==null?void 0:r.localParticipant.setCameraEnabled(o)),o?this.emit("track.unmuted",{source:"camera",enabled:!0}):this.emit("track.muted",{source:"camera",enabled:!1})}catch(s){throw console.error("VoxketClient: Failed to toggle camera:",s),new De("Failed to toggle camera","PERMISSION_DENIED",s)}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!0))}catch(i){throw new De("Failed to start screen share","PERMISSION_DENIED",i)}}async stopScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!1))}catch(i){throw new De("Failed to stop screen share","PERMISSION_DENIED",i)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(i=>i.kind==="audioinput")}catch(n){throw new De("Failed to get audio input devices","DEVICE_ERROR",n)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(i=>i.kind==="videoinput")}catch(n){throw new De("Failed to get video input devices","DEVICE_ERROR",n)}}async setAudioInputDevice(n){var i;try{if(!((i=this.room)!=null&&i.localParticipant))throw new Error("Not connected to room")}catch(r){throw new De("Failed to set audio input device","DEVICE_ERROR",r)}}async setVideoInputDevice(n){var i;try{if(!((i=this.room)!=null&&i.localParticipant))throw new Error("Not connected to room")}catch(r){throw new De("Failed to set video input device","DEVICE_ERROR",r)}}getLocalParticipant(){var n;return((n=this.room)==null?void 0:n.localParticipant)??null}getRemoteParticipants(){var n;return Array.from(((n=this.room)==null?void 0:n.remoteParticipants.values())??[])}getPublishPermissions(){const n=this.getLocalParticipant();if(!n)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const i=n.permissions;if(!i)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const r=s=>!!i.canPublish&&(i.canPublishSources.length===0||i.canPublishSources.includes(s));return{camera:r(1),microphone:r(2),screenShare:r(3),data:i.canPublishData??!1}}canPublishSource(n){return this.getPublishPermissions()[n]}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===ge.Connected}getMicrophoneTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,i]of n.trackPublications)if(i.source===V.Source.Microphone)return i.track;return null}getCameraTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,i]of n.trackPublications)if(i.source===V.Source.Camera)return i.track;return null}getScreenShareTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,i]of n.trackPublications)if(i.source===V.Source.ScreenShare)return i.track;return null}get isMicrophoneEnabled(){const n=this.getMicrophoneTrack();return n?!n.isMuted:!1}get isCameraEnabled(){const n=this.getCameraTrack();return n?!n.isMuted:!1}get isScreenShareEnabled(){const n=this.getScreenShareTrack();return n?!n.isMuted:!1}registerPlugin(n){this.pluginManager.register(n)}getPluginManager(){return this.pluginManager}getParticipants(){if(!this.room)return[];const n=[];return this.room.localParticipant&&n.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(i=>{n.push({id:i.identity,name:i.name||i.identity,isLocal:!1})}),n}getSessionMetrics(){var n,i;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((i=this.room)==null?void 0:i.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]}:null}updateConfig(n){this.config={...this.config,...n}}async startRecording(){var n;try{this.emit("recording.started",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(i){throw new De("Failed to start recording","RECORDING_ERROR",i)}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(i){throw new De("Failed to stop recording","RECORDING_ERROR",i)}}async registerFrontendRPC(n,i,r="embedded"){return this.rpcManager.registerFrontendRPC(n,i,r)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}registerEventListener(n,i){return this.on(n,i)}registerEventEmitter(n,i){if(!this.room)throw new Error("Room not available");try{this.room.registerTextStreamHandler(n,async r=>{try{const s=await r.readAll();i(s)}catch(s){console.error(`Error processing event for topic '${n}':`,s)}})}catch(r){console.warn(`VoxketClient: Handler for topic '${n}' may already be registered:`,r)}}convertMarkdownToText(n){if(!n)return"";let i=n;return i=i.replace(/\*\*(.*?)\*\*/g,"$1"),i=i.replace(/__(.*?)__/g,"$1"),i=i.replace(/\*(.*?)\*/g,"$1"),i=i.replace(/_(.*?)_/g,"$1"),i=i.replace(/~~(.*?)~~/g,"$1"),i=i.replace(/`([^`]+)`/g,"$1"),i=i.replace(/```[\s\S]*?```/g,""),i=i.replace(/^#{1,6}\s+/gm,""),i=i.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),i.trim()}}function Gj({children:t,className:e="",theme:n="vox",style:i}){const r=["voxket-widget-root",`theme-${n}`,e].filter(Boolean).join(" ");return m.jsx("div",{className:r,style:i,children:t})}const Zj=xe.create(kj),Yj=xe.create(Oj),Jj=xe.create(Lj),Xj=xe.create(Uj);function Qj({onClick:t,text:e="Open Chat",position:n="bottom-right",theme:i}){const r={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},s=St(i);return m.jsx(xe.button,{onClick:t,className:`fixed ${r[n]} z-50 px-4 py-2 rounded-full shadow-lg ${s.popupTrigger} transition-all duration-200 hover:scale-105`,initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:0,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},children:e})}function P0({children:t,theme:e,displayType:n="widget",onClose:i,popupPosition:r="bottom-right",onExpand:s}){const o=St(e);if(n==="fullscreen")return m.jsx("div",{className:"fixed inset-0 z-50 bg-black bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",children:m.jsxs("div",{className:"w-full h-full max-w-6xl max-h-[90vh] rounded-2xl relative bg-transparent",children:[i&&m.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),i()},className:"absolute top-4 cursor-pointer right-4 z-[100] w-12 h-12 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border border-gray-700 backdrop-blur-sm",title:"Exit Fullscreen",type:"button",children:m.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:m.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),m.jsxs("div",{id:"voice-card",className:`${o.card} w-full h-full flex flex-col rounded-xl shadow-2xl`,style:{minHeight:"600px"},children:[m.jsx("div",{className:o.cardTopGradient}),m.jsx("div",{className:o.cardPurpleBlur}),m.jsx("div",{className:o.cardPinkBlur}),m.jsx("div",{className:" flex flex-col h-full",children:t}),m.jsx("div",{className:o.cardPulse1}),m.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){const a={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"};return m.jsx("div",{className:"fixed rounded-2xl inset-0 z-50 pointer-events-none",children:m.jsxs("div",{className:`fixed rounded-2xl ${a[r]} pointer-events-auto`,children:[i&&m.jsx("button",{onClick:i,className:"absolute -top-2 -right-2 z-10 w-8 h-8 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 text-sm shadow-lg border border-gray-700",children:"×"}),m.jsxs("div",{id:"voice-card",className:`${o.card} rounded-2xl flex flex-col`,style:{width:"300px",height:"450px"},children:[m.jsx("div",{className:o.cardPurpleBlur}),m.jsx("div",{className:o.cardPinkBlur}),m.jsx("div",{className:" flex flex-col h-full",children:t}),m.jsx("div",{className:o.cardPulse1}),m.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return m.jsxs("div",{id:"voice-card",className:`${o.card}`,children:[s&&m.jsx("button",{onClick:s,className:"absolute top-4 right-4 z-20 w-10 h-10 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border border-gray-700 backdrop-blur-sm",title:"Enter Fullscreen",children:m.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:m.jsx("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})})}),m.jsx("div",{className:o.cardTopGradient}),m.jsx("div",{className:o.cardPurpleBlur}),m.jsx("div",{className:o.cardPinkBlur}),t,m.jsx("div",{className:o.cardPulse1}),m.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})}function sw(t){if(typeof window>"u")return null;console.log("🎯 Widget component rendering with props:",{displayType:t.displayType,popupPosition:t.popupPosition,theme:t.theme});const{agentId:e,participantName:n,baseUrl:i,appSecret:r,appId:s,prompts:o,statusMessage:a,welcomeTitle:c,welcomeSubTitle:l,className:d,width:u,height:f,loadingText:p,suportsChatInput:g=!0,suportsVideoInput:h=!0,suportsScreenShare:y=!0,theme:b="vox",onSessionStart:w,onSessionEnd:C,enableSessionLogging:S=!0,onSessionLogsUpdate:x,onSessionMetricsUpdate:T,modalities:E=["voice"],displayType:P="widget",popupPosition:_="bottom-right",popupTriggerText:k="Open Chat",onPopupToggle:I,voxketClient:N,onDisplayTypeChange:K}=t,[J,se]=v.useState(()=>N?!!N.getCurrentSession():!1),[ie,X]=v.useState(!1),[O,oe]=v.useState(e||""),[L,F]=v.useState(n||"User"),[te,j]=v.useState(()=>N?N.getCurrentSession():null),[q,ee]=v.useState(()=>{var ve,tn,At;if(N){const $e=N.getCurrentSession();if((ve=$e==null?void 0:$e.activeModalities)!=null&&ve.includes("chat"))return"chat";if((tn=$e==null?void 0:$e.activeModalities)!=null&&tn.includes("voice"))return"voice";if((At=$e==null?void 0:$e.activeModalities)!=null&&At.includes("video"))return"video"}return"welcome"}),[G,D]=v.useState(!1);v.useEffect(()=>{console.log("🎯 Widget displayType prop changed to:",P)},[P]),v.useEffect(()=>{console.log("📊 Session state changed:",{currentMode:q,sessionStarted:J,loading:ie,currentSession:te==null?void 0:te.id,isPopupOpen:G})},[q,J,ie,te,G]);const $=v.useMemo(()=>{if(N)return console.log("🔄 Using passed VoxketClient to preserve session state"),N;console.log("🆕 Creating new VoxketClient instance");const ve={appId:s,appSecret:r,baseUrl:i,agentId:O,participantName:L||"User",modalities:E};return new bo(ve)},[N,s,r,i,O,L,E]),Q=E,W=v.useMemo(()=>$.getRoom()||new pi,[$]),ce={suportsChatInput:g,suportsVideoInput:h,suportsScreenShare:y},{sessionMetrics:z,sessionLogs:me,logEvent:Ee}=tw({room:W,onSessionStart:w,onSessionEnd:C,enableConsoleLogging:S,enableLocalStorage:S,voxketSessionId:te==null?void 0:te.id});v.useEffect(()=>{x&&x(me)},[me,x]),v.useEffect(()=>{T&&z&&T(z)},[z,T]),v.useEffect(()=>{const ve=At=>{console.log("🔴 Room disconnected:",At),X(!1),se(!1),j(null),ee("welcome")},tn=At=>{console.log("📹 Media devices error:",At),No({title:"Allow access to your microphone/camera",description:`${At.name}: ${At.message}`})};return W.on(U.MediaDevicesError,tn),W.on(U.Disconnected,ve),()=>{W.off(U.Disconnected,ve),W.off(U.MediaDevicesError,tn)}},[W]);const qe=async()=>{try{console.log("🎤 Starting voice session...",{agentId:O,participantName:L}),console.log("🎤 Pre-start state:",{currentMode:q,sessionStarted:J,loading:ie}),X(!0),se(!0),ee("voice"),console.log("🎤 State after mode change:",{currentMode:"voice",sessionStarted:!0,loading:!0}),Ee("USER_STARTED_VOICE_SESSION",{agentId:O,participantName:L});const ve=await $.startSession(O,{participantName:L||"User",modalities:["voice",...h?["video"]:[]]});console.log("✅ Voice session started successfully:",ve.id),j(ve),X(!1),w&&w(ve.id)}catch(ve){console.error("❌ Failed to start voice session:",ve),No({title:"Failed to start voice session",description:ve instanceof Error?ve.message:"Unknown error occurred"}),X(!1),se(!1),ee("welcome")}},Ct=async()=>{try{X(!0),se(!0),ee("chat"),Ee("USER_STARTED_CHAT_SESSION",{agentId:O,participantName:L});const ve=await $.startSession(O,{participantName:L||"User",modalities:["chat"]});j(ve),X(!1),w&&w(ve.id)}catch(ve){console.error("Failed to start chat session:",ve),No({title:"Failed to start chat session",description:ve instanceof Error?ve.message:"Unknown error occurred"}),X(!1),se(!1),ee("welcome")}},gn=async()=>{try{console.log("📺 Starting video session...",{agentId:O,participantName:L}),console.log("📺 Pre-start state:",{currentMode:q,sessionStarted:J,loading:ie}),X(!0),se(!0),ee("video"),console.log("📺 State after mode change:",{currentMode:"video",sessionStarted:!0,loading:!0}),Ee("USER_STARTED_VIDEO_SESSION",{agentId:O,participantName:L});const ve=await $.startSession(O,{participantName:L||"User",modalities:["video","voice"]});console.log("✅ Video session started successfully:",ve.id),j(ve),X(!1),w&&w(ve.id)}catch(ve){console.error("❌ Failed to start video session:",ve),No({title:"Failed to start video session",description:ve instanceof Error?ve.message:"Unknown error occurred"}),X(!1),se(!1),ee("welcome")}},vn=()=>{ee("welcome"),K&&K(t.displayType||"widget"),te&&J&&(se(!1),j(null),$.disconnect()),P==="popup"&&!G&&D(!0)},Et=()=>{const ve=!G;D(ve),I&&I(ve),!ve&&!(te&&J)&&(ee("welcome"),se(!1),j(null))},Ec=()=>{console.log("🔄 Closing fullscreen, switching to widget display type"),t.onDisplayTypeChange?t.onDisplayTypeChange("widget"):console.warn("⚠️ No onDisplayTypeChange callback provided")},Pc=()=>{t.onDisplayTypeChange&&t.onDisplayTypeChange("fullscreen")};v.useEffect(()=>{var ve,tn,At;if(N&&$){console.log("🔄 Syncing widget state with existing client session state");const $e=$.getCurrentSession(),Rc=$.connected;console.log("🔍 Existing session state:",{hasSession:!!$e,sessionId:$e==null?void 0:$e.id,isConnected:Rc,activeModalities:$e==null?void 0:$e.activeModalities}),$e&&(console.log("✅ Restoring session state from existing client"),j($e),se(!0),X(!1),(ve=$e.activeModalities)!=null&&ve.includes("chat")?ee("chat"):(tn=$e.activeModalities)!=null&&tn.includes("voice")?ee("voice"):(At=$e.activeModalities)!=null&&At.includes("video")&&ee("video"))}},[N,$]),v.useEffect(()=>()=>{console.log("🧹 Cleaning up widget component"),N?console.log("🔄 Widget cleanup: preserving passed client instance"):(console.log("🧹 Widget cleanup: disconnecting self-created client"),$.disconnect())},[$,N]);let _i="w-96",ms="h-[25rem]",ps={};if(u&&(u.startsWith("w-")?_i=u:(ps.width=u,_i="")),f&&(f.startsWith("h-")?ms=f:(ps.height=f,ms="")),P==="popup"&&!G)return console.log("🟡 Showing popup trigger button"),m.jsx(Qj,{onClick:Et,text:k,position:_,theme:b});console.log("🟢 Rendering widget content, displayType:",P,"isPopupOpen:",G,"currentMode:",q,"sessionStarted:",J,"loading:",ie);let or=`voxket-widget-root theme-${b}`,Ni={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};P==="widget"?(or+=` flex items-center justify-center min-h-fit ${_i} ${ms} ${d}`,Ni={...Ni,...ps}):(or=`${d||""}`,Ni={});const gs=m.jsx(Gj,{theme:b,children:m.jsxs(Vr,{mode:"wait",children:[q==="welcome"&&!ie&&m.jsx(Xj,{agentId:O,participantName:L||"",onAgentIdChange:oe,onParticipantNameChange:F,onStartCall:qe,onStartChat:Ct,onStartVideo:gn,disabled:J||ie,prompts:o,statusMessage:a,title:c,subTitle:l,theme:b,modalities:Q,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),q==="voice"&&m.jsxs(Da.Provider,{value:W,children:[m.jsx(tg,{}),m.jsx(Xp,{label:"Start Audio"}),m.jsx(Zj,{loadingText:p,participantName:L||"User",capabilities:ce,sessionStarted:J,disabled:!J,theme:b,client:$,displayType:P,onBack:P==="popup"?Et:vn,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"session-view")]}),q==="chat"&&m.jsx(Yj,{client:$,theme:b,displayType:P,onBack:P==="popup"?Et:vn,onEndChat:vn,disabled:!J,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),q==="video"&&m.jsxs(Da.Provider,{value:W,children:[m.jsx(tg,{}),m.jsx(Xp,{label:"Start Audio"}),m.jsx(Jj,{client:$,theme:b,displayType:P,onBack:P==="popup"?Et:vn,onEndCall:vn,disabled:!J,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-view")]})]})});return P==="fullscreen"||P==="popup"?(console.log("📱 Rendering fullscreen/popup mode, displayType:",P),m.jsx(P0,{theme:b,displayType:P,popupPosition:_,onClose:P==="fullscreen"?Ec:Et,children:gs})):(console.log("📦 Rendering widget mode"),m.jsx("div",{className:or,style:Ni,children:m.jsx(P0,{theme:b,displayType:P,popupPosition:_,onExpand:Pc,children:gs})}))}function eL({logs:t,onClear:e,onExport:n}){const[i,r]=R.useState(!1),[s,o]=R.useState(""),a=t.filter(c=>!s||c.event.toLowerCase().includes(s.toLowerCase()));return i?m.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:m.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[m.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[m.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",t.length,")"]}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("input",{type:"text",placeholder:"Filter events...",value:s,onChange:c=>o(c.target.value),className:"px-3 py-1 border rounded text-sm"}),m.jsx("button",{onClick:e,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),m.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),m.jsx("button",{onClick:()=>r(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),m.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?m.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):m.jsx("div",{className:"space-y-2",children:a.map((c,l)=>m.jsxs("div",{className:"border rounded p-3 text-sm",children:[m.jsxs("div",{className:"flex items-center justify-between mb-1",children:[m.jsx("span",{className:"font-semibold text-blue-600",children:c.event}),m.jsx("span",{className:"text-gray-500 text-xs",children:new Date(c.timestamp).toLocaleTimeString()})]}),c.sessionId&&m.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",c.sessionId]}),c.data&&m.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:m.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(c.data,null,2)})})]},l))})})]})}):m.jsxs("button",{onClick:()=>r(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",t.length,")"]})}function tL({metrics:t}){return t?m.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[m.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),m.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Session ID:"}),m.jsx("div",{className:"font-mono text-xs",children:t.sessionId})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Start Time:"}),m.jsx("div",{children:new Date(t.startTime).toLocaleString()})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Messages:"}),m.jsx("div",{children:t.totalMessages})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Participants:"}),m.jsx("div",{children:t.participantCount})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),m.jsx("div",{children:t.connectionIssues})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Duration:"}),m.jsxs("div",{children:[Math.round((Date.now()-new Date(t.startTime).getTime())/1e3),"s"]})]})]})]}):null}function sr(){const{currentSession:t,sessionState:e,sessionMetrics:n,createSession:i,endSession:r}=jn(),s=R.useCallback(async(a,c)=>await i(a,c),[i]),o=R.useCallback(async()=>await r(),[r]);return{session:t,state:e,metrics:n,isActive:t!==null&&e!=="disconnected",isConnecting:e==="connecting",isConnected:e==="connected"||e==="active",start:s,stop:o}}function ow(){const{sessionMetrics:t,currentSession:e}=jn();return{metrics:t,sessionId:e==null?void 0:e.id,duration:t==null?void 0:t.duration,participantCount:t==null?void 0:t.participantCount,messageCount:t==null?void 0:t.messageCount,audioQuality:t==null?void 0:t.audioQuality,networkStats:t==null?void 0:t.networkStats}}function aw(){const{setMicrophoneEnabled:t,client:e}=jn(),[n,i]=R.useState(!1),[r,s]=R.useState(!1),o=R.useCallback(async()=>{if(!r){s(!0);try{const l=!n;await t(l),i(l)}catch(l){console.error("Failed to toggle microphone:",l)}finally{s(!1)}}},[n,r,t]),a=R.useCallback(async()=>{if(!(n||r)){s(!0);try{await t(!0),i(!0)}catch(l){console.error("Failed to enable microphone:",l)}finally{s(!1)}}},[n,r,t]),c=R.useCallback(async()=>{if(!(!n||r)){s(!0);try{await t(!1),i(!1)}catch(l){console.error("Failed to disable microphone:",l)}finally{s(!1)}}},[n,r,t]);return{isEnabled:n,isLoading:r,toggle:o,enable:a,disable:c}}function cw(){const{setCameraEnabled:t}=jn(),[e,n]=R.useState(!1),[i,r]=R.useState(!1),s=R.useCallback(async()=>{if(!i){r(!0);try{const c=!e;await t(c),n(c)}catch(c){console.error("Failed to toggle camera:",c)}finally{r(!1)}}},[e,i,t]),o=R.useCallback(async()=>{if(!(e||i)){r(!0);try{await t(!0),n(!0)}catch(c){console.error("Failed to enable camera:",c)}finally{r(!1)}}},[e,i,t]),a=R.useCallback(async()=>{if(!(!e||i)){r(!0);try{await t(!1),n(!1)}catch(c){console.error("Failed to disable camera:",c)}finally{r(!1)}}},[e,i,t]);return{isEnabled:e,isLoading:i,toggle:s,enable:o,disable:a}}function lw(){const{startScreenShare:t,stopScreenShare:e}=jn(),[n,i]=R.useState(!1),[r,s]=R.useState(!1),o=R.useCallback(async()=>{if(!(n||r)){s(!0);try{await t(),i(!0)}catch(l){console.error("Failed to start screen share:",l)}finally{s(!1)}}},[n,r,t]),a=R.useCallback(async()=>{if(!(!n||r)){s(!0);try{await e(),i(!1)}catch(l){console.error("Failed to stop screen share:",l)}finally{s(!1)}}},[n,r,e]),c=R.useCallback(async()=>{n?await a():await o()},[n,o,a]);return{isSharing:n,isLoading:r,start:o,stop:a,toggle:c}}function nL(){const{client:t}=jn(),[e,n]=R.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),i=R.useMemo(()=>e.tracks.find(h=>h.isLocal),[e.tracks]),r=R.useMemo(()=>e.tracks.filter(h=>!h.isLocal),[e.tracks]),s=R.useCallback(async()=>{try{i!=null&&i.isEnabled?await(t==null?void 0:t.disableCamera()):await(t==null?void 0:t.enableCamera())}catch(h){throw console.error("Failed to toggle camera:",h),h}},[t,i]),o=R.useCallback(async()=>{try{e.tracks.find(y=>y.isScreenShare)?await(t==null?void 0:t.stopScreenShare()):await(t==null?void 0:t.startScreenShare())}catch(h){throw console.error("Failed to toggle screen share:",h),h}},[t,e.tracks]),a=R.useCallback(h=>{n(y=>({...y,layout:h}))},[]),c=R.useCallback(h=>{n(y=>({...y,pinnedTrack:h}))},[]),l=R.useCallback(()=>{n(h=>({...h,pinnedTrack:void 0}))},[]),d=R.useCallback(async()=>{try{await(t==null?void 0:t.startRecording()),n(h=>({...h,isRecording:!0}))}catch(h){throw console.error("Failed to start recording:",h),h}},[t]),u=R.useCallback(async()=>{try{await(t==null?void 0:t.stopRecording()),n(h=>({...h,isRecording:!1}))}catch(h){throw console.error("Failed to stop recording:",h),h}},[t]),f=R.useCallback(h=>e.tracks.find(y=>y.id===h),[e.tracks]),p=R.useCallback(h=>e.tracks.filter(y=>y.participantId===h),[e.tracks]),g=R.useCallback(h=>h.isEnabled&&e.tracks.includes(h),[e.tracks]);return R.useEffect(()=>{if(!t)return;const h=w=>{n(C=>({...C,tracks:[...C.tracks.filter(S=>S.id!==w.id),w]}))},y=w=>{n(C=>{var S;return{...C,tracks:C.tracks.filter(x=>x.id!==w),pinnedTrack:((S=C.pinnedTrack)==null?void 0:S.id)===w?void 0:C.pinnedTrack}})},b=w=>{n(C=>({...C,tracks:C.tracks.map(S=>S.id===w.id?w:S)}))};return t.on("videoTrackAdded",h),t.on("videoTrackRemoved",y),t.on("videoTrackUpdated",b),()=>{t.off("videoTrackAdded",h),t.off("videoTrackRemoved",y),t.off("videoTrackUpdated",b)}},[t]),{tracks:e.tracks,localTrack:i,remoteTraracks:r,pinnedTrack:e.pinnedTrack,layout:e.layout,isRecording:e.isRecording,toggleCamera:s,toggleScreenShare:o,setLayout:a,pinTrack:c,unpinTrack:l,startRecording:d,stopRecording:u,getTrackById:f,getTracksByParticipant:p,isTrackActive:g}}function Tc(){const{chatMessages:t,sendChatMessage:e,currentSession:n}=jn(),[i,r]=R.useState(!1),s=R.useCallback(async l=>{if(!(!l.trim()||i||!n)){r(!0);try{await e(l.trim())}catch(d){throw console.error("Failed to send chat message:",d),d}finally{r(!1)}}},[e,i,n]),{userMessages:o,agentMessages:a,allMessages:c}=R.useMemo(()=>{const l=t.filter(u=>u.sender.type==="participant"),d=t.filter(u=>u.sender.type==="agent");return{userMessages:l,agentMessages:d,allMessages:t}},[t]);return{messages:c,userMessages:o,agentMessages:a,messageCount:c.length,isSending:i,canSend:!!n&&!i,send:s}}function iL(){const{send:t,isSending:e,canSend:n}=Tc(),[i,r]=R.useState(""),s=R.useCallback(async()=>{if(!(!i.trim()||!n))try{await t(i),r("")}catch(a){throw a}},[i,t,n]),o=R.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),s())},[s]);return{value:i,setValue:r,send:s,handleKeyPress:o,isSending:e,canSend:n&&i.trim().length>0}}function oh(){const{isConnected:t,isConnecting:e,connectionError:n,connect:i,disconnect:r}=jn(),s=R.useCallback(async()=>{if(!(t||e))try{await i()}catch(a){throw console.error("Failed to connect:",a),a}},[i,t,e]),o=R.useCallback(async()=>{if(t)try{await r()}catch(a){throw console.error("Failed to disconnect:",a),a}},[r,t]);return{isConnected:t,isConnecting:e,isDisconnected:!t&&!e,error:n,hasError:!!n,connect:s,disconnect:o}}function dw(){const{participants:t}=jn();return{participants:t,count:t.length,localParticipant:t.find(e=>e.isLocal),remoteParticipants:t.filter(e=>!e.isLocal)}}const uw=R.createContext({}),xo=()=>R.useContext(uw);function fw({children:t,...e}){return m.jsx(uw.Provider,{value:e,children:t})}function ya({name:t,children:e,fallback:n,className:i}){return m.jsx("div",{className:`voxket-slot voxket-slot--${t} ${i||""}`,children:e||n})}function hw(t,e={}){return Object.assign(t,e)}function mw({showMicrophoneControl:t=!0,showCameraControl:e=!0,showScreenShareControl:n=!0,showSessionActions:i=!0,customControls:r,className:s=""}){const o=sr(),a=aw(),c=cw(),l=lw(),d=xo(),u=["voxket-session-controls",`voxket-session-controls--${d.variant||"default"}`,`voxket-session-controls--${d.size||"md"}`,o.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",s].filter(Boolean).join(" ");return!o.isActive&&!i?m.jsx("div",{className:u,children:m.jsx("div",{className:"voxket-controls-inactive",children:m.jsx("p",{children:"Controls available during active session"})})}):m.jsxs("div",{className:u,children:[i&&m.jsx("div",{className:"voxket-session-actions",children:o.isActive?m.jsx("button",{onClick:o.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):m.jsx(rL,{})}),o.isActive&&m.jsxs("div",{className:"voxket-media-controls",children:[t&&m.jsxs("button",{onClick:a.toggle,disabled:a.isLoading,className:`voxket-button voxket-button--media ${a.isEnabled?"voxket-button--active":""}`,title:a.isEnabled?"Mute microphone":"Unmute microphone",children:[m.jsx("span",{className:"voxket-icon",children:"🎤"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),e&&m.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isEnabled?"voxket-button--active":""}`,title:c.isEnabled?"Stop camera":"Start camera",children:[m.jsx("span",{className:"voxket-icon",children:"📹"}),c.isLoading?"Loading...":c.isEnabled?"Stop Video":"Start Video"]}),n&&m.jsxs("button",{onClick:l.toggle,disabled:l.isLoading,className:`voxket-button voxket-button--media ${l.isSharing?"voxket-button--active":""}`,title:l.isSharing?"Stop screen share":"Start screen share",children:[m.jsx("span",{className:"voxket-icon",children:"🖥️"}),l.isLoading?"Loading...":l.isSharing?"Stop Share":"Share Screen"]})]}),r&&m.jsx("div",{className:"voxket-custom-controls",children:r})]})}function rL(){sr();const[t,e]=R.useState(!1),n=async()=>{e(!0);try{console.log("Start session - agentId needed")}catch(i){console.error("Failed to start session:",i)}finally{e(!1)}};return m.jsx("button",{onClick:n,disabled:t,className:"voxket-button voxket-button--primary",children:t?"Starting...":"Start Session"})}function ah({showConnectionStatus:t=!0,showSessionInfo:e=!0,showAgentInfo:n=!0,className:i=""}){const r=sr(),s=oh(),o=xo(),a=["voxket-session-header",`voxket-session-header--${o.variant||"default"}`,`voxket-session-header--${o.size||"md"}`,i].filter(Boolean).join(" ");return m.jsxs("div",{className:a,children:[t&&m.jsxs("div",{className:"voxket-connection-status",children:[m.jsx("div",{className:`voxket-status-indicator ${s.isConnected?"connected":"disconnected"}`}),m.jsx("span",{className:"voxket-status-text",children:s.isConnecting?"Connecting...":s.isConnected?"Connected":"Disconnected"})]}),e&&r.session&&m.jsxs("div",{className:"voxket-session-info",children:[m.jsxs("div",{className:"voxket-session-id",children:["Session: ",r.session.id.slice(-8)]}),m.jsxs("div",{className:"voxket-session-state",children:["State: ",r.state]})]}),n&&r.session&&m.jsxs("div",{className:"voxket-agent-info",children:[m.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",r.session.agentId]}),m.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",r.session.activeModalities.join(", ")]})]}),s.error&&m.jsxs("div",{className:"voxket-error-message",children:["Error: ",s.error.message]})]})}function ch({showChat:t=!0,showTranscriptions:e=!1,customContent:n,className:i=""}){const r=sr(),s=Tc(),o=xo(),a=["voxket-session-content",`voxket-session-content--${o.variant||"default"}`,`voxket-session-content--${o.size||"md"}`,i].filter(Boolean).join(" ");return r.isActive?m.jsx("div",{className:a,children:n||m.jsxs(m.Fragment,{children:[t&&m.jsxs("div",{className:"voxket-chat-container",children:[m.jsxs("div",{className:"voxket-chat-messages",children:[s.messages.map(c=>m.jsxs("div",{className:`voxket-message voxket-message--${c.sender.type}`,children:[m.jsxs("div",{className:"voxket-message-header",children:[m.jsx("span",{className:"voxket-message-sender",children:c.sender.name}),m.jsx("span",{className:"voxket-message-time",children:c.timestamp.toLocaleTimeString()})]}),m.jsx("div",{className:"voxket-message-content",children:c.content})]},c.id)),s.messages.length===0&&m.jsx("div",{className:"voxket-empty-messages",children:m.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),m.jsx(sL,{})]}),e&&m.jsx("div",{className:"voxket-transcriptions",children:m.jsx("div",{className:"voxket-transcription-placeholder",children:m.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):m.jsx("div",{className:a,children:m.jsx("div",{className:"voxket-inactive-state",children:m.jsxs("div",{className:"voxket-inactive-message",children:[m.jsx("h3",{children:"Start a conversation"}),m.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function sL(){const t=Tc(),[e,n]=R.useState(""),i=async()=>{if(!(!e.trim()||!t.canSend))try{await t.send(e),n("")}catch(s){console.error("Failed to send message:",s)}},r=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),i())};return m.jsxs("div",{className:"voxket-chat-input",children:[m.jsx("input",{type:"text",value:e,onChange:s=>n(s.target.value),onKeyPress:r,placeholder:"Type your message...",disabled:!t.canSend,className:"voxket-input"}),m.jsx("button",{onClick:i,disabled:!t.canSend||!e.trim(),className:"voxket-send-button",children:t.isSending?"Sending...":"Send"})]})}function lh({showMetrics:t=!0,showParticipants:e=!0,showStatus:n=!0,customFooter:i,className:r=""}){const s=sr(),o=ow(),a=dw(),c=xo(),l=["voxket-session-footer",`voxket-session-footer--${c.variant||"default"}`,`voxket-session-footer--${c.size||"md"}`,r].filter(Boolean).join(" ");return s.isActive?m.jsx("div",{className:l,children:i||m.jsxs(m.Fragment,{children:[n&&m.jsxs("div",{className:"voxket-session-status",children:[m.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),m.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),t&&o.metrics&&m.jsxs("div",{className:"voxket-session-metrics",children:[m.jsxs("div",{className:"voxket-metric",children:[m.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),m.jsx("span",{className:"voxket-metric-value",children:oL(o.duration||0)})]}),m.jsxs("div",{className:"voxket-metric",children:[m.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),m.jsx("span",{className:"voxket-metric-value",children:o.metrics.messageCount})]})]}),e&&m.jsxs("div",{className:"voxket-participants-info",children:[m.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&m.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(d=>m.jsx("span",{className:"voxket-participant-name",children:d.name},d.id))})]})]})}):m.jsx("div",{className:l,children:m.jsx("div",{className:"voxket-footer-inactive",children:m.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function oL(t){const e=Math.floor(t/1e3),n=Math.floor(e/60),i=Math.floor(n/60);return i>0?`${i}:${(n%60).toString().padStart(2,"0")}:${(e%60).toString().padStart(2,"0")}`:`${n}:${(e%60).toString().padStart(2,"0")}`}function aL({agentId:t,sessionConfig:e,autoStart:n=!1,onSessionStart:i,onSessionEnd:r,variant:s="default",size:o="md",theme:a,className:c="",children:l}){var p;const d=sr(),u=oh();R.useEffect(()=>{n&&t&&u.isConnected&&!d.isActive&&d.start(t,e).catch(console.error)},[n,t,u.isConnected,d.isActive]),R.useEffect(()=>{var g;(g=d.session)!=null&&g.id&&i&&i(d.session.id)},[(p=d.session)==null?void 0:p.id,i]),R.useEffect(()=>()=>{d.isActive&&r&&d.stop().then(r).catch(console.error)},[]);const f=["voxket-session",`voxket-session--${s}`,`voxket-session--${o}`,d.isActive?"voxket-session--active":"voxket-session--inactive",c].filter(Boolean).join(" ");return m.jsx(fw,{variant:s,size:o,theme:a,className:c,children:m.jsx("div",{className:f,children:l||m.jsxs(m.Fragment,{children:[m.jsx(ya,{name:"header",fallback:m.jsx(ah,{})}),m.jsx(ya,{name:"content",fallback:m.jsx(ch,{})}),m.jsx(ya,{name:"footer",fallback:m.jsx(lh,{})})]})})})}const pw=hw(aL,{Header:ah,Content:ch,Footer:lh,Controls:mw}),Gi={name:"default",colors:{primary:"#3B82F6",secondary:"#6B7280",accent:"#8B5CF6",background:"#FFFFFF",surface:"#F9FAFB",text:{primary:"#111827",secondary:"#6B7280",muted:"#9CA3AF",inverse:"#FFFFFF"},status:{success:"#10B981",warning:"#F59E0B",error:"#EF4444",info:"#3B82F6"},border:"#E5E7EB",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},typography:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700},lineHeight:{tight:1.25,normal:1.5,relaxed:1.75}},spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{none:"0",sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},shadows:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1)"}},vu={...Gi,name:"dark",colors:{primary:"#60A5FA",secondary:"#9CA3AF",accent:"#A78BFA",background:"#111827",surface:"#1F2937",text:{primary:"#F9FAFB",secondary:"#D1D5DB",muted:"#9CA3AF",inverse:"#111827"},status:{success:"#34D399",warning:"#FBBF24",error:"#F87171",info:"#60A5FA"},border:"#374151",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.3)"}},yu={...Gi,name:"enterprise",colors:{primary:"#1E40AF",secondary:"#64748B",accent:"#7C3AED",background:"#FFFFFF",surface:"#F8FAFC",text:{primary:"#0F172A",secondary:"#475569",muted:"#94A3B8",inverse:"#FFFFFF"},status:{success:"#059669",warning:"#D97706",error:"#DC2626",info:"#1E40AF"},border:"#CBD5E1",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},borderRadius:{none:"0",sm:"0.125rem",md:"0.25rem",lg:"0.375rem",full:"9999px"}},gw=R.createContext(null),vw=()=>{const t=R.useContext(gw);if(!t)throw new Error("useTheme must be used within a ThemeProvider");return t};function cL({theme:t="default",themes:e={},children:n,cssVariables:i=!0,className:r=""}){const[s,o]=R.useState(()=>{const f={default:Gi,dark:vu,enterprise:yu,...e};return typeof t=="string"?f[t]||Gi:t}),[a,c]=R.useState(()=>({default:Gi,dark:vu,enterprise:yu,...e})),l=f=>{if(typeof f=="string"){const p=a[f];p&&o(p)}else o(f)},d=f=>{c(p=>({...p,[f.name]:f}))};R.useEffect(()=>{if(i&&typeof document<"u"){const f=document.documentElement;Object.entries(yw(s)).forEach(([p,g])=>{f.style.setProperty(`--voxket-${p}`,g)})}},[s,i]);const u={theme:s,setTheme:l,themes:a,registerTheme:d};return m.jsx(gw.Provider,{value:u,children:m.jsx("div",{className:`voxket-theme voxket-theme--${s.name} ${r}`,children:n})})}function yw(t){const e={},n=(i,r="")=>{for(const[s,o]of Object.entries(i)){const a=r?`${r}-${s}`:s;typeof o=="object"&&o!==null&&!Array.isArray(o)?n(o,a):e[a]=String(o)}};return n(t),e}function lL(t=Gi,e){return{...t,...e,colors:{...t.colors,...e.colors},typography:{...t.typography,...e.typography},spacing:{...t.spacing,...e.spacing},borderRadius:{...t.borderRadius,...e.borderRadius},shadows:{...t.shadows,...e.shadows}}}function dL(t){var n;const{theme:e}=vw();return((n=e.components)==null?void 0:n[t])||{}}const uL=sh("voice-modality","voice",{onActivate:async t=>{const e=t.config;e.enableTranscription&&fL(t),e.enableVoiceActivation&&hL(t,e),console.log("Voice modality activated",e)},onDeactivate:async t=>{console.log("Voice modality deactivated")},onMessage:async(t,e)=>{e.type==="audio"&&mL(t,e)}});function fL(t,e){t.on("participant.speaking.started",n=>{console.log("Transcription: Started for",n.name)}),t.on("participant.speaking.stopped",n=>{console.log("Transcription: Stopped for",n.name)})}function hL(t,e){const n=e.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function mL(t,e){console.log("Playing audio response:",e.content)}const pL=sh("chat-modality","chat",{onActivate:async t=>{const e=t.config;e.enableRichText&&gL(),e.enableFileUpload&&vL(t),e.enableCustomComponents&&yL(),console.log("Chat modality activated",e)},onDeactivate:async t=>{console.log("Chat modality deactivated")},onMessage:async(t,e)=>{const n=t.config;e.type==="ui_component"?bL(t,e):e.type==="text"&&n.enableRichText&&xL(t,e)}});function gL(t){console.log("Rich text support enabled")}function vL(t){console.log("File upload enabled"),t.on("chat.file.uploaded",e=>{console.log("File uploaded:",e.name)})}function yL(t){console.log("Custom components enabled");const e=new Map;e.set("quick-actions",SL),e.set("form",wL),e.set("card",CL),e.set("chart",kL)}function bL(t,e){const{componentType:n,props:i}=e.metadata;console.log("Rendering custom component:",n,i),t.emit("chat.component.render",{type:n,props:i,timestamp:new Date})}function xL(t,e){console.log("Processing rich text message:",e.content)}function SL(t){return{type:"quick-actions",actions:t.actions||[],layout:t.layout||"horizontal"}}function wL(t){return{type:"form",fields:t.fields||[],submitAction:t.submitAction,validation:t.validation}}function CL(t){return{type:"card",title:t.title,content:t.content,actions:t.actions,variant:t.variant||"default"}}function kL(t){return{type:"chart",chartType:t.chartType||"line",data:t.data,options:t.options}}function ba({track:t,participantName:e,showControls:n=!0,showName:i=!0,showMuteIndicator:r=!0,isPinned:s=!1,className:o="",onClick:a,onPin:c,onUnpin:l}){const d=R.useRef(null),[u,f]=R.useState(!1);R.useEffect(()=>{if(!d.current||!t.isEnabled)return;const y=d.current;return y.srcObject=null,()=>{y.srcObject&&(y.srcObject=null)}},[t]);const p=()=>{a==null||a(t)},g=y=>{y.stopPropagation(),s?l==null||l(t):c==null||c(t)},h=["voxket-video-tile",t.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",t.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",s?"voxket-video-tile--pinned":"",t.isEnabled?"":"voxket-video-tile--disabled",u?"voxket-video-tile--hovered":"",o].filter(Boolean).join(" ");return m.jsxs("div",{className:h,onClick:p,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),style:{aspectRatio:t.dimensions?`${t.dimensions.width} / ${t.dimensions.height}`:"16 / 9"},children:[m.jsx("video",{ref:d,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:t.isLocal}),!t.isEnabled&&m.jsxs("div",{className:"voxket-video-placeholder",children:[m.jsx("div",{className:"voxket-video-placeholder-icon",children:t.isScreenShare?"🖥️":"📹"}),m.jsx("p",{className:"voxket-video-placeholder-text",children:t.isScreenShare?"Screen sharing paused":"Camera off"})]}),m.jsxs("div",{className:"voxket-video-overlay",children:[i&&e&&m.jsxs("div",{className:"voxket-video-name",children:[e,t.isLocal&&" (You)"]}),r&&!t.isEnabled&&m.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),n&&(u||s)&&m.jsxs("div",{className:"voxket-video-controls",children:[m.jsx("button",{className:`voxket-video-control-btn ${s?"voxket-video-control-btn--active":""}`,onClick:g,title:s?"Unpin video":"Pin video",children:"📌"}),t.isScreenShare&&m.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),t.source&&m.jsx("div",{className:"voxket-video-source",children:t.source})]})]}),!t.isEnabled&&m.jsx("div",{className:"voxket-video-loading",children:m.jsx("div",{className:"voxket-spinner"})})]})}function TL({tracks:t,layout:e,className:n="",onLayoutChange:i,onTrackClick:r,maxVisibleTracks:s=9,showPagination:o=!0}){const[a,c]=R.useState(0),[l,d]=R.useState(null),u=R.useMemo(()=>{let w=[...t];e.type==="speaker"&&l&&(w=[l,...t.filter(x=>x.id!==l.id)]);const C=a*s,S=C+s;return w.slice(C,S)},[t,e,l,a,s]),f=Math.ceil(t.length/s),p=R.useMemo(()=>{const w=u.length;switch(e.type){case"grid":const C=Math.ceil(Math.sqrt(w)),S=Math.ceil(w/C);return{display:"grid",gridTemplateColumns:`repeat(${C}, 1fr)`,gridTemplateRows:`repeat(${S}, 1fr)`,gap:"8px"};case"speaker":return{display:"flex",flexDirection:"column",gap:"8px"};case"sidebar":return{display:"flex",gap:"8px"};case"gallery":return{display:"flex",flexWrap:"wrap",gap:"8px",justifyContent:"center"};default:return{}}},[e.type,u.length]),g=w=>{d(w)},h=()=>{d(null)},y=w=>{i==null||i({...e,type:w})},b=["voxket-video-grid",`voxket-video-grid--${e.type}`,`voxket-video-grid--${u.length}-tracks`,n].filter(Boolean).join(" ");return t.length===0?m.jsx("div",{className:"voxket-video-grid-empty",children:m.jsxs("div",{className:"voxket-video-grid-empty-content",children:[m.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),m.jsx("p",{children:"No video tracks available"})]})}):m.jsxs("div",{className:b,children:[m.jsxs("div",{className:"voxket-video-grid-controls",children:[m.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(w=>m.jsx("button",{className:`voxket-layout-btn ${e.type===w?"voxket-layout-btn--active":""}`,onClick:()=>y(w),title:`Switch to ${w} layout`,children:EL(w)},w))}),m.jsxs("div",{className:"voxket-video-count",children:[t.length," participant",t.length!==1?"s":""]})]}),m.jsx("div",{className:"voxket-video-grid-content",style:p,children:e.type==="speaker"&&l?m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"voxket-video-speaker-main",children:m.jsx(ba,{track:l,participantName:`Participant ${l.participantId}`,isPinned:!0,onClick:r,onUnpin:h})}),m.jsx("div",{className:"voxket-video-speaker-sidebar",children:u.filter(w=>w.id!==l.id).map(w=>m.jsx(ba,{track:w,participantName:`Participant ${w.participantId}`,showControls:!1,onClick:r,onPin:g},w.id))})]}):u.map(w=>m.jsx(ba,{track:w,participantName:`Participant ${w.participantId}`,isPinned:(l==null?void 0:l.id)===w.id,onClick:r,onPin:g,onUnpin:h},w.id))}),o&&f>1&&m.jsxs("div",{className:"voxket-video-pagination",children:[m.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.max(0,a-1)),disabled:a===0,children:"←"}),m.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",f]}),m.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.min(f-1,a+1)),disabled:a===f-1,children:"→"})]})]})}function EL(t){switch(t){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function PL({localTrack:t,onToggleCamera:e,onToggleScreenShare:n,onLayoutChange:i,showLayoutControls:r=!0,showCameraControls:s=!0,showScreenShareControls:o=!0,className:a=""}){const c=["voxket-video-controls",a].filter(Boolean).join(" "),l=d=>{i==null||i({type:d,showLocalVideo:!0,aspectRatio:"16:9"})};return m.jsxs("div",{className:c,children:[s&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),m.jsxs("button",{className:`voxket-control-btn ${t!=null&&t.isEnabled?"voxket-control-btn--active":""}`,onClick:e,title:t!=null&&t.isEnabled?"Turn off camera":"Turn on camera",children:[m.jsx("span",{className:"voxket-control-icon",children:t!=null&&t.isEnabled?"📹":"📷"}),m.jsx("span",{className:"voxket-control-label",children:t!=null&&t.isEnabled?"Camera On":"Camera Off"})]}),(t==null?void 0:t.dimensions)&&m.jsxs("div",{className:"voxket-video-info",children:[t.dimensions.width," × ",t.dimensions.height]})]}),o&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),m.jsxs("button",{className:`voxket-control-btn ${t!=null&&t.isScreenShare?"voxket-control-btn--active":""}`,onClick:n,title:t!=null&&t.isScreenShare?"Stop screen sharing":"Start screen sharing",children:[m.jsx("span",{className:"voxket-control-icon",children:t!=null&&t.isScreenShare?"🛑":"🖥️"}),m.jsx("span",{className:"voxket-control-label",children:t!=null&&t.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),r&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),m.jsx("div",{className:"voxket-layout-buttons",children:[{type:"grid",icon:"⊞",label:"Grid"},{type:"speaker",icon:"🎤",label:"Speaker"},{type:"sidebar",icon:"⫸",label:"Sidebar"},{type:"gallery",icon:"⊡",label:"Gallery"}].map(({type:d,icon:u,label:f})=>m.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>l(d),title:`Switch to ${f} layout`,children:[m.jsx("span",{className:"voxket-control-icon",children:u}),m.jsx("span",{className:"voxket-control-label",children:f})]},d))})]}),m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),m.jsxs("div",{className:"voxket-video-settings",children:[m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Quality"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"high",children:"High (720p)"}),m.jsx("option",{value:"medium",children:"Medium (480p)"}),m.jsx("option",{value:"low",children:"Low (240p)"})]})]}),m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"30",children:"30 fps"}),m.jsx("option",{value:"15",children:"15 fps"}),m.jsx("option",{value:"10",children:"10 fps"})]})]}),m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"unlimited",children:"Unlimited"}),m.jsx("option",{value:"1000",children:"1 Mbps"}),m.jsx("option",{value:"500",children:"500 Kbps"}),m.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),m.jsxs("div",{className:"voxket-video-stats",children:[m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),m.jsx("span",{className:"voxket-stat-value",children:t!=null&&t.dimensions?`${t.dimensions.width}×${t.dimensions.height}`:"N/A"})]}),m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Source:"}),m.jsx("span",{className:"voxket-stat-value",children:(t==null?void 0:t.source)||"None"})]}),m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Status:"}),m.jsx("span",{className:`voxket-stat-value ${t!=null&&t.isEnabled?"voxket-stat-value--active":"voxket-stat-value--inactive"}`,children:t!=null&&t.isEnabled?"Active":"Inactive"})]})]})]})]})}const bw=({handler:t,loadData:e,data:n,client:i,addLocalMessage:r})=>{const[s,o]=v.useState(null),[a,c]=v.useState(!0),[l,d]=v.useState(!1),[u]=v.useState(Date.now());v.useEffect(()=>{(async()=>{try{if(c(!0),console.log("📋 AssignmentView: Loading assignment data..."),console.log("📋 AssignmentView: Received data from RPC:",n),n&&typeof n=="object"){const y={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};o(y),console.log("📋 AssignmentView: Assignment loaded from RPC data:",y)}}catch(y){console.error("📋 AssignmentView: Error loading assignment:",y),o({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{c(!1)}})()},[n,e]);const f=({message:h,assignment:y})=>{const b=h.toLowerCase().includes("declined"),w=b?"bg-red-50 border-red-200":"bg-green-50 border-green-200",C=b?"text-red-700":"text-green-700",S=b?"❌":"🎉";return m.jsxs("div",{className:`max-w-sm mx-auto ${w} border rounded-lg shadow p-3 flex flex-col items-center`,children:[m.jsx("div",{className:"text-2xl mb-2",children:S}),m.jsx("div",{className:`${C} font-semibold text-sm mb-1`,children:h}),m.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:y.title}),m.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},p=async()=>{if(!(!s||!t)){d(!0);try{const h={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",h),t.didSuccess(h,m.jsx(f,{message:"Assignment accepted!",assignment:s}))}catch(h){console.error("📋 AssignmentView: Error accepting assignment:",h),t.didFail({error:"Failed to accept assignment"})}finally{d(!1)}}},g=async()=>{if(!(!s||!t)){d(!0);try{const h={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",h),t.didSuccess(h,m.jsx(f,{message:"Assignment declined",assignment:s}))}catch(h){console.error("📋 AssignmentView: Error declining assignment:",h),t.didFail({error:"Failed to decline assignment"})}finally{d(!1)}}};return a?m.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:m.jsxs("div",{className:"flex items-center justify-center py-4",children:[m.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),m.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):s?m.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[m.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:m.jsx("div",{className:"flex items-center justify-between",children:m.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:s.title})})}),m.jsxs("div",{className:"p-3",children:[m.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:m.jsx("p",{className:"text-xs text-gray-700 leading-snug",children:s.description})}),m.jsx("div",{className:"mb-3",children:m.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[m.jsx("span",{className:"text-xs mr-1",children:"📅"}),m.jsxs("span",{children:["Est: ",s.estimated_time_of_completion]})]})}),m.jsxs("div",{className:"flex gap-2",children:[m.jsx("button",{onClick:p,disabled:l,className:"flex-1 bg-green-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:l?m.jsxs("span",{className:"flex items-center justify-center",children:[m.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),m.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),m.jsx("button",{onClick:g,disabled:l,className:"flex-1 bg-red-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Decline"})]})]})]}):m.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:m.jsxs("div",{className:"text-center py-4",children:[m.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),m.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function RL(){const[t,e]=v.useState(null),[n,i]=v.useState([]);v.useEffect(()=>{const a=new bo({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return e(a),a.on("rpc.method.called",c=>{console.log("RPC Method Called:",c)}),a.on("rpc.interaction.completed",c=>{console.log("RPC Interaction Completed:",c)}),()=>{a.disconnect()}},[]);const r=async()=>{if(t)try{await t.registerFrontendRPC("give_assignment",bw,"embedded");const a=t.getRegisteredRpcMethods();i(a),console.log("✅ Assignment RPC registered successfully")}catch(a){console.error("❌ Failed to register assignment RPC:",a)}},s=async()=>{if(!t)return;const a=({handler:c,timeout:l})=>{const[d,u]=v.useState(""),f=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],p=h=>{u(h)},g=()=>{const h=f.find(y=>y.id===d);c==null||c.didSuccess({selectedProduct:d,productName:h==null?void 0:h.name,price:h==null?void 0:h.price,timestamp:new Date().toISOString()})};return m.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[m.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),m.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),m.jsx("div",{className:"space-y-3 mb-6",children:f.map(h=>m.jsx("div",{onClick:()=>p(h.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${d===h.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:m.jsxs("div",{className:"flex justify-between items-center",children:[m.jsxs("div",{children:[m.jsx("h4",{className:"font-medium",children:h.name}),m.jsx("p",{className:"text-gray-600 text-sm",children:h.price})]}),m.jsx("div",{className:`w-4 h-4 rounded-full ${d===h.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},h.id))}),m.jsxs("div",{className:"flex justify-end space-x-3",children:[m.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),m.jsx("button",{onClick:g,disabled:!d,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),l&&m.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",l," seconds"]})]})};try{await t.registerFrontendRPC("recommend_product",a,"modal");const c=t.getRegisteredRpcMethods();i(c),console.log("✅ Product Recommendation RPC registered successfully")}catch(c){console.error("❌ Failed to register product recommendation RPC:",c)}},o=async()=>{if(!t)return;const a=({handler:c})=>{const[l,d]=v.useState(0),[u,f]=v.useState(""),p=()=>{c==null||c.didSuccess({rating:l,comment:u,timestamp:new Date().toISOString()})};return m.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),m.jsxs("div",{className:"mb-4",children:[m.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),m.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(g=>m.jsx("button",{onClick:()=>d(g),className:`text-2xl ${g<=l?"text-yellow-400":"text-gray-300"}`,children:"⭐"},g))})]}),m.jsxs("div",{className:"mb-4",children:[m.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),m.jsx("textarea",{value:u,onChange:g=>f(g.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),m.jsxs("div",{className:"flex justify-end space-x-2",children:[m.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),m.jsx("button",{onClick:p,disabled:l===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await t.registerFrontendRPC("collect_feedback",a,"embedded");const c=t.getRegisteredRpcMethods();i(c),console.log("✅ Feedback RPC registered successfully")}catch(c){console.error("❌ Failed to register feedback RPC:",c)}};return m.jsxs("div",{className:"p-6",children:[m.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),m.jsxs("div",{className:"space-y-4 mb-6",children:[m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),m.jsxs("div",{className:"space-x-2",children:[m.jsx("button",{onClick:r,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),m.jsx("button",{onClick:s,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),m.jsx("button",{onClick:o,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?m.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>m.jsx("li",{className:"text-gray-700",children:m.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):m.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),m.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),m.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[m.jsxs("li",{children:["Register RPC methods with React components using ",m.jsx("code",{children:"client.registerFrontendRPC()"})]}),m.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),m.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),m.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),m.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),m.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),m.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),m.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
318
+ `,style:{minHeight:"2.5rem",display:o===i?"block":"none"},children:s},o))})}function Fj({statusMessage:t,theme:e}){const n=St(e);return m.jsxs("div",{className:"z-10 flex items-center space-x-2 mt-2 pb-2",children:[m.jsx("div",{className:n.statusIndicator}),m.jsx("span",{className:`text-xs ${n.text.muted}`,children:t})]})}const Uj=({disabled:t,onStartCall:e,onStartChat:n,onStartVideo:i,prompts:r=['"Book a meeting with the marketing team"',`"What's the status of project Alpha?"`,`"Summarize yesterday's sales report"`,'"Find a good Italian restaurant nearby"','"Remind me to call John tomorrow at 10 AM"'],statusMessage:s="Agent is ready",title:o="Choose how to interact",subTitle:a="Ask me anything or give me a task to complete",theme:c="vox",modalities:l=["voice","chat","video"]})=>{const d=St(c),u=l.includes("voice"),f=l.includes("chat"),p=l.includes("video"),g=[u,f,p].filter(Boolean).length;return console.log("🎯 Welcome component debug:",{modalities:l,hasVoice:u,hasChat:f,hasVideo:p,totalButtons:g,onStartVideo:!!i}),m.jsxs("div",{inert:t,className:"flex p-8 flex-col items-center h-full justify-center w-full",children:[m.jsxs("div",{className:"mt-1 relative flex items-center justify-center mb-8 w-full",style:{minHeight:"120px"},children:[m.jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[m.jsx("div",{className:d.pulseRings.ring1}),m.jsx("div",{className:d.pulseRings.ring2,style:{animationDelay:"0.5s"}}),m.jsx("div",{className:d.pulseRings.ring3,style:{animationDelay:"1s"}})]}),m.jsx("div",{className:"relative z-10 flex items-center justify-center",children:u&&f&&p?m.jsxs("div",{className:"flex gap-4 items-center justify-center",children:[m.jsx(Wo,{onClick:e,disabled:t,theme:c}),m.jsx(Ul,{onClick:n,disabled:t,theme:c}),m.jsx(Bl,{onClick:i||e,disabled:t,theme:c})]}):g>1?m.jsxs("div",{className:"flex gap-6 items-center justify-center",children:[u&&m.jsx(Wo,{onClick:e,disabled:t,theme:c}),f&&m.jsx(Ul,{onClick:n,disabled:t,theme:c}),p&&i&&m.jsx(Bl,{onClick:i,disabled:t,theme:c})]}):m.jsx("div",{className:"flex items-center justify-center",children:u?m.jsx(Wo,{onClick:e,disabled:t,theme:c}):f?m.jsx(Ul,{onClick:n,disabled:t,theme:c}):p&&i?m.jsx(Bl,{onClick:i,disabled:t,theme:c}):m.jsx(Wo,{onClick:e,disabled:t,theme:c})})})]}),m.jsxs("div",{className:"text-center flex flex-col items-center gap-y-2 mb-6 w-full",children:[m.jsx("h3",{className:`text-xl font-semibold mb-2 ${d.text.accent}`,children:o}),m.jsx("p",{className:`text-sm leading-relaxed px-4 ${d.text.secondary}`,children:a}),g>1&&m.jsxs("div",{className:"flex gap-6 mt-4 text-xs justify-center",children:[u&&m.jsxs("div",{className:"flex flex-col items-center gap-1",children:[m.jsx(QS,{className:"w-4 h-4"}),m.jsx("span",{className:d.text.muted,children:"Voice"})]}),f&&m.jsxs("div",{className:"flex flex-col items-center gap-1",children:[m.jsx(XS,{className:"w-4 h-4"}),m.jsx("span",{className:d.text.muted,children:"Chat"})]}),p&&m.jsxs("div",{className:"flex flex-col items-center gap-1",children:[m.jsx(ew,{className:"w-4 h-4"}),m.jsx("span",{className:d.text.muted,children:"Video"})]})]})]}),m.jsx(Vj,{prompts:r,theme:c}),m.jsx(Fj,{statusMessage:s,theme:c})]})};function tw({room:t,onSessionEnd:e,onSessionStart:n,enableConsoleLogging:i=!0,enableLocalStorage:r=!0,voxketSessionId:s}={}){const[o,a]=v.useState(null),[c,l]=v.useState([]),[d,u]=v.useState(null),[f,p]=v.useState([]),g=v.useCallback((w,C)=>{const S={timestamp:new Date,event:w,data:C,sessionId:o==null?void 0:o.sessionId,participantId:d==null?void 0:d.identity};if(l(x=>[...x,S]),r){const x=JSON.parse(localStorage.getItem("voxket-session-logs")||"[]");x.push(S),localStorage.setItem("voxket-session-logs",JSON.stringify(x))}return S},[o==null?void 0:o.sessionId,d==null?void 0:d.identity,i,r]);v.useEffect(()=>{if(!t)return;const w=()=>{const k=s||`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,I=new Date,N={sessionId:k,startTime:I,totalMessages:0,connectionIssues:0,participantCount:f.length,events:[]};a(N),g("SESSION_STARTED",{sessionId:k,startTime:I}),n==null||n(k)},C=()=>{if(o){const k=new Date,I=k.getTime()-o.startTime.getTime(),N={...o,endTime:k,duration:I,events:c};g("SESSION_ENDED",{sessionId:o.sessionId,duration:`${Math.round(I/1e3)}s`,totalMessages:o.totalMessages,connectionIssues:o.connectionIssues}),e==null||e(N),a(null),l([])}},S=k=>{g("CONNECTION_STATE_CHANGED",{state:k}),k===ge.Reconnecting&&o&&(a(I=>I?{...I,connectionIssues:I.connectionIssues+1}:null),g("CONNECTION_ISSUE",{type:"reconnecting"}))},x=k=>{g("TRACK_PUBLISHED",{trackKind:k.kind,trackSource:k.source})},T=k=>{g("TRACK_UNPUBLISHED",{trackKind:k.kind,trackSource:k.source})},E=(k,I)=>{o&&a(N=>N?{...N,totalMessages:N.totalMessages+1}:null),g("DATA_RECEIVED",{participantId:I==null?void 0:I.identity,dataSize:k.length})},P=k=>{g("PARTICIPANT_CONNECTED",{participantId:k.identity,participantName:k.name}),p(I=>[...I,k]),o&&a(I=>I?{...I,participantCount:I.participantCount+1}:null)},_=k=>{g("PARTICIPANT_DISCONNECTED",{participantId:k.identity,participantName:k.name}),p(I=>I.filter(N=>N.identity!==k.identity))};return t.localParticipant&&u(t.localParticipant),t.on(U.Connected,w),t.on(U.Disconnected,C),t.on(U.ConnectionStateChanged,S),t.on(U.TrackPublished,x),t.on(U.TrackUnpublished,T),t.on(U.DataReceived,E),t.on(U.ParticipantConnected,P),t.on(U.ParticipantDisconnected,_),()=>{t.off(U.Connected,w),t.off(U.Disconnected,C),t.off(U.ConnectionStateChanged,S),t.off(U.TrackPublished,x),t.off(U.TrackUnpublished,T),t.off(U.DataReceived,E),t.off(U.ParticipantConnected,P),t.off(U.ParticipantDisconnected,_)}},[t,o,c,f.length,g,e,n]);const h=v.useCallback(()=>r?JSON.parse(localStorage.getItem("voxket-session-logs")||"[]"):c,[c,r]),y=v.useCallback(()=>{r&&localStorage.removeItem("voxket-session-logs"),l([])},[r]),b=v.useCallback(()=>{const w=h(),C=JSON.stringify(w,null,2),S="data:application/json;charset=utf-8,"+encodeURIComponent(C),x=`voxket-session-logs-${new Date().toISOString().split("T")[0]}.json`,T=document.createElement("a");T.setAttribute("href",S),T.setAttribute("download",x),T.click()},[h]);return{sessionMetrics:o,sessionLogs:c,logEvent:g,getSessionLogs:h,clearSessionLogs:y,exportSessionLogs:b}}var wr={},E0;function Bj(){if(E0)return wr;E0=1;var t=bu;if(process.env.NODE_ENV==="production")wr.createRoot=t.createRoot,wr.hydrateRoot=t.hydrateRoot;else{var e=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;wr.createRoot=function(n,i){e.usingClientEntryPoint=!0;try{return t.createRoot(n,i)}finally{e.usingClientEntryPoint=!1}},wr.hydrateRoot=function(n,i,r){e.usingClientEntryPoint=!0;try{return t.hydrateRoot(n,i,r)}finally{e.usingClientEntryPoint=!1}}}return wr}var $j=Bj();class rh{constructor(){at(this,"listeners",{})}on(e,n){return this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(n),()=>this.off(e,n)}once(e,n){const i=(...r)=>{this.off(e,i),n(...r)};return this.on(e,i)}off(e,n){const i=this.listeners[e];if(!i)return;const r=i.indexOf(n);r>-1&&i.splice(r,1)}removeAllListeners(e){e?delete this.listeners[e]:this.listeners={}}emit(e,...n){const i=this.listeners[e];if(!i)return;const r=[...i];for(const s of r)try{s(...n)}catch(o){console.error(`Error in event listener for ${String(e)}:`,o)}}listenerCount(e){var n;return((n=this.listeners[e])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class nw{constructor(e){at(this,"plugins",new Map);at(this,"installedPlugins",new Set);at(this,"context");this.context={client:e,emit:e.emit.bind(e),on:e.on.bind(e),config:{}}}register(e){if(this.plugins.has(e.name))throw new Error(`Plugin '${e.name}' is already registered`);if(e.dependencies){for(const n of e.dependencies)if(!this.plugins.has(n))throw new Error(`Plugin '${e.name}' depends on '${n}' which is not registered`)}this.plugins.set(e.name,e)}async install(e,n){const i=this.plugins.get(e);if(!i)throw new Error(`Plugin '${e}' is not registered`);if(this.installedPlugins.has(e))throw new Error(`Plugin '${e}' is already installed`);if(i.dependencies)for(const s of i.dependencies)this.installedPlugins.has(s)||await this.install(s);const r={...this.context,config:{...i.config,...n}};i.install&&await i.install(r),this.installedPlugins.add(e),this.setupPluginEvents(i,r)}async uninstall(e){var i;const n=this.plugins.get(e);if(!n)throw new Error(`Plugin '${e}' is not registered`);if(this.installedPlugins.has(e)){for(const[r,s]of this.plugins)if(this.installedPlugins.has(r)&&((i=s.dependencies)!=null&&i.includes(e)))throw new Error(`Cannot uninstall '${e}' because '${r}' depends on it`);n.uninstall&&await n.uninstall(this.context),this.installedPlugins.delete(e)}}isInstalled(e){return this.installedPlugins.has(e)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(e){return this.plugins.get(e)}setupPluginEvents(e,n){e.onSessionStart&&n.on("session.started",i=>{e.onSessionStart(n,i.id)}),e.onSessionEnd&&n.on("session.ended",i=>{e.onSessionEnd(n,i.id)}),e.onAgentResponse&&n.on("agent.response",i=>{e.onAgentResponse(n,i)})}}function Hj(t){return t}function sh(t,e,n){return{name:t,version:"1.0.0",description:`${e} modality plugin`,install:async i=>{n.onActivate&&await n.onActivate(i)},uninstall:async i=>{n.onDeactivate&&await n.onDeactivate(i)},onAgentResponse:n.onMessage}}const zj={name:"analytics",version:"1.0.0",description:"Built-in analytics tracking",install:async t=>{console.log("Analytics plugin installed"),t.on("session.started",e=>{console.log("Analytics: Session started",e.id)}),t.on("session.ended",(e,n)=>{console.log("Analytics: Session ended",e.id,n)}),t.on("chat.message.sent",e=>{console.log("Analytics: User message sent",e.content.length)})}},Wj={name:"debug",version:"1.0.0",description:"Debug logging and development tools",install:async t=>{console.log("Debug plugin installed");const e=t.emit;t.emit=(n,...i)=>(console.log(`[Debug] Event: ${String(n)}`,i),e(n,...i))}},qj={name:"metrics",version:"1.0.0",description:"Advanced metrics collection",install:async t=>{console.log("Metrics plugin installed");const e=new Map;t.on("session.started",n=>{e.set(n.id,{startTime:Date.now(),events:[]})}),t.on("agent.response",n=>{console.log("Metrics: Agent response analyzed",{type:n.type,length:n.content.length,timestamp:n.timestamp})})}},iw=R.createContext(null);function rw({config:t,children:e,autoConnect:n=!1}){const[i,r]=R.useState(null),[s,o]=R.useState(!1),[a,c]=R.useState(!1),[l,d]=R.useState(null),[u,f]=R.useState(null),[p,g]=R.useState("idle"),[h,y]=R.useState(null),[b,w]=R.useState([]),[C,S]=R.useState([]),[x,T]=R.useState([]);R.useEffect(()=>{const O=new bo(t);return r(O),E(O),n&&P(O),()=>{O.disconnect().catch(console.error)}},[t,n]);const E=O=>{O.on("connection.connecting",()=>{c(!0),d(null)}),O.on("connection.connected",()=>{o(!0),c(!1),d(null)}),O.on("connection.disconnected",()=>{o(!1),c(!1),f(null),g("idle"),w([]),S([]),T([])}),O.on("connection.error",oe=>{d(oe),c(!1)}),O.on("session.created",oe=>{f(oe),g(oe.state)}),O.on("session.state.changed",oe=>{g(oe),u&&f({...u,state:oe})}),O.on("session.ended",(oe,L)=>{f(null),g("idle"),y(L),w([]),S([]),T([])}),O.on("participant.joined",oe=>{w(L=>[...L,oe])}),O.on("participant.left",oe=>{w(L=>L.filter(F=>F.id!==oe.id))}),O.on("chat.message.received",oe=>{S(L=>[...L,oe])}),O.on("chat.message.sent",oe=>{S(L=>[...L,oe])}),O.on("transcription.received",oe=>{T(L=>[...L,oe])})},P=async O=>{const oe=O||i;if(oe)try{await oe.connect()}catch(L){console.error("Failed to connect:",L)}},X={client:i,isConnected:s,isConnecting:a,connectionError:l,currentSession:u,sessionState:p,sessionMetrics:h,participants:b,chatMessages:C,transcriptions:x,connect:()=>P(),disconnect:async()=>{if(i)try{await i.disconnect()}catch(O){console.error("Failed to disconnect:",O)}},createSession:async(O,oe={})=>{if(!i)throw new Error("Client not initialized");const L={agentId:O,participantName:oe.participantName||"User",metadata:oe.metadata,modalities:oe.modalities||["voice"]};return await i.createSession(L)},endSession:async()=>i?await i.endSession():null,sendChatMessage:async O=>{if(!i)throw new Error("Client not initialized");await i.sendChatMessage(O)},setMicrophoneEnabled:async O=>{if(!i)throw new Error("Client not initialized");await i.setMicrophoneEnabled(O)},setCameraEnabled:async O=>{if(!i)throw new Error("Client not initialized");await i.setCameraEnabled(O)},startScreenShare:async()=>{if(!i)throw new Error("Client not initialized");await i.startScreenShare()},stopScreenShare:async()=>{if(!i)throw new Error("Client not initialized");await i.stopScreenShare()}};return m.jsx(iw.Provider,{value:X,children:e})}function jn(){const t=R.useContext(iw);if(!t)throw new Error("useVoxket must be used within a VoxketProvider");return t}class Kj extends rh{constructor(n){super();at(this,"room",null);at(this,"registeredMethods",new Map);at(this,"activeInteractions",new Map);at(this,"currentInteraction",null);n&&this.setRoom(n)}setRoom(n){this.room=n}async registerFrontendRPC(n,i,r="embedded"){if(console.log(`RpcManager: Starting registration for method '${n}'`),!this.room)throw console.error(`RpcManager: Cannot register '${n}' - no room instance`),new Error("Room not initialized. Cannot register RPC method.");if(!this.room.localParticipant)throw console.error(`RpcManager: Cannot register '${n}' - no local participant`),new Error("Local participant not available for RPC registration");console.log(`RpcManager: Room state: ${this.room.state}`),console.log(`RpcManager: Local participant: ${this.room.localParticipant.identity}`),console.log(`RpcManager: Registering frontend RPC method: ${n}`);const s={methodName:n,component:i,presentationMode:r};this.registeredMethods.set(n,s);try{this.room.registerRpcMethod(n,async o=>{console.log(`RpcManager: RPC method '${n}' called by ${o.callerIdentity}`),console.log("RpcManager: Payload:",o.payload),this.emit("rpc.method.called",{methodName:n,data:o});let a;console.log(`RpcManager: Current registration for '${n}':`,s);let c=o.responseTimeout||30;try{a=JSON.parse(o.payload)}catch{a=o.payload}try{const l=await this.awaitUserInteraction(n,i,r,a,c);return JSON.stringify(l)}catch(l){throw console.error(`RpcManager: Error in RPC method '${n}':`,l),l}}),this.emit("rpc.method.registered",{methodName:n}),console.log(`RpcManager: Successfully registered RPC method: ${n}`)}catch(o){throw console.error(`RpcManager: Failed to register RPC method '${n}':`,o),o}}async awaitUserInteraction(n,i,r,s,o){return new Promise((a,c)=>{const l=`${n}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${n}, timeout: ${o} seconds`);const d={didSuccess:(f,p)=>{console.log(`RpcManager: User interaction successful for method: ${n}`,f),this.clearInteraction(l),this.currentInteraction=null;const g={success:!0,message:"User interaction completed successfully",data:f,timestamp:new Date,...p?{successView:p}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:g}),a(g)},didFail:f=>{console.log(`RpcManager: User interaction failed for method: ${n}`,f),this.clearInteraction(l);const p={success:!1,message:"User interaction failed",error:f,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:p}),a(p)},dismissView:()=>{var p;console.log(`RpcManager: User dismissed interaction for method: ${n}`),console.log("RpcManager: Current interaction before dismiss:",(p=this.currentInteraction)==null?void 0:p.methodName),this.clearInteraction(l),this.currentInteraction=null,console.log("RpcManager: Current interaction after dismiss:",this.currentInteraction);const f={success:!0,data:{dismissed:!0,reason:"User dismissed the interaction"},message:"User interaction dismissed",timestamp:new Date};this.emit("rpc.interaction.dismissed",{methodName:n,response:f}),this.emit("rpc.interaction.completed",{methodName:n,response:f}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(f)},didTimeout:f=>{console.log(`RpcManager: User interaction timeout for method: ${n}`),this.clearInteraction(l),this.currentInteraction=null;const p={success:!0,message:`User interaction timed out after ${o} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...f?{timeoutView:f}:{}};this.emit("rpc.interaction.timeout",{methodName:n,response:p}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(p)}},u=setTimeout(()=>{d.didTimeout&&d.didTimeout()},o);this.activeInteractions.set(l,{resolve:f=>a(JSON.parse(f)),reject:c,timeoutId:u}),this.currentInteraction={isVisible:!0,methodName:n,component:i,presentationMode:r,timeout:o,data:s,handler:d},this.emit("rpc.interaction.started",{methodName:n,presentationMode:r}),setTimeout(async()=>{var f;if((f=this.currentInteraction)!=null&&f.handler)try{console.log(`RpcManager: Component created for method: ${n} with data:`,s)}catch(p){console.error("RpcManager: Error loading data into component:",p),d.didFail({error:"Failed to load data into component"})}},100)})}clearInteraction(n){const i=this.activeInteractions.get(n);i&&(console.log(`RpcManager: Clearing interaction: ${n}`),clearTimeout(i.timeoutId),this.activeInteractions.delete(n))}getCurrentInteraction(){return this.currentInteraction}dismissCurrentInteraction(){var n;this.currentInteraction&&(console.log(`RpcManager: Dismissing current interaction: ${this.currentInteraction.methodName}`),(n=this.currentInteraction.handler)==null||n.dismissView(),setTimeout(()=>{this.currentInteraction&&(console.log("RpcManager: Force clearing lingering interaction"),this.currentInteraction=null)},0))}getRegisteredMethods(){return Array.from(this.registeredMethods.keys())}unregisterMethod(n){this.registeredMethods.delete(n),console.log(`RpcManager: Unregistered RPC method: ${n}`)}clear(){for(const[n,i]of this.activeInteractions)clearTimeout(i.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null,console.log("RpcManager: Cleared all registrations and interactions")}}class De extends Error{constructor(e,n,i){super(e),this.code=n,this.details=i,this.name="VoxketError"}}class bo extends rh{constructor(n){super();at(this,"config");at(this,"room",null);at(this,"pluginManager");at(this,"rpcManager");at(this,"isConnected",!1);at(this,"currentSession",null);at(this,"connectionState",ge.Disconnected);at(this,"renderedComponents",new Map);at(this,"textStreamHandlersRegistered",!1);at(this,"currentAgentInfo",null);at(this,"chatMessages",[]);this.config=n,this.pluginManager=new nw(this),this.rpcManager=new Kj,this.setupEventListeners(),this.initializeClient()}setupEventListeners(){this.on("connection.connected",()=>{var n,i;this.isConnected=!0,(i=(n=this.config).onConnected)==null||i.call(n)}),this.on("connection.disconnected",n=>{var i,r;this.isConnected=!1,(r=(i=this.config).onDisconnected)==null||r.call(i,n)}),this.on("connection.error",n=>{var i,r;(r=(i=this.config).onError)==null||r.call(i,n)}),this.on("chat.message.received",n=>{var i,r;this.addChatMessage(n),(r=(i=this.config).onMessageReceived)==null||r.call(i,n)}),this.on("chat.message.updated",n=>{this.updateChatMessage(n)}),this.on("chat.message.sent",n=>{this.addChatMessage(n)}),this.on("transcription.received",n=>{var i,r;(r=(i=this.config).onTranscriptionReceived)==null||r.call(i,n)}),this.on("session.state.changed",n=>{var i,r;(r=(i=this.config).onSessionStateChanged)==null||r.call(i,n)}),this.on("session.created",n=>{var i,r;(r=(i=this.config).onSessionStart)==null||r.call(i,n.id)}),this.on("session.ended",(n,i)=>{var r,s;(s=(r=this.config).onSessionEnd)==null||s.call(r,i)}),this.on("participant.joined",n=>{var i,r;(r=(i=this.config).onUserJoined)==null||r.call(i,n.id)}),this.on("participant.left",n=>{var i,r;(r=(i=this.config).onUserLeft)==null||r.call(i,n.id)}),this.setupRpcEventForwarding()}setupRpcEventForwarding(){if(!this.rpcManager){console.warn("RpcManager not initialized, skipping event forwarding setup");return}this.rpcManager.on("rpc.method.registered",n=>this.emit("rpc.method.registered",n)),this.rpcManager.on("rpc.method.called",n=>this.emit("rpc.method.called",n)),this.rpcManager.on("rpc.interaction.started",n=>this.emit("rpc.interaction.started",n)),this.rpcManager.on("rpc.interaction.completed",n=>this.emit("rpc.interaction.completed",n)),this.rpcManager.on("rpc.interaction.timeout",n=>this.emit("rpc.interaction.timeout",n)),this.rpcManager.on("rpc.interaction.dismissed",n=>this.emit("rpc.interaction.dismissed",n))}initializeClient(){this.room=new pi,this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(U.Connected,()=>{var n,i;this.connectionState=ge.Connected,this.emit("connection.connected"),this.rpcManager.setRoom(this.room),(i=(n=this.currentSession)==null?void 0:n.activeModalities)!=null&&i.includes("voice")&&setTimeout(async()=>{var r;try{(r=this.room)!=null&&r.localParticipant&&(this.room.localParticipant.isMicrophoneEnabled?this.emit("track.unmuted",{source:"microphone",enabled:!0}):(await this.room.localParticipant.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0})))}catch(s){console.warn("VoxketClient: Failed to enable microphone after room connection:",s)}},1e3),this.textStreamHandlersRegistered||this.setupTextStreamHandlers()}),this.room.on(U.Disconnected,n=>{this.connectionState=ge.Disconnected,this.textStreamHandlersRegistered=!1,this.emit("connection.disconnected",n==null?void 0:n.toString())}),this.room.on(U.ConnectionStateChanged,n=>{this.connectionState=n,n===ge.Connecting&&this.emit("connection.connecting")}),this.room.on(U.ParticipantConnected,n=>{const i={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.joined",i)}),this.room.on(U.ParticipantDisconnected,n=>{const i={id:n.identity,name:n.name||n.identity,isLocal:!1};this.emit("participant.left",i)}))}setupTextStreamHandlers(){if(this.room){try{this.room.registerTextStreamHandler("lk.chat",async(n,i)=>{try{const r=await n.readAll(),s={id:`msg_${Date.now()}_${i.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:r,timestamp:new Date,sender:{id:i.identity||"user",name:i.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.emit("chat.message.received",s)}catch(r){console.error("VoxketClient: Failed to process lk.chat message:",r)}})}catch(n){console.warn("VoxketClient: lk.chat handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("lk.transcription",async(n,i)=>{var r,s;try{const o=`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`;let a="";const c=((r=this.currentAgentInfo)==null?void 0:r.name)||i.identity||"AI Assistant",l={id:o,content:"",timestamp:new Date,sender:{id:i.identity||"agent",name:c,type:"agent"},metadata:{topic:"lk.transcription",streaming:!0}};this.emit("chat.message.received",l);for await(const f of n){a+=f;const p=this.convertMarkdownToText(a),g={...l,content:p,metadata:{...l.metadata,streaming:!0}};this.emit("chat.message.updated",g)}const d=this.convertMarkdownToText(a),u={...l,content:d,metadata:{...l.metadata,streaming:!1}};this.emit("chat.message.updated",u)}catch(o){console.error("VoxketClient: Failed to process lk.transcription message:",o);try{const a=await n.readAll(),c=((s=this.currentAgentInfo)==null?void 0:s.name)||i.identity||"AI Assistant",l={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:a,timestamp:new Date,sender:{id:i.identity||"agent",name:c,type:"agent"},metadata:{topic:"lk.transcription"}};this.emit("chat.message.received",l)}catch(a){console.error("VoxketClient: Fallback failed for lk.transcription:",a)}}})}catch(n){console.warn("VoxketClient: lk.transcription handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("suggested_response",async n=>{const i=await n.readAll();let r=[];try{r=["tes","hello how are you","algebra make me learn that ","what is the meaning of life"]}catch(s){console.warn("VoxketClient: Failed to parse suggested_response:",s,i)}this.emit("suggested.response",r)})}catch(n){console.warn("VoxketClient: suggested_response handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("agent_state_changed",async(n,i)=>{const r=await n.readAll();let s={};try{s=typeof r=="string"?JSON.parse(r.replace(/'/g,'"')):r}catch(o){console.warn("VoxketClient: Failed to parse agent_state_changed:",o,r)}s.new_state==="speaking"?this.emit("agent.speaking",s):s.new_state==="thinking"&&this.emit("agent.thinking",s)})}catch(n){console.warn("VoxketClient: conversation_item_added handler already registered, skipping:",n)}try{this.room.registerTextStreamHandler("images",async(n,i)=>{try{const r=await n.readAll()}catch(r){console.error("VoxketClient: Error processing images stream:",r)}})}catch(n){console.warn("VoxketClient: images handler already registered, skipping:",n)}try{this.room.registerByteStreamHandler("images",async(n,i)=>{var r,s;try{const o=n.info,a={id:`img_${Date.now()}_${i.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`�️ ${o.name||"Image"}`,sender:{id:i.identity||"agent",name:i.identity||"Agent",type:i.identity===((s=(r=this.room)==null?void 0:r.localParticipant)==null?void 0:s.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:o.name,fileSize:o.size,mimeType:o.mimeType,streamId:o.id,downloading:!0}};this.emit("chat.message.received",a),n.onProgress&&(n.onProgress=f=>{const p={...a,metadata:{...a.metadata,downloadProgress:f||0}};this.emit("chat.message.updated",p)});const c=[];for await(const f of n)c.push(f);const l=new Blob(c,{type:o.mimeType||"application/octet-stream"}),d=URL.createObjectURL(l),u={...a,metadata:{...a.metadata,downloading:!1,downloadProgress:1,downloadUrl:d,blob:l}};this.emit("chat.message.updated",u)}catch(o){console.error("VoxketClient: Error processing image attachment:",o)}})}catch(n){console.warn("VoxketClient: image handler already registered, skipping:",n)}this.textStreamHandlersRegistered=!0}}async fetchConnectionDetails(n,i,r){const s=n||this.config.agentId||"default-agent",o=i||this.config.participantName||"User",a=r||this.config.modalities||["voice"];try{const c={agent_id:s,participant_name:o,participant_metadata:{user_id:""},modality:a[0]},l=await fetch(`${this.config.baseUrl}/api/live/agent/session`,{method:"POST",headers:{accept:"application/json","X-APP-ID":this.config.appId,"X-APP-SECRET":this.config.appSecret,"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok){let f=`HTTP ${l.status}: Failed to fetch connection details`;try{const p=await l.json();p&&(p.error?f=`API Error: ${p.error}`:p.detail?f=`API Error: ${p.detail}`:p.message&&(f=`API Error: ${p.message}`))}catch{try{const g=await l.text();g&&(f=`API Error: ${g}`)}catch{}}throw new Error(f)}const d=await l.json();let u;return d.agent_info&&(u={id:d.agent_info.id||s,name:d.agent_info.name||"AI Assistant",avatar:d.agent_info.avatar,capabilities:d.agent_info.capabilities||["voice_interaction","text_chat"],metadata:d.agent_info.metadata||{}},this.currentAgentInfo=u),{serverUrl:d.wss_url,participantToken:d.token,voxketSessionId:d.session_id,agentInfo:u}}catch(c){console.error("VoxketClient: fetchConnectionDetails failed:",c);const l=new De(`Failed to fetch connection details: ${c instanceof Error?c.message:"Unknown error"}`,"CONNECTION_FAILED",c);throw this.emit("connection.error",l),l}}async connect(n,i,r){var s;try{this.emit("connection.connecting");const o=await this.fetchConnectionDetails(n,i,r);return await((s=this.room)==null?void 0:s.connect(o.serverUrl,o.participantToken)),this.isConnected=!0,o}catch(o){console.error("VoxketClient: Connection failed:",o);const a=new De(`Failed to connect to Voxket services: ${o instanceof Error?o.message:"Unknown error"}`,"CONNECTION_FAILED",o);throw this.emit("connection.error",a),a}}async disconnect(){var n;try{await((n=this.room)==null?void 0:n.disconnect()),this.isConnected=!1,this.currentSession=null,this.currentAgentInfo=null,this.textStreamHandlersRegistered=!1,this.clearChatMessages(),this.room=new pi,this.setupRoomEventListeners()}catch(i){const r=new De("Failed to disconnect properly","NETWORK_ERROR",i);throw this.emit("connection.error",r),r}}async createSession(n){var i,r;try{const s=await this.connect(n.agentId,n.participantName,n.modalities),o={id:s.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:s.agentInfo||this.currentAgentInfo};if(this.currentSession=o,this.emit("session.created",o),(i=n.modalities)!=null&&i.includes("voice"))try{await new Promise(a=>setTimeout(a,500)),(r=this.room)!=null&&r.localParticipant?(await this.room.localParticipant.setMicrophoneEnabled(!0,void 0,{preConnectBuffer:!0}),this.emit("track.unmuted",{source:"microphone",enabled:!0})):console.warn("VoxketClient: No local participant found, microphone not enabled")}catch(a){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",a)}return setTimeout(()=>{this.currentSession&&(this.currentSession.state="active",this.emit("session.state.changed","active",this.currentSession.state))},1e3),o}catch(s){throw console.error("VoxketClient: Failed to create session:",s),s instanceof De?s:s instanceof TypeError&&s.message.includes("fetch")?new De("Network connection failed","CONNECTION_FAILED",s):s instanceof Error&&s.message.includes("Failed to fetch connection details")?new De(`API connection failed: ${s.message}`,"CONNECTION_FAILED",s):new De(`Failed to create session: ${s instanceof Error?s.message:"Unknown error"}`,"SESSION_NOT_FOUND",s)}}async startSession(n,i){const r={agentId:n||this.config.agentId||"default-agent",participantName:(i==null?void 0:i.participantName)||this.config.participantName||"User",modalities:(i==null?void 0:i.modalities)||this.config.modalities||["voice","chat"],metadata:i==null?void 0:i.metadata};return this.createSession(r)}async endSession(){var n,i;if(!this.currentSession)return null;try{const r={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((i=this.room)==null?void 0:i.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]};return this.currentSession.endedAt=new Date,this.currentSession.state="disconnected",this.emit("session.ended",this.currentSession,r),await this.disconnect(),r}catch(r){throw new De("Failed to end session","SESSION_NOT_FOUND",r)}}getCurrentSession(){return this.currentSession}getCurrentAgentInfo(){return this.currentAgentInfo}getChatMessages(){return[...this.chatMessages]}addChatMessage(n){this.chatMessages.some(r=>r.id===n.id)||this.chatMessages.push(n)}updateChatMessage(n){const i=this.chatMessages.findIndex(r=>r.id===n.id);i!==-1&&(this.chatMessages[i]=n)}clearChatMessages(){this.chatMessages=[],this.dismissCurrentInteraction(),this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays(),this.emit("chat.history.cleared")}renderUI(n={}){var c,l,d;const i=this.resolveTarget(n.target||"body"),r=this.getTargetKey(i),s=this.renderedComponents.get(r);s&&s.target===i||this.removeUI(i);const o=(s==null?void 0:s.root)||$j.createRoot(i),a={agentId:n.agentId||this.config.agentId||"default-agent",participantName:n.participantName||this.config.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:n.className,theme:typeof n.theme=="string"?n.theme:void 0,modalities:n.modality||this.config.modalities||["voice"],suportsChatInput:((c=n.modality)==null?void 0:c.includes("chat"))!==!1,suportsVideoInput:((l=n.modality)==null?void 0:l.includes("video"))===!0,suportsScreenShare:((d=n.modality)==null?void 0:d.includes("screen_share"))===!0,autoStart:n.autoStart,displayType:n.displayType||"widget",popupPosition:n.popupPosition||"bottom-right",popupTriggerText:n.popupTriggerText||"Open Chat",width:n.width,height:n.height,onDisplayTypeChange:n.onDisplayTypeChange,prompts:n.prompts,statusMessage:n.statusMessage,welcomeTitle:n.welcomeTitle,welcomeSubTitle:n.welcomeSubTitle,loadingText:n.loadingText,voxketClient:this};o.render(R.createElement(rw,{config:this.config,autoConnect:n.autoStart||!1,children:R.createElement(sw,a)})),this.renderedComponents.set(r,{root:o,target:i})}removeUI(n){const i=n?this.resolveTarget(n):null;if(i){const r=this.getTargetKey(i),s=this.renderedComponents.get(r);s&&(s.root.unmount(),this.renderedComponents.delete(r),i.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(a=>{try{a.remove()}catch(c){console.warn("Failed to remove element:",c)}}),i===document.body&&i.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(c=>{if(c.classList.contains("bg-black")&&c.classList.contains("backdrop-blur-sm"))try{c.remove()}catch(l){console.warn("Failed to remove fixed element:",l)}}))}}removeAllUI(){for(const[n,i]of this.renderedComponents)i.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(i=>{if(i.classList.contains("bg-black")&&(i.classList.contains("backdrop-blur-sm")||i.classList.contains("bg-opacity-30")))try{i.remove()}catch(r){console.warn("Failed to remove overlay:",r)}})}resolveTarget(n){if(typeof n=="string"){const i=document.querySelector(n);if(!i)throw new Error(`Target element not found: ${n}`);return i}return n}getTargetKey(n){return n.id?n.id:n.className?n.tagName+"_"+n.className.replace(/\s+/g,"_"):n.tagName+"_"+n.outerHTML.length%1e3}async sendMessage(n,i){var r;if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new De("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new De("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new De("No local participant","CONNECTION_FAILED");this.dismissCurrentInteraction();try{const s={id:`msg_${Date.now()}`,content:n,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:i||{}},o=await((r=this.room)==null?void 0:r.localParticipant.sendText(n,{topic:"lk.chat",destinationIdentities:[]}));this.emit("chat.message.sent",s)}catch(s){throw console.error("VoxketClient: Failed to send chat message:",s),new De("Failed to send message","NETWORK_ERROR",s)}}async sendChatMessage(n,i){return this.sendMessage(n,i)}async sendAttachments(n,i){if(!this.currentSession)throw console.error("VoxketClient: No active session found"),new De("No active session","SESSION_NOT_FOUND");if(!this.room)throw console.error("VoxketClient: No room instance found"),new De("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw console.error("VoxketClient: No local participant found"),new De("No local participant","CONNECTION_FAILED");if(!n||n.length===0)throw new De("No files provided","INVALID_PARAMETER");this.dismissCurrentInteraction();const r=n.filter(s=>s.type.startsWith("image/"));if(r.length===0)throw new De("Only image files are allowed","INVALID_PARAMETER");r.length!==n.length&&console.warn("VoxketClient: Some non-image files were filtered out");try{const s=r.map(async(o,a)=>{const l={id:`att_${Date.now()}_${a}`,content:`📎 ${o.name}`,sender:{id:"user",name:this.config.participantName||"User",type:"participant"},timestamp:new Date,metadata:{...i,type:"attachment",fileName:o.name,fileSize:o.size,mimeType:o.type,uploading:!0}};this.emit("chat.message.sent",l);const d=await this.room.localParticipant.sendFile(o,{mimeType:o.type,topic:"images",onProgress:f=>{const p={...l,metadata:{...l.metadata,uploadProgress:f}};this.emit("chat.message.updated",p)}});try{const f=new FileReader,p=new Promise((y,b)=>{f.onload=()=>{typeof f.result=="string"?y(f.result):b(new Error("Failed to convert to base64"))},f.onerror=b});f.readAsDataURL(o);const h={type:"image",data:await p,filename:o.name,mimeType:o.type,size:o.size};await this.room.localParticipant.sendText(JSON.stringify(h),{topic:"images",destinationIdentities:[]})}catch(f){console.warn("VoxketClient: Failed to send image data to agent:",f);try{const p=`I've shared an image: ${o.name}`;await this.room.localParticipant.sendText(p,{topic:"lk.chat",destinationIdentities:[]})}catch(p){console.warn("VoxketClient: Failed to send image notification to agent:",p)}}const u={...l,metadata:{...l.metadata,uploading:!1,uploadProgress:1,streamId:d.id}};return this.emit("chat.message.updated",u),d});await Promise.all(s)}catch(s){throw console.error("VoxketClient: Failed to send attachments:",s),new De("Failed to send attachments","NETWORK_ERROR",s)}}async sendAttachment(n,i){return this.sendAttachments([n],i)}toggleMicrophone(n){return this.setMicrophoneEnabled(n!==!1)}async setMicrophoneEnabled(n){var i,r;try{const s=(i=this.room)==null?void 0:i.localParticipant.isMicrophoneEnabled,o=n??!s;await((r=this.room)==null?void 0:r.localParticipant.setMicrophoneEnabled(o)),o?this.emit("track.unmuted",{source:"microphone",enabled:!0}):this.emit("track.muted",{source:"microphone",enabled:!1})}catch(s){throw console.error("VoxketClient: Failed to toggle microphone:",s),new De("Failed to toggle microphone","PERMISSION_DENIED",s)}}toggleCamera(n){return this.setCameraEnabled(n!==!1)}async setCameraEnabled(n){var i,r;try{const s=(i=this.room)==null?void 0:i.localParticipant.isCameraEnabled,o=n??!s;await((r=this.room)==null?void 0:r.localParticipant.setCameraEnabled(o)),o?this.emit("track.unmuted",{source:"camera",enabled:!0}):this.emit("track.muted",{source:"camera",enabled:!1})}catch(s){throw console.error("VoxketClient: Failed to toggle camera:",s),new De("Failed to toggle camera","PERMISSION_DENIED",s)}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!0))}catch(i){throw new De("Failed to start screen share","PERMISSION_DENIED",i)}}async stopScreenShare(){var n;try{await((n=this.room)==null?void 0:n.localParticipant.setScreenShareEnabled(!1))}catch(i){throw new De("Failed to stop screen share","PERMISSION_DENIED",i)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(i=>i.kind==="audioinput")}catch(n){throw new De("Failed to get audio input devices","DEVICE_ERROR",n)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(i=>i.kind==="videoinput")}catch(n){throw new De("Failed to get video input devices","DEVICE_ERROR",n)}}async setAudioInputDevice(n){var i;try{if(!((i=this.room)!=null&&i.localParticipant))throw new Error("Not connected to room")}catch(r){throw new De("Failed to set audio input device","DEVICE_ERROR",r)}}async setVideoInputDevice(n){var i;try{if(!((i=this.room)!=null&&i.localParticipant))throw new Error("Not connected to room")}catch(r){throw new De("Failed to set video input device","DEVICE_ERROR",r)}}getLocalParticipant(){var n;return((n=this.room)==null?void 0:n.localParticipant)??null}getRemoteParticipants(){var n;return Array.from(((n=this.room)==null?void 0:n.remoteParticipants.values())??[])}getPublishPermissions(){const n=this.getLocalParticipant();if(!n)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const i=n.permissions;if(!i)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const r=s=>!!i.canPublish&&(i.canPublishSources.length===0||i.canPublishSources.includes(s));return{camera:r(1),microphone:r(2),screenShare:r(3),data:i.canPublishData??!1}}canPublishSource(n){return this.getPublishPermissions()[n]}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===ge.Connected}getMicrophoneTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,i]of n.trackPublications)if(i.source===V.Source.Microphone)return i.track;return null}getCameraTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,i]of n.trackPublications)if(i.source===V.Source.Camera)return i.track;return null}getScreenShareTrack(){const n=this.getLocalParticipant();if(!n)return null;for(const[,i]of n.trackPublications)if(i.source===V.Source.ScreenShare)return i.track;return null}get isMicrophoneEnabled(){const n=this.getMicrophoneTrack();return n?!n.isMuted:!1}get isCameraEnabled(){const n=this.getCameraTrack();return n?!n.isMuted:!1}get isScreenShareEnabled(){const n=this.getScreenShareTrack();return n?!n.isMuted:!1}registerPlugin(n){this.pluginManager.register(n)}getPluginManager(){return this.pluginManager}getParticipants(){if(!this.room)return[];const n=[];return this.room.localParticipant&&n.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(i=>{n.push({id:i.identity,name:i.name||i.identity,isLocal:!1})}),n}getSessionMetrics(){var n,i;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((i=this.room)==null?void 0:i.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]}:null}updateConfig(n){this.config={...this.config,...n}}async startRecording(){var n;try{this.emit("recording.started",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(i){throw new De("Failed to start recording","RECORDING_ERROR",i)}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(i){throw new De("Failed to stop recording","RECORDING_ERROR",i)}}async registerFrontendRPC(n,i,r="embedded"){return this.rpcManager.registerFrontendRPC(n,i,r)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}registerEventListener(n,i){return this.on(n,i)}registerEventEmitter(n,i){if(!this.room)throw new Error("Room not available");try{this.room.registerTextStreamHandler(n,async r=>{try{const s=await r.readAll();i(s)}catch(s){console.error(`Error processing event for topic '${n}':`,s)}})}catch(r){console.warn(`VoxketClient: Handler for topic '${n}' may already be registered:`,r)}}convertMarkdownToText(n){if(!n)return"";let i=n;return i=i.replace(/\*\*(.*?)\*\*/g,"$1"),i=i.replace(/__(.*?)__/g,"$1"),i=i.replace(/\*(.*?)\*/g,"$1"),i=i.replace(/_(.*?)_/g,"$1"),i=i.replace(/~~(.*?)~~/g,"$1"),i=i.replace(/`([^`]+)`/g,"$1"),i=i.replace(/```[\s\S]*?```/g,""),i=i.replace(/^#{1,6}\s+/gm,""),i=i.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),i.trim()}}const Gj=xe.create(kj),Zj=xe.create(Oj),Yj=xe.create(Lj),Jj=xe.create(Uj);function Xj({onClick:t,text:e="Open Chat",position:n="bottom-right",theme:i}){const r={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},s=St(i);return m.jsx(xe.button,{onClick:t,className:`fixed ${r[n]} z-50 px-4 py-2 rounded-full shadow-lg ${s.popupTrigger} transition-all duration-200 hover:scale-105`,initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:0,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},children:e})}function P0({children:t,theme:e,displayType:n="widget",onClose:i,popupPosition:r="bottom-right",onExpand:s}){const o=St(e);if(n==="fullscreen")return m.jsx("div",{className:"fixed inset-0 z-50 bg-black bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",children:m.jsxs("div",{className:"w-full h-full max-w-6xl max-h-[90vh] rounded-2xl relative bg-transparent",children:[i&&m.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),i()},className:"absolute top-4 cursor-pointer right-4 z-[100] w-12 h-12 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border border-gray-700 backdrop-blur-sm",title:"Exit Fullscreen",type:"button",children:m.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:m.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),m.jsxs("div",{id:"voice-card",className:`${o.card} w-full h-full flex flex-col rounded-xl shadow-2xl`,style:{minHeight:"600px"},children:[m.jsx("div",{className:o.cardTopGradient}),m.jsx("div",{className:o.cardPurpleBlur}),m.jsx("div",{className:o.cardPinkBlur}),m.jsx("div",{className:" flex flex-col h-full",children:t}),m.jsx("div",{className:o.cardPulse1}),m.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){const a={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"};return m.jsx("div",{className:"fixed rounded-2xl inset-0 z-50 pointer-events-none",children:m.jsxs("div",{className:`fixed rounded-2xl ${a[r]} pointer-events-auto`,children:[i&&m.jsx("button",{onClick:i,className:"absolute -top-2 -right-2 z-10 w-8 h-8 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 text-sm shadow-lg border border-gray-700",children:"×"}),m.jsxs("div",{id:"voice-card",className:`${o.card} rounded-2xl flex flex-col`,style:{width:"300px",height:"450px"},children:[m.jsx("div",{className:o.cardPurpleBlur}),m.jsx("div",{className:o.cardPinkBlur}),m.jsx("div",{className:" flex flex-col h-full",children:t}),m.jsx("div",{className:o.cardPulse1}),m.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return m.jsxs("div",{id:"voice-card",className:`${o.card}`,children:[s&&m.jsx("button",{onClick:s,className:"absolute top-4 right-4 z-20 w-10 h-10 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border border-gray-700 backdrop-blur-sm",title:"Enter Fullscreen",children:m.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:m.jsx("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})})}),m.jsx("div",{className:o.cardTopGradient}),m.jsx("div",{className:o.cardPurpleBlur}),m.jsx("div",{className:o.cardPinkBlur}),t,m.jsx("div",{className:o.cardPulse1}),m.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})}function sw(t){if(typeof window>"u")return null;console.log("🎯 Widget component rendering with props:",{displayType:t.displayType,popupPosition:t.popupPosition,theme:t.theme});const{agentId:e,participantName:n,baseUrl:i,appSecret:r,appId:s,prompts:o,statusMessage:a,welcomeTitle:c,welcomeSubTitle:l,className:d,width:u,height:f,loadingText:p,suportsChatInput:g=!0,suportsVideoInput:h=!0,suportsScreenShare:y=!0,theme:b="vox",onSessionStart:w,onSessionEnd:C,enableSessionLogging:S=!0,onSessionLogsUpdate:x,onSessionMetricsUpdate:T,modalities:E=["voice"],displayType:P="widget",popupPosition:_="bottom-right",popupTriggerText:k="Open Chat",onPopupToggle:I,voxketClient:N,onDisplayTypeChange:K}=t,[J,se]=v.useState(()=>N?!!N.getCurrentSession():!1),[ie,X]=v.useState(!1),[O,oe]=v.useState(e||""),[L,F]=v.useState(n||"User"),[te,j]=v.useState(()=>N?N.getCurrentSession():null),[q,ee]=v.useState(()=>{var ve,tn,At;if(N){const $e=N.getCurrentSession();if((ve=$e==null?void 0:$e.activeModalities)!=null&&ve.includes("chat"))return"chat";if((tn=$e==null?void 0:$e.activeModalities)!=null&&tn.includes("voice"))return"voice";if((At=$e==null?void 0:$e.activeModalities)!=null&&At.includes("video"))return"video"}return"welcome"}),[G,D]=v.useState(!1);v.useEffect(()=>{console.log("🎯 Widget displayType prop changed to:",P)},[P]),v.useEffect(()=>{console.log("📊 Session state changed:",{currentMode:q,sessionStarted:J,loading:ie,currentSession:te==null?void 0:te.id,isPopupOpen:G})},[q,J,ie,te,G]);const $=v.useMemo(()=>{if(N)return console.log("🔄 Using passed VoxketClient to preserve session state"),N;console.log("🆕 Creating new VoxketClient instance");const ve={appId:s,appSecret:r,baseUrl:i,agentId:O,participantName:L||"User",modalities:E};return new bo(ve)},[N,s,r,i,O,L,E]),Q=E,W=v.useMemo(()=>$.getRoom()||new pi,[$]),ce={suportsChatInput:g,suportsVideoInput:h,suportsScreenShare:y},{sessionMetrics:z,sessionLogs:me,logEvent:Ee}=tw({room:W,onSessionStart:w,onSessionEnd:C,enableConsoleLogging:S,enableLocalStorage:S,voxketSessionId:te==null?void 0:te.id});v.useEffect(()=>{x&&x(me)},[me,x]),v.useEffect(()=>{T&&z&&T(z)},[z,T]),v.useEffect(()=>{const ve=At=>{console.log("🔴 Room disconnected:",At),X(!1),se(!1),j(null),ee("welcome")},tn=At=>{console.log("📹 Media devices error:",At),No({title:"Allow access to your microphone/camera",description:`${At.name}: ${At.message}`})};return W.on(U.MediaDevicesError,tn),W.on(U.Disconnected,ve),()=>{W.off(U.Disconnected,ve),W.off(U.MediaDevicesError,tn)}},[W]);const qe=async()=>{try{console.log("🎤 Starting voice session...",{agentId:O,participantName:L}),console.log("🎤 Pre-start state:",{currentMode:q,sessionStarted:J,loading:ie}),X(!0),se(!0),ee("voice"),console.log("🎤 State after mode change:",{currentMode:"voice",sessionStarted:!0,loading:!0}),Ee("USER_STARTED_VOICE_SESSION",{agentId:O,participantName:L});const ve=await $.startSession(O,{participantName:L||"User",modalities:["voice",...h?["video"]:[]]});console.log("✅ Voice session started successfully:",ve.id),j(ve),X(!1),w&&w(ve.id)}catch(ve){console.error("❌ Failed to start voice session:",ve),No({title:"Failed to start voice session",description:ve instanceof Error?ve.message:"Unknown error occurred"}),X(!1),se(!1),ee("welcome")}},Ct=async()=>{try{X(!0),se(!0),ee("chat"),Ee("USER_STARTED_CHAT_SESSION",{agentId:O,participantName:L});const ve=await $.startSession(O,{participantName:L||"User",modalities:["chat"]});j(ve),X(!1),w&&w(ve.id)}catch(ve){console.error("Failed to start chat session:",ve),No({title:"Failed to start chat session",description:ve instanceof Error?ve.message:"Unknown error occurred"}),X(!1),se(!1),ee("welcome")}},gn=async()=>{try{console.log("📺 Starting video session...",{agentId:O,participantName:L}),console.log("📺 Pre-start state:",{currentMode:q,sessionStarted:J,loading:ie}),X(!0),se(!0),ee("video"),console.log("📺 State after mode change:",{currentMode:"video",sessionStarted:!0,loading:!0}),Ee("USER_STARTED_VIDEO_SESSION",{agentId:O,participantName:L});const ve=await $.startSession(O,{participantName:L||"User",modalities:["video","voice"]});console.log("✅ Video session started successfully:",ve.id),j(ve),X(!1),w&&w(ve.id)}catch(ve){console.error("❌ Failed to start video session:",ve),No({title:"Failed to start video session",description:ve instanceof Error?ve.message:"Unknown error occurred"}),X(!1),se(!1),ee("welcome")}},vn=()=>{ee("welcome"),K&&K(t.displayType||"widget"),te&&J&&(se(!1),j(null),$.disconnect()),P==="popup"&&!G&&D(!0)},Et=()=>{const ve=!G;D(ve),I&&I(ve),!ve&&!(te&&J)&&(ee("welcome"),se(!1),j(null))},Ec=()=>{console.log("🔄 Closing fullscreen, switching to widget display type"),t.onDisplayTypeChange?t.onDisplayTypeChange("widget"):console.warn("⚠️ No onDisplayTypeChange callback provided")},Pc=()=>{t.onDisplayTypeChange&&t.onDisplayTypeChange("fullscreen")};v.useEffect(()=>{var ve,tn,At;if(N&&$){console.log("🔄 Syncing widget state with existing client session state");const $e=$.getCurrentSession(),Rc=$.connected;console.log("🔍 Existing session state:",{hasSession:!!$e,sessionId:$e==null?void 0:$e.id,isConnected:Rc,activeModalities:$e==null?void 0:$e.activeModalities}),$e&&(console.log("✅ Restoring session state from existing client"),j($e),se(!0),X(!1),(ve=$e.activeModalities)!=null&&ve.includes("chat")?ee("chat"):(tn=$e.activeModalities)!=null&&tn.includes("voice")?ee("voice"):(At=$e.activeModalities)!=null&&At.includes("video")&&ee("video"))}},[N,$]),v.useEffect(()=>()=>{console.log("🧹 Cleaning up widget component"),N?console.log("🔄 Widget cleanup: preserving passed client instance"):(console.log("🧹 Widget cleanup: disconnecting self-created client"),$.disconnect())},[$,N]);let _i="w-96",ms="h-[25rem]",ps={};if(u&&(u.startsWith("w-")?_i=u:(ps.width=u,_i="")),f&&(f.startsWith("h-")?ms=f:(ps.height=f,ms="")),P==="popup"&&!G)return console.log("🟡 Showing popup trigger button"),m.jsx(Xj,{onClick:Et,text:k,position:_,theme:b});console.log("🟢 Rendering widget content, displayType:",P,"isPopupOpen:",G,"currentMode:",q,"sessionStarted:",J,"loading:",ie);let or=`voxket-widget-root theme-${b}`,Ni={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};P==="widget"?(or+=` flex items-center justify-center min-h-fit ${_i} ${ms} ${d}`,Ni={...Ni,...ps}):(or=`${d||""}`,Ni={});const gs=m.jsx(m.Fragment,{children:m.jsxs(Vr,{mode:"wait",children:[q==="welcome"&&!ie&&m.jsx(Jj,{agentId:O,participantName:L||"",onAgentIdChange:oe,onParticipantNameChange:F,onStartCall:qe,onStartChat:Ct,onStartVideo:gn,disabled:J||ie,prompts:o,statusMessage:a,title:c,subTitle:l,theme:b,modalities:Q,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),q==="voice"&&m.jsxs(Da.Provider,{value:W,children:[m.jsx(tg,{}),m.jsx(Xp,{label:"Start Audio"}),m.jsx(Gj,{loadingText:p,participantName:L||"User",capabilities:ce,sessionStarted:J,disabled:!J,theme:b,client:$,displayType:P,onBack:P==="popup"?Et:vn,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"session-view")]}),q==="chat"&&m.jsx(Zj,{client:$,theme:b,displayType:P,onBack:P==="popup"?Et:vn,onEndChat:vn,disabled:!J,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),q==="video"&&m.jsxs(Da.Provider,{value:W,children:[m.jsx(tg,{}),m.jsx(Xp,{label:"Start Audio"}),m.jsx(Yj,{client:$,theme:b,displayType:P,onBack:P==="popup"?Et:vn,onEndCall:vn,disabled:!J,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-view")]})]})});return P==="fullscreen"||P==="popup"?(console.log("📱 Rendering fullscreen/popup mode, displayType:",P),m.jsx(P0,{theme:b,displayType:P,popupPosition:_,onClose:P==="fullscreen"?Ec:Et,children:gs})):(console.log("📦 Rendering widget mode"),m.jsx("div",{className:or,style:Ni,children:m.jsx(P0,{theme:b,displayType:P,popupPosition:_,onExpand:Pc,children:gs})}))}function Qj({logs:t,onClear:e,onExport:n}){const[i,r]=R.useState(!1),[s,o]=R.useState(""),a=t.filter(c=>!s||c.event.toLowerCase().includes(s.toLowerCase()));return i?m.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:m.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[m.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[m.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",t.length,")"]}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("input",{type:"text",placeholder:"Filter events...",value:s,onChange:c=>o(c.target.value),className:"px-3 py-1 border rounded text-sm"}),m.jsx("button",{onClick:e,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),m.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),m.jsx("button",{onClick:()=>r(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),m.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?m.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):m.jsx("div",{className:"space-y-2",children:a.map((c,l)=>m.jsxs("div",{className:"border rounded p-3 text-sm",children:[m.jsxs("div",{className:"flex items-center justify-between mb-1",children:[m.jsx("span",{className:"font-semibold text-blue-600",children:c.event}),m.jsx("span",{className:"text-gray-500 text-xs",children:new Date(c.timestamp).toLocaleTimeString()})]}),c.sessionId&&m.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",c.sessionId]}),c.data&&m.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:m.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(c.data,null,2)})})]},l))})})]})}):m.jsxs("button",{onClick:()=>r(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",t.length,")"]})}function eL({metrics:t}){return t?m.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[m.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),m.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Session ID:"}),m.jsx("div",{className:"font-mono text-xs",children:t.sessionId})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Start Time:"}),m.jsx("div",{children:new Date(t.startTime).toLocaleString()})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Messages:"}),m.jsx("div",{children:t.totalMessages})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Participants:"}),m.jsx("div",{children:t.participantCount})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),m.jsx("div",{children:t.connectionIssues})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Duration:"}),m.jsxs("div",{children:[Math.round((Date.now()-new Date(t.startTime).getTime())/1e3),"s"]})]})]})]}):null}function sr(){const{currentSession:t,sessionState:e,sessionMetrics:n,createSession:i,endSession:r}=jn(),s=R.useCallback(async(a,c)=>await i(a,c),[i]),o=R.useCallback(async()=>await r(),[r]);return{session:t,state:e,metrics:n,isActive:t!==null&&e!=="disconnected",isConnecting:e==="connecting",isConnected:e==="connected"||e==="active",start:s,stop:o}}function ow(){const{sessionMetrics:t,currentSession:e}=jn();return{metrics:t,sessionId:e==null?void 0:e.id,duration:t==null?void 0:t.duration,participantCount:t==null?void 0:t.participantCount,messageCount:t==null?void 0:t.messageCount,audioQuality:t==null?void 0:t.audioQuality,networkStats:t==null?void 0:t.networkStats}}function aw(){const{setMicrophoneEnabled:t,client:e}=jn(),[n,i]=R.useState(!1),[r,s]=R.useState(!1),o=R.useCallback(async()=>{if(!r){s(!0);try{const l=!n;await t(l),i(l)}catch(l){console.error("Failed to toggle microphone:",l)}finally{s(!1)}}},[n,r,t]),a=R.useCallback(async()=>{if(!(n||r)){s(!0);try{await t(!0),i(!0)}catch(l){console.error("Failed to enable microphone:",l)}finally{s(!1)}}},[n,r,t]),c=R.useCallback(async()=>{if(!(!n||r)){s(!0);try{await t(!1),i(!1)}catch(l){console.error("Failed to disable microphone:",l)}finally{s(!1)}}},[n,r,t]);return{isEnabled:n,isLoading:r,toggle:o,enable:a,disable:c}}function cw(){const{setCameraEnabled:t}=jn(),[e,n]=R.useState(!1),[i,r]=R.useState(!1),s=R.useCallback(async()=>{if(!i){r(!0);try{const c=!e;await t(c),n(c)}catch(c){console.error("Failed to toggle camera:",c)}finally{r(!1)}}},[e,i,t]),o=R.useCallback(async()=>{if(!(e||i)){r(!0);try{await t(!0),n(!0)}catch(c){console.error("Failed to enable camera:",c)}finally{r(!1)}}},[e,i,t]),a=R.useCallback(async()=>{if(!(!e||i)){r(!0);try{await t(!1),n(!1)}catch(c){console.error("Failed to disable camera:",c)}finally{r(!1)}}},[e,i,t]);return{isEnabled:e,isLoading:i,toggle:s,enable:o,disable:a}}function lw(){const{startScreenShare:t,stopScreenShare:e}=jn(),[n,i]=R.useState(!1),[r,s]=R.useState(!1),o=R.useCallback(async()=>{if(!(n||r)){s(!0);try{await t(),i(!0)}catch(l){console.error("Failed to start screen share:",l)}finally{s(!1)}}},[n,r,t]),a=R.useCallback(async()=>{if(!(!n||r)){s(!0);try{await e(),i(!1)}catch(l){console.error("Failed to stop screen share:",l)}finally{s(!1)}}},[n,r,e]),c=R.useCallback(async()=>{n?await a():await o()},[n,o,a]);return{isSharing:n,isLoading:r,start:o,stop:a,toggle:c}}function tL(){const{client:t}=jn(),[e,n]=R.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),i=R.useMemo(()=>e.tracks.find(h=>h.isLocal),[e.tracks]),r=R.useMemo(()=>e.tracks.filter(h=>!h.isLocal),[e.tracks]),s=R.useCallback(async()=>{try{i!=null&&i.isEnabled?await(t==null?void 0:t.disableCamera()):await(t==null?void 0:t.enableCamera())}catch(h){throw console.error("Failed to toggle camera:",h),h}},[t,i]),o=R.useCallback(async()=>{try{e.tracks.find(y=>y.isScreenShare)?await(t==null?void 0:t.stopScreenShare()):await(t==null?void 0:t.startScreenShare())}catch(h){throw console.error("Failed to toggle screen share:",h),h}},[t,e.tracks]),a=R.useCallback(h=>{n(y=>({...y,layout:h}))},[]),c=R.useCallback(h=>{n(y=>({...y,pinnedTrack:h}))},[]),l=R.useCallback(()=>{n(h=>({...h,pinnedTrack:void 0}))},[]),d=R.useCallback(async()=>{try{await(t==null?void 0:t.startRecording()),n(h=>({...h,isRecording:!0}))}catch(h){throw console.error("Failed to start recording:",h),h}},[t]),u=R.useCallback(async()=>{try{await(t==null?void 0:t.stopRecording()),n(h=>({...h,isRecording:!1}))}catch(h){throw console.error("Failed to stop recording:",h),h}},[t]),f=R.useCallback(h=>e.tracks.find(y=>y.id===h),[e.tracks]),p=R.useCallback(h=>e.tracks.filter(y=>y.participantId===h),[e.tracks]),g=R.useCallback(h=>h.isEnabled&&e.tracks.includes(h),[e.tracks]);return R.useEffect(()=>{if(!t)return;const h=w=>{n(C=>({...C,tracks:[...C.tracks.filter(S=>S.id!==w.id),w]}))},y=w=>{n(C=>{var S;return{...C,tracks:C.tracks.filter(x=>x.id!==w),pinnedTrack:((S=C.pinnedTrack)==null?void 0:S.id)===w?void 0:C.pinnedTrack}})},b=w=>{n(C=>({...C,tracks:C.tracks.map(S=>S.id===w.id?w:S)}))};return t.on("videoTrackAdded",h),t.on("videoTrackRemoved",y),t.on("videoTrackUpdated",b),()=>{t.off("videoTrackAdded",h),t.off("videoTrackRemoved",y),t.off("videoTrackUpdated",b)}},[t]),{tracks:e.tracks,localTrack:i,remoteTraracks:r,pinnedTrack:e.pinnedTrack,layout:e.layout,isRecording:e.isRecording,toggleCamera:s,toggleScreenShare:o,setLayout:a,pinTrack:c,unpinTrack:l,startRecording:d,stopRecording:u,getTrackById:f,getTracksByParticipant:p,isTrackActive:g}}function Tc(){const{chatMessages:t,sendChatMessage:e,currentSession:n}=jn(),[i,r]=R.useState(!1),s=R.useCallback(async l=>{if(!(!l.trim()||i||!n)){r(!0);try{await e(l.trim())}catch(d){throw console.error("Failed to send chat message:",d),d}finally{r(!1)}}},[e,i,n]),{userMessages:o,agentMessages:a,allMessages:c}=R.useMemo(()=>{const l=t.filter(u=>u.sender.type==="participant"),d=t.filter(u=>u.sender.type==="agent");return{userMessages:l,agentMessages:d,allMessages:t}},[t]);return{messages:c,userMessages:o,agentMessages:a,messageCount:c.length,isSending:i,canSend:!!n&&!i,send:s}}function nL(){const{send:t,isSending:e,canSend:n}=Tc(),[i,r]=R.useState(""),s=R.useCallback(async()=>{if(!(!i.trim()||!n))try{await t(i),r("")}catch(a){throw a}},[i,t,n]),o=R.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),s())},[s]);return{value:i,setValue:r,send:s,handleKeyPress:o,isSending:e,canSend:n&&i.trim().length>0}}function oh(){const{isConnected:t,isConnecting:e,connectionError:n,connect:i,disconnect:r}=jn(),s=R.useCallback(async()=>{if(!(t||e))try{await i()}catch(a){throw console.error("Failed to connect:",a),a}},[i,t,e]),o=R.useCallback(async()=>{if(t)try{await r()}catch(a){throw console.error("Failed to disconnect:",a),a}},[r,t]);return{isConnected:t,isConnecting:e,isDisconnected:!t&&!e,error:n,hasError:!!n,connect:s,disconnect:o}}function dw(){const{participants:t}=jn();return{participants:t,count:t.length,localParticipant:t.find(e=>e.isLocal),remoteParticipants:t.filter(e=>!e.isLocal)}}const uw=R.createContext({}),xo=()=>R.useContext(uw);function fw({children:t,...e}){return m.jsx(uw.Provider,{value:e,children:t})}function ya({name:t,children:e,fallback:n,className:i}){return m.jsx("div",{className:`voxket-slot voxket-slot--${t} ${i||""}`,children:e||n})}function hw(t,e={}){return Object.assign(t,e)}function mw({showMicrophoneControl:t=!0,showCameraControl:e=!0,showScreenShareControl:n=!0,showSessionActions:i=!0,customControls:r,className:s=""}){const o=sr(),a=aw(),c=cw(),l=lw(),d=xo(),u=["voxket-session-controls",`voxket-session-controls--${d.variant||"default"}`,`voxket-session-controls--${d.size||"md"}`,o.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",s].filter(Boolean).join(" ");return!o.isActive&&!i?m.jsx("div",{className:u,children:m.jsx("div",{className:"voxket-controls-inactive",children:m.jsx("p",{children:"Controls available during active session"})})}):m.jsxs("div",{className:u,children:[i&&m.jsx("div",{className:"voxket-session-actions",children:o.isActive?m.jsx("button",{onClick:o.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):m.jsx(iL,{})}),o.isActive&&m.jsxs("div",{className:"voxket-media-controls",children:[t&&m.jsxs("button",{onClick:a.toggle,disabled:a.isLoading,className:`voxket-button voxket-button--media ${a.isEnabled?"voxket-button--active":""}`,title:a.isEnabled?"Mute microphone":"Unmute microphone",children:[m.jsx("span",{className:"voxket-icon",children:"🎤"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),e&&m.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isEnabled?"voxket-button--active":""}`,title:c.isEnabled?"Stop camera":"Start camera",children:[m.jsx("span",{className:"voxket-icon",children:"📹"}),c.isLoading?"Loading...":c.isEnabled?"Stop Video":"Start Video"]}),n&&m.jsxs("button",{onClick:l.toggle,disabled:l.isLoading,className:`voxket-button voxket-button--media ${l.isSharing?"voxket-button--active":""}`,title:l.isSharing?"Stop screen share":"Start screen share",children:[m.jsx("span",{className:"voxket-icon",children:"🖥️"}),l.isLoading?"Loading...":l.isSharing?"Stop Share":"Share Screen"]})]}),r&&m.jsx("div",{className:"voxket-custom-controls",children:r})]})}function iL(){sr();const[t,e]=R.useState(!1),n=async()=>{e(!0);try{console.log("Start session - agentId needed")}catch(i){console.error("Failed to start session:",i)}finally{e(!1)}};return m.jsx("button",{onClick:n,disabled:t,className:"voxket-button voxket-button--primary",children:t?"Starting...":"Start Session"})}function ah({showConnectionStatus:t=!0,showSessionInfo:e=!0,showAgentInfo:n=!0,className:i=""}){const r=sr(),s=oh(),o=xo(),a=["voxket-session-header",`voxket-session-header--${o.variant||"default"}`,`voxket-session-header--${o.size||"md"}`,i].filter(Boolean).join(" ");return m.jsxs("div",{className:a,children:[t&&m.jsxs("div",{className:"voxket-connection-status",children:[m.jsx("div",{className:`voxket-status-indicator ${s.isConnected?"connected":"disconnected"}`}),m.jsx("span",{className:"voxket-status-text",children:s.isConnecting?"Connecting...":s.isConnected?"Connected":"Disconnected"})]}),e&&r.session&&m.jsxs("div",{className:"voxket-session-info",children:[m.jsxs("div",{className:"voxket-session-id",children:["Session: ",r.session.id.slice(-8)]}),m.jsxs("div",{className:"voxket-session-state",children:["State: ",r.state]})]}),n&&r.session&&m.jsxs("div",{className:"voxket-agent-info",children:[m.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",r.session.agentId]}),m.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",r.session.activeModalities.join(", ")]})]}),s.error&&m.jsxs("div",{className:"voxket-error-message",children:["Error: ",s.error.message]})]})}function ch({showChat:t=!0,showTranscriptions:e=!1,customContent:n,className:i=""}){const r=sr(),s=Tc(),o=xo(),a=["voxket-session-content",`voxket-session-content--${o.variant||"default"}`,`voxket-session-content--${o.size||"md"}`,i].filter(Boolean).join(" ");return r.isActive?m.jsx("div",{className:a,children:n||m.jsxs(m.Fragment,{children:[t&&m.jsxs("div",{className:"voxket-chat-container",children:[m.jsxs("div",{className:"voxket-chat-messages",children:[s.messages.map(c=>m.jsxs("div",{className:`voxket-message voxket-message--${c.sender.type}`,children:[m.jsxs("div",{className:"voxket-message-header",children:[m.jsx("span",{className:"voxket-message-sender",children:c.sender.name}),m.jsx("span",{className:"voxket-message-time",children:c.timestamp.toLocaleTimeString()})]}),m.jsx("div",{className:"voxket-message-content",children:c.content})]},c.id)),s.messages.length===0&&m.jsx("div",{className:"voxket-empty-messages",children:m.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),m.jsx(rL,{})]}),e&&m.jsx("div",{className:"voxket-transcriptions",children:m.jsx("div",{className:"voxket-transcription-placeholder",children:m.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):m.jsx("div",{className:a,children:m.jsx("div",{className:"voxket-inactive-state",children:m.jsxs("div",{className:"voxket-inactive-message",children:[m.jsx("h3",{children:"Start a conversation"}),m.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function rL(){const t=Tc(),[e,n]=R.useState(""),i=async()=>{if(!(!e.trim()||!t.canSend))try{await t.send(e),n("")}catch(s){console.error("Failed to send message:",s)}},r=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),i())};return m.jsxs("div",{className:"voxket-chat-input",children:[m.jsx("input",{type:"text",value:e,onChange:s=>n(s.target.value),onKeyPress:r,placeholder:"Type your message...",disabled:!t.canSend,className:"voxket-input"}),m.jsx("button",{onClick:i,disabled:!t.canSend||!e.trim(),className:"voxket-send-button",children:t.isSending?"Sending...":"Send"})]})}function lh({showMetrics:t=!0,showParticipants:e=!0,showStatus:n=!0,customFooter:i,className:r=""}){const s=sr(),o=ow(),a=dw(),c=xo(),l=["voxket-session-footer",`voxket-session-footer--${c.variant||"default"}`,`voxket-session-footer--${c.size||"md"}`,r].filter(Boolean).join(" ");return s.isActive?m.jsx("div",{className:l,children:i||m.jsxs(m.Fragment,{children:[n&&m.jsxs("div",{className:"voxket-session-status",children:[m.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),m.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),t&&o.metrics&&m.jsxs("div",{className:"voxket-session-metrics",children:[m.jsxs("div",{className:"voxket-metric",children:[m.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),m.jsx("span",{className:"voxket-metric-value",children:sL(o.duration||0)})]}),m.jsxs("div",{className:"voxket-metric",children:[m.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),m.jsx("span",{className:"voxket-metric-value",children:o.metrics.messageCount})]})]}),e&&m.jsxs("div",{className:"voxket-participants-info",children:[m.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&m.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(d=>m.jsx("span",{className:"voxket-participant-name",children:d.name},d.id))})]})]})}):m.jsx("div",{className:l,children:m.jsx("div",{className:"voxket-footer-inactive",children:m.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function sL(t){const e=Math.floor(t/1e3),n=Math.floor(e/60),i=Math.floor(n/60);return i>0?`${i}:${(n%60).toString().padStart(2,"0")}:${(e%60).toString().padStart(2,"0")}`:`${n}:${(e%60).toString().padStart(2,"0")}`}function oL({agentId:t,sessionConfig:e,autoStart:n=!1,onSessionStart:i,onSessionEnd:r,variant:s="default",size:o="md",theme:a,className:c="",children:l}){var p;const d=sr(),u=oh();R.useEffect(()=>{n&&t&&u.isConnected&&!d.isActive&&d.start(t,e).catch(console.error)},[n,t,u.isConnected,d.isActive]),R.useEffect(()=>{var g;(g=d.session)!=null&&g.id&&i&&i(d.session.id)},[(p=d.session)==null?void 0:p.id,i]),R.useEffect(()=>()=>{d.isActive&&r&&d.stop().then(r).catch(console.error)},[]);const f=["voxket-session",`voxket-session--${s}`,`voxket-session--${o}`,d.isActive?"voxket-session--active":"voxket-session--inactive",c].filter(Boolean).join(" ");return m.jsx(fw,{variant:s,size:o,theme:a,className:c,children:m.jsx("div",{className:f,children:l||m.jsxs(m.Fragment,{children:[m.jsx(ya,{name:"header",fallback:m.jsx(ah,{})}),m.jsx(ya,{name:"content",fallback:m.jsx(ch,{})}),m.jsx(ya,{name:"footer",fallback:m.jsx(lh,{})})]})})})}const pw=hw(oL,{Header:ah,Content:ch,Footer:lh,Controls:mw}),Gi={name:"default",colors:{primary:"#3B82F6",secondary:"#6B7280",accent:"#8B5CF6",background:"#FFFFFF",surface:"#F9FAFB",text:{primary:"#111827",secondary:"#6B7280",muted:"#9CA3AF",inverse:"#FFFFFF"},status:{success:"#10B981",warning:"#F59E0B",error:"#EF4444",info:"#3B82F6"},border:"#E5E7EB",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},typography:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700},lineHeight:{tight:1.25,normal:1.5,relaxed:1.75}},spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{none:"0",sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},shadows:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1)"}},vu={...Gi,name:"dark",colors:{primary:"#60A5FA",secondary:"#9CA3AF",accent:"#A78BFA",background:"#111827",surface:"#1F2937",text:{primary:"#F9FAFB",secondary:"#D1D5DB",muted:"#9CA3AF",inverse:"#111827"},status:{success:"#34D399",warning:"#FBBF24",error:"#F87171",info:"#60A5FA"},border:"#374151",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.3)"}},yu={...Gi,name:"enterprise",colors:{primary:"#1E40AF",secondary:"#64748B",accent:"#7C3AED",background:"#FFFFFF",surface:"#F8FAFC",text:{primary:"#0F172A",secondary:"#475569",muted:"#94A3B8",inverse:"#FFFFFF"},status:{success:"#059669",warning:"#D97706",error:"#DC2626",info:"#1E40AF"},border:"#CBD5E1",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},borderRadius:{none:"0",sm:"0.125rem",md:"0.25rem",lg:"0.375rem",full:"9999px"}},gw=R.createContext(null),vw=()=>{const t=R.useContext(gw);if(!t)throw new Error("useTheme must be used within a ThemeProvider");return t};function aL({theme:t="default",themes:e={},children:n,cssVariables:i=!0,className:r=""}){const[s,o]=R.useState(()=>{const f={default:Gi,dark:vu,enterprise:yu,...e};return typeof t=="string"?f[t]||Gi:t}),[a,c]=R.useState(()=>({default:Gi,dark:vu,enterprise:yu,...e})),l=f=>{if(typeof f=="string"){const p=a[f];p&&o(p)}else o(f)},d=f=>{c(p=>({...p,[f.name]:f}))};R.useEffect(()=>{if(i&&typeof document<"u"){const f=document.documentElement;Object.entries(yw(s)).forEach(([p,g])=>{f.style.setProperty(`--voxket-${p}`,g)})}},[s,i]);const u={theme:s,setTheme:l,themes:a,registerTheme:d};return m.jsx(gw.Provider,{value:u,children:m.jsx("div",{className:`voxket-theme voxket-theme--${s.name} ${r}`,children:n})})}function yw(t){const e={},n=(i,r="")=>{for(const[s,o]of Object.entries(i)){const a=r?`${r}-${s}`:s;typeof o=="object"&&o!==null&&!Array.isArray(o)?n(o,a):e[a]=String(o)}};return n(t),e}function cL(t=Gi,e){return{...t,...e,colors:{...t.colors,...e.colors},typography:{...t.typography,...e.typography},spacing:{...t.spacing,...e.spacing},borderRadius:{...t.borderRadius,...e.borderRadius},shadows:{...t.shadows,...e.shadows}}}function lL(t){var n;const{theme:e}=vw();return((n=e.components)==null?void 0:n[t])||{}}const dL=sh("voice-modality","voice",{onActivate:async t=>{const e=t.config;e.enableTranscription&&uL(t),e.enableVoiceActivation&&fL(t,e),console.log("Voice modality activated",e)},onDeactivate:async t=>{console.log("Voice modality deactivated")},onMessage:async(t,e)=>{e.type==="audio"&&hL(t,e)}});function uL(t,e){t.on("participant.speaking.started",n=>{console.log("Transcription: Started for",n.name)}),t.on("participant.speaking.stopped",n=>{console.log("Transcription: Stopped for",n.name)})}function fL(t,e){const n=e.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function hL(t,e){console.log("Playing audio response:",e.content)}const mL=sh("chat-modality","chat",{onActivate:async t=>{const e=t.config;e.enableRichText&&pL(),e.enableFileUpload&&gL(t),e.enableCustomComponents&&vL(),console.log("Chat modality activated",e)},onDeactivate:async t=>{console.log("Chat modality deactivated")},onMessage:async(t,e)=>{const n=t.config;e.type==="ui_component"?yL(t,e):e.type==="text"&&n.enableRichText&&bL(t,e)}});function pL(t){console.log("Rich text support enabled")}function gL(t){console.log("File upload enabled"),t.on("chat.file.uploaded",e=>{console.log("File uploaded:",e.name)})}function vL(t){console.log("Custom components enabled");const e=new Map;e.set("quick-actions",xL),e.set("form",SL),e.set("card",wL),e.set("chart",CL)}function yL(t,e){const{componentType:n,props:i}=e.metadata;console.log("Rendering custom component:",n,i),t.emit("chat.component.render",{type:n,props:i,timestamp:new Date})}function bL(t,e){console.log("Processing rich text message:",e.content)}function xL(t){return{type:"quick-actions",actions:t.actions||[],layout:t.layout||"horizontal"}}function SL(t){return{type:"form",fields:t.fields||[],submitAction:t.submitAction,validation:t.validation}}function wL(t){return{type:"card",title:t.title,content:t.content,actions:t.actions,variant:t.variant||"default"}}function CL(t){return{type:"chart",chartType:t.chartType||"line",data:t.data,options:t.options}}function ba({track:t,participantName:e,showControls:n=!0,showName:i=!0,showMuteIndicator:r=!0,isPinned:s=!1,className:o="",onClick:a,onPin:c,onUnpin:l}){const d=R.useRef(null),[u,f]=R.useState(!1);R.useEffect(()=>{if(!d.current||!t.isEnabled)return;const y=d.current;return y.srcObject=null,()=>{y.srcObject&&(y.srcObject=null)}},[t]);const p=()=>{a==null||a(t)},g=y=>{y.stopPropagation(),s?l==null||l(t):c==null||c(t)},h=["voxket-video-tile",t.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",t.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",s?"voxket-video-tile--pinned":"",t.isEnabled?"":"voxket-video-tile--disabled",u?"voxket-video-tile--hovered":"",o].filter(Boolean).join(" ");return m.jsxs("div",{className:h,onClick:p,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),style:{aspectRatio:t.dimensions?`${t.dimensions.width} / ${t.dimensions.height}`:"16 / 9"},children:[m.jsx("video",{ref:d,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:t.isLocal}),!t.isEnabled&&m.jsxs("div",{className:"voxket-video-placeholder",children:[m.jsx("div",{className:"voxket-video-placeholder-icon",children:t.isScreenShare?"🖥️":"📹"}),m.jsx("p",{className:"voxket-video-placeholder-text",children:t.isScreenShare?"Screen sharing paused":"Camera off"})]}),m.jsxs("div",{className:"voxket-video-overlay",children:[i&&e&&m.jsxs("div",{className:"voxket-video-name",children:[e,t.isLocal&&" (You)"]}),r&&!t.isEnabled&&m.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),n&&(u||s)&&m.jsxs("div",{className:"voxket-video-controls",children:[m.jsx("button",{className:`voxket-video-control-btn ${s?"voxket-video-control-btn--active":""}`,onClick:g,title:s?"Unpin video":"Pin video",children:"📌"}),t.isScreenShare&&m.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),t.source&&m.jsx("div",{className:"voxket-video-source",children:t.source})]})]}),!t.isEnabled&&m.jsx("div",{className:"voxket-video-loading",children:m.jsx("div",{className:"voxket-spinner"})})]})}function kL({tracks:t,layout:e,className:n="",onLayoutChange:i,onTrackClick:r,maxVisibleTracks:s=9,showPagination:o=!0}){const[a,c]=R.useState(0),[l,d]=R.useState(null),u=R.useMemo(()=>{let w=[...t];e.type==="speaker"&&l&&(w=[l,...t.filter(x=>x.id!==l.id)]);const C=a*s,S=C+s;return w.slice(C,S)},[t,e,l,a,s]),f=Math.ceil(t.length/s),p=R.useMemo(()=>{const w=u.length;switch(e.type){case"grid":const C=Math.ceil(Math.sqrt(w)),S=Math.ceil(w/C);return{display:"grid",gridTemplateColumns:`repeat(${C}, 1fr)`,gridTemplateRows:`repeat(${S}, 1fr)`,gap:"8px"};case"speaker":return{display:"flex",flexDirection:"column",gap:"8px"};case"sidebar":return{display:"flex",gap:"8px"};case"gallery":return{display:"flex",flexWrap:"wrap",gap:"8px",justifyContent:"center"};default:return{}}},[e.type,u.length]),g=w=>{d(w)},h=()=>{d(null)},y=w=>{i==null||i({...e,type:w})},b=["voxket-video-grid",`voxket-video-grid--${e.type}`,`voxket-video-grid--${u.length}-tracks`,n].filter(Boolean).join(" ");return t.length===0?m.jsx("div",{className:"voxket-video-grid-empty",children:m.jsxs("div",{className:"voxket-video-grid-empty-content",children:[m.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),m.jsx("p",{children:"No video tracks available"})]})}):m.jsxs("div",{className:b,children:[m.jsxs("div",{className:"voxket-video-grid-controls",children:[m.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(w=>m.jsx("button",{className:`voxket-layout-btn ${e.type===w?"voxket-layout-btn--active":""}`,onClick:()=>y(w),title:`Switch to ${w} layout`,children:TL(w)},w))}),m.jsxs("div",{className:"voxket-video-count",children:[t.length," participant",t.length!==1?"s":""]})]}),m.jsx("div",{className:"voxket-video-grid-content",style:p,children:e.type==="speaker"&&l?m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"voxket-video-speaker-main",children:m.jsx(ba,{track:l,participantName:`Participant ${l.participantId}`,isPinned:!0,onClick:r,onUnpin:h})}),m.jsx("div",{className:"voxket-video-speaker-sidebar",children:u.filter(w=>w.id!==l.id).map(w=>m.jsx(ba,{track:w,participantName:`Participant ${w.participantId}`,showControls:!1,onClick:r,onPin:g},w.id))})]}):u.map(w=>m.jsx(ba,{track:w,participantName:`Participant ${w.participantId}`,isPinned:(l==null?void 0:l.id)===w.id,onClick:r,onPin:g,onUnpin:h},w.id))}),o&&f>1&&m.jsxs("div",{className:"voxket-video-pagination",children:[m.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.max(0,a-1)),disabled:a===0,children:"←"}),m.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",f]}),m.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.min(f-1,a+1)),disabled:a===f-1,children:"→"})]})]})}function TL(t){switch(t){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function EL({localTrack:t,onToggleCamera:e,onToggleScreenShare:n,onLayoutChange:i,showLayoutControls:r=!0,showCameraControls:s=!0,showScreenShareControls:o=!0,className:a=""}){const c=["voxket-video-controls",a].filter(Boolean).join(" "),l=d=>{i==null||i({type:d,showLocalVideo:!0,aspectRatio:"16:9"})};return m.jsxs("div",{className:c,children:[s&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),m.jsxs("button",{className:`voxket-control-btn ${t!=null&&t.isEnabled?"voxket-control-btn--active":""}`,onClick:e,title:t!=null&&t.isEnabled?"Turn off camera":"Turn on camera",children:[m.jsx("span",{className:"voxket-control-icon",children:t!=null&&t.isEnabled?"📹":"📷"}),m.jsx("span",{className:"voxket-control-label",children:t!=null&&t.isEnabled?"Camera On":"Camera Off"})]}),(t==null?void 0:t.dimensions)&&m.jsxs("div",{className:"voxket-video-info",children:[t.dimensions.width," × ",t.dimensions.height]})]}),o&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),m.jsxs("button",{className:`voxket-control-btn ${t!=null&&t.isScreenShare?"voxket-control-btn--active":""}`,onClick:n,title:t!=null&&t.isScreenShare?"Stop screen sharing":"Start screen sharing",children:[m.jsx("span",{className:"voxket-control-icon",children:t!=null&&t.isScreenShare?"🛑":"🖥️"}),m.jsx("span",{className:"voxket-control-label",children:t!=null&&t.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),r&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),m.jsx("div",{className:"voxket-layout-buttons",children:[{type:"grid",icon:"⊞",label:"Grid"},{type:"speaker",icon:"🎤",label:"Speaker"},{type:"sidebar",icon:"⫸",label:"Sidebar"},{type:"gallery",icon:"⊡",label:"Gallery"}].map(({type:d,icon:u,label:f})=>m.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>l(d),title:`Switch to ${f} layout`,children:[m.jsx("span",{className:"voxket-control-icon",children:u}),m.jsx("span",{className:"voxket-control-label",children:f})]},d))})]}),m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),m.jsxs("div",{className:"voxket-video-settings",children:[m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Quality"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"high",children:"High (720p)"}),m.jsx("option",{value:"medium",children:"Medium (480p)"}),m.jsx("option",{value:"low",children:"Low (240p)"})]})]}),m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"30",children:"30 fps"}),m.jsx("option",{value:"15",children:"15 fps"}),m.jsx("option",{value:"10",children:"10 fps"})]})]}),m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"unlimited",children:"Unlimited"}),m.jsx("option",{value:"1000",children:"1 Mbps"}),m.jsx("option",{value:"500",children:"500 Kbps"}),m.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),m.jsxs("div",{className:"voxket-video-stats",children:[m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),m.jsx("span",{className:"voxket-stat-value",children:t!=null&&t.dimensions?`${t.dimensions.width}×${t.dimensions.height}`:"N/A"})]}),m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Source:"}),m.jsx("span",{className:"voxket-stat-value",children:(t==null?void 0:t.source)||"None"})]}),m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Status:"}),m.jsx("span",{className:`voxket-stat-value ${t!=null&&t.isEnabled?"voxket-stat-value--active":"voxket-stat-value--inactive"}`,children:t!=null&&t.isEnabled?"Active":"Inactive"})]})]})]})]})}const bw=({handler:t,loadData:e,data:n,client:i,addLocalMessage:r})=>{const[s,o]=v.useState(null),[a,c]=v.useState(!0),[l,d]=v.useState(!1),[u]=v.useState(Date.now());v.useEffect(()=>{(async()=>{try{if(c(!0),console.log("📋 AssignmentView: Loading assignment data..."),console.log("📋 AssignmentView: Received data from RPC:",n),n&&typeof n=="object"){const y={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};o(y),console.log("📋 AssignmentView: Assignment loaded from RPC data:",y)}}catch(y){console.error("📋 AssignmentView: Error loading assignment:",y),o({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{c(!1)}})()},[n,e]);const f=({message:h,assignment:y})=>{const b=h.toLowerCase().includes("declined"),w=b?"bg-red-50 border-red-200":"bg-green-50 border-green-200",C=b?"text-red-700":"text-green-700",S=b?"❌":"🎉";return m.jsxs("div",{className:`max-w-sm mx-auto ${w} border rounded-lg shadow p-3 flex flex-col items-center`,children:[m.jsx("div",{className:"text-2xl mb-2",children:S}),m.jsx("div",{className:`${C} font-semibold text-sm mb-1`,children:h}),m.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:y.title}),m.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},p=async()=>{if(!(!s||!t)){d(!0);try{const h={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",h),t.didSuccess(h,m.jsx(f,{message:"Assignment accepted!",assignment:s}))}catch(h){console.error("📋 AssignmentView: Error accepting assignment:",h),t.didFail({error:"Failed to accept assignment"})}finally{d(!1)}}},g=async()=>{if(!(!s||!t)){d(!0);try{const h={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",h),t.didSuccess(h,m.jsx(f,{message:"Assignment declined",assignment:s}))}catch(h){console.error("📋 AssignmentView: Error declining assignment:",h),t.didFail({error:"Failed to decline assignment"})}finally{d(!1)}}};return a?m.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:m.jsxs("div",{className:"flex items-center justify-center py-4",children:[m.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),m.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):s?m.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[m.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:m.jsx("div",{className:"flex items-center justify-between",children:m.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:s.title})})}),m.jsxs("div",{className:"p-3",children:[m.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:m.jsx("p",{className:"text-xs text-gray-700 leading-snug",children:s.description})}),m.jsx("div",{className:"mb-3",children:m.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[m.jsx("span",{className:"text-xs mr-1",children:"📅"}),m.jsxs("span",{children:["Est: ",s.estimated_time_of_completion]})]})}),m.jsxs("div",{className:"flex gap-2",children:[m.jsx("button",{onClick:p,disabled:l,className:"flex-1 bg-green-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:l?m.jsxs("span",{className:"flex items-center justify-center",children:[m.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),m.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),m.jsx("button",{onClick:g,disabled:l,className:"flex-1 bg-red-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Decline"})]})]})]}):m.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:m.jsxs("div",{className:"text-center py-4",children:[m.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),m.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function PL(){const[t,e]=v.useState(null),[n,i]=v.useState([]);v.useEffect(()=>{const a=new bo({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return e(a),a.on("rpc.method.called",c=>{console.log("RPC Method Called:",c)}),a.on("rpc.interaction.completed",c=>{console.log("RPC Interaction Completed:",c)}),()=>{a.disconnect()}},[]);const r=async()=>{if(t)try{await t.registerFrontendRPC("give_assignment",bw,"embedded");const a=t.getRegisteredRpcMethods();i(a),console.log("✅ Assignment RPC registered successfully")}catch(a){console.error("❌ Failed to register assignment RPC:",a)}},s=async()=>{if(!t)return;const a=({handler:c,timeout:l})=>{const[d,u]=v.useState(""),f=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],p=h=>{u(h)},g=()=>{const h=f.find(y=>y.id===d);c==null||c.didSuccess({selectedProduct:d,productName:h==null?void 0:h.name,price:h==null?void 0:h.price,timestamp:new Date().toISOString()})};return m.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[m.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),m.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),m.jsx("div",{className:"space-y-3 mb-6",children:f.map(h=>m.jsx("div",{onClick:()=>p(h.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${d===h.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:m.jsxs("div",{className:"flex justify-between items-center",children:[m.jsxs("div",{children:[m.jsx("h4",{className:"font-medium",children:h.name}),m.jsx("p",{className:"text-gray-600 text-sm",children:h.price})]}),m.jsx("div",{className:`w-4 h-4 rounded-full ${d===h.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},h.id))}),m.jsxs("div",{className:"flex justify-end space-x-3",children:[m.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),m.jsx("button",{onClick:g,disabled:!d,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),l&&m.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",l," seconds"]})]})};try{await t.registerFrontendRPC("recommend_product",a,"modal");const c=t.getRegisteredRpcMethods();i(c),console.log("✅ Product Recommendation RPC registered successfully")}catch(c){console.error("❌ Failed to register product recommendation RPC:",c)}},o=async()=>{if(!t)return;const a=({handler:c})=>{const[l,d]=v.useState(0),[u,f]=v.useState(""),p=()=>{c==null||c.didSuccess({rating:l,comment:u,timestamp:new Date().toISOString()})};return m.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),m.jsxs("div",{className:"mb-4",children:[m.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),m.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(g=>m.jsx("button",{onClick:()=>d(g),className:`text-2xl ${g<=l?"text-yellow-400":"text-gray-300"}`,children:"⭐"},g))})]}),m.jsxs("div",{className:"mb-4",children:[m.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),m.jsx("textarea",{value:u,onChange:g=>f(g.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),m.jsxs("div",{className:"flex justify-end space-x-2",children:[m.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),m.jsx("button",{onClick:p,disabled:l===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await t.registerFrontendRPC("collect_feedback",a,"embedded");const c=t.getRegisteredRpcMethods();i(c),console.log("✅ Feedback RPC registered successfully")}catch(c){console.error("❌ Failed to register feedback RPC:",c)}};return m.jsxs("div",{className:"p-6",children:[m.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),m.jsxs("div",{className:"space-y-4 mb-6",children:[m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),m.jsxs("div",{className:"space-x-2",children:[m.jsx("button",{onClick:r,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),m.jsx("button",{onClick:s,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),m.jsx("button",{onClick:o,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?m.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>m.jsx("li",{className:"text-gray-700",children:m.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):m.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),m.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),m.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[m.jsxs("li",{children:["Register RPC methods with React components using ",m.jsx("code",{children:"client.registerFrontendRPC()"})]}),m.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),m.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),m.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),m.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),m.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),m.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),m.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
330
319
  const response = await participant.performRpc({
331
320
  method: 'give_assignment',
332
321
  data: JSON.stringify({
@@ -337,4 +326,4 @@ const response = await participant.performRpc({
337
326
  })
338
327
  });
339
328
 
340
- console.log('User response:', response);`})]})]})}const AL={async checkAvailableRpcs(t){const e=t.getRegisteredRpcMethods();return console.log("🔍 Agent: Available RPC methods:",e),e},async triggerAssignment(t,e){const n={title:"Complete Q4 Sales Analysis Report",description:"Please analyze the Q4 sales data and create a comprehensive report with insights, trends, and recommendations for the upcoming quarter. Include visualizations and executive summary.",estimated_time_of_completion:"2-3 hours"};try{console.log("🤖 Agent: Triggering give_assignment RPC with data:",n);const i=await t.localParticipant.performRpc(e,"give_assignment",JSON.stringify(n),{responseTimeout:12e4}),r=JSON.parse(i);return console.log("✅ Agent: Received user response:",r),await this.processAssignmentResponse(r),r}catch(i){throw console.error("❌ Agent: RPC failed:",i),i}},async processAssignmentResponse(t){console.log("🧠 Agent: Processing assignment response...");const e=t.status,n=t.assignmentId,i=t.timeSpent;return e==="accepted"?(console.log("🎉 Agent: User accepted the assignment!"),console.log(`� Assignment ID: ${n}`),console.log(`⏱️ Time to respond: ${i}ms`),console.log("💬 Agent: Sending follow-up:","Great! I've recorded that you've accepted the assignment. You'll receive the detailed requirements and access to the data shortly. Let me know if you need any clarification!")):e==="declined"?(console.log("❌ Agent: User declined the assignment"),console.log("💬 Agent: Sending follow-up:","No problem! Is there anything specific about this assignment that doesn't work for you? I can suggest alternatives or modify the requirements.")):e==="completed"&&(console.log("✅ Agent: User completed the assignment"),console.log("💬 Agent: Sending follow-up:","Excellent work! Could you please share the completed report? I'm excited to review your analysis and insights.")),{status:e,assignmentId:n,timeSpent:i,processed:!0,followupAction:e==="accepted"?"send_requirements":e==="declined"?"offer_alternatives":"request_deliverables"}},getAssignmentExamples(){return{marketing:{title:"Create Social Media Campaign",description:"Design and plan a social media campaign for our new product launch. Include content calendar, post designs, and engagement strategy.",estimated_time_of_completion:"4-5 hours"},technical:{title:"API Integration Documentation",description:"Create comprehensive documentation for our new API endpoints, including examples, error codes, and best practices for developers.",estimated_time_of_completion:"6-8 hours"},research:{title:"Market Research Analysis",description:"Research and analyze competitor pricing strategies in our target market. Provide recommendations for our pricing model.",estimated_time_of_completion:"3-4 hours"},quick:{title:"Customer Feedback Summary",description:"Review this week's customer feedback and create a summary of key themes and actionable insights.",estimated_time_of_completion:"30-45 minutes"}}}},IL=t=>typeof window>"u"?null:R.createElement(sw,t);exports.AssignmentView=bw;exports.CompoundProvider=fw;exports.InteractiveComponent=Qr;exports.PluginManager=nw;exports.RpcExamples=RL;exports.SessionContainer=pw;exports.SessionContent=ch;exports.SessionControls=mw;exports.SessionFooter=lh;exports.SessionHeader=ah;exports.SessionLogViewer=eL;exports.SessionMetricsComponent=tL;exports.Slot=ya;exports.ThemeProvider=cL;exports.VideoControls=PL;exports.VideoGrid=TL;exports.VideoTile=ba;exports.VoxketClient=bo;exports.VoxketEventEmitter=rh;exports.VoxketProvider=rw;exports.VoxketSDK=bo;exports.VoxketSessionComponent=pw;exports.agentRpcExample=AL;exports.analyticsPlugin=zj;exports.chatModalityPlugin=pL;exports.createCustomTheme=lL;exports.createModalityPlugin=sh;exports.createPlugin=Hj;exports.darkTheme=vu;exports.debugPlugin=Wj;exports.default=IL;exports.defaultTheme=Gi;exports.enterpriseTheme=yu;exports.flattenTheme=yw;exports.metricsPlugin=qj;exports.useComponentTheme=dL;exports.useCompoundContext=xo;exports.useSessionLogging=tw;exports.useTheme=vw;exports.useVoxket=jn;exports.useVoxketCamera=cw;exports.useVoxketChat=Tc;exports.useVoxketChatInput=iL;exports.useVoxketConnection=oh;exports.useVoxketMetrics=ow;exports.useVoxketMicrophone=aw;exports.useVoxketParticipants=dw;exports.useVoxketScreenShare=lw;exports.useVoxketSession=sr;exports.useVoxketVideo=nL;exports.voiceModalityPlugin=uL;exports.withCompoundComponent=hw;
329
+ console.log('User response:', response);`})]})]})}const RL={async checkAvailableRpcs(t){const e=t.getRegisteredRpcMethods();return console.log("🔍 Agent: Available RPC methods:",e),e},async triggerAssignment(t,e){const n={title:"Complete Q4 Sales Analysis Report",description:"Please analyze the Q4 sales data and create a comprehensive report with insights, trends, and recommendations for the upcoming quarter. Include visualizations and executive summary.",estimated_time_of_completion:"2-3 hours"};try{console.log("🤖 Agent: Triggering give_assignment RPC with data:",n);const i=await t.localParticipant.performRpc(e,"give_assignment",JSON.stringify(n),{responseTimeout:12e4}),r=JSON.parse(i);return console.log("✅ Agent: Received user response:",r),await this.processAssignmentResponse(r),r}catch(i){throw console.error("❌ Agent: RPC failed:",i),i}},async processAssignmentResponse(t){console.log("🧠 Agent: Processing assignment response...");const e=t.status,n=t.assignmentId,i=t.timeSpent;return e==="accepted"?(console.log("🎉 Agent: User accepted the assignment!"),console.log(`� Assignment ID: ${n}`),console.log(`⏱️ Time to respond: ${i}ms`),console.log("💬 Agent: Sending follow-up:","Great! I've recorded that you've accepted the assignment. You'll receive the detailed requirements and access to the data shortly. Let me know if you need any clarification!")):e==="declined"?(console.log("❌ Agent: User declined the assignment"),console.log("💬 Agent: Sending follow-up:","No problem! Is there anything specific about this assignment that doesn't work for you? I can suggest alternatives or modify the requirements.")):e==="completed"&&(console.log("✅ Agent: User completed the assignment"),console.log("💬 Agent: Sending follow-up:","Excellent work! Could you please share the completed report? I'm excited to review your analysis and insights.")),{status:e,assignmentId:n,timeSpent:i,processed:!0,followupAction:e==="accepted"?"send_requirements":e==="declined"?"offer_alternatives":"request_deliverables"}},getAssignmentExamples(){return{marketing:{title:"Create Social Media Campaign",description:"Design and plan a social media campaign for our new product launch. Include content calendar, post designs, and engagement strategy.",estimated_time_of_completion:"4-5 hours"},technical:{title:"API Integration Documentation",description:"Create comprehensive documentation for our new API endpoints, including examples, error codes, and best practices for developers.",estimated_time_of_completion:"6-8 hours"},research:{title:"Market Research Analysis",description:"Research and analyze competitor pricing strategies in our target market. Provide recommendations for our pricing model.",estimated_time_of_completion:"3-4 hours"},quick:{title:"Customer Feedback Summary",description:"Review this week's customer feedback and create a summary of key themes and actionable insights.",estimated_time_of_completion:"30-45 minutes"}}}},AL=t=>typeof window>"u"?null:R.createElement(sw,t);exports.AssignmentView=bw;exports.CompoundProvider=fw;exports.InteractiveComponent=Qr;exports.PluginManager=nw;exports.RpcExamples=PL;exports.SessionContainer=pw;exports.SessionContent=ch;exports.SessionControls=mw;exports.SessionFooter=lh;exports.SessionHeader=ah;exports.SessionLogViewer=Qj;exports.SessionMetricsComponent=eL;exports.Slot=ya;exports.ThemeProvider=aL;exports.VideoControls=EL;exports.VideoGrid=kL;exports.VideoTile=ba;exports.VoxketClient=bo;exports.VoxketEventEmitter=rh;exports.VoxketProvider=rw;exports.VoxketSDK=bo;exports.VoxketSessionComponent=pw;exports.agentRpcExample=RL;exports.analyticsPlugin=zj;exports.chatModalityPlugin=mL;exports.createCustomTheme=cL;exports.createModalityPlugin=sh;exports.createPlugin=Hj;exports.darkTheme=vu;exports.debugPlugin=Wj;exports.default=AL;exports.defaultTheme=Gi;exports.enterpriseTheme=yu;exports.flattenTheme=yw;exports.metricsPlugin=qj;exports.useComponentTheme=lL;exports.useCompoundContext=xo;exports.useSessionLogging=tw;exports.useTheme=vw;exports.useVoxket=jn;exports.useVoxketCamera=cw;exports.useVoxketChat=Tc;exports.useVoxketChatInput=nL;exports.useVoxketConnection=oh;exports.useVoxketMetrics=ow;exports.useVoxketMicrophone=aw;exports.useVoxketParticipants=dw;exports.useVoxketScreenShare=lw;exports.useVoxketSession=sr;exports.useVoxketVideo=tL;exports.voiceModalityPlugin=dL;exports.withCompoundComponent=hw;