PageSourceSearch

https://shizenlearn.com/assets/ChatInterface-BuVRzb_J.js

js shizenlearn.com collected 2026-10-02 01:47:13 UTC 548,739 bytes, 450 lines download raw bytes

1import{r as w,j as d,f as fl,i as Kd,L as bn,g as Yd,h as Xd}from"./react-vendor-CR6PEHFZ.js";import{P as Wn}from"./PaintedText-C3MsEoHx.js";import{ah as pl,aj as Os,ak as ml,e as Hr,A as Sr,bT as Qd,aq as Zd,bU as Ye,ar as Ca,bV as eh,bO as th,bW as nh,bX as rh,bN as Kr,bP as gl,bQ as _n,bY as vl,bZ as bl,b_ as ih,b$ as yl,c0 as sh,c1 as ah,bS as wl,c2 as oh,c3 as ch,c4 as lh,c5 as uh,c6 as dh,i as Fe,at as Nr,b1 as hh,aC as fh,aN as _l,b5 as vi,C as ph,aU as mh,c7 as gh,aY as vh,aZ as bh,c8 as yh,a_ as kl,c9 as Sl,aW as wh,aX as _h,aV as kh,as as Gt,u as Sh,j as xh,b as Eh,a as Ch,bx as Mh,ca as Ah,W as Th}from"./index-4BgFHtDy.js";import{u as xl}from"./useOnboardingFlags-D5_aYXjw.js";import{c as Ps}from"./chaticon-DZxf-s8N.js";import{u as Nh}from"./useWCTabScrollReset-BPl6Zvom.js";import{I as El}from"./InlineFeedback-CJuZxr0M.js";import{Live2DCharacter as Oh}from"./Live2DCharacter-b1XA5yzB.js";import{u as Ph}from"./useCreditWallet-ChOMb_5V.js";import{R as jh,T as Ih,a as Rh,b as Lh}from"./index-BnQD89Lm.js";import{A as Yr,m as Or}from"./motion-CJOt5odT.js";import{L as Pr}from"./loader-circle-DgPKf1KX.js";import{P as Dh}from"./pause-COwvhF_2.js";import{P as Fh}from"./play-B3bwd9OM.js";import{R as Bh}from"./rotate-ccw-CmJRy1RL.js";import{M as $h,S as Uh}from"./RailArtwork-Cp1Qge4W.js";import{W as Vh,a as zh}from"./WCSidebarSelection-Cb1TWNa8.js";import{W as Wh}from"./WCSignupGate-D4ErDc4r.js";import{F as qh,C as bi}from"./public-credit-policy-CN2LG31-.js";import{M as Jh}from"./ModuleNextUp-DSNvsQCL.js";import{W as Gh}from"./WCEmptyState-B8IO2YhP.js";import{u as Hh}from"./atmosphereSafeZones-B11pJ5DC.js";import{W as Kh,S as Yh,F as Xh,P as Qh,n as Zh,N as Ma,o as ef,L as tf,i as nf,p as rf,V as Aa,q as Ta,k as sf,B as af,r as of}from"./three-BeWplow9.js";import{S as cf}from"./SourceTypewriter-CgJBTIXy.js";import{C as Cl,p as lf,a as uf}from"./ChatHeroDemo-xYJd1DIo.js";import{W as df}from"./WCSection-DDY9O0K4.js";import{b as hf}from"./button-CRdmeocy.js";import{G as ff,a as Na}from"./onboarding-tour-queue-C1gdrxkC.js";import{T as Oa}from"./trash-2-CKdhC_W2.js";import"./charts-B4FZmgI2.js";import"./sentry-vendor-TOuwz_QY.js";import"./triangle-alert-BSz8P4Zw.js";import"./info-Dr44RUm_.js";import"./circle-check-CUzFLvbA.js";import"./pixi-Ij46LKnn.js";import"./index-BdQq_4o_.js";import"./index-COLRoJoj.js";/* empty css                       */import"./index-B_LjxDKQ.js";import"./index-7DpCkYeO.js";import"./useVisualViewportRect-D1a4QLn_.js";const js="/assets/roleplayicon-D9pJfWs1.webp";function pf({messageContent:n,isSpeaking:e}){const[t,r]=w.useState("idle");return w.useEffect(()=>{if(e){r("speaking");return}if(!n){r("idle");return}const i=n.toLowerCase();if(i.includes("!")||i.includes("すごい")||i.includes("great")||i.includes("excellent")||i.includes("wonderful")||i.includes("素晴らしい")||i.includes("完璧")){r("happy");return}if(i.includes("wow")||i.includes("えっ")||i.includes("really")||i.includes("本当")||i.includes("まさか")){r("surprised");return}if(i.includes("?")||i.includes("どう")||i.includes("why")||i.includes("how")||i.includes("何")||i.includes("なぜ")||i.includes("どうして")){r("confused");return}if(i.includes("let me think")||i.includes("考え")||i.includes("思う")||i.includes("maybe")||i.includes("perhaps")){r("thinking");return}r("idle")},[n,e]),t}const mf="/assets/chat_background-CzQZn339.webp",gf=.5,vf=1.5,bf=.05;function yf(n){return(Math.round(n*100)/100).toFixed(2).replace(/\.?0+$/,t=>t.endsWith(".")?".0":t)+"×"}function wf({value:n,onCommit:e,hidden:t}){const[r,i]=w.useState(n);w.useEffect(()=>{i(n)},[n]);const s=w.useCallback(o=>{o.length>0&&i(o[0])},[]),a=w.useCallback(o=>{if(o.length>0){const l=Math.round(o[0]*100)/100;i(l),e(l)}},[e]);return t?null:d.jsxs("div",{className:"ch-conv-speed wc-pencil-frame wc-pencil-frame--xs",style:{display:"inline-flex",alignItems:"center",gap:10,padding:"5px 12px",background:"#fdfbf7",border:0},children:[d.jsx("span",{"aria-hidden":"true",style:{fontFamily:"var(--font-ui)",fontSize:10,letterSpacing:0,textTransform:"none",color:"#55606c"},children:"Speed"}),d.jsxs(jh,{value:[r],onValueChange:s,onValueCommit:a,min:gf,max:vf,step:bf,"aria-label":"TTS speaking rate",style:{position:"relative",display:"flex",alignItems:"center",userSelect:"none",touchAction:"none",width:100,height:18},children:[d.jsx(Ih,{style:{position:"relative",flexGrow:1,background:"rgba(42, 53, 64, 0.14)",borderRadius:999,height:3},children:d.jsx(Rh,{style:{position:"absolute",background:"hsl(var(--module-accent))",borderRadius:999,height:3}})}),d.jsx(Lh,{style:{display:"block",width:14,height:14,background:"hsl(var(--module-accent))",border:"1.5px solid #fdfbf7",borderRadius:"50%",boxShadow:"0 1px 3px rgba(42, 53, 64, 0.25)",cursor:"grab"}})]}),d.jsx("span",{"aria-live":"polite",style:{fontFamily:"var(--font-ui)",fontSize:11,color:"#2a3540",minWidth:38,textAlign:"right"},children:yf(r)})]})}const _f=n=>{if(!Number.isFinite(n)||n<0)return"0:00";const e=Math.floor(n/60),t=Math.floor(n%60);return`${e}:${t.toString().padStart(2,"0")}`};function yi({messages:n,liveTranscript:e,isBotSpeaking:t,mouthOpenYRef:r,bigNodSignal:i,agentFace:s,agentMotion:a,expression:o,currentEmotion:l,live2dKey:u,realtimeStatus:f,realtimeError:g,realtimeNotice:_,onDismissNotice:k,noticeActionLabel:b,onStartVoice:v,onStopVoice:E,startPending:C=!1,sessionElapsedSeconds:O,onStartFreshConversation:j,isPro:S,greetingMessage:x,ttsSpeed:T,onTtsSpeedChange:I,backgroundSrc:F,foregroundSrc:$,avatarPlacement:z,sceneSelector:fe}){const me=z?.scale??1,je=z?.top??.12,_e=z?.offsetX??0,Te=z?.anchorY??1,{wallet:Ie,loading:Re,refresh:ke}=Ph(),ie=f==="live",Se=f==="connecting",Ne=f==="closing",Be=n.length>0||e.length>0,c=Se||Ne||C,p=w.useRef(f);w.useEffect(()=>{const U=p.current;p.current=f,U==="live"&&(f==="idle"||f==="error")&&ke()},[f,ke]);const h=[...e].reverse().find(U=>U.role==="assistant"),m=n.filter(U=>U.role==="assistant").slice(-1)[0],y=h?.text||m?.content||(x&&!n.some(U=>U.role==="assistant")?x:"")||"",N=w.useRef(null);
1w.useLayoutEffect(()=>{const U=N.current;U&&(U.scrollTop=U.scrollHeight)},[y,t]);const P=600,R=w.useRef(null),B=w.useRef(null);w.useLayoutEffect(()=>{const U=B.current,ye=R.current;if(!U||!ye)return;const ge=U.parentElement;if(!ge)return;const $e=()=>{const pe=ge.clientWidth,Ee=ge.clientHeight;if(!pe||!Ee)return;const Z=parseFloat(getComputedStyle(U).getPropertyValue("--content-aspect"))||1.4;let te,se;pe/Ee>Z?(se=Ee,te=Ee*Z):(te=pe,se=pe/Z),U.style.width=`${te}px`,U.style.height=`${se}px`,ye.style.setProperty("--scene-cover",String(Math.max(te,se)/P))};$e();const xe=new ResizeObserver($e);return xe.observe(ge),()=>xe.disconnect()},[]);const V=!!y||ie||Se;return d.jsx("div",{className:"ch-conv",children:d.jsxs("div",{className:"ch-conv-frame",children:[d.jsxs("div",{"data-tour-id":"chat-voice-settings",className:"ch-conv-head",children:[d.jsx("div",{className:"ch-conv-head-left",children:d.jsxs("div",{className:"ch-conv-head-tutor",children:[fe??d.jsx("span",{className:"title",children:"Conversation"}),d.jsx("span",{className:"ch-conv-credits",children:Re?"…":Ie===null?"—":`${Ie.available.toLocaleString()} credits`})]})}),typeof T=="number"&&I&&d.jsx("div",{className:"ch-conv-head-right",children:d.jsx(wf,{value:T,onCommit:I})})]}),d.jsx(Yr,{children:_&&d.jsx(El,{message:_,variant:"info",action:k?{label:b??"Dismiss",onClick:k}:void 0,className:"ch-conv-notice"})}),d.jsxs("div",{className:"ch-conv-stage",children:[d.jsx("div",{className:"ch-conv-viewport",ref:B,children:d.jsxs("div",{className:"ch-conv-scene",ref:R,style:{"--scene-anchor-y":String(Te)},children:[d.jsx("img",{src:F??mf,alt:"","aria-hidden":"true",className:"ch-conv-avatar-bg"}),d.jsx("div",{"data-tour-id":"chat-avatar",className:"ch-conv-avatar-scaled",style:{"--l2d-scale":String(me),"--l2d-top":String(je),"--l2d-x":String(_e)},children:d.jsx(Oh,{mouthOpenYRef:r,bigNodSignal:i,isBotSpeaking:t,expression:o,emotion:l,face:s,motion:a,width:400,height:600,className:"w-full h-full"},u)}),$&&d.jsx("img",{src:$,alt:"","aria-hidden":"true",className:"ch-conv-avatar-fg"})]})}),V&&d.jsx("div",{className:"ch-conv-reply-wrap",children:d.jsxs("div",{className:"ch-conv-reply",children:[d.jsx("span",{className:"ch-conv-reply-tag jp",children:"コンパニオン"}),d.jsx("div",{ref:N,className:"ch-conv-reply-body","aria-live":"polite",children:Se&&!y?d.jsxs("div",{className:"ch-conv-reply-loading",children:[d.jsx(Pr,{size:14,className:"animate-spin","aria-hidden":"true"}),d.jsx("span",{children:"Connecting…"})]}):ie&&!y?d.jsxs("div",{className:"ch-conv-reply-loading",children:[d.jsx("span",{className:"ch-conv-reply-listen-dot","aria-hidden":"true"}),d.jsx("span",{children:"Listening… say something to start."})]}):d.jsxs("p",{className:"ch-conv-reply-stream",children:[y,t&&d.jsx("span",{className:"ch-conv-reply-caret","aria-hidden":"true"})]})})]})})]}),d.jsx("div",{"data-tour-id":"chat-input-bar",className:"ch-conv-input-wrap",children:d.jsxs("div",{className:"ch-conv-input ch-conv-input--realtime",children:[d.jsxs("div",{className:"ch-conv-status-row",children:[d.jsx(kf,{status:f,isBotSpeaking:t}),ie&&d.jsx("span",{className:"ch-conv-elapsed",style:{fontFamily:"var(--font-ui)",fontSize:12,letterSpacing:0,color:"var(--ink-soft)",tabularNums:"tabular-nums"},children:_f(O)}),g&&d.jsx("span",{style:{fontSize:12,color:"var(--ink-soft)"},role:"alert",children:g})]}),d.jsxs("div",{className:"ch-conv-cta-row",children:[d.jsxs("button",{type:"button",onClick:ie?E:v,disabled:c,className:"wc-cta-square wc-cta-square--ink","aria-label":ie?"Pause voice chat":Be?"Resume conversation":"Start voice chat",children:[c?d.jsx(Pr,{size:14,className:"animate-spin","aria-hidden":"true"}):ie?d.jsx(Dh,{size:14,"aria-hidden":"true"}):d.jsx(Fh,{size:14,"aria-hidden":"true"}),d.jsx("span",{children:Se||C?"Connecting…":Ne?"Pausing…":ie?"Pause":Be?"Resume conversation":"Start talking"})]}),j&&!ie&&!Se&&!Ne&&d.jsxs("button",{type:"button",onClick:j,className:"wc-cta-square wc-cta-square-quiet--ink",title:"Delete this conversation and start over",children:[d.jsx(Bh,{size:14,"aria-hidden":"true"}),d.jsx("span",{children:"New conversation"})]})]})]})})]})})}function kf({status:n,isBotSpeaking:e}){return n==="live"?d.jsxs("span",{className:"ch-conv-status ch-conv-status--rec",children:[d.jsxs("span",{className:"dot",children:[d.jsx("span",{className:"ping"}),d.jsx("span",{className:"core"})]}),e?"Speaking":"Listening"]}):n==="connecting"?d.jsxs("span",{className:"ch-conv-status",children:[d.jsx(Pr,{size:12,className:"animate-spin","aria-hidden":"true"}),"Connecting"]}):n==="closing"?d.jsxs("span",{className:"ch-conv-status",children:[d.jsx(Pr,{size:12,className:"animate-spin","aria-hidden":"true"}),"Ending"]}):n==="error"?d.jsx("span",{className:"ch-conv-status",children:"Error"}):null}const Sf=[{id:"overview",label:"Overview",iconSrc:pl},{id:"lesson-review",label:"Lesson Review",iconSrc:Os},{id:"roleplay",label:"Roleplay",iconSrc:js},{id:"free-chat",label:"Open conversation",iconSrc:Ps},{id:"settings",label:"Settings",iconSrc:ml}];function xf({activeSection:n,onSectionChange:e,settingsDisabled:t=!1,publicOverview:r=!1}){const i=Sf.map(s=>({...s,disabled:s.id==="settings"&&t}));return d.jsxs("nav",{className:`ch-sidebar${r?" ml-sidebar":""}`,"aria-label":"Chat sections",children:[d.jsx("div",{className:"ch-sidebar-items",children:d.jsx(Vh,{id:"chat-sidebar-selection",children:i.map(s=>{const a=n===s.id;return d.jsxs("button",{type:"button",className:`ch-sidebar-item wc-sidebar-selection-host${r?" ml-nav-item":""}${a?" is-active":""}`,"data-tour-id":`chat-sidebar-${s.id}`,"aria-current":a?"page":void 0,disabled:s.disabled,onClick:()=>!s.disabled&&e(s.id),children:[a&&d.jsx(zh,{layoutId:"active-tab"}),d.jsx("span",{className:"ch-sidebar-item-iconwrap",children:d.jsx("img",{src:s.iconSrc,alt:"","aria-hidden":"true",className:"ch-sidebar-item-iconimg","data-icon":s.id})}),d.jsx("span",{className:"ch-sidebar-item-text",children:d.jsx("span",{className:"en",children:s.label})})]},s.id)})})}),d.jsx($h,{module:"conversation"})]})}const Ef=["inworld"],Ml="chat.realtimeProvider",Al="chat.ttsSpeed",Tl="inworld",Nl=1,Pa=.5,ja=1.5;function Ol(n){return typeof n=="string"&&Ef.includes(n)}function Pl(n){return Ol(n)?n:Tl}function Qi(n){const e=typeof n=="number"?n:Number(n);return Number.isFinite(e)?e<Pa?Pa:e>ja?ja:Math.round(e*100)/100:Nl}function Cf(){try{const n=localStorage.getItem(Ml);if(n!==null)return Pl(n)}catch{}return Tl}function wi(n){try{localStorage.setItem(Ml,n)}catch{}}function Mf(){try{const n=localStorage.getItem(Al);if(n!==null)return Qi(Number(n))}catch{}return Nl}function _i(n){try{localStorage.setItem(Al,String(n))}catch{}}function jl(){const{session:n}=Hr(),e=n?.access_token??null,[t,r]=w.useState(()=>Cf()),[i,s]=w.useState(()=>Mf()),[a,o]=w.useState(!0);w.useEffect(()=>{if(!e){o(!1);return}let f=!1;return(async()=>{try{const g=await fetch(`${Sr}/api/chat/preferences`,{headers:{Authorization:`Bearer ${e}`}});if(!g.ok)return;const _=await g.json().catch(()=>({}));if(f)return;if(_?.realtime_provider!==void 0&&_?.realtime_provider!==null){const k=Pl(_.realtime_provider);r(k),wi(k)}if(_?.tts_speed!==void 0&&_?.tts_speed!==null){const k=Qi(_.tts_speed);s(k),_i(k)}}catch{}finally{f||o(!1)}})(),()=>{f=!0}},[e]);const l=w.useCallback(async f=>{if(!Ol(f))return;const g=t;if(g!==f&&(r(f),wi(f),!!e))try{const _=await fetch(`${Sr}/api/chat/preferences`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({realtime_provider:f})});if(!_.ok)throw new Error(`preferences POST ${_.status}`)}catch{r(g),wi(g)}},[e,t]),u=w.useCallback(async f=>{const g=Qi(f),_=i;if(g!==_&&(s(g),_i(g),!!e))try{const k=await fetch(`${Sr}/api/chat/preferences`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({tts_speed:g})});if(!k.ok)throw new Error(`preferences POST ${k.status}`)}catch{s(_),_i(_)}},[e,i]);return{realtimeProvider:t,ttsSpeed:i,isLoading:a,setRealtimeProvider:l,setTtsSpeed:u}}function Af({provider:n,isLoading:e}){const t=n==="inworld",r=e?"Loading voice engine…":t?"Inworld Realtime":"Voice engine unavailable",i={dis
1play:"inline-flex",alignItems:"center",gap:8,padding:"5px 10px 5px 9px",background:"#fdfbf7",border:"6px solid transparent",borderImageSource:`url(${Qd})`,borderImageSlice:"80 120 fill",borderImageWidth:"6px 8px",borderImageRepeat:"stretch",borderRadius:0,fontFamily:"var(--font-ui)",fontSize:12.5,color:"#2a3540"};return d.jsxs("div",{style:{fontFamily:"var(--font-ui)"},children:[d.jsxs("span",{role:"status","aria-live":"polite",style:i,children:[d.jsx("span",{"aria-hidden":"true",style:{width:7,height:7,borderRadius:"50%",background:"hsl(var(--brand-reading))",flexShrink:0}}),d.jsx("span",{children:r})]}),!e&&t&&d.jsxs("details",{style:{marginTop:8,fontSize:12,color:"var(--ink-soft)"},children:[d.jsx("summary",{style:{cursor:"pointer",width:"fit-content"},children:"Technical details"}),d.jsx("p",{style:{margin:"6px 0 0",lineHeight:1.5},children:"Inworld Realtime API uses Gemini 2.5 Flash and Inworld TTS for English and Japanese conversation."})]})]})}function Tf({isPro:n}){const{realtimeProvider:e,isLoading:t}=jl();return d.jsx("div",{className:"ch-settings",children:d.jsxs("div",{className:"ch-settings-grid",children:[d.jsxs("div",{className:"ch-settings-panel is-full",children:[d.jsx("header",{className:"ch-settings-head",children:d.jsx("h3",{children:"Conversation practice"})}),d.jsx("p",{className:"ch-settings-sub",children:"Speak and listen naturally — the latest real-time voice and conversation models hear you, think, and speak back in one continuous stream. No turn buttons, no waiting for transcripts."}),d.jsxs("div",{className:"wc-pencil-frame wc-pencil-frame--xs",style:{marginTop:12,padding:14,background:"var(--paper)",fontSize:13,lineHeight:1.6,color:"var(--ink)"},children:[d.jsxs("p",{style:{margin:0},children:[d.jsx("strong",{children:"How it works."})," Open a conversation and start speaking — the tutor detects when you’ve finished and replies out loud. Interrupt at any time; the tutor will yield."]}),d.jsx("p",{style:{margin:"10px 0 0 0",color:"var(--ink-soft)"},children:"Voice character, sensitivity, and the tutor’s style are tuned centrally. Per-user voice / personality controls aren’t exposed yet — let us know what you’d like to customize."})]})]}),d.jsxs("div",{className:"ch-settings-panel is-full",children:[d.jsx("header",{className:"ch-settings-head",children:d.jsx("h3",{children:"Voice engine"})}),d.jsx("p",{className:"ch-settings-sub",children:"Your tutor sessions run on the Inworld Realtime engine — fluent in both English and Japanese."}),d.jsx("div",{style:{marginTop:12,display:"flex",alignItems:"center",gap:12},children:d.jsx(Af,{provider:e,isLoading:t})})]}),d.jsxs("div",{className:"ch-settings-panel is-full",children:[d.jsx("header",{className:"ch-settings-head",children:d.jsx("h3",{children:"Shared credits"})}),d.jsx("p",{className:"ch-settings-sub",children:"Voice chat uses the same flexible AI & processing credits as AI reading help, OCR, annotations, subtitles, and media mnemonics. Only active conversation uses credits; idle time costs nothing."}),d.jsxs("details",{style:{marginTop:10,color:"var(--ink-soft)",fontFamily:"var(--font-ui)",fontSize:13},children:[d.jsx("summary",{style:{cursor:"pointer",width:"fit-content"},children:"How voice credits are used"}),d.jsx("p",{style:{margin:"8px 0 0",lineHeight:1.6},children:"A session temporarily authorizes at most 500 credits at a time. It settles only the text, speech-to-text audio, and spoken reply actually used before requesting another authorization. If there are not enough credits for the next authorization, the conversation closes gracefully."})]})]})]})})}function Nf(){const{user:n,getAccessToken:e}=Hr(),[t,r]=w.useState(null),{streak:i,last7Days:s}=Zd(),a=20;w.useEffect(()=>{if(!n){r(null);return}let f=!1;return(async()=>{try{const g=await e();if(!g||f)return;Ye.setAccessToken(g);const _=await Ye.getChatStats();f||r(_)}catch(g){console.warn("Failed to load chat stats:",g)}})(),()=>{f=!0}},[n,e]);const o=t?.totalSessions??0,l=t?.messagesToday??0,u=Math.min(1,l/a);return d.jsxs("aside",{className:"ch-stats-rail wc-stats-rail","aria-label":"Chat stats",tabIndex:0,children:[d.jsxs("div",{className:"ch-stats-tile ch-stats-tile--conversations",children:[d.jsx(Uh,{module:"conversation",className:"ch-stats-heading",children:"Conversations"}),d.jsxs("div",{className:"wc-stat-compact",children:[d.jsx("span",{className:"wc-stat-compact-label",children:"Chats"}),d.jsx("span",{className:"wc-stat-compact-value",children:o})]}),d.jsxs("div",{className:"ch-stats-bigrow",children:[d.jsx("span",{className:"ch-stats-bignum",children:o}),d.jsx("span",{className:"ch-stats-biglabel",children:"total"})]})]}),d.jsxs("div",{className:"ch-stats-tile",children:[d.jsx("h3",{className:"ch-stats-heading",children:"Today’s chat"}),d.jsxs("div",{className:"wc-stat-compact",children:[d.jsx("span",{className:"wc-stat-compact-label",children:"Messages"}),d.jsxs("span",{className:"wc-stat-compact-value",children:[l,d.jsxs("span",{className:"u",children:["/",a]})]})]}),d.jsxs("div",{className:"ch-stats-goal",children:[d.jsxs("div",{className:"ch-stats-goal-head",children:[d.jsxs("span",{className:"label",children:["Daily practice goal: ",a," messages"]}),d.jsxs("span",{className:"ratio",children:[l," / ",a]})]}),d.jsx("div",{className:"ch-stats-goal-bar",children:d.jsx("div",{className:"fill",style:{width:`${u*100}%`}})})]})]}),d.jsxs("div",{className:"ch-stats-tile",children:[d.jsx("h3",{className:"ch-stats-heading",children:"Day streak"}),d.jsxs("div",{className:"wc-stat-compact",children:[d.jsx("span",{className:"wc-stat-compact-label",children:"Streak"}),d.jsxs("span",{className:"wc-stat-compact-value",children:[d.jsx("img",{src:Ca,alt:"","aria-hidden":"true",className:"wc-stat-compact-flame"}),i]})]}),d.jsxs("div",{className:"ch-stats-streak-row",children:[d.jsx("img",{src:Ca,alt:"","aria-hidden":"true",className:"ch-stats-streak-flame"}),d.jsxs("span",{className:"ch-stats-streak-days",children:[d.jsx("span",{className:"num",children:i})," ",i===1?"day":"days"]})]}),d.jsx("p",{className:"ch-stats-streak-msg",children:i>0?"Nice! Keep it going.":"Start your streak today."}),d.jsx("div",{className:"ch-stats-streak-week","aria-hidden":"true",children:["M","T","W","T","F","S","S"].map((f,g)=>d.jsxs("div",{className:"day",children:[d.jsx("span",{className:"lbl",children:f}),d.jsx("span",{className:`dot${s[g]?" is-on":""}`})]},g))})]})]})}function Of(n){const e=Pf(n),t=w.forwardRef((r,i)=>{const{children:s,...a}=r,o=w.Children.toArray(s),l=o.find(If);if(l){const u=l.props.children,f=o.map(g=>g===l?w.Children.count(u)>1?w.Children.only(null):w.isValidElement(u)?u.props.children:null:g);return d.jsx(e,{...a,ref:i,children:w.isValidElement(u)?w.cloneElement(u,void 0,f):null})}return d.jsx(e,{...a,ref:i,children:s})});return t.displayName=`${n}.Slot`,t}function Pf(n){const e=w.forwardRef((t,r)=>{const{children:i,...s}=t;if(w.isValidElement(i)){const a=Lf(i),o=Rf(s,i.props);return i.type!==w.Fragment&&(o.ref=r?eh(r,a):a),w.cloneElement(i,o)}return w.Children.count(i)>1?w.Children.only(null):null});return e.displayName=`${n}.SlotClone`,e}var jf=Symbol("radix.slottable");function If(n){return w.isValidElement(n)&&typeof n.type=="function"&&"__radixId"in n.type&&n.type.__radixId===jf}function Rf(n,e){const t={...e};for(const r in e){const i=n[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?t[r]=(...o)=>{const l=s(...o);return i(...o),l}:i&&(t[r]=i):r==="style"?t[r]={...i,...s}
vendor: 4,891 bytes, line 1
1:r==="className"&&(t[r]=[i,s].filter(Boolean).join(" "))}return{...n,...t}}function Lf(n){let e=Object.getOwnPropertyDescriptor(n.props,"ref")?.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?n.ref:(e=Object.getOwnPropertyDescriptor(n,"ref")?.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?n.props.ref:n.props.ref||n.ref)}var Xr="Popover",[Il]=wl(Xr,[yl]),Yn=yl(),[Df,Ht]=Il(Xr),Rl=n=>{const{__scopePopover:e,children:t,open:r,defaultOpen:i,onOpenChange:s,modal:a=!1}=n,o=Yn(e),l=w.useRef(null),[u,f]=w.useState(!1),[g,_]=th({prop:r,defaultProp:i??!1,onChange:s,caller:Xr});return d.jsx(nh,{...o,children:d.jsx(Df,{scope:e,contentId:rh(),triggerRef:l,open:g,onOpenChange:_,onOpenToggle:w.useCallback(()=>_(k=>!k),[_]),hasCustomAnchor:u,onCustomAnchorAdd:w.useCallback(()=>f(!0),[]),onCustomAnchorRemove:w.useCallback(()=>f(!1),[]),modal:a,children:t})})};Rl.displayName=Xr;var Ll="PopoverAnchor",Ff=w.forwardRef((n,e)=>{const{__scopePopover:t,...r}=n,i=Ht(Ll,t),s=Yn(t),{onCustomAnchorAdd:a,onCustomAnchorRemove:o}=i;return w.useEffect(()=>(a(),()=>o()),[a,o]),d.jsx(vl,{...s,...r,ref:e})});Ff.displayName=Ll;var Dl="PopoverTrigger",Fl=w.forwardRef((n,e)=>{const{__scopePopover:t,...r}=n,i=Ht(Dl,t),s=Yn(t),a=Kr(e,i.triggerRef),o=d.jsx(gl.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":zl(i.open),...r,ref:a,onClick:_n(n.onClick,i.onOpenToggle)});return i.hasCustomAnchor?o:d.jsx(vl,{asChild:!0,...s,children:o})});Fl.displayName=Dl;var Is="PopoverPortal",[Bf,$f]=Il(Is,{forceMount:void 0}),Bl=n=>{const{__scopePopover:e,forceMount:t,children:r,container:i}=n,s=Ht(Is,e);return d.jsx(Bf,{scope:e,forceMount:t,children:d.jsx(bl,{present:t||s.open,children:d.jsx(ih,{asChild:!0,container:i,children:r})})})};Bl.displayName=Is;var En="PopoverContent",$l=w.forwardRef((n,e)=>{const t=$f(En,n.__scopePopover),{forceMount:r=t.forceMount,...i}=n,s=Ht(En,n.__scopePopover);return d.jsx(bl,{present:r||s.open,children:s.modal?d.jsx(Vf,{...i,ref:e}):d.jsx(zf,{...i,ref:e})})});$l.displayName=En;var Uf=Of("PopoverContent.RemoveScroll"),Vf=w.forwardRef((n,e)=>{const t=Ht(En,n.__scopePopover),r=w.useRef(null),i=Kr(e,r),s=w.useRef(!1);return w.useEffect(()=>{const a=r.current;if(a)return sh(a)},[]),d.jsx(ah,{as:Uf,allowPinchZoom:!0,children:d.jsx(Ul,{...n,ref:i,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:_n(n.onCloseAutoFocus,a=>{a.preventDefault(),s.current||t.triggerRef.current?.focus()}),onPointerDownOutside:_n(n.onPointerDownOutside,a=>{const o=a.detail.originalEvent,l=o.button===0&&o.ctrlKey===!0,u=o.button===2||l;s.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:_n(n.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),zf=w.forwardRef((n,e)=>{const t=Ht(En,n.__scopePopover),r=w.useRef(!1),i=w.useRef(!1);return d.jsx(Ul,{...n,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{n.onCloseAutoFocus?.(s),s.defaultPrevented||(r.current||t.triggerRef.current?.focus(),s.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:s=>{n.onInteractOutside?.(s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const a=s.target;t.triggerRef.current?.contains(a)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&i.current&&s.preventDefault()}})}),Ul=w.forwardRef((n,e)=>{const{__scopePopover:t,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:a,onEscapeKeyDown:o,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,...g}=n,_=Ht(En,t),k=Yn(t);return oh(),d.jsx(ch,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:s,children:d.jsx(lh,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:f,onEscapeKeyDown:o,onPointerDownOutside:l,onFocusOutside:u,onDismiss:()=>_.onOpenChange(!1),children:d.jsx(uh,{"data-state":zl(_.open),role:"dialog",id:_.contentId,...k,...g,ref:e,style:{...g.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),Vl="PopoverClose",Wf=w.forwardRef((n,e)=>{const{__scopePopover:t,...r}=n,i=Ht(Vl,t);return d.jsx(gl.button,{type:"button",...r,ref:e,onClick:_n(n.onClick,()=>i.onOpenChange(!1))})});Wf.displayName=Vl;var qf="PopoverArrow",Jf=w.forwardRef((n,e)=>{const{__scopePopover:t,...r}=n,i=Yn(t);return d.jsx(dh,{...i,...r,ref:e})});Jf.displayName=qf;function zl(n){return n?"open":"closed"}var Gf=Rl,Hf=Fl,Kf=Bl,Yf=$l;const Xf={settings:{glyph:"設",heading:"Sign up to chat",body:`Sign in to start a live voice conversation. Free includes ${bi.free.toLocaleStr
1ing("en-US")} ${qh} each month; Pro includes ${bi.pro.toLocaleString("en-US")}, Premium ${bi.premium.toLocaleString("en-US")}. Chat uses the shared balance only for audio and responses actually processed.`}};function Qf({reason:n,onSignup:e,onDismiss:t}){const r=Xf[n];return d.jsx(Wh,{glyph:r.glyph,heading:r.heading,body:r.body,ctaVariant:"lake",onSignup:e,onDismiss:t})}function Zf({lastLessonReviewLabel:n,lastFreeChatLabel:e,onPickLessonReview:t,onPickRoleplay:r,onPickFreeChat:i}){const s=[{id:"lesson_review",title:"Lesson review",description:"Bring a grammar lesson into conversation. Revisit the ideas, then try using them with your tutor.",action:"Pick a lesson",accessible:"Pick a lesson to review",image:"/watercolor/system-v2/overviews/lesson-notebook.webp",onPick:t,hint:n},{id:"roleplay",title:"Roleplay",description:"Order a meal, ask for directions, or try another everyday scene. Your tutor plays the other part.",action:"Choose a scene",accessible:"Choose a scenario to roleplay",image:"/watercolor/system-v2/overviews/conversation-cafe.webp",onPick:r},{id:"free_chat",title:"Open conversation",description:"Your day, a favorite show, whatever comes to mind. Start anywhere and let the conversation unfold.",action:"Start talking",accessible:"Start an open conversation",image:"/watercolor/system-v2/public-pages/concepts/conversation-exchange.webp",onPick:i,hint:e}];return d.jsxs("section",{className:"ov-conversation-modes","aria-labelledby":"ov-modes-title",children:[d.jsxs("div",{className:"ov-section-heading",children:[d.jsx("h2",{id:"ov-modes-title",children:"What would you like to talk about?"}),d.jsx("p",{children:"Three ways to practise, at your own pace. Conversation uses credits."})]}),d.jsx("div",{className:"ov-mode-list",children:s.map(a=>d.jsxs("button",{type:"button",className:"ov-mode","aria-label":a.accessible,onClick:()=>{Fe("chat_mode_selected",{mode:a.id,source:"overview_card"}),a.onPick()},children:[d.jsx("img",{src:a.image,alt:"","aria-hidden":"true",loading:"lazy"}),d.jsxs("span",{className:"ov-mode-copy",children:[d.jsx("span",{className:"ov-option-title",children:a.title}),d.jsx("span",{className:"ov-option-description",children:a.description}),a.hint&&d.jsx("span",{className:"ov-meta",children:a.hint}),d.jsxs("span",{className:"ov-option-action",children:[a.action," ",d.jsx("span",{"aria-hidden":"true",children:"→"})]})]})]},a.id))})]})}const ep={free_chat:{label:"Open conversation"},lesson_review:{label:"Lesson review"},roleplay:{label:"Roleplay"}};function tp({refreshKey:n,onPick:e}){const{user:t,getAccessToken:r}=Hr(),[i,s]=w.useState(null),[a,o]=w.useState(!1);w.useEffect(()=>{if(!t){s([]),o(!0);return}let u=!1;return(async()=>{try{const f=await r();if(!f||u)return;Ye.setAccessToken(f);const g=await Ye.getChatRecentSessions();u||(s(g.sessions),o(!0))}catch(f){console.warn("Failed to load recent chat sessions:",f),u||(s([]),o(!0))}})(),()=>{u=!0}},[t,r,n]);const l=(i?.length??0)>0;return a&&!l?d.jsxs("section",{className:"ch-recent-sessions ch-recent-sessions--empty","aria-label":"Recent chats",children:[d.jsx("h2",{className:"ov-history-title",children:"Recent conversations"}),d.jsx("p",{className:"ch-recent-empty-msg",children:"Your chats will show up here. Pick a mode above to get started."})]}):d.jsxs("section",{className:"ch-recent-sessions","aria-label":"Recent chats",children:[d.jsx("h2",{className:"ov-history-title",children:"Recent conversations"}),d.jsx("ul",{className:"ch-recent-list",children:i?.map(u=>{const f=ep[u.mode],g=u.lessonTitle||u.scenarioLabel||(u.mode==="free_chat"?"Open conversation":f.label),_=np(u.updatedAt);return d.jsx("li",{className:"ch-recent-row",children:d.jsxs("button",{type:"button",className:"ch-recent-row-btn",onClick:()=>e(u),"aria-label":`Open ${g} (${f.label})`,children:[d.jsx("span",{className:`ch-recent-chip ch-recent-chip--${u.mode.replace("_","-")}`,style:{fontFamily:"var(--font-ui)",fontSize:12},children:f.label}),d.jsx("span",{className:"ch-recent-title",children:g}),d.jsx("span",{className:"ch-recent-time",children:_}),d.jsx("span",{className:"ch-recent-arrow","aria-hidden":"true",children:"→"})]})},u.sessionId)})})]})}function np(n){try{const e=new Date(n).getTime(),t=Date.now(),r=Math.max(0,Math.floor((t-e)/1e3));if(r<60)return"Just now";const i=Math.floor(r/60);if(i<60)return`${i} min ago`;const s=Math.floor(i/60);if(s<24)return`${s} hr ago`;const a=Math.floor(s/24);return a===1?"Yesterday":a<7?`${a} days ago`:new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric"}).format(new Date(n))}catch{return""}}function rp(){const n=fl();w.useEffect(()=>{Fe("chat_overview_viewed")},[]);const e=w.useCallback((i,s)=>{const a=i==="free_chat"?"free-chat":i==="lesson_review"?"lesson-review":"roleplay",o=s?`?resume=${encodeURIComponent(s)}`:"";n(`/chat/${a}${o}`)},[n]),r=w.useCallback(i=>
1{e(i.mode,i.sessionId)},[e]);return d.jsxs("div",{className:"ch-overview",children:[d.jsx(Zf,{onPickLessonReview:()=>n("/chat/lesson-review"),onPickRoleplay:()=>n("/chat/roleplay"),onPickFreeChat:()=>n("/chat/free-chat")}),d.jsx(tp,{onPick:r})]})}const ip={lesson_review:{label:"Lesson review",description:"Revisit the ideas from this lesson, then try using them with your tutor.",invitation:"Bring a question from the lesson, or practise a pattern you want to feel more comfortable with.",icon:Os},roleplay:{label:"Roleplay",description:"Step back into your scene. Your tutor plays the other part.",invitation:"Take the next turn in the exchange, at your own pace.",icon:js},free_chat:{label:"Open conversation",description:"Your day, a favourite show, or a new thought. There’s always somewhere to begin.",invitation:"Tell your tutor about one small thing that happened today.",icon:Ps}};function sp(n){const e=new Date(n);return Number.isFinite(e.getTime())?new Intl.DateTimeFormat("en",{day:"numeric",month:"short",...e.getFullYear()!==new Date().getFullYear()?{year:"numeric"}:{}}).format(e):null}function ap({candidate:n,onResume:e}){if(!n)return null;const t=ip[n.mode],r=n.mode==="lesson_review"&&n.lessonNumber!=null?Nr.find(f=>f.number===n.lessonNumber):void 0,i=n.lessonTitle?.trim(),s=!i||i.toLowerCase()===`lesson ${n.lessonNumber}`,a=n.mode==="lesson_review"?s&&r?.title||i||"Continue your lesson":n.mode==="roleplay"?n.scenarioLabel?.trim()||"Your last roleplay":"A little more Japanese, together.",o=n.lastMessagePreview?.trim(),l=r&&(s||i===r.title)?r.description:null,u=sp(n.updatedAt);return d.jsx(Jh,{className:"ch-overview-next",label:"Continue with your tutor",meta:u?d.jsxs("time",{dateTime:n.updatedAt,children:["Last active ",u]}):void 0,title:a,subtitle:d.jsxs("span",{className:"ch-resume-mode",children:[d.jsx("img",{src:t.icon,alt:"","aria-hidden":"true"}),t.label,n.mode==="lesson_review"&&n.lessonNumber!=null&&d.jsxs("span",{children:["· Lesson ",n.lessonNumber]})]}),description:t.description+" Conversation uses credits.",detail:d.jsxs("div",{className:"ch-resume-context",children:[d.jsx("p",{className:"ch-resume-context-label",children:o?"Where you left off":l?"Practice focus":"A way back in"}),o?d.jsx("blockquote",{className:"ch-resume-excerpt",children:o}):d.jsx("p",{className:"ch-resume-invitation",children:l||t.invitation})]}),scene:"/watercolor/system-v2/next-up/conversation-scene-v1.webp",action:"Continue conversation",actionLabel:"Continue conversation: "+a,onAction:()=>e(n),variant:"lake"})}const op={1:"一",2:"二",3:"三",4:"四",5:"五"},Ia=[1,2,3,4,5];function cp({onPick:n}){const[e]=Kd(),t=e.has("resume"),r=e.get("resume"),i=r&&/^\d+$/.test(r)?Number(r):null,[s,a]=w.useState(""),[o,l]=w.useState({1:!1,2:!1,3:!1,4:!1,5:!1}
1),u=s.trim().toLowerCase(),f=u.length>0,g=w.useMemo(()=>{const b=f?Nr.filter(E=>E.title.toLowerCase().includes(u)||E.titleJa.toLowerCase().includes(u)||String(E.number).includes(u)):Nr,v={1:[],2:[],3:[],4:[],5:[]};for(const E of b)v[E.part].push(E);return v},[u,f]),_=w.useMemo(()=>Ia.reduce((b,v)=>b+g[v].length,0),[g]),k=b=>{l(v=>({...v,[b]:!v[b]}))};return d.jsx("div",{className:"ch-lesson-picker",children:d.jsxs("div",{className:"ch-lesson-frame wc-pencil-frame wc-pencil-frame--md",children:[d.jsx("div",{className:"ch-lesson-picker-search",children:d.jsx(hh,{value:s,onChange:a,placeholder:"Search lessons by name…",ariaLabel:"Search lessons"})}),f&&_===0?d.jsx(Gh,{glyph:"迷",title:"No lessons match",description:`Nothing for “${s}”. Try a different keyword or clear the search.`,variant:"plain"}):d.jsx("div",{className:"ch-lesson-list",children:Ia.map(b=>{const v=g[b];if(f&&v.length===0)return null;const E=f?v.length>0:o[b],C=fh[b];return d.jsxs("section",{className:"ch-lesson-part",children:[d.jsxs("button",{type:"button",className:`ch-lesson-part-header${E?" is-open":""}`,onClick:()=>k(b),"aria-expanded":E,"aria-controls":`ch-lesson-part-${b}-rows`,children:[d.jsxs("span",{className:"ch-lesson-part-eyebrow",children:[d.jsx("span",{className:"num jp","aria-hidden":"true",children:op[b]}),d.jsx("span",{className:"rule","aria-hidden":"true"}),d.jsx("span",{className:"lbl",children:C.en}),d.jsx("span",{className:"jp","aria-hidden":"true",children:C.ja})]}),d.jsx("span",{className:"ch-lesson-part-count",children:v.length}),d.jsx(_l,{size:16,className:"ch-lesson-part-chevron","aria-hidden":"true"})]}),d.jsx(Yr,{initial:!1,children:E&&d.jsx(Or.div,{id:`ch-lesson-part-${b}-rows`,className:"ch-lesson-part-rows",initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.22,ease:[.22,1,.36,1]},children:v.map(O=>{const j=t&&i===O.number;return d.jsxs("button",{type:"button",className:`ch-lesson-row${j?" is-resume":""}`,onClick:()=>n(O.number),"data-tour-id":j?"chat-lesson-resume":void 0,children:[d.jsx("span",{className:"ch-lesson-row-num","aria-hidden":"true",children:O.number}),d.jsxs("span",{className:"ch-lesson-row-body",children:[d.jsx("span",{className:"ch-lesson-row-title",children:O.title}),d.jsx("span",{className:"ch-lesson-row-titleja jp",children:O.titleJa})]}),j&&d.jsxs("span",{className:"ch-lesson-row-badge",children:["Resumes from Lesson ",O.number]})]},O.dbId)})})})]},b)})})]})})}function Ra({onPick:n,activeSession:e,onBack:t,chatConversation:r,topSlot:i}){const s=o=>{const l=Nr.find(u=>u.number===o);n(o,l?.title)},a=!!(e&&r);return d.jsxs("div",{className:"ch-overview ch-picker",children:[d.jsxs("header",{className:"ch-page-header",children:[d.jsx("h1",{className:"ch-page-title",children:d.jsx(Wn,{paint:"blue",children:"Lesson Review"})}),d.jsx("p",{className:"ch-page-lede",children:"Pick a grammar lesson and the tutor will re-teach the idea, then quiz you on it in conversation."})]}),i,a?d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"ch-active-strip",children:[d.jsxs("div",{className:"ch-active-strip-meta",children:[d.jsx("span",{className:"ch-active-strip-label",children:"Reviewing"}),d.jsxs("span",{className:"ch-active-strip-title",children:[e?.lessonNumber!=null&&d.jsxs("span",{className:"ch-active-strip-num",children:[e.lessonNumber,"."]}),e?.lessonTitle??"Lesson"]})]}),d.jsxs("button",{type:"button",className:"ch-active-strip-back",onClick:t,children:[d.jsx("span",{"aria-hidden":"true",className:"arrow",children:"←"}),d.jsx("span",{children:"Change lesson"})]})]}),r]}):d.jsx(cp,{onPick:s})]})}const La="/assets/chatdirectionbackground-DbUgxya1.webp",lp="/assets/konbinibackground-CSIgDb_q.webp",up="/assets/konbiniforeground-DZUDFZBs.webp",dp="/assets/restaurantbackground-CEGhTt9c.webp",hp="/assets/restaurantforeground-DLvzaEI6.webp",fp="/assets/konbini-CK8gKigE.webp",pp="/assets/restaurant-CX7dnjac.webp",mp="/assets/street-Cc7nfdTF.webp",nn={ordering_food:{id:"ordering_food",label:"Ordering food",labelJa:"食事を注文する",glyph:"食",description:"You're at a casual Japanese restaurant. Order a meal, ask about menu items, deal with the small talk a waitress brings.",backgroundAsset:dp,foregroundAsset:hp,coverImage:pp,avatarPlacement:{scale:1,top:-.
1025,anchorY:1}},asking_directions:{id:"asking_directions",label:"Asking for directions",labelJa:"道を尋ねる",glyph:"道",description:"You're lost in a Japanese neighborhood. Stop a passerby and figure out how to get to the train station, a cafe, or a landmark.",backgroundAsset:La,coverImage:mp,avatarPlacement:{scale:1,top:.04,anchorY:.43}},meeting_someone:{id:"meeting_someone",label:"Meeting someone new",labelJa:"初対面の自己紹介",glyph:"初",description:"You're at a casual gathering and you've just been introduced to someone. Exchange self-introductions and find common ground.",backgroundAsset:La,avatarPlacement:{scale:1,top:.04,anchorY:.43}},konbini_shopping:{id:"konbini_shopping",label:"Konbini shopping",labelJa:"コンビニで買い物",glyph:"店",description:"You're at a 7-Eleven or Lawson, picking up snacks and a drink. Work through the cashier interaction.",backgroundAsset:lp,foregroundAsset:up,coverImage:fp,avatarPlacement:{scale:.8,top:-.06,anchorY:0}}},gp=["ordering_food","asking_directions","meeting_someone","konbini_shopping"],vp=gp.map(n=>nn[n]);function bp({onPick:n}){return d.jsx("div",{className:"ch-scenario-grid",role:"list",children:vp.map((e,t)=>d.jsxs(vi,{as:"div",size:"md",className:"ch-scenario-card",index:t,onClick:()=>n(e.id),onKeyDown:r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n(e.id))},"data-tour-id":`chat-scenario-${e.id}`,children:[d.jsxs(vi.Body,{className:"ch-scenario-card-body",children:[d.jsx("h3",{className:"ch-scenario-card-title",children:e.label}),d.jsx("p",{className:"ch-scenario-card-desc",children:e.description})]}),d.jsx(vi.Foot,{className:"ch-scenario-card-foot",children:d.jsxs("span",{className:"wc-cta-square wc-cta-square--ink ch-scenario-card-cta","aria-hidden":"true",children:["Start scene ",d.jsx("span",{"aria-hidden":"true",children:"→"})]})})]},e.id))})}function Da({onPick:n,activeSession:e,chatConversation:t,topSlot:r}){const i=a=>{const o=nn[a];n(a,o?.label)},s=!!(e&&t);return d.jsxs("div",{className:"ch-overview ch-picker",children:[d.jsxs("header",{className:"ch-page-header",children:[d.jsx("h1",{className:"ch-page-title",children:d.jsx(Wn,{paint:"blue",children:"Roleplay"})}),d.jsx("p",{className:"ch-page-lede",children:"Step into a scene. The tutor stays in character — a waiter, a stranger, a cashier — and you respond in Japanese."})]}),r,s?t:d.jsx(bp,{onPick:i})]})}function yp(){const t=[];t.push(0,0,0),t.push(0,-1.5,0);for(let i=0;i<12;i++){const s=Math.acos(-1+2*i/12),a=Math.sqrt(12*Math.PI)*s,o=.6*Math.cos(a)*Math.sin(s),l=.6*Math.sin(a)*Math.sin(s),u=.6*Math.cos(s);t.push(0,0,0);const f=.8+Math.random()*.4;t.push(o*f,Math.abs(l*f)+.1,u*f)}const r=new af;return r.setAttribute("position",new of(t,3)),r}function wp(){const e=document.createElement("canvas");e.width=256,e.height=256;const t=e.getContext("2d"),r=[{x:.5,y:.5,r:.45,opacity:.35},{x:.35,y:.45,r:.35,opacity:.25},{x:.65,y:.45,r:.35,opacity:.25},{x:.5,y:.38,r:.3,opacity:.3}
1,{x:.42,y:.55,r:.28,opacity:.2},{x:.58,y:.55,r:.28,opacity:.2}];for(const s of r){const a=s.x*256,o=s.y*256,l=s.r*256,u=t.createRadialGradient(a,o,0,a,o,l);u.addColorStop(0,`rgba(255, 255, 255, ${s.opacity})`),u.addColorStop(.4,`rgba(255, 255, 255, ${s.opacity*.7})`),u.addColorStop(.7,`rgba(255, 255, 255, ${s.opacity*.3})`),u.addColorStop(1,"rgba(255, 255, 255, 0)"),t.fillStyle=u,t.fillRect(0,0,256,256)}const i=new sf(e);return i.needsUpdate=!0,i}const _p=({seedCount:n=150,cloudCount:e=40,seedColor:t="#ffffff",showClouds:r=!0,mouseReactive:i=!0,className:s="",disabled:a=!1,zIndex:o=0})=>{const l=w.useRef(null);Hh(l);const u=w.useRef(0),f=w.useRef(!0),g=w.useRef(i);g.current=i;const _=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches,k=!a&&!_,b=w.useCallback(()=>{f.current=!document.hidden},[]);return w.useEffect(()=>{if(!k)return;const v=l.current;if(!v)return;const E=v.clientWidth||window.innerWidth,C=v.clientHeight||window.innerHeight;if(E===0||C===0)return;const O=80,j=40,S=25;let x;try{x=new Kh({antialias:!0,alpha:!0})}catch{return}const T=new Yh;T.fog=new Xh(5149642,.008);const I=new Qh(60,E/C,.1,200);I.position.z=20,x.setClearColor(0,0),x.setPixelRatio(Math.min(window.devicePixelRatio,2)),x.setSize(E,C),x.domElement.style.pointerEvents="none",v.appendChild(x.domElement),x.domElement.addEventListener("webglcontextlost",c=>{c.preventDefault(),cancelAnimationFrame(u.current)});const F=r?wp():null,$=[],z=[];for(let c=0;c<(r?e:0);c++){const p=new Zh({map:F,transparent:!0,opacity:.25+Math.random()*.3,depthWrite:!1,blending:Ma});z.push(p);const h=new ef(p),m=15+Math.random()*20,y=m*(.35+Math.random()*.25);h.scale.set(m,y,1);const N=(Math.random()-.5)*100,P=4+Math.random()*16,R=-10-Math.random()*50;h.position.set(N,P,R),T.add(h),$.push({mesh:h,baseX:N,baseY:P,z:R,speed:.003+Math.random()*.008,wobblePhase:Math.random()*Math.PI*2,wobbleAmp:.3+Math.random()*.5,wobbleSpeed:.002+Math.random()*.003})}const fe=yp(),me=new tf({color:new nf(t),transparent:!0,opacity:.85,depthWrite:!1,blending:Ma}),je=[],_e=[];for(let c=0;c<n;c++){const p=new rf(fe,me);p.position.set((Math.random()-.5)*60,(Math.random()-.5)*40,(Math.random()-.5)*O),p.rotation.set(Math.random()*Math.PI,Math.random()*Math.PI,Math.random()*Math.PI);const h=.5+Math.random()*.5;p.scale.set(h,h,h),T.add(p),je.push(p),_e.push({velocity:new Aa(0,0,0),rotationSpeed:new Aa((Math.random()-.5)*.02,(Math.random()-.5)*.02,(Math.random()-.5)*.02),scaleOffset:Math.random(),floatSpeed:.01+Math.random()*.02})}let Te=0,Ie=0;const Re=new Ta(0,0),ke=new Ta(.05,.02);let ie=0;const Se=c=>{g.current&&(Te=c.clientX/window.innerWidth*2-1,Ie=-(c.clientY/window.innerHeight)*2+1,Re.x=Te*.1,Re.y=Ie*.05)},Ne=()=>{if(!v)return;const c=v.clientWidth,p=v.clientHeight;I.aspect=c/p,I.updateProjectionMatrix(),x.setSize(c,p)};window.addEventListener("resize",Ne),document.addEventListener("mousemove",Se),document.addEventListener("visibilitychange",b);const Be=()=>{if(u.current=requestAnimationFrame(Be),!f.current)return;ie+=.005,ke.x+=(Re.x-ke.x)*.05,ke.y+=(Re.y-ke.y)*.05;const c=Math.sin(ie)*.002;for(let p=0;p<$.length;p++){const h=$[p];h.baseX+=h.speed+ke.x*.003;const m=Math.sin(ie*h.wobbleSpeed*60+h.wobblePhase)*h.wobbleAmp;h.mesh.position.x=h.baseX,h.mesh.position.y=h.baseY+m,h.baseX>60?h.baseX=-60:h.baseX<-60&&(h.baseX=60)}for(let p=0;p<je.length;p++){const h=je[p],m=_e[p];m.velocity.x+=ke.x*.01+c,m.velocity.y+=ke.y*.01+Math.cos(ie+m.scaleOffset*10)*5e-4,m.velocity.y+=2e-4,m.velocity.multiplyScalar(.98),h.position.add(m.velocity),h.rotation.x+=m.rotationSpeed.x,h.rotation.y+=m.rotationSpeed.y,h.rotation.z+=m.rotationSpeed.z,h.position.x>j?(h.position.x=-j,h.position.y=(Math.random()-.5)*S):h.position.x<-j&&(h.position.x=j,h.position.y=(Math.random()-.5)*S),h.position.y>S?(h.position.y=-S,h.position.x=(Math.random()-.5)*j*1.5):h.position.y<-S&&(h.position.y=S),h.position.z>20&&(h.position.z=-O)}g.current&&(I.position.x+=(Te*2-I.position.x)*.02,I.position.y+=(Ie*2-I.position.y)*.02),I.lookAt(T.position),x.render(T,I)};return u.current=requestAnimationFrame(Be),()=>{cancelAnimationFrame(u.current),window.removeEventListener("resize",Ne),document.removeEventListener("mousemove",Se),document.removeEventListener("visibilitychange",b),fe.dispose(),me.dispose(),F?.dispose();for(const c of z)c.dispose();x.dispose(),v.contains(x.domElement)&&v.removeChild(x.domElement)}},[k,n,e,t,r,b]),k?d.jsx("div",{ref:l,className:`fixed inset-0 pointer-events-none ${s}`,style:{zIndex:o},"aria-hidden":"true"}):null};function kp({mode:n,scenarioId:e}){return d.jsx(_p,{mouseReactive:!1})}function Sp({scenarioId:n,onSelect:e}){const[t,r]=w.useState(!1),i=n?nn[n]:null;return d.jsxs(Gf,{open:t,onOpenChange:r,children:[d.jsx(Hf,{asChild:!0,children:d.jsxs("button",{type:"button",className:"ch-scene-trigger","aria-label":"Change scene",children:[d.jsx("span",{className:"ch-scene-trigger-eyebrow",children:"Change scene"}),d.jsxs("span",{className:"ch-scene-trigger-current",children:[i?.glyph&&d.jsx("span",{className:"glyph jp","aria-hidden":"true",children:i.glyph}),d.jsx("span",{className:"name",children:i?.label??"Pick a scene"}),d.jsx(_l,{size:13,className:"chev","aria-hidden":"true"})]})]})}),d.jsx(Kf,{children:d.jsxs(Yf,{align:"start",sideOffset:10,className:"ch-scene-menu-panel",children:[d.jsx("div",{className:"ch-scene-menu-paper","aria-hidden":"true"}),d.jsx("div",{className:"ch-scene-menu-pencil","aria-hidden":"true"}),d.jsxs("div",{className:"ch-scene-menu-head",children:[d.jsx("span",{className:"lbl",children:"Change scene"}),d.jsx("span",{className:"jp",children:"場面"})]}),d.jsx("div",{className:"ch-scene-menu-list",children:Object.entries(nn).map(([s,a])=>{const o=s===n;return d.jsxs("button",{type:"button",className:`ch-scene-menu-item${o?" is-selected":""}`,onClick:()=>{e(s),r(!1)},children:[d.jsx("span",{className:"glyph jp","aria-hidden":"true",children:a.glyph}),d.jsx("span",{className:"name",children:a.label}),o&&d.jsx(ph,{size:14,className:"check","aria-hidden":"true"})]},s)})})]})})]})}const ki=[{at:0,role:"user",jp:"週末は何をしましたか?",en:"What did you do this weekend?"},{at:2.2,role:"tutor",jp:"映画を見ましたよ。",en:"I watched a movie."},{at:4.5,role:"tutor",jp:"とても面白かったです。あなたは?",en:"It was really fun. How about you?"},{at:7.8,role:"user",jp:"友達と富士山に登りました!",en:"I climbed Mt. Fuji with a friend!"},{at:10.5,role:"tutor",jp:"わあ、いいですね!",en:"Wow, nice!"},{at:12.8,role:"tutor",jp:"お天気はどうでしたか?",en:"How was the weather?"},{at:15.5,role:"user",jp:"晴れて、気持ちよかったです。",en:"Sunny — it felt great."},{at:17.8,role:"tutor",jp:"それは最高ですね!",en:"That's the best!"}];function xp(){const n=w.useRef(null);return w.useEffect(()=>{const e=n.current,t=e?.querySelector("video.ch-hero-video"),r=e?.querySelector(".ch-conv-stage");if(!e||!t||!r)return;const i=document.createElement("section");i.className="journey-transcript",i.setAttribute("aria-label","Conversation transcript");const s=document.createElement("ol");s.className="journey-transcript-stream",s.tabIndex=0,s.setAttribute("role","log"),s.setAttribute("aria-label","Japanese conversation with English translations"),s.setAttribute("aria-live","off"),s.addEventListener("scroll",()=>{s.dataset.scrolled=String(s.scrollTop>1)},{passive:!0});const a=ki.map(O=>{const j=document.createElement("li");j.className=`journey-transcript-line journey-transcript-line--${O.role}`;const S=document.createElement("span");S.className="journey-transcript-speaker",S.textContent=O.role==="tutor"?"Tutor":"You";const x=document.createElement("p");x.lang="ja",x.textContent=O.jp;const T=document.createElement("p");return T.className="journey-transcript-gloss",T.lang="en",T.textContent=O.en,j.append(S,x,T),s.append(j),j});i.append(s),r.append(i);const o=window.matchMedia("(prefers-reduced-motion: reduce)");let l=-1;const u=()=>{let O=0;for(let S=0;S<ki.length;S++)t.currentTime>=ki[S].at&&(O=S);if(O===l)return;const j=O<l;l=O,a.forEach((S,x)=>{S.hidden=x>l,S.classList.toggle("is-current",x===l),S.setAttribute("aria-current",String(x===l))}),i.dataset.activeCue=String(l),requestAnimationFrame(()=>s.scrollTo({top:s.scrollHeight,behavior:j||o.matches||t.paused?"instant":"smooth"}))},f=["loadedmetadata","timeupdate","seeked","play","pause","ended"];f.forEach(O=>
1t.addEventListener(O,u)),u(),t.muted=!0,t.playsInline=!0,t.preload="auto",t.loop=!0;const g=document.createElement("div");g.className="module-tutor-controls";const _=document.createElement("button");_.type="button",_.className="reset-video-control";const k=document.createElement("button");k.type="button",k.className="reset-video-control";const b=()=>{_.textContent=t.paused?"Play recording":"Pause recording",_.setAttribute("aria-label",t.paused?"Play conversation preview":"Pause conversation preview"),k.textContent=t.muted?"Turn sound on":"Mute sound",k.setAttribute("aria-label",t.muted?"Turn conversation preview sound on":"Mute conversation preview sound"),k.setAttribute("aria-pressed",String(!t.muted))},v=()=>{t.paused?t.play().catch(()=>{}):t.pause()},E=()=>{t.muted=!t.muted};_.addEventListener("click",v),k.addEventListener("click",E),t.addEventListener("play",b),t.addEventListener("pause",b),t.addEventListener("volumechange",b),g.append(_,k),e.append(g),b();const C=new IntersectionObserver(([O])=>{!O.isIntersecting||o.matches?t.pause():t.play().catch(()=>{})},{threshold:.15});return C.observe(e),o.matches&&t.pause(),()=>{C.disconnect(),f.forEach(O=>t.removeEventListener(O,u)),t.removeEventListener("play",b),t.removeEventListener("pause",b),t.removeEventListener("volumechange",b),_.removeEventListener("click",v),k.removeEventListener("click",E),t.pause(),i.remove(),g.remove()}},[]),d.jsx("div",{className:"ch-public-transcript-host",ref:n,children:d.jsx(Cl,{autoPlay:!1})})}const Ep="/assets/hl-blue-BpjfO_F7.webp",Cp="/assets/summer_stamp1floating-CDy4f6uo.webp",Mp="/assets/epsilon-bg-sKBMR9Qm.webp",Ap=[.22,1,.36,1],Fa=[{role:"user",jp:"週末は何をしましたか?",gloss:"What did you do this weekend?",showAt:0},{role:"tutor",jp:"映画を見ましたよ。",gloss:"I watched a movie.",showAt:2.2},{role:"tutor",jp:"とても面白かったです。あなたは?",gloss:"It was really fun. How about you?",showAt:4.5},{role:"user",jp:"友達と富士山に登りました!",gloss:"I climbed Mt. Fuji with a friend!",showAt:7.8},{role:"tutor",jp:"わあ、いいですね!",gloss:"Wow, nice!",showAt:10.5},{role:"tutor",jp:"お天気はどうでしたか?",gloss:"How was the weather?",showAt:12.8},{role:"user",jp:"晴れて、気持ちよかったです。",gloss:"Sunny — it felt great.",showAt:15.5},{role:"tutor",jp:"それは最高ですね!",gloss:"That's the best!",showAt:17.8}];function Tp(){const n=w.useRef(null),e=w.useRef(null),t=w.useRef(null),[r,i]=w.useState(0),[s,a]=w.useState(!1);return w.useEffect(()=>{const o=n.current;if(!o||s)return;if(typeof IntersectionObserver>"u"){a(!0);return}const l=new IntersectionObserver(([u])=>{u?.isIntersecting&&(a(!0),l.disconnect())},{rootMargin:"320px 0px"});return l.observe(o),()=>l.disconnect()},[s]),w.useEffect(()=>{const o=e.current;if(!o)return;const l=()=>{const f=o.currentTime;let g=0;for(const _ of Fa)f>=_.showAt&&g++;i(_=>_===g?_:g)},u=()=>{o.currentTime<.3&&i(0)};return o.addEventListener("timeupdate",l),o.addEventListener("seeked",u),()=>{o.removeEventListener("timeupdate",l),o.removeEventListener("seeked",u)}},[]),w.useEffect(()=>{const o=t.current;o&&o.scrollTo({top:o.scrollHeight,behavior:"smooth"})},[r]),d.jsxs(df,{className:"demo-section demo-section--ink",style:{"--demo-accent":"var(--brand-reading)","--demo-accent-hl":`url(${Ep})`},children:[d.jsx("img",{src:Cp,alt:"",className:"wc-stamp","aria-hidden":"true",loading:"lazy",decoding:"async"}),d.jsxs("div",{className:"demo-head",children:[d.jsxs("div",{className:"demo-eyebrow",children:[d.jsx("span",{className:"num jp",children:"五"}),d.jsx("span",{className:"rule","aria-hidden":"true"}),d.jsx("span",{className:"lbl",children:"Conversation"}),d.jsx("span",{className:"jp",children:"会話"})]}),d.jsxs("div",{className:"demo-head-row",children:[d.jsx("h2",{children:"Hear a conversation in Japanese."}),d.jsx("p",{children:"Hear an AI practice partner respond, with an animated face and text you can follow. This is a recorded example; live conversations use credits."})]})]}),d.jsx("div",{ref:n,className:"demo-body",children:d.jsx("div",{className:"demo-panel",children:d.jsxs("div",{className:"tutor-stage",children:[d.jsxs("div",{className:"tutor-avatar",children:[d.jsx("img",{src:Mp,alt:"","aria-hidden":"true",className:"bg"}),d.jsx("video",{ref:e,className:"tutor-video",src:s?"/watercolor/epsilon-weekend-chat.webm":void 0,autoPlay:!0,loop:!0,muted:!0,playsInl
1ine:!0,preload:"none","aria-hidden":"true"})]}),d.jsxs("div",{className:"tutor-chat",children:[d.jsxs("div",{className:"head",children:[d.jsx("span",{className:"live-dot"}),d.jsx("span",{children:"Tutor · Voice On"})]}),d.jsx("div",{ref:t,className:"stream",children:d.jsx(Yr,{initial:!1,children:Fa.slice(0,r).map((o,l)=>d.jsxs(Or.div,{className:`chat-bubble ${o.role}`,initial:{opacity:0,y:10,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0},transition:{duration:.35,ease:Ap},children:[d.jsx("div",{children:o.jp}),d.jsx("div",{className:"gloss",children:o.gloss})]},l))})})]})]})})})]})}const Np="/watercolor/system-v2/public-pages/concepts",Op=[["When should I try conversation?","It helps to know some kana, everyday words and basic grammar so you can follow a simple exchange. If you are just starting, the free foundations are a comfortable place to begin. Conversation is optional, and you can return when you want speaking practice."],["Do I need a microphone?","For spoken conversation, you will need a microphone, permission to use it and a place where you are comfortable speaking aloud."],["Will it correct every mistake?","The tutor can offer corrections and explanations, but it may miss a mistake or give an imperfect suggestion. Ask follow-up questions and use your lessons or dictionary to check anything that seems unclear."],["How is conversation paid for?","Conversation uses credits. Choose an allowance that fits your practice, with paid options available when you want more. See the current plans for details."],["Can I keep learning without conversation?","Yes. Kana, vocabulary and grammar learning are free, and you can build your foundations, read and review at your own pace. Speaking practice is another option when you want it."]];function Pp(){return d.jsxs("header",{className:"ch-page-header ml-hero ch-public-hero","data-conversation-transcript":"",children:[d.jsx("h1",{className:"ch-page-title",children:"Find your words. Try saying them."}),d.jsxs("p",{className:"hero-lede wc-herolede-full",children:[d.jsx(cf,{page:"conversation",ariaLabel:"Module features",lead:"Find your voice with",phrases:[{text:"An AI practice partner",accent:"reading",paint:"blue"},{text:"Live voice conversation",accent:"reading",paint:"blue"},{text:"Everyday roleplay",accent:"reading",paint:"blue"},{text:"Lesson-based conversation",accent:"reading",paint:"blue"},{text:"A chat about your day",accent:"reading",paint:"blue"}]}),d.jsx("span",{className:"hero-rotation__intro",children:"Practise a lesson, try an everyday situation, or talk about your day with an AI practice partner."})]}),d.jsx(xp,{}),d.jsxs("div",{className:"hero-ctas ch-hero-ctas",children:[d.jsx(bn,{className:"ml-button",to:"/chat/free-chat",children:"Explore conversation"}),d.jsxs("a",{className:"ml-link ml-hero-link",href:"#module-preview",children:[d.jsx("span",{children:"See the recorded preview"}),d.jsx("span",{className:"ml-hero-link-arrow","aria-hidden":"true",children:"→"})]})]}),d.jsx("p",{className:"ml-hero-proof",children:"Optional conversation practice uses credits. The previews on this page are recordings."})]})}function jp(){return d.jsxs("div",{className:"wc-root ch-overview ch-anon-marketing ml-conversation-story",children:[d.jsxs("section",{className:"ml-section ml-feature-row ml-story-opening",children:[d.jsxs("div",{className:"ml-copy",children:[d.jsx("p",{className:"ml-eyebrow",children:"Make room for a first attempt"}),d.jsx("h2",{children:"You can start with something simple."}),d.jsx("p",{children:"A sentence from a lesson. Something you ate today. A question you would like to ask in a café."}),d.jsx("p",{children:"Use an animated practice partner to try putting familiar Japanese into words, notice what needs work, and have another go."})]}),d.jsx("img",{className:"ml-art ml-conversation-exchange",src:`${Np}/conversation-exchange.webp`,alt:"A watercolor illustration of a friendly exchange",loading:"lazy"})]}),d.jsxs("section",{className:"ml-section ml-demo-section",id:"module-preview",children:[d.jsxs("div",{className:"ml-section-head",children:[d.jsx("p",{className:"ml-eyebrow",children:"Hear a little of the experience"}),d.jsx("h2",{children:"A voice, an animated face, a reply to follow."}),d.jsx("p",{className:"ml-lede",children:"Play this recorded conversation to hear the tutor and follow the exchange."})]}),d.jsx(Tp,{})]}),d.jsxs("section",{className:"ml-section",children:[d.jsxs("div",{className:"ml-section-head",children:[d.jsx("p",{className:"ml-eyebrow",children:"Choose a starting point"}),d.jsx("h2",{children:"One lesson, one situation, or your own idea."})]}),d.jsxs("div",{className:"ml-cards ml-conversation-modes",children:[d.jsxs("article",{className:"ml-card",children:[d.jsx("h3",{children:"Revisit a lesson"}),d.jsx("p",{children:"Bring a grammar lesson into conversation. Practise using the pattern you have just been learning."}),d.jsx(bn,{className:"ml-link",to:"/chat/lesson-review",children:"Explore lesson review"})]}),d.jsxs("article",{className:"ml-card",children:[d.jsx("h3",{children:"Try an everyday situation"}),d.jsx("p",{children:"Choose a roleplay and practise finding the words for a café, a journey or another familiar scene."}),d.jsx(bn,{className:"ml-link",to:"/chat/roleplay",children:"Explore roleplay"})]}),d.jsxs("article",{className:"ml-card",children:[d.jsx("h3",{children:"Talk about your day"}),d.jsx("p",{children:"Talk about your day, an interest, or a topic you choose."}),d.jsx(bn,{className:"ml-link",to:"/chat/free-chat",children:"Explore open conversation"})]})]})]}),d.jsxs("section",{className:"ml-section ml-speaking-support",children:[d.jsxs("div",{className:"ml-section-head",children:[d.jsx("p",{className:"ml-eyebrow",children:"Something to learn from the reply"}),d.jsx("h2",{children:"Listen, notice, try again."}),d.jsx("p",{className:"ml-lede",children:"Spoken replies and visible text give you something to follow. Corrections and explanations can help you revisit the words or grammar you were reaching for."})]}),d.jsxs("div",{className:"ml-steps",children:[d.jsxs("article",{className:"ml-step",children:[d.jsx("span",{className:"ml-step-number",children:"1"}),d.jsx("h3",{children:"Say a little."}),d.jsx("p",{children:"Choose a manageable idea. You do not need a long answer to begin practising."})]}),d.jsxs("article",{className:"ml-step",children:[d.jsx("span",{className:"ml-step-number",children:"2"}),d.jsx("h3",{children:"Take a closer look."}),d.jsx("p",{children:"Follow the reply and ask about wording you do not understand. Use a correction as a point to explore."})]}),d.jsxs("article",{className:"ml-step",children:[d.jsx("span",{className:"ml-step-number",children:"3"}),d.jsx("h3",{children:"Bring it into your next attempt."}),d.jsx("p",{children:"Try the phrase again or return to the related grammar lesson. Speaking can sit alongside your reading and review."})]})]})]}),d.jsxs("section",{className:"ml-section ml-faq",children:[d.jsxs("div",{className:"ml-section-head",children:[d.jsx("p",{className:"ml-eyebrow",children:"A few things to know"}),d.jsx("h2",{children:"Make yourself comfortable."})]}),Op.map(([n,e])=>d.jsxs("details",{children:[d.jsx("summary",{children:n}),d.jsx("p",{children:e})]},n))]}),d.jsxs("section",{className:"ml-section ml-closer",children:[d.jsx("img",{className:"ml-closing-nature",src:"/watercolor/system-v2/modules/journey-conversation.webp",alt:"",loading:"lazy"}),d.jsx("h2",{children:"A little Japanese, in your own words."}
1),d.jsx("p",{children:"Choose a familiar topic and give yourself room to try."}),d.jsxs("div",{className:"ml-closing-actions",children:[d.jsx(bn,{className:"ml-button",to:"/chat/free-chat",children:"Explore conversation"}),d.jsx(bn,{className:"ml-button ml-button--secondary",to:"/grammar/overview",children:"Build your foundations"})]})]})]})}var Ip=Symbol("radix.slottable");function Rp(n){const e=({children:t})=>d.jsx(d.Fragment,{children:t});return e.displayName=`${n}.Slottable`,e.__radixId=Ip,e}var Wl="AlertDialog",[Lp]=wl(Wl,[Sl]),Pt=Sl(),ql=n=>{const{__scopeAlertDialog:e,...t}=n,r=Pt(e);return d.jsx(mh,{...r,...t,modal:!0})};ql.displayName=Wl;var Dp="AlertDialogTrigger",Fp=w.forwardRef((n,e)=>{const{__scopeAlertDialog:t,...r}=n,i=Pt(t);return d.jsx(kh,{...i,...r,ref:e})});Fp.displayName=Dp;var Bp="AlertDialogPortal",Jl=n=>{const{__scopeAlertDialog:e,...t}=n,r=Pt(e);return d.jsx(wh,{...r,...t})};Jl.displayName=Bp;var $p="AlertDialogOverlay",Gl=w.forwardRef((n,e)=>{const{__scopeAlertDialog:t,...r}=n,i=Pt(t);return d.jsx(_h,{...i,...r,ref:e})});Gl.displayName=$p;var kn="AlertDialogContent",[Up,Vp]=Lp(kn),zp=Rp("AlertDialogContent"),Hl=w.forwardRef((n,e)=>{const{__scopeAlertDialog:t,children:r,...i}=n,s=Pt(t),a=w.useRef(null),o=Kr(e,a),l=w.useRef(null);return d.jsx(gh,{contentName:kn,titleName:Kl,docsSlug:"alert-dialog",children:d.jsx(Up,{scope:t,cancelRef:l,children:d.jsxs(vh,{role:"alertdialog",...s,...i,ref:o,onOpenAutoFocus:_n(i.onOpenAutoFocus,u=>{u.preventDefault(),l.current?.focus({preventScroll:!0})}),onPointerDownOutside:u=>u.preventDefault(),onInteractOutside:u=>u.preventDefault(),children:[d.jsx(zp,{children:r}),d.jsx(qp,{contentRef:a})]})})})});Hl.displayName=kn;var Kl="AlertDialogTitle",Yl=w.forwardRef((n,e)=>{const{__scopeAlertDialog:t,...r}=n,i=Pt(t);return d.jsx(bh,{...i,...r,ref:e})});Yl.displayName=Kl;var Xl="AlertDialogDescription",Ql=w.forwardRef((n,e)=>{const{__scopeAlertDialog:t,...r}=n,i=Pt(t);return d.jsx(yh,{...i,...r,ref:e})});Ql.displayName=Xl;var Wp="AlertDialogAction",Zl=w.forwardRef((n,e)=>{const{__scopeAlertDialog:t,...r}=n,i=Pt(t);return d.jsx(kl,{...i,...r,ref:e})});Zl.displayName=Wp;var eu="AlertDialogCancel",tu=w.forwardRef((n,e)=>{const{__scopeAlertDialog:t,...r}=n,{cancelRef:i}=Vp(eu,t),s=Pt(t),a=Kr(e,i);return d.jsx(kl,{...s,...r,ref:a})});tu.displayName=eu;var qp=({contentRef:n})=>{const e=`\`${kn}\` requires a description for the component to be accessible for screen reader users.
2
3You can add a description to the \`${kn}\` by passing a \`${Xl}\` component as a child, which also benefits sighted users by adding visible context to the dialog.
4
5Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${kn}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component.
6
7For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return w.useEffect(()=>{document.getElementById(n.current?.getAttribute("aria-describedby"))||console.warn(e)},[e,n]),null},Jp=ql,Gp=Jl,Hp=Gl,Kp=Hl,Yp=Zl,Xp=tu,Qp=Yl,Zp=Ql;function Ba({...n}){return d.jsx(Jp,{"data-slot":"alert-dialog",...n})}function em({...n}){return d.jsx(Gp,{"data-slot":"alert-dialog-portal",...n})}function tm({className:n,...e}){return d.jsx(Hp,{"data-slot":"alert-dialog-overlay",className:Gt("mobile-viewport-dialog-overlay data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 bg-black/50",n),...e})}function $a({className:n,...e}){return d.jsxs(em,{children:[d.jsx(tm,{}),d.jsx(Kp,{"data-slot":"alert-dialog-content",className:Gt("mobile-viewport-dialog-content wc-modal-root wc-alert-dialog-default wc-pencil-frame wc-pencil-frame--md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 p-6 duration-200 sm:max-w-lg",n),...e})]})}function Ua({className:n,...e}){return d.jsx("div",{"data-slot":"alert-dialog-header",className:Gt("flex flex-col gap-2 text-center sm:text-left",n),...e})}function Va({className:n,...e}){return d.jsx("div",{"data-slot":"alert-dialog-footer",className:Gt("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",n),...e})}function za({className:n,...e}){return d.jsx(Qp,{"data-slot":"alert-dialog-title",className:Gt("text-lg font-semibold",n),...e})}function Wa({className:n,...e}){return d.jsx(Zp,{"data-slot":"alert-dialog-description",className:Gt("text-muted-foreground text-sm",n),...e})}function qa({className:n,...e}){const t=n?.includes("bg-destructive");return d.jsx(Yp,{className:Gt(t?hf():"wc-cta-square wc-cta-square--ink",n),...e})}function Ja({className:n,...e}){return d.jsx(Xp,{className:Gt("wc-cta-square wc-cta-square-secondary--ink",n),...e})}var rr={exports:{}},Ga;
vendor: 5,010 bytes, line 7
7function nm(){if(Ga)return rr.exports;Ga=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(x,T,I){return Function.prototype.apply.call(x,T,I)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(x){return Object.getOwnPropertyNames(x).concat(Object.getOwnPropertySymbols(x))}:t=function(x){return Object.getOwnPropertyNames(x)};function r(S){console&&console.warn&&console.warn(S)}var i=Number.isNaN||function(x){return x!==x};function s(){s.init.call(this)}rr.exports=s,rr.exports.once=C,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(S){if(typeof S!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof S)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(S){if(typeof S!="number"||S<0||i(S))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+S+".");a=S}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(x){if(typeof x!="number"||x<0||i(x))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+x+".");return this._maxListeners=x,this};function l(S){return S._maxListeners===void 0?s.defaultMaxListeners:S._maxListeners}s.prototype.getMaxListeners=function(){return l(this)},s.prototype.emit=function(x){for(var T=[],I=1;I<arguments.length;I++)T.push(arguments[I]);var F=x==="error",$=this._events;if($!==void 0)F=F&&$.error===void 0;else if(!F)return!1;if(F){var z;if(T.length>0&&(z=T[0]),z instanceof Error)throw z;var fe=new Error("Unhandled error."+(z?" ("+z.message+")":""));throw fe.context=z,fe}var me=$[x];if(me===void 0)return!1;if(typeof me=="function")e(me,this,T);else for(var je=me.length,_e=b(me,je),I=0;I<je;++I)e(_e[I],this,T);return!0};function u(S,x,T,I){var F,$,z;if(o(T),$=S._events,$===void 0?($=S._events=Object.create(null),S._eventsCount=0):($.newListener!==void 0&&(S.emit("newListener",x,T.listener?T.listener:T),$=S._events),z=$[x]),z===void 0)z=$[x]=T,++S._eventsCount;else if(typeof z=="function"?z=$[x]=I?[T,z]:[z,T]:I?z.unshift(T):z.push(T),F=l(S),F>0&&z.length>F&&!z.warned){z.warned=!0;var fe=new Error("Possible EventEmitter memory leak detected. "+z.length+" "+String(x)+" listeners added. Use emitter.setMaxListeners() to increase limit");fe.name="MaxListenersExceededWarning",fe.emitter=S,fe.type=x,fe.count=z.length,r(fe)}return S}s.prototype.addListener=function(x,T){return u(this,x,T,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(x,T){return u(this,x,T,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function g(S,x,T){var I={fired:!1,wrapFn:void 0,target:S,type:x,listener:T},F=f.bind(I);return F.listener=T,I.wrapFn=F,F}s.prototype.once=function(x,T){return o(T),this.on(x,g(this,x,T)),this},s.prototype.prependOnceListener=function(x,T){return o(T),this.prependListener(x,g(this,x,T)),this},s.prototype.removeListener=function(x,T){var I,F,$,z,fe;if(o(T),F=this._events,F===void 0)return this;if(I=F[x],I===void 0)return this;if(I===T||I.listener===T)--this._eventsCount===0?this._events=Object.create(null):(delete F[x],F.removeListener&&this.emit("removeListener",x,I.listener||T));else if(typeof I!="function"){for($=-1,z=I.length-1;z>=0;z--)if(I[z]===T||I[z].listener===T){fe=I[z].listener,$=z;break}if($<0)return this;$===0?I.shift():v(I,$),I.length===1&&(F[x]=I[0]),F.removeListener!==void 0&&this.emit("removeListener",x,fe||T)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(x){var T,I,F;if(I=this._events,I===void 0)return this;if(I.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):I[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete I[x]),this;if(arguments.length===0){var $=Object.keys(I),z;for(F=0;F<$.length;++F)z=$[F],z!=="removeListener"&&this.removeAllListeners(z);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(T=I[x],typeof T=="function")this.removeListener(x,T);else if(T!==void 0)for(F=T.length-1;F>=0;F--)this.removeListener(x,T[F]);return this};function _(S,x,T){var I=S._events;if(I===void 0)return[];var F=I[x];return F===void 0?[]:typeof F=="function"?T?[F.listener||F]:[F]:T?E(F):b(F,F.length)}s.prototype.listeners=function(x){return _(this,x,!0)},s.prototype.rawListeners=function(x){return _(this,x,!1)},s.listenerCount=function(S,x){return typeof S.listenerCount=="function"?S.listenerCount(x
7):k.call(S,x)},s.prototype.listenerCount=k;function k(S){var x=this._events;if(x!==void 0){var T=x[S];if(typeof T=="function")return 1;if(T!==void 0)return T.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function b(S,x){for(var T=new Array(x),I=0;I<x;++I)T[I]=S[I];return T}function v(S,x){for(;x+1<S.length;x++)S[x]=S[x+1];S.pop()}function E(S){for(var x=new Array(S.length),T=0;T<x.length;++T)x[T]=S[T].listener||S[T];return x}function C(S,x){return new Promise(function(T,I){function F(z){S.removeListener(x,$),I(z)}function $(){typeof S.removeListener=="function"&&S.removeListener("error",F),T([].slice.call(arguments))}j(S,x,$,{once:!0}),x!=="error"&&O(S,F,{once:!0})})}function O(S,x,T){typeof S.on=="function"&&j(S,"error",x,T)}function j(S,x,T,I){if(typeof S.on=="function")I.once?S.once(x,T):S.on(x,T);else if(typeof S.addEventListener=="function")S.addEventListener(x,function F($){I.once&&S.removeEventListener(x,F),T($)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof S)}return rr.exports}var nu=nm();const rm=Yd(nu),De=[];for(let n=0;n<256;++n)De.push((n+256).toString(16).slice(1));function im(n,e=0){return(De[n[e+0]]+De[n[e+1]]+De[n[e+2]]+De[n[e+3]]+"-"+De[n[e+4]]+De[n[e+5]]+"-"+De[n[e+6]]+De[n[e+7]]+"-"+De[n[e+8]]+De[n[e+9]]+"-"+De[n[e+10]]+De[n[e+11]]+De[n[e+12]]+De[n[e+13]]+De[n[e+14]]+De[n[e+15]]).toLowerCase()}let Si;const sm=new Uint8Array(16);function am(){if(!Si){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Si=crypto.getRandomValues.bind(crypto)}return Si(sm)}const om=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ha={randomUUID:om};function cm(n,e,t){if(Ha.randomUUID&&!e&&!n)return Ha.randomUUID();n=n||{};const r=n.random??n.rng?.()??am();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(t=t||0,t<0||t+16>e.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[t+i]=r[i];return e}return im(r)}const lm={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},ru={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},J={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},Ue={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},Bt={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"};class M{static getFirstMatch(e,t){const r=t.match(e);return r&&r.length>0&&r[1]||""}static getSecondMatch(e,t){const r=t.match(e);return r&&r.length>1&&r[2]||""}static matchAndReturnConst(e,t,r){if(e.test(t))return r}
vendor: 22,318 bytes, line 7
7static getWindowsVersionName(e){switch(e){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(e){const t=e.split(".").splice(0,2).map(s=>parseInt(s,10)||0);t.push(0);const r=t[0],i=t[1];if(r===10)switch(i){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(r){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}}static getAndroidVersionName(e){const t=e.split(".").splice(0,2).map(r=>parseInt(r,10)||0);if(t.push(0),!(t[0]===1&&t[1]<5)){if(t[0]===1&&t[1]<6)return"Cupcake";if(t[0]===1&&t[1]>=6)return"Donut";if(t[0]===2&&t[1]<2)return"Eclair";if(t[0]===2&&t[1]===2)return"Froyo";if(t[0]===2&&t[1]>2)return"Gingerbread";if(t[0]===3)return"Honeycomb";if(t[0]===4&&t[1]<1)return"Ice Cream Sandwich";if(t[0]===4&&t[1]<4)return"Jelly Bean";if(t[0]===4&&t[1]>=4)return"KitKat";if(t[0]===5)return"Lollipop";if(t[0]===6)return"Marshmallow";if(t[0]===7)return"Nougat";if(t[0]===8)return"Oreo";if(t[0]===9)return"Pie"}}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,t,r=!1){const i=M.getVersionPrecision(e),s=M.getVersionPrecision(t);let a=Math.max(i,s),o=0;const l=M.map([e,t],u=>{const f=a-M.getVersionPrecision(u),g=u+new Array(f+1).join(".0");return M.map(g.split("."),_=>new Array(20-_.length).join("0")+_).reverse()});for(r&&(o=a-Math.min(i,s)),a-=1;a>=o;){if(l[0][a]>l[1][a])return 1;if(l[0][a]===l[1][a]){if(a===o)return 0;a-=1}else if(l[0][a]<l[1][a])return-1}}static map(e,t){const r=[];let i;if(Array.prototype.map)return Array.prototype.map.call(e,t);for(i=0;i<e.length;i+=1)r.push(t(e[i]));return r}static find(e,t){let r,i;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,i=e.length;r<i;r+=1){const s=e[r];if(t(s,r))return s}}static assign(e,...t){const r=e;let i,s;if(Object.assign)return Object.assign(e,...t);for(i=0,s=t.length;i<s;i+=1){const a=t[i];typeof a=="object"&&a!==null&&Object.keys(a).forEach(l=>{r[l]=a[l]})}return e}static getBrowserAlias(e){return lm[e]}static getBrowserTypeByAlias(e){return ru[e]||""}}const H=/version\/(\d+(\.?_?\d+)+)/i,um=[{test:[/gptbot/i],describe(n){const e={name:"GPTBot"},t=M.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/chatgpt-user/i],describe(n){const e={name:"ChatGPT-User"},t=M.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/oai-searchbot/i],describe(n){const e={name:"OAI-SearchBot"},t=M.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(n){const e={name:"ClaudeBot"},t=M.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/omgilibot/i,/webzio-extended/i],describe(n){const e={name:"Omgilibot"},t=M.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/diffbot/i],describe(n){const e={name:"Diffbot"},t=M.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/perplexitybot/i],describe(n){const e={name:"PerplexityBot"},t=M.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/perplexity-user/i],describe(n){const e={name:"Perplexity-User"},t=M.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/youbot/i],describe(n){const e={name:"YouBot"},t=M.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/meta-webindexer/i],describe(n){const e={name:"Meta-WebIndexer"},t=M.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/meta-externalads/i],describe(n){const e={name:"Meta-ExternalAds"},t=M.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/meta-externalagent/i],describe(n){const e={name:"Meta-ExternalAgent"},t=M.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/meta-externalfetcher/i],describe(n){const e={name:"Meta-ExternalFetcher"},t=M.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/googlebot/i],describe(n){const e={name:"Googlebot"},t=M.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/linespider/i],describe(n){const e={name:"Linespider"},t=M.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/amazonbot/i],describe(n){const e={name:"AmazonBot"},t=M.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/bingbot/i],describe(n){const e={name:"BingCrawler"},t=M.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/baiduspider/i],describe(n){const e={name:"BaiduSpider"},t=M.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/duckduckbot/i],describe(n){const e={name:"DuckDuckBot"},t=M.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/ia_archiver/i],describe(n){const e={name:"InternetArchiveCrawler"},t=M.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe(n){const e={name:"SlackBot"},t=M.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/yahoo!?[\s/]*slurp/i],describe(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe(){return{name:"PingdomBot"}}},{test:[/opera/i],describe(n){const e={name:"Opera"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/opr\/|opios/i],describe(n){const e={name:"Opera"},t=M.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/SamsungBrowser/i],describe(n){const e={name:"Samsung Internet for Android"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/Whale/i],describe(n){const e={name:"NAVER Whale Browser"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/PaleMoon/i],describe(n){const e={name:"Pale Moon"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/MZBrowser/i],describe(n){const e={name:"MZ Browser"},t=M.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/focus/i],describe(n){const e={name:"Focus"},t=M.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/swing/i],describe(n){const e={name:"Swing"},t=M.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/coast/i],describe(n){const e={name:"Opera Coast"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(n){const e={name:"Opera Touch"},t=M.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/yabrowser/i],describe(n){const e={name:"Yandex Browser"},t=M.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/ucbrowser/i],describe(n){const e={name:"UC Browser"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/Maxthon|mxios/i],describe(n){const e={name:"Maxthon"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/epiphany/i],describe(n){const e={name:"Epiphany"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/puffin/i],describe(n){const e={name:"Puffin"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/sleipnir/i],describe(n){const e={name:"Sleipnir"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/k-meleon/i],describe(n){const e={name:"K-Meleon"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/micromessenger/i],describe(n){const e={name:"WeChat"},t=M.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/qqbrowser/i],describe(n){const e={name:/qqbrowserlite/i.test(n)?"QQ Browser Lite":"QQ Browser"},t=M.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/msie|trident/i],describe(n){const e={name:"Internet Explorer"},t=M.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/\sedg\//i],describe(n){const e={name:"Microsoft Edge"},t=M.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/edg([ea]|ios)/i],describe(n){const e={name:"Microsoft Edge"},t=M.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/vivaldi/i],describe(n){const e={name:"Vivaldi"},t=M.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/seamonkey/i],describe(n){const e={name:"SeaMonkey"},t=M.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/sailfish/i],describe(n){const e={name:"Sailfish"},t=M.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,n);return t&&(e.version=t),e}},{test:[/silk/i],describe(n){const e={name:"Amazon Silk"},t=M.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/phantom/i],describe(n){const e={name:"PhantomJS"},t=M.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/slimerjs/i],describe(n){const e={name:"SlimerJS"},t=M.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(n){const e={name:"BlackBerry"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/(web|hpw)[o0]s/i],describe(n){const e={name:"WebOS Browser"},t=M.getFirstMatch(H,n)||M.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/bada/i],describe(n){const e={name:"Bada"},t=M.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/tizen/i],describe(n){const e={name:"Tizen"},t=M.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/qupzilla/i],describe(n){const e={name:"QupZilla"},t=M.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/librewolf/i],describe(n){const e={name:"LibreWolf"},t=M.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/firefox|iceweasel|fxios/i],describe(n){const e={name:"Firefox"},t=M.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/electron/i],describe(n){const e={name:"Electron"},t=M.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe(n){const e={name:"Sogou Browser"},t=M.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,n),r=M.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),i=M.getFirstMatch(/se ([\d.]+)x/i,n),s=t||r||i;return s&&(e.version=s),e}},{test:[/MiuiBrowser/i],describe(n){const e={name:"Miui"},t=M.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test(n){return n.hasBrand("DuckDuckGo")?!0:n.test(/\sDdg\/[\d.]+$/i)},describe(n,e){const t={name:"DuckDuckGo"};if(e){const i=e.getBrandVersion("DuckDuckGo");if(i)return t.version=i,t}const r=M.getFirstMatch(/\sDdg\/([\d.]+)$/i,n);return r&&(t.version=r),t}},{test(n){return n.hasBrand("Brave")},describe(n,e){const t={name:"Brave"};if(e){const r=e.getBrandVersion("Brave");if(r)return t.version=r,t}return t}},{test:[/chromium/i],describe(n){const e={name:"Chromium"},t=M.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,n)||M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/chrome|crios|crmo/i],describe(n){const e={name:"Chrome"},t=M.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/GSA/i],describe(n){const e={name:"Google Search"},t=M.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test(n){const e=!n.test(/like android/i),t=n.test(/android/i);return e&&t},describe(n){const e={name:"Android Browser"},t=M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/playstation 4/i],describe(n){const e={name:"PlayStation 4"},t=M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/safari|applewebkit/i],describe(n){const e={name:"Safari"},t=M.getFirstMatch(H,n);return t&&(e.version=t),e}},{test:[/.*/i],describe(n){const e=/^(.*)\/(.*) /,t=/^(.*)\/(.*)[ \t]\((.*)/,i=n.search("\\(")!==-1?t:e;return{name:M.getFirstMatch(i,n),version:M.getSecondMatch(i,n)}}}],dm=[{test:[/Roku\/DVP/],describe(n){const e=M.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,n);return{name:Ue.Roku,version:e}}},{test:[/windows phone/i],describe(n){const e=M.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,n);return{name:Ue.WindowsPhone,version:e}}},{test:[/windows /i],describe(n){const e=M.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,n),t=M.getWindowsVersionName(e);return{name:Ue.Windows,version:e,versionName:t}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(n){const e={name:Ue.iOS},t=M.getSecondMatch(/(Version\/)(\d[\d.]+)/,n);return t&&(e.version=t),e}},{test:[/macintosh/i],describe(n){const e=M.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,n).replace(/[_\s]/g,"."),t=M.getMacOSVersionName(e),r={name:Ue.MacOS,version:e};return t&&(r.versionName=t),r}},{test:[/(ipod|iphone|ipad)/i],describe(n){const e=M.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,n).replace(/[_\s]/g,".");return{name:Ue.iOS,version:e}}},{test:[/OpenHarmony/i],describe(n){const e=M.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,n);return{name:Ue.HarmonyOS,version:e}}},{test(n){const e=!n.test(/like android/i),t=n.test(/android/i);return e&&t},describe(n){const e=M.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,n),t=M.getAndroidVersionName(e),r={name:Ue.Android,version:e};return t&&(r.versionName=t),r}},{test:[/(web|hpw)[o0]s/i],describe(n){const e=M.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,n),t={name:Ue.WebOS};return e&&e.length&&(t.version=e),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(n){const e=M.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,n)||M.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,n)||M.getFirstMatch(/\bbb(\d+)/i,n);return{name:Ue.BlackBerry,version:e}}},{test:[/bada/i],describe(n){const e=M.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,n);return{name:Ue.Bada,version:e}}},{test:[/tizen/i],describe(n){const e=M.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,n);return{name:Ue.Tizen,version:e}}},{test:[/linux/i],describe(){return{name:Ue.Linux}}},{test:[/CrOS/],describe(){return{name:Ue.ChromeOS}}},{test:[/PlayStation 4/],describe(n){const e=M.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,n);return{name:Ue.PlayStation4,version:e}}}],hm=[{test:[/googlebot/i],describe(){return{type:J.bot,vendor:"Google"}}},{test:[/linespider/i],describe(){return{type:J.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe(){return{type:J.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe(){return{type:J.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe(){return{type:J.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe(){return{type:J.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe(){return{type:J.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe(){return{type:J.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe(){return{type:J.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(){return{type:J.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe(){return{type:J.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe(){return{type:J.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe(){return{type:J.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe(){return{type:J.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe(){return{type:J.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe(){return{type:J.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe(){return{type:J.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe(){return{type:J.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe(){return{type:J.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe(){return{type:J.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe(){return{type:J.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe(){return{type:J.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe(){return{type:J.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe(){return{type:J.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe(){return{type:J.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe(n){const e=M.getFirstMatch(/(can-l01)/i,n)&&"Nova",t={type:J.mobile,vendor:"Huawei"};return e&&(t.model=e),t}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:J.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:J.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:J.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:J.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:J.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:J.tablet}}},{test(n){const e=n.test(/ipod|iphone/i),t=n.test(/like (ipod|iphone)/i);return e&&!t},describe(n){const e=M.getFirstMatch(/(ipod|iphone)/i,n);return{type:J.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:J.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe(n){const e=M.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,n),t={type:J.mobile,vendor:"Nokia"};return e&&(t.model=e),t}},{test:[/[^-]mobi/i],describe(){return{type:J.mobile}}},{test(n){return n.getBrowserName(!0)==="blackberry"},describe(){return{type:J.mobile,vendor:"BlackBerry"}}},{test(n){return n.getBrowserName(!0)==="bada"},describe(){return{type:J.mobile}}},{test(n){return n.getBrowserName()==="windows phone"},describe(){return{type:J.mobile,vendor:"Microsoft"}}},{test(n){const e=Number(String(n.getOSVersion()).split(".")[0]);return n.getOSName(!0)==="android"&&e>=3},describe(){return{type:J.tablet}}},{test(n){return n.getOSName(!0)==="android"},describe(){return{type:J.mobile}}},{test:[/smart-?tv|smarttv/i],describe(){return{type:J.tv}}},{test:[/netcast/i],describe(){return{type:J.tv}}},{test(n){return n.getOSName(!0)==="macos"},describe(){return{type:J.desktop,vendor:"Apple"}}},{test(n){return n.getOSName(!0)==="windows"},describe(){return{type:J.desktop}}},{test(n){return n.getOSName(!0)==="linux"},describe(){return{type:J.desktop}}},{test(n){return n.getOSName(!0)==="playstation 4"},describe(){return{type:J.tv}}},{test(n){return n.getOSName(!0)==="roku"},describe(){return{type:J.tv}}}],fm=[{test(n){return n.getBrowserName(!0)==="microsoft edge"},describe(n){if(/\sedg\//i.test(n))return{name:Bt.Blink};const t=M.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,n);return{name:Bt.EdgeHTML,version:t}}},{test:[/trident/i],describe(n){const e={name:Bt.Trident},t=M.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test(n){return n.test(/presto/i)},describe(n){const e={name:Bt.Presto},t=M.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test(n){const e=n.test(/gecko/i),t=n.test(/like gecko/i);return e&&!t},describe(n){const e={name:Bt.Gecko},t=M.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Bt.Blink}}},{test:[/(apple)?webkit/i],describe(n){const e={name:Bt.WebKit},t=M.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}}];class Ka{constructor(e,t=!1,r=null){if(e==null||e==="")throw new Error("UserAgent parameter can't be empty");this._ua=e;let i=!1;typeof t=="boolean"?(i=t,this._hints=r):t!=null&&typeof t=="object"?this._hints=t:this._hints=null,this.parsedResult={},i!==!0&&this.parse()}getHints(){return this._hints}hasBrand(e){if(!this._hints||!Array.isArray(this._hints.brands))return!1;const t=e.toLowerCase();return this._hints.brands.some(r=>r.brand&&r.brand.toLowerCase()===t)}getBrandVersion(e){if(!this._hints||!Array.isArray(this._hints.brands))return;const t=e.toLowerCase(),r=this._hints.brands.find(i=>i.brand&&i.brand.toLowerCase()===t);return r?r.version:void 0}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=M.find(um,t=>{if(typeof t.test=="function")return t.test(this);if(Array.isArray(t.test))return t.test.some(r=>this.test(r));
7throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.browser=e.describe(this.getUA(),this)),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const e=M.find(dm,t=>{if(typeof t.test=="function")return t.test(this);if(Array.isArray(t.test))return t.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.os=e.describe(this.getUA())),this.parsedResult.os}getOSName(e){const{name:t}=this.getOS();return e?String(t).toLowerCase()||"":t||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:t}=this.getPlatform();return e?String(t).toLowerCase()||"":t||""}parsePlatform(){this.parsedResult.platform={};const e=M.find(hm,t=>{if(typeof t.test=="function")return t.test(this);if(Array.isArray(t.test))return t.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.platform=e.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const e=M.find(fm,t=>{if(typeof t.test=="function")return t.test(this);if(Array.isArray(t.test))return t.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.engine=e.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return M.assign({},this.parsedResult)}satisfies(e){const t={};let r=0;const i={};let s=0;if(Object.keys(e).forEach(o=>{const l=e[o];typeof l=="string"?(i[o]=l,s+=1):typeof l=="object"&&(t[o]=l,r+=1)}),r>0){const o=Object.keys(t),l=M.find(o,f=>this.isOS(f));if(l){const f=this.satisfies(t[l]);if(f!==void 0)return f}const u=M.find(o,f=>this.isPlatform(f));if(u){const f=this.satisfies(t[u]);if(f!==void 0)return f}}if(s>0){const o=Object.keys(i),l=M.find(o,u=>this.isBrowser(u,!0));if(l!==void 0)return this.compareVersion(i[l])}}isBrowser(e,t=!1){const r=this.getBrowserName().toLowerCase();let i=e.toLowerCase();const s=M.getBrowserTypeByAlias(i);return t&&s&&(i=s.toLowerCase()),i===r}compareVersion(e){let t=[0],r=e,i=!1;const s=this.getBrowserVersion();if(typeof s=="string")return e[0]===">"||e[0]==="<"?(r=e.substr(1),e[1]==="="?(i=!0,r=e.substr(2)):t=[],e[0]===">"?t.push(1):t.push(-1)):e[0]==="="?r=e.substr(1):e[0]==="~"&&(i=!0,r=e.substr(1)),t.indexOf(M.compareVersions(s,r,i))>-1}isOS(e){return this.getOSName(!0)===String(e).toLowerCase()}isPlatform(e){return this.getPlatformType(!0)===String(e).toLowerCase()}isEngine(e){return this.getEngineName(!0)===String(e).toLowerCase()}is(e,t=!1){return this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some(t=>this.is(t))}}class pm{static getParser(e,t=!1,r=null){if(typeof e!="string")throw new Error("UserAgent should be a string");return new Ka(e,t,r)}static parse(e,t=null){return new Ka(e,t).getResult()}static get BROWSER_MAP(){return ru}static get ENGINE_MAP(){return Bt}static get OS_MAP(){return Ue}static get PLATFORMS_MAP(){return J}}function ot(n,e){return Object.keys(e).forEach(function(t){t==="default"||t==="__esModule"||Object.prototype.hasOwnProperty.call(n,t)||Object.defineProperty(n,t,{enumerable:!0,get:function(){return e[t]}})}),n}function ue(n,e,t,r){Object.defineProperty(n,e,{get:t,set:r,enumerable:!0,configurable:!0})}function mm(n){return n&&n.__esModule?n.default:n}var hn={},iu={};ue(iu,"A11ySnapshotStreamer",()=>uu);const gm=10,jr=200,xi=50,vm=100,bm=20,Ya=2e3,Cn=new WeakMap,Xa=typeof WeakRef>"u"?void 0:WeakRef,xr=new Map;let ym=0;function Ir(n){const e=Cn.get(n);if(e)return e;const t=`e${++ym}`;return Cn.set(n,t),xr.set(t,Xa?new Xa(n):n),t}function wm(n){const e=xr.get(n);if(!e)return null;const t="deref"in e?e.deref():e;return!t||!t.isConnected?(xr.delete(n),null):t}function _m(n){return Cn.get(n)??null}const su=new Set(["script","style","link","meta","noscript","template"]);function km(n){if(su.has(n.tagName.toLowerCase())||n.getAttribute("aria-hidden")==="true"||n.hasAttribute("data-a11y-exclude")||n.hidden)return!0;
7if(n instanceof HTMLElement&&n.offsetParent===null&&n.tagName!=="BODY"){const e=window.getComputedStyle(n);if(e.display==="none"||e.visibility==="hidden")return!0}return!1}const Sm=new Set(["button","link","checkbox","radio","textbox","combobox","switch","menuitem","tab"]),au=new Set([...Sm,"heading","img"]);function xm(n){return!!(n.hasAttribute("aria-label")||n.hasAttribute("aria-labelledby")||(n.textContent??"").trim().length>0)}function Em(n){const e=n.getAttribute("role");if(e)return e;const t=n.tagName.toLowerCase();switch(t){case"main":case"nav":case"header":case"aside":case"footer":return t;case"article":case"section":return xm(n)?"region":null;case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":return"heading";case"a":return n.hasAttribute("href")?"link":null;case"button":return"button";case"input":{const r=n.type;return r==="checkbox"?"checkbox":r==="radio"?"radio":r==="submit"||r==="button"||r==="reset"?"button":r==="hidden"?null:"textbox"}case"select":return"combobox";case"textarea":return"textbox";case"label":return null;case"img":return n.getAttribute("alt")!==null?"img":null;case"p":return"paragraph";case"ul":case"ol":return"list";case"li":return"listitem";case"table":return"table";case"tr":return"row";case"th":return"columnheader";case"td":return"cell";default:return n.hasAttribute("aria-label")||n.hasAttribute("aria-labelledby")||n.hasAttribute("tabindex")?"generic":null}}function ou(n){return n.replace(/\s+/g," ").trim()}function xt(n,e=vm){const t=ou(n);return t.length<=e?t:t.slice(0,e-1)+"…"}function Cm(n){const e=n.getAttribute("aria-labelledby");if(!e)return;const t=[];for(const i of e.split(/\s+/)){if(!i)continue;const s=n.ownerDocument.getElementById(i);s&&t.push(Rs(s))}return t.filter(Boolean).join(" ")||void 0}function Rs(n){const e=[];for(let t=0;t<n.childNodes.length;t++){const r=n.childNodes[t];if(r.nodeType===3){const i=(r.textContent??"").trim();i&&e.push(i)}else if(r.nodeType===1){const i=r;if(su.has(i.tagName.toLowerCase())||i.getAttribute("aria-hidden")==="true")continue;const s=Rs(i);s&&e.push(s)}}return e.join(" ").replace(/\s+/g," ").trim()}function Mm(n,e){const t=n.getAttribute("aria-label");if(t)return xt(t);const r=Cm(n);if(r)return xt(r);const i=n.tagName.toLowerCase();if(i==="input"||i==="textarea"||i==="select"){const s=n.getAttribute("id");if(s){const l=n.ownerDocument.getElementsByTagName("label");for(let u=0;u<l.length;u++)if(l[u].htmlFor===s&&l[u].textContent)return xt(l[u].textContent??"")}const a=n.closest("label");if(a?.textContent)return xt(a.textContent);const o=n.getAttribute("placeholder");return o?xt(o):void 0}if(i==="img"){const s=n.getAttribute("alt");return s?xt(s):void 0}if(au.has(e)||e==="paragraph"){const s=Rs(n);return s?xt(s):void 0}}function Am(n){if(n instanceof HTMLInputElement)return n.type==="password"||n.type==="checkbox"||n.type==="radio"||n.type==="hidden"?void 0:n.value||void 0;if(n instanceof HTMLTextAreaElement)return n.value||void 0;if(n instanceof HTMLSelectElement){const t=n.selectedOptions[0]?.text?.trim();return t||n.value||void 0}}function Tm(n){const e=[];return n.ownerDocument.activeElement===n&&e.push("focused"),n.getAttribute("aria-expanded")==="true"&&e.push("expanded"),n.getAttribute("aria-selected")==="true"&&e.push("selected"),(n.hasAttribute("disabled")||n.getAttribute("aria-disabled")==="true")&&e.push("disabled"),n.getAttribute("aria-checked")==="true"&&e.push("checked"),n instanceof HTMLInputElement&&(n.type==="checkbox"||n.type==="radio")&&n.checked&&(e.includes("checked")||e.push("checked")),e}function Nm(n){const e=n.getBoundingClientRect();if(e.width===0&&e.height===0)return!0;const t=window.innerWidth||document.documentElement.clientWidth,r=window.innerHeight||document.documentElement.clientHeight;return e.bottom<=0||e.top>=r||e.right<=0||e.left>=t}function Om(n,e){if(e!=="heading")return;const r=n.tagName.toLowerCase().match(/^h([1-6])$/);if(r)return parseInt(r[1],10);const i=n.getAttribute("aria-level");if(i){const s=parseInt(i,10);if(!Number.isNaN(s))return s}}function Qa(n,e){const t=n.getAttribute(e);if(!t)return;const r=parseInt(t,10);if(!(Number.isNaN(r)||r<0))return r}function Pm(n,e,t,r,i=!1){if(km(n))return[];if(t.count>=jr)return[];if(e>gm)return t.count++,[{ref:Ir(n),role:"ellipsis",name:"<truncated: max depth>"}];const s=Em(n);if(s===null)return Zi(n,e,t,r,{skipTextNodes:i});t.count++;const a={ref:Ir(n),role:s},o=Mm(n,s);o&&(a.name=o);const l=Am(n);l!==void 0&&(a.value=l);const u=Tm(n);r.trackViewport&&Nm(n)&&u.push("offscreen"),u.length&&(a.state=u);const f=Om(n,s);f!==void 0&&(a.level=f);const g=Qa(n,"aria-colcount");g!==void 0&&(a.colcount=g);const _=Qa(n,"aria-rowcount");if(_!==void 0&&(a.rowcount=_),au.has(s)){if(n instanceof HTMLSelectElement){const k=jm(n,t,a.ref);k.length>0&&(a.children=k)}}
7else{const k=s==="paragraph",b=Zi(n,e+1,t,r,{skipTextNodes:k});if(b.length>0)if(b.length>xi){const v=b.slice(0,xi);v.push({ref:`${a.ref}.more`,role:"ellipsis",name:`${b.length-xi} more`}),a.children=v}else a.children=b}return[a]}function jm(n,e,t){const r=[],i=n.options;let s=0;for(let a=0;a<i.length&&!(e.count>=jr);a++){const o=i[a];if(o.hidden||o.getAttribute("aria-hidden")==="true")continue;if(s>=bm){e.count++,r.push({ref:`${t}.more`,role:"ellipsis",name:`${i.length-s} more`});break}e.count++,s++;const l=(o.text||o.value||"").trim(),u={ref:Ir(o),role:"option",name:xt(l)},f=[];o.selected&&f.push("selected"),o.disabled&&f.push("disabled"),f.length&&(u.state=f),r.push(u)}return r}function Zi(n,e,t,r,i={}){const s=[];for(let a=0;a<n.childNodes.length;a++){const o=n.childNodes[a];if(o.nodeType===3){if(i.skipTextNodes)continue;const l=ou(o.textContent??"");if(l){if(t.count>=jr)break;t.count++,s.push({ref:"",role:"text",name:xt(l)})}}else if(o.nodeType===1){const l=Pm(o,e,t,r,i.skipTextNodes);for(const u of l)s.push(u);if(t.count>=jr)break}}return s}function Im(n){let e=n;for(;e;){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("data-a11y-exclude"))return null;if(Cn.has(e))return e;e=e.parentElement}return null}function Za(n){return n.length<=Ya?n:n.slice(0,Ya-1)+"…"}function cu(){if(typeof document>"u")return null;const n=document.activeElement;if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement){const o=n.selectionStart,l=n.selectionEnd;if(o!==null&&l!==null&&o!==l){const u=Cn.get(n);if(!u)return null;const f=n.value.slice(o,l);return f?{ref:u,text:Za(f),start_offset:o,end_offset:l}:null}}const e=document.getSelection();if(!e||e.rangeCount===0||e.isCollapsed)return null;const t=e.toString();if(!t)return null;let i=e.getRangeAt(0).commonAncestorContainer;for(;i&&i.nodeType!==1;)i=i.parentNode;const s=Im(i);if(!s)return null;const a=Cn.get(s);return a?{ref:a,text:Za(t)}:null}function lu(n,e={}){const t=n??(typeof document<"u"?document.body:null);if(!t)return{root:{ref:"e0",role:"generic"},captured_at:Date.now()};const r={trackViewport:e.trackViewport??!0},s=Zi(t,0,{count:0},r),a=cu();return{root:{ref:Ir(t),role:"generic",...s.length>0?{children:s}:{}},captured_at:Date.now(),...a?{selection:a}:{}}}class uu{constructor(e,t={}){this.running=!1,this.emitSnapshot=e,this.debounceMs=t.debounceMs??300,this.trackViewport=t.trackViewport??!0,this.logSnapshots=t.logSnapshots??!1}start(){this.running||typeof document>"u"||(this.running=!0,this.schedule(),this.observer=new MutationObserver(()=>this.schedule()),this.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["role","aria-label","aria-labelledby","aria-expanded","aria-selected","aria-checked","aria-disabled","aria-level","aria-hidden","aria-colcount","aria-rowcount","data-a11y-exclude","disabled","hidden","tabindex","href"]}),this.focusHandler=()=>this.schedule(),document.addEventListener("focusin",this.focusHandler),document.addEventListener("focusout",this.focusHandler),this.scrollEndHandler=()=>this.schedule(),window.addEventListener("scrollend",this.scrollEndHandler,{capture:!0}),this.resizeHandler=()=>this.schedule(),window.addEventListener("resize",this.resizeHandler),this.visibilityHandler=()=>{document.visibilityState==="visible"&&this.schedule()},document.addEventListener("visibilitychange",this.visibilityHandler),this.selectionHandler=()=>this.schedule(),document.addEventListener("selectionchange",this.selectionHandler),this.formHandler=()=>this.schedule(),document.addEventListener("input",this.formHandler,{capture:!0}),document.addEventListener("change",this.formHandler,{capture:!0}))}stop(){this.running&&(this.running=!1,this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0),typeof document<"u"&&(this.focusHandler&&(document.removeEventListener("focusin",this.focusHandler),document.removeEventListener("focusout",this.focusHandler)),this.visibilityHandler&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.selectionHandler&&document.removeEventListener("selectionchange",this.selectionHandler),this.formHandler&&(document.removeEventListener("input",this.formHandler,{capture:!0}),document.removeEventListener("change",this.formHandler,{capture:!0}))),typeof window<"u"&&(this.scrollEndHandler&&window.removeEventListener("scrollend",this.scrollEndHandler,{capture:!0}),this.resizeHandler&&window.removeEventListener("resize",this.resizeHandler)),this.focusHandler=void 0,this.scrollEndHandler=void 0,this.resizeHandler=void 0,this.visibilityHandler=void 0,this.selectionHandler=void 0,this.formHandler=void 0)}schedule(){this.running&&(this.timer!==void 0&&clearTimeout(this.timer),this.timer=setTimeout(()=>
7this.emit(),this.debounceMs))}emit(){if(this.timer=void 0,!!this.running)try{const e=lu(void 0,{trackViewport:this.trackViewport});if(this.emitSnapshot(e),this.logSnapshots){const t=du(e.root),r=Math.round(JSON.stringify(e).length/4);console.groupCollapsed(`[A11ySnapshotStreamer] emit: ${t} nodes, ~${r} tokens`),console.log("snapshot:",e),console.groupEnd()}}catch{}}}function du(n){let e=1;const t=n.children;if(t)for(const r of t)e+=du(r);return e}var hu={};ue(hu,"PipecatClient",()=>ct);var Mn={};Mn=JSON.parse('{"name":"@pipecat-ai/client-js","version":"1.12.0","license":"BSD-2-Clause","main":"dist/index.js","module":"dist/index.module.js","types":"dist/index.d.ts","source":"index.ts","repository":{"type":"git","url":"git+https://github.com/pipecat-ai/pipecat-client-web.git"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.module.js","require":"./dist/index.js"}},"files":["dist","package.json","README.md"],"scripts":{"build":"jest --silent --passWithNoTests && parcel build --no-cache","dev":"parcel watch","lint":"eslint . --report-unused-disable-directives --max-warnings 0","test":"jest"},"jest":{"preset":"ts-jest","testEnvironment":"jsdom","setupFilesAfterEnv":["<rootDir>/tests/jest.setup.ts"]},"devDependencies":{"@jest/globals":"^29.7.0","@types/clone-deep":"^4.0.4","@types/jest":"^29.5.12","eslint":"^9.11.1","eslint-config-prettier":"^9.1.0","eslint-plugin-simple-import-sort":"^12.1.1","jest":"^29.7.0","jest-environment-jsdom":"^30.0.2","ts-jest":"^29.2.5","whatwg-fetch":"^3.6.20"},"dependencies":{"@types/events":"^3.0.3","bowser":"^2.11.0","clone-deep":"^4.0.1","events":"^3.3.0","typed-emitter":"^2.1.0","uuid":"^11.1.1"}}');var jt={};ue(jt,"findElementByRef",()=>wm);ue(jt,"findRefForElement",()=>_m);ue(jt,"serializeSelection",()=>cu);ue(jt,"snapshotDocument",()=>lu);var fu={};ue(fu,"TransportStateEnum",()=>es);var es;(function(n){n.DISCONNECTED="disconnected",n.INITIALIZING="initializing",n.INITIALIZED="initialized",n.AUTHENTICATING="authenticating",n.AUTHENTICATED="authenticated",n.CONNECTING="connecting",n.CONNECTED="connected",n.READY="ready",n.DISCONNECTING="disconnecting",n.ERROR="error"})(es||(es={}));var vt={};ue(vt,"RTVIError",()=>He);ue(vt,"ConnectionTimeoutError",()=>Rm);ue(vt,"StartBotError",()=>pu);ue(vt,"TransportStartError",()=>ts);ue(vt,"InvalidTransportParamsError",()=>Lm);ue(vt,"BotNotReadyError",()=>mu);ue(vt,"BotAlreadyStartedError",()=>gu);ue(vt,"UnsupportedFeatureError",()=>rn);ue(vt,"MessageTooLargeError",()=>vu);ue(vt,"DeviceError",()=>Et);class He extends Error{constructor(e,t){super(e),this.status=t}}class Rm extends He{constructor(e){super(e??"Bot did not enter ready state within the specified timeout period.")}}class pu extends He{constructor(e,t){super(e??"Failed to connect / invalid auth bundle from base url",t??500),this.error="invalid-request-error"}}class ts extends He{constructor(e){super(e??"Unable to connect to transport")}}class Lm extends He{constructor(e){super(e??"Invalid transport connection parameters")}}class mu extends He{constructor(e){super(e??"Attempt to call action on transport when not in 'ready' state.")}}class gu extends He{constructor(e){super(e??"Pipecat client has already been started. Please call disconnect() before starting again.")}}class rn extends He{constructor(e,t,r){let i=`${e} not supported${r?`: ${r}`:""}`;t&&(i=`${t} does not support ${e}${r?`: ${r}`:""}`),super(i),this.feature=e}}class vu extends He{constructor(e){super(e??"Message size exceeds the maximum allowed limit for transport.")}}
7class Et extends He{constructor(e,t,r,i){super(r??`Device error for ${e.join(", ")}: ${t}`),this.devices=e,this.type=t,this.details=i}}var bu={};ue(bu,"RTVIEvent",()=>q);var q;(function(n){n.Connected="connected",n.Disconnected="disconnected",n.TransportStateChanged="transportStateChanged",n.BotStarted="botStarted",n.BotConnected="botConnected",n.BotReady="botReady",n.BotDisconnected="botDisconnected",n.Error="error",n.ServerMessage="serverMessage",n.ServerResponse="serverResponse",n.MessageError="messageError",n.UICommand="uiCommand",n.UIJobGroup="uiJobGroup",n.Metrics="metrics",n.BotStartedSpeaking="botStartedSpeaking",n.BotStoppedSpeaking="botStoppedSpeaking",n.UserStartedSpeaking="userStartedSpeaking",n.UserStoppedSpeaking="userStoppedSpeaking",n.UserMuteStarted="userMuteStarted",n.UserMuteStopped="userMuteStopped",n.UserTranscript="userTranscript",n.BotOutput="botOutput",n.BotTranscript="botTranscript",n.UserLlmText="userLlmText",n.BotLlmText="botLlmText",n.BotLlmStarted="botLlmStarted",n.BotLlmStopped="botLlmStopped",n.LLMFunctionCall="llmFunctionCall",n.LLMFunctionCallStarted="llmFunctionCallStarted",n.LLMFunctionCallInProgress="llmFunctionCallInProgress",n.LLMFunctionCallStopped="llmFunctionCallStopped",n.BotLlmSearchResponse="botLlmSearchResponse",n.BotTtsText="botTtsText",n.BotTtsStarted="botTtsStarted",n.BotTtsStopped="botTtsStopped",n.ParticipantConnected="participantConnected",n.ParticipantLeft="participantLeft",n.TrackStarted="trackStarted",n.TrackStopped="trackStopped",n.ScreenTrackStarted="screenTrackStarted",n.ScreenTrackStopped="screenTrackStopped",n.ScreenShareError="screenShareError",n.LocalAudioLevel="localAudioLevel",n.RemoteAudioLevel="remoteAudioLevel",n.AvailableCamsUpdated="availableCamsUpdated",n.AvailableMicsUpdated="availableMicsUpdated",n.AvailableSpeakersUpdated="availableSpeakersUpdated",n.CamUpdated="camUpdated",n.MicUpdated="micUpdated",n.SpeakerUpdated="speakerUpdated",n.DeviceError="deviceError",n.MediaStateUpdated="mediaStateUpdated",n.UnsupportedFeature="unsupportedFeature"})(q||(q={}));var fn={};ue(fn,"RTVI_PROTOCOL_VERSION",()=>Ls);ue(fn,"RTVI_MESSAGE_LABEL",()=>yu);ue(fn,"RTVIMessageType",()=>Y);ue(fn,"AggregationType",()=>ns);ue(fn,"setAboutClient",()=>wu);ue(fn,"RTVIMessage",()=>Ce);const Ls="2.0.0",yu="rtvi-ai";var Y;(function(n){n.CLIENT_READY="client-ready",n.DISCONNECT_BOT="disconnect-bot",n.CLIENT_MESSAGE="client-message",n.SEND_TEXT="send-text",n.UI_EVENT="ui-event",n.UI_SNAPSHOT="ui-snapshot",n.UI_CANCEL_JOB_GROUP="ui-cancel-job-group",n.APPEND_TO_CONTEXT="append-to-context",n.BOT_READY="bot-ready",n.ERROR="error",n.METRICS="metrics",n.SERVER_MESSAGE="server-message",n.SERVER_RESPONSE="server-response",n.ERROR_RESPONSE="error-response",n.APPEND_TO_CONTEXT_RESULT="append-to-context-result",n.UI_COMMAND="ui-command",n.UI_JOB_GROUP="ui-job-group",n.USER_STARTED_SPEAKING="user-started-speaking",n.USER_STOPPED_SPEAKING="user-stopped-speaking",n.BOT_STARTED_SPEAKING="bot-started-speaking",n.BOT_STOPPED_SPEAKING="bot-stopped-speaking",n.USER_MUTE_STARTED="user-mute-started",n.USER_MUTE_STOPPED="user-mute-stopped",n.USER_TRANSCRIPTION="user-transcription",n.BOT_OUTPUT="bot-output",n.BOT_TRANSCRIPTION="bot-transcription",n.USER_LLM_TEXT="user-llm-text",n.BOT_LLM_TEXT="bot-llm-text",n.BOT_LLM_STARTED="bot-llm-started",n.BOT_LLM_STOPPED="bot-llm-stopped",n.LLM_FUNCTION_CALL="llm-function-call",n.LLM_FUNCTION_CALL_STARTED="llm-function-call-started",n.LLM_FUNCTION_CALL_IN_PROGRESS="llm-function-call-in-progress",n.LLM_FUNCTION_CALL_STOPPED="llm-function-call-stopped",n.LLM_FUNCTION_CALL_RESULT="llm-function-call-result",n.BOT_LLM_SEARCH_RESPONSE="bot-llm-search-response",n.BOT_TTS_TEXT="bot-tts-text",n.BOT_TTS_STARTED="bot-tts-started",n.BOT_TTS_STOPPED="bot-tts-stopped"})(Y||(Y={}));var ns;(function(n){n.WORD="word",n.SENTENCE="sentence"})(ns||(ns={}));let Un;function wu(n){Un?Un={...Un,...n}:Un=n}class Ce{constructor(e,t,r){this.label=yu,this.type=e,this.data=t,this.id=r||cm().slice(0,8)}static clientReady(){return new Ce(Y.CLIENT_READY,{version:Ls,about:Un||{library:Mn.name,library_version:Mn.version}})}static disconnectBot(){return new Ce(Y.DISCONNECT_BOT,{})}
7static error(e,t=!1){return new Ce(Y.ERROR,{message:e,fatal:t})}}var Dm={};ot(jt,fu);ot(jt,vt);ot(jt,bu);ot(jt,fn);ot(jt,Dm);function pn(n,e,t){const r=t.value;return t.value=function(...i){if(this.state==="ready")return r.apply(this,i);throw new mu(`Attempt to call ${e.toString()} when transport not in ready state. Await connect() first.`)},t}function Ds(n,e,t){const r=t.value,i=["authenticating","connecting","connected","ready"];return t.value=function(...s){if(i.includes(this.state))throw new gu(`Attempt to call ${e.toString()} when client already started. Please call disconnect() before starting again.`);return r.apply(this,s)},t}var _u={};ue(_u,"MessageDispatcher",()=>ku);var Fs={};ue(Fs,"LogLevel",()=>Vt);ue(Fs,"logger",()=>ee);var Vt;(function(n){n[n.NONE=0]="NONE",n[n.ERROR=1]="ERROR",n[n.WARN=2]="WARN",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG"})(Vt||(Vt={}));class yn{constructor(){this.level=Vt.DEBUG}static getInstance(){return yn.instance||(yn.instance=new yn),yn.instance}setLevel(e){this.level=e}debug(...e){this.level>=Vt.DEBUG&&console.debug(...e)}info(...e){this.level>=Vt.INFO&&console.info(...e)}warn(...e){this.level>=Vt.WARN&&console.warn(...e)}error(...e){this.level>=Vt.ERROR&&console.error(...e)}}const ee=yn.getInstance();class ku{constructor(e){this._queue=new Array,this._gcInterval=void 0,this._queue=[],this._sendMethod=e}disconnect(){this.clearQueue(),clearInterval(this._gcInterval),this._gcInterval=void 0}dispatch(e,t=Y.CLIENT_MESSAGE,r=1e4){this._gcInterval||(this._gcInterval=setInterval(()=>{this._gc()},2e3));const i=new Ce(t,e),s=new Promise((a,o)=>{this._queue.push({message:i,timestamp:Date.now(),timeout:r,resolve:a,reject:o})});ee.debug("[MessageDispatcher] dispatch",i);try{this._sendMethod(i)}catch(a){return ee.error("[MessageDispatcher] Error sending message",a),Promise.reject(a)}return this._gc(),s}clearQueue(){this._queue=[]}_resolveReject(e,t=!0){const r=this._queue.find(i=>i.message.id===e.id);return r&&(t?(ee.debug("[MessageDispatcher] Resolve",e),r.resolve(e)):(ee.debug("[MessageDispatcher] Reject",e),r.reject(e)),this._queue=this._queue.filter(i=>i.message.id!==e.id),ee.debug("[MessageDispatcher] Queue",this._queue)),e}resolve(e){return this._resolveReject(e,!0)}reject(e){return this._resolveReject(e,!1)}_gc(){const e=[];this._queue=this._queue.filter(t=>{const r=Date.now()-t.timestamp<t.timeout;return r||e.push(t),r}),e.forEach(t=>{t.message.type===Y.CLIENT_MESSAGE&&t.reject(new Ce(Y.ERROR_RESPONSE,{error:"Timed out waiting for response",msgType:t.message.data.t,data:t.message.data.d,fatal:!1}))}),ee.debug("[MessageDispatcher] GC",this._queue)}}var Bs={};ue(Bs,"isAPIRequest",()=>Su);ue(Bs,"makeRequest",()=>xu);function Su(n){if(typeof n=="object"&&n!==null&&Object.keys(n).includes("endpoint")){const e=n.endpoint;return typeof e=="string"||e instanceof URL||typeof Request<"u"&&e instanceof Request}return!1}async function xu(n,e){e||(e=new AbortController);let t;return new Promise((r,i)=>{(async()=>{n.timeout&&(t=setTimeout(async()=>{e.abort(),i(new Error("Timed out"))},n.timeout));let s;typeof Request<"u"&&n.endpoint instanceof Request?(s=new Request(n.endpoint,{signal:e.signal}),n.requestData&&ee.warn("[Pipecat Client] requestData in APIRequest is ignored when endpoint is a Request object"),n.headers&&ee.warn("[Pipecat Client] headers in APIRequest is ignored when endpoint is a Request object")):s=new Request(n.endpoint,{method:"POST",mode:"cors",headers:new Headers({"Content-Type":"application/json",...Object.fromEntries((n.headers??new Headers).entries())}),body:JSON.stringify(n.requestData),signal:e.signal}),ee.debug(`[Pipecat Client] Fetching from ${s.url}`),fetch(s).then(a=>{if(ee.debug(`[Pipecat Client] Received response from ${s.url}`,a),!a.ok){i(a);return}return a.json()}).then(a=>{r(a)}).catch(a=>
7{ee.error(`[Pipecat Client] Error fetching: ${a}`),i(a)}).finally(()=>{t&&clearTimeout(t)})})()})}var $s={};ue($s,"Transport",()=>Eu);ue($s,"TransportWrapper",()=>Cu);class Eu{constructor(){this._state="disconnected",this._maxMessageSize=65536}connect(e){this._abortController=new AbortController;let t=e;try{t=this._validateConnectionParams(e)}catch(r){throw new He(`Invalid connection params: ${r.message}. Please check your connection params and try again.`)}return this._connect(t)}get startBotParams(){return this._startBotParams}set startBotParams(e){if(typeof Request<"u"&&e.endpoint instanceof Request){this._startBotParams={...e,endpoint:e.endpoint.clone()};return}this._startBotParams=e}disconnect(){return this._abortController&&this._abortController.abort(),this._disconnect()}get maxMessageSize(){return this._maxMessageSize}}class Cu{constructor(e){this._transport=e,this._proxy=new Proxy(this._transport,{get:(t,r,i)=>{if(typeof t[r]=="function"){let s;switch(String(r)){case"initialize":s="Direct calls to initialize() are disabled and used internally by the PipecatClient.";break;case"initDevices":s="Direct calls to initDevices() are disabled. Please use the PipecatClient.initDevices() wrapper or let PipecatClient.connect() call it for you.";break;case"sendReadyMessage":s="Direct calls to sendReadyMessage() are disabled and used internally by the PipecatClient.";break;case"connect":s="Direct calls to connect() are disabled. Please use the PipecatClient.connect() wrapper.";break;case"disconnect":s="Direct calls to disconnect() are disabled. Please use the PipecatClient.disconnect() wrapper.";break}return s?()=>{throw new Error(s)}:(...a)=>t[r](...a)}return Reflect.get(t,r,i)}})}get proxy(){return this._proxy}}var Us={};ue(Us,"learnAboutClient",()=>Mu);ue(Us,"messageSizeWithinLimit",()=>Au);function Mu(){let n={library:Mn.name,library_version:Mn.version,platform_details:{}},e=null;if(window?.navigator?.userAgent)try{e=pm.parse(window.navigator.userAgent)}catch{}return e?.browser?.name&&(n.platform_details.browser=e.browser.name),e?.browser?.name==="Safari"&&!e.browser.version?n.platform_details.browser_version="Web View":e?.browser?.version&&(n.platform_details.browser_version=e.browser.version),e?.platform?.type&&(n.platform_details.platform_type=e.platform.type),e?.engine?.name&&(n.platform_details.engine=e.engine.name),e?.os&&(n.platform=e.os.name,n.platform_version=e.os.version),n}function Au(n,e){return(i=>{const s=JSON.stringify(i);return new TextEncoder().encode(s).length})(n)<=e}var kt=function(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var o=n.length-1;o>=0;o--)(a=n[o])&&(s=(i<3?a(s):i>3?a(e,t,s):a(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s};function Fm(n){switch(n){case"in-use":return"already-in-use";case"permissions":return"blocked";case"not-found":return"not-found";case"undefined-mediadevices":return"not-supported";case"constraints":return"invalid-constraints";default:return"unknown"}}class Bm extends rm{}class ct extends Bm{constructor(e){super(),this._functionCallCallbacks={},this._botTranscriptionWarned=!1,this._llmFunctionCallWarned=!1,this._mediaState={mic:{state:"uninitialized"},cam:{state:"uninitialized"}},wu(Mu()),this._transport=e.transport,this._transportWrapper=new Cu(this._transport),this._disconnectOnBotDisconnect=e.disconnectOnBotDisconnect??!0;const t={...e.callbacks,onMessageError:r=>{e?.callbacks?.onMessageError?.(r),this.emit(q.MessageError,r)},onError:r=>{e?.callbacks?.onError?.(r);try{this.emit(q.Error,r)}catch(s){s instanceof Error&&s.message.includes("Unhandled error")?e?.callbacks?.onError||ee.debug("No onError callback registered to handle error",r):ee.debug("Could not emit error",r,s)}r.data?.fatal&&(ee.error("Fatal error reported. Disconnecting..."),this.disconnect())},onConnected:()=>{e?.callbacks?.onConnected?.(),this.emit(q.Connected)},onDisconnected:()=>{e?.callbacks?.onDisconnected?.(),this.emit(q.Disconnected)},onTransportStateChanged:r=>
7{e?.callbacks?.onTransportStateChanged?.(r),this.emit(q.TransportStateChanged,r),r==="ready"&&this._flushPendingUISnapshot()},onParticipantJoined:r=>{e?.callbacks?.onParticipantJoined?.(r),this.emit(q.ParticipantConnected,r)},onParticipantLeft:r=>{e?.callbacks?.onParticipantLeft?.(r),this.emit(q.ParticipantLeft,r)},onTrackStarted:(r,i)=>{e?.callbacks?.onTrackStarted?.(r,i),this.emit(q.TrackStarted,r,i)},onTrackStopped:(r,i)=>{e?.callbacks?.onTrackStopped?.(r,i),this.emit(q.TrackStopped,r,i)},onScreenTrackStarted:(r,i)=>{e?.callbacks?.onScreenTrackStarted?.(r,i),this.emit(q.ScreenTrackStarted,r,i)},onScreenTrackStopped:(r,i)=>{e?.callbacks?.onScreenTrackStopped?.(r,i),this.emit(q.ScreenTrackStopped,r,i)},onScreenShareError:r=>{e?.callbacks?.onScreenShareError?.(r),this.emit(q.ScreenShareError,r)},onUnsupportedFeature:r=>{e?.callbacks?.onUnsupportedFeature?.(r),this.emit(q.UnsupportedFeature,r)},onAvailableCamsUpdated:r=>{e?.callbacks?.onAvailableCamsUpdated?.(r),this.emit(q.AvailableCamsUpdated,r)},onAvailableMicsUpdated:r=>{e?.callbacks?.onAvailableMicsUpdated?.(r),this.emit(q.AvailableMicsUpdated,r)},onAvailableSpeakersUpdated:r=>{e?.callbacks?.onAvailableSpeakersUpdated?.(r),this.emit(q.AvailableSpeakersUpdated,r)},onCamUpdated:r=>{r?.deviceId&&this._markDeviceGranted("cam"),e?.callbacks?.onCamUpdated?.(r),this.emit(q.CamUpdated,r)},onMicUpdated:r=>{r?.deviceId&&this._markDeviceGranted("mic"),e?.callbacks?.onMicUpdated?.(r),this.emit(q.MicUpdated,r)},onSpeakerUpdated:r=>{e?.callbacks?.onSpeakerUpdated?.(r),this.emit(q.SpeakerUpdated,r)},onDeviceError:r=>{this._classifyAndApplyDeviceError(r),e?.callbacks?.onDeviceError?.(r),this.emit(q.DeviceError,r)},onBotStarted:r=>{e?.callbacks?.onBotStarted?.(r),this.emit(q.BotStarted,r)},onBotConnected:r=>{e?.callbacks?.onBotConnected?.(r),this.emit(q.BotConnected,r)},onBotReady:r=>{e?.callbacks?.onBotReady?.(r),this.emit(q.BotReady,r)},onBotDisconnected:r=>{e?.callbacks?.onBotDisconnected?.(r),this.emit(q.BotDisconnected,r),this._disconnectOnBotDisconnect&&(ee.info("Bot disconnected. Disconnecting client..."),this.disconnect())},onUserStartedSpeaking:()=>{e?.callbacks?.onUserStartedSpeaking?.(),this.emit(q.UserStartedSpeaking)},onUserStoppedSpeaking:()=>{e?.callbacks?.onUserStoppedSpeaking?.(),this.emit(q.UserStoppedSpeaking)},onBotStartedSpeaking:()=>{e?.callbacks?.onBotStartedSpeaking?.(),this.emit(q.BotStartedSpeaking)},onBotStoppedSpeaking:()=>{e?.callbacks?.onBotStoppedSpeaking?.(),this.emit(q.BotStoppedSpeaking)},onRemoteAudioLevel:(r,i)=>{e?.callbacks?.onRemoteAudioLevel?.(r,i),this.emit(q.RemoteAudioLevel,r,i)},onLocalAudioLevel:r=>{e?.callbacks?.onLocalAudioLevel?.(r),this.emit(q.LocalAudioLevel,r)},onUserMuteStarted:()=>{e?.callbacks?.onUserMuteStarted?.(),this.emit(q.UserMuteStarted)},onUserMuteStopped:()=>{e?.callbacks?.onUserMuteStopped?.(),this.emit(q.UserMuteStopped)},onUserTranscript:r=>{e?.callbacks?.onUserTranscript?.(r),this.emit(q.UserTranscript,r)},onBotOutput:r=>{e?.callbacks?.onBotOutput?.(r),this.emit(q.BotOutput,r)},onBotTranscript:r=>{(e?.callbacks?.onBotTranscript||this.listenerCount(q.BotTranscript)>0)&&!this._botTranscriptionWarned&&(ee.warn("[Pipecat Client] Bot transcription is deprecated. Please use the onBotOutput instead."),this._botTranscriptionWarned=!0),e?.callbacks?.onBotTranscript?.(r),this.emit(q.BotTranscript,r)},onBotLlmText:r=>{e?.callbacks?.onBotLlmText?.(r),this.emit(q.BotLlmText,r)},onBotLlmStarted:()=>{e?.callbacks?.onBotLlmStarted?.(),this.emit(q.BotLlmStarted)},onBotLlmStopped:()=>{e?.callbacks?.onBotLlmStopped?.(),this.emit(q.BotLlmStopped)},onBotTtsText:r=>{e?.callbacks?.onBotTtsText?.(r),this.emit(q.BotTtsText,r)},onBotTtsStarted:()=>{e?.callbacks?.onBotTtsStarted?.(),this.emit(q.BotTtsStarted)},onBotTtsStopped:()=>{e?.callbacks?.onBotTtsStopped?.(),this.emit(q.BotTtsStopped)}};this._options={...e,callbacks:t,enableMic:e.enableMic??!0,enableCam:e.enableCam??!1,enableScreenShare:e.enableScreenShare??!1},this._initialize(),ee.debug("[Pipecat Client] Initialized",this.version)}setLogLevel(e){ee.setLevel(e)}
7async initDevices(){ee.debug("[Pipecat Client] Initializing devices..."),this._setMediaState({mic:{state:"initializing"},cam:{state:"initializing"}});try{await this._transport.initDevices(),this._resolveLingeringInitializing({state:"uninitialized"})}catch(e){throw this._resolveLingeringInitializing({state:"error",reason:"unknown"}),e}finally{await this._enrichFromPermissionsAPI()}}_resolveLingeringInitializing(e){const t={};for(const r of["mic","cam"])this._mediaState[r].state==="initializing"&&(t[r]=e);Object.keys(t).length>0&&this._setMediaState(t)}_markDeviceGranted(e){this._mediaState[e].state!=="granted"&&this._setMediaState({[e]:{state:"granted"}})}async startBot(e){this.needsInit()&&await this.initDevices(),this._transport.state="authenticating",this._transport.startBotParams=e,this._abortController=new AbortController;let t;try{t=await xu(e,this._abortController)}catch(r){let i="An unknown error occurred while starting the bot.",s;if(r instanceof Response){const a=await r.json();i=a.info??a.detail??r.statusText,s=r.status}else r instanceof Error&&(i=r.message);throw this._options.callbacks?.onError?.(new Ce(Y.ERROR_RESPONSE,{message:i,fatal:!0})),new pu(i,s)}return this._transport.state="authenticated",this._options.callbacks?.onBotStarted?.(t),t}async connect(e){return e&&Su(e)?(ee.warn("Calling connect with an API endpoint is deprecated. Use startBotAndConnect() instead."),this.startBotAndConnect(e)):new Promise((t,r)=>{(async()=>{this._connectResolve=t,this.needsInit()&&await this.initDevices();try{await this._transport.connect(e),await this._transport.sendReadyMessage()}catch(i){this.disconnect(),r(i);return}})()})}async startBotAndConnect(e){const t=await this.startBot(e);return this.connect(t)}async disconnect(){this.stopUISnapshotStream(),await this._transport.disconnect(),this._messageDispatcher.disconnect()}_initialize(){this._transport.initialize(this._options,this.handleMessage.bind(this)),this._messageDispatcher=new ku(this._sendMessage.bind(this))}_setMediaState(e){const t={...this._mediaState,...e};this._statusEquals(t.mic,this._mediaState.mic)&&this._statusEquals(t.cam,this._mediaState.cam)||(this._mediaState=t,this._options.callbacks?.onMediaStateChanged?.(this.mediaState),this.emit(q.MediaStateUpdated,this.mediaState))}_statusEquals(e,t){return e.state!==t.state?!1:e.state==="error"&&t.state==="error"?e.reason===t.reason&&e.details===t.details:!0}_classifyAndApplyDeviceError(e){const t={state:"error",reason:Fm(e.type),details:e.details},r={};e.devices.includes("mic")&&(r.mic=t),e.devices.includes("cam")&&(r.cam=t),Object.keys(r).length!==0&&this._setMediaState(r)}async _enrichFromPermissionsAPI(){const e=globalThis.navigator?.permissions;
7if(!e?.query)return;const t=e.query.bind(e),r={};await Promise.all(["mic","cam"].map(async i=>{try{(await t({name:i==="mic"?"microphone":"camera"})).state==="denied"&&(r[i]={state:"error",reason:"blocked"})}catch{}})),Object.keys(r).length>0&&this._setMediaState(r)}_sendMessage(e){if(!Au(e,this._transport.maxMessageSize)){const t=`Message data too large. Max size is ${this._transport.maxMessageSize}`;throw this._options.callbacks?.onError?.(Ce.error(t,!1)),new vu(t)}try{this._transport.sendMessage(e)}catch(t){throw t instanceof Error?this._options.callbacks?.onError?.(Ce.error(t.message,!1)):this._options.callbacks?.onError?.(Ce.error("Unknown error sending message",!1)),t}}get connected(){return["connected","ready"].includes(this._transport.state)}get transport(){return this._transportWrapper.proxy}get state(){return this._transport.state}get mediaState(){return{mic:{...this._mediaState.mic},cam:{...this._mediaState.cam}}}needsInit(){return this._options.enableMic!==!1&&this._mediaState.mic.state==="uninitialized"||this._options.enableCam!==!1&&this._mediaState.cam.state==="uninitialized"}get version(){return mm(Mn).version}async getAllMics(){return await this._transport.getAllMics()}async getAllCams(){return await this._transport.getAllCams()}async getAllSpeakers(){return await this._transport.getAllSpeakers()}get selectedMic(){return this._transport.selectedMic}get selectedCam(){try{return this._transport.selectedCam}catch(e){if(e instanceof rn)return this._options.callbacks?.onUnsupportedFeature?.(e),{};throw e}}get selectedSpeaker(){return this._transport.selectedSpeaker}updateMic(e){this._transport.updateMic(e)}updateCam(e){this._transport.updateCam(e)}updateSpeaker(e){this._transport.updateSpeaker(e)}enableMic(e){this._transport.enableMic(e)}get isMicEnabled(){return this._transport.isMicEnabled}enableCam(e){try{this._transport.enableCam(e)}catch(t){if(t instanceof rn)this._options.callbacks?.onUnsupportedFeature?.(t);else throw t}}get isCamEnabled(){return this._transport.isCamEnabled}tracks(){return this._transport.tracks()}enableScreenShare(e){try{return this._transport.enableScreenShare(e)}catch(t){if(t instanceof rn)this._options.callbacks?.onUnsupportedFeature?.(t);else throw t}}get isSharingScreen(){return this._transport.isSharingScreen}sendClientMessage(e,t){this._sendMessage(new Ce(Y.CLIENT_MESSAGE,{t:e,d:t}))}sendUIEvent(e,t){const r={event:e,payload:t};this._sendMessage(new Ce(Y.UI_EVENT,r))}startUISnapshotStream(e={}){this.stopUISnapshotStream(),this._uiSnapshotStreamer=new uu(t=>{if(this.state!=="ready"){this._pendingUISnapshot=t;return}this._sendUISnapshot(t)},e),this._uiSnapshotStreamer.start()}stopUISnapshotStream(){this._uiSnapshotStreamer?.stop(),this._uiSnapshotStreamer=void 0,this._pendingUISnapshot=void 0}_sendUISnapshot(e){const t={tree:e};this._sendMessage(new Ce(Y.UI_SNAPSHOT,t))}_flushPendingUISnapshot(){if(!this._pendingUISnapshot||this.state!=="ready")return;
7const e=this._pendingUISnapshot;this._pendingUISnapshot=void 0,this._sendUISnapshot(e)}cancelUIJobGroup(e,t){const r={job_id:e};t!==void 0&&(r.reason=t),this._sendMessage(new Ce(Y.UI_CANCEL_JOB_GROUP,r))}async sendClientRequest(e,t,r){const i={t:e,d:t};return(await this._messageDispatcher.dispatch(i,Y.CLIENT_MESSAGE,r)).data.d}registerFunctionCallHandler(e,t){this._functionCallCallbacks[e]=t}unregisterFunctionCallHandler(e){delete this._functionCallCallbacks[e]}unregisterAllFunctionCallHandlers(){this._functionCallCallbacks={}}async appendToContext(e){return ee.warn("appendToContext() is deprecated. Use sendText() instead."),await this._sendMessage(new Ce(Y.APPEND_TO_CONTEXT,{role:e.role,content:e.content,run_immediately:e.run_immediately})),!0}async sendText(e,t={}){await this._sendMessage(new Ce(Y.SEND_TEXT,{content:e,options:t}))}disconnectBot(){this._sendMessage(new Ce(Y.DISCONNECT_BOT,{}))}handleMessage(e){switch(ee.debug("[RTVI Message]",e),e.type){case Y.BOT_READY:{const t=e.data,r=t.version?t.version.split(".").map(Number):[0,0,0];ee.debug(`[Pipecat Client] Bot is ready. Version: ${t.version}`),r[0]<2&&ee.warn(`[Pipecat Client] Bot protocol version ${t.version} is older than this client (${Ls}). Compatibility issues may occur.`),this._connectResolve?.(e.data),this._options.callbacks?.onBotReady?.(e.data);break}case Y.ERROR:this._options.callbacks?.onError?.(e);break;case Y.SERVER_RESPONSE:this._messageDispatcher.resolve(e);break;case Y.ERROR_RESPONSE:{const t=this._messageDispatcher.reject(e);this._options.callbacks?.onMessageError?.(t);break}case Y.USER_STARTED_SPEAKING:this._options.callbacks?.onUserStartedSpeaking?.();break;case Y.USER_STOPPED_SPEAKING:this._options.callbacks?.onUserStoppedSpeaking?.();break;case Y.BOT_STARTED_SPEAKING:this._options.callbacks?.onBotStartedSpeaking?.();break;case Y.BOT_STOPPED_SPEAKING:this._options.callbacks?.onBotStoppedSpeaking?.();break;case Y.USER_MUTE_STARTED:this._options.callbacks?.onUserMuteStarted?.();break;case Y.USER_MUTE_STOPPED:this._options.callbacks?.onUserMuteStopped?.();break;case Y.USER_TRANSCRIPTION:{const t=e.data;this._options.callbacks?.onUserTranscript?.(t);break}case Y.USER_LLM_TEXT:{const t=e.data;this._options.callbacks?.onUserLlmText?.(t),this.emit(q.UserLlmText,t);break}case Y.BOT_OUTPUT:this._options.callbacks?.onBotOutput?.(e.data);break;case Y.BOT_TRANSCRIPTION:this._options.callbacks?.onBotTranscript?.(e.data);break;case Y.BOT_LLM_TEXT:this._options.callbacks?.onBotLlmText?.(e.data);break;case Y.BOT_LLM_STARTED:this._options.callbacks?.onBotLlmStarted?.();break;case Y.BOT_LLM_STOPPED:this._options.callbacks?.onBotLlmStopped?.();break;case Y.BOT_TTS_TEXT:this._options.callbacks?.onBotTtsText?.(e.data);break;case Y.BOT_TTS_STARTED:this._options.callbacks?.onBotTtsStarted?.();break;case Y.BOT_TTS_STOPPED:this._options.callbacks?.onBotTtsStopped?.();break;case Y.METRICS:this._options.callbacks?.onMetrics?.(e.data),this.emit(q.Metrics,e.data);break;case Y.SERVER_MESSAGE:this._options.callbacks?.onServerMessage?.(e.data),this.emit(q.ServerMessage,e.data);break;case Y.UI_COMMAND:{const t=e.data;this._options.callbacks?.onUICommand?.(t),this.emit(q.UICommand,t);break}case Y.UI_JOB_GROUP:{const t=e.data;this._options.callbacks?.onUIJobGroup?.(t),this.emit(q.UIJobGroup,t);break}case Y.LLM_FUNCTION_CALL_STARTED:{const t=e.data;this._options.callbacks?.onLLMFunctionCallStarted?.(t),this.emit(q.LLMFunctionCallStarted,t);break}case Y.LLM_FUNCTION_CALL_IN_PROGRESS:{const t=e.data;this._maybeTriggerFunctionCallCallback(t),this._options.callbacks?.onLLMFunctionCallInProgress?.(t),this.emit(q.LLMFunctionCallInProgress,t);break}case Y.LLM_FUNCTION_CALL_STOPPED:{const t=e.data;this._options.callbacks?.onLLMFunctionCallStopped?.(t),this.emit(q.LLMFunctionCallStopped,t);break}case Y.LLM_FUNCTION_CALL:{const t=e.data,r={function_name:t.function_name,tool_call_id:t.tool_call_id,arguments:t.args};this._maybeTriggerFunctionCallCallback(r),this._options.callbacks?.onLLMFunctionCall&&(this._llmFunctionCallWarned||(ee.warn("[Pipecat Client] onLLMFunctionCall is deprecated. Please use onLLMFunctionCallInProgress 
7instead."),this._llmFunctionCallWarned=!0)),this._options.callbacks?.onLLMFunctionCall?.(t),this.emit(q.LLMFunctionCall,t);break}case Y.BOT_LLM_SEARCH_RESPONSE:{const t=e.data;this._options.callbacks?.onBotLlmSearchResponse?.(t),this.emit(q.BotLlmSearchResponse,t);break}default:ee.debug("[Pipecat Client] Unrecognized message type",e.type);break}}_maybeTriggerFunctionCallCallback(e){if(!e.function_name)return;const t=this._functionCallCallbacks[e.function_name];if(t){const r={functionName:e.function_name??"",arguments:e.arguments??{}};t(r).then(i=>{i!=null&&this._sendMessage(new Ce(Y.LLM_FUNCTION_CALL_RESULT,{function_name:e.function_name,tool_call_id:e.tool_call_id,arguments:e.arguments??{},result:i}))}).catch(i=>{ee.error("Error in function call callback",i)})}}}kt([Ds],ct.prototype,"startBot",null);kt([Ds],ct.prototype,"connect",null);kt([Ds],ct.prototype,"startBotAndConnect",null);kt([pn],ct.prototype,"sendClientMessage",null);kt([pn],ct.prototype,"sendUIEvent",null);kt([pn],ct.prototype,"cancelUIJobGroup",null);kt([pn],ct.prototype,"sendClientRequest",null);kt([pn],ct.prototype,"appendToContext",null);kt([pn],ct.prototype,"sendText",null);kt([pn],ct.prototype,"disconnectBot",null);ot(hn,iu);ot(hn,hu);ot(hn,_u);ot(hn,Fs);ot(hn,Bs);ot(hn,$s);ot(hn,Us);function eo(n,e){if(n==null)return{};var t,r,i=(function(a,o){if(a==null)return{};var l={};for(var u in a)if({}.hasOwnProperty.call(a,u)){if(o.indexOf(u)!==-1)continue;l[u]=a[u]}return l})(n,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);for(r=0;r<s.length;r++)t=s[r],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(n,t)&&(i[t]=n[t])}return i}function et(n,e){if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")}function le(n){return le=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},le(n)}function Tu(n){var e=(function(t,r){if(le(t)!="object"||!t)return t;var i=t[Symbol.toPrimitive];if(i!==void 0){var s=i.call(t,r);
7if(le(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)})(n,"string");return le(e)=="symbol"?e:e+""}function to(n,e){for(var t=0;t<e.length;t++){var r=e[t];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(n,Tu(r.key),r)}}function tt(n,e,t){return e&&to(n.prototype,e),t&&to(n,t),Object.defineProperty(n,"prototype",{writable:!1}),n}function Qr(n,e){if(e&&(le(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return(function(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t})(n)}function gt(n){return gt=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},gt(n)}function Hn(n,e){return Hn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,r){return t.__proto__=r,t},Hn(n,e)}function Zr(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");n.prototype=Object.create(e&&e.prototype,{constructor:{value:n,writable:!0,configurable:!0}}),Object.defineProperty(n,"prototype",{writable:!1}),e&&Hn(n,e)}function wt(n,e,t){return(e=Tu(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function no(n,e,t,r,i,s,a){try{var o=n[s](a),l=o.value}catch(u){return void t(u)}o.done?e(l):Promise.resolve(l).then(r,i)}function X(n){return function(){var e=this,t=arguments;return new Promise(function(r,i){var s=n.apply(e,t);function a(l){no(s,r,i,a,o,"next",l)}function o(l){no(s,r,i,a,o,"throw",l)}a(void 0)})}}function ro(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,r=Array(e);t<e;t++)r[t]=n[t];return r}function Pe(n,e){return(function(t){if(Array.isArray(t))return t})(n)||(function(t,r){var i=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(i!=null){var s,a,o,l,u=[],f=!0,g=!1;try{if(o=(i=i.call(t)).next,r===0){if(Object(i)!==i)return;f=!1}else for(;!(f=(s=o.call(i)).done)&&(u.push(s.value),u.length!==r);f=!0);}catch(_){g=!0,a=_}finally{try{if(!f&&i.return!=null&&(l=i.return(),Object(l)!==l))return}finally{if(g)throw a}}return u}})(n,e)||(function(t,r){if(t){if(typeof t=="string")return ro(t,r);var i={}.toString.call(t).slice(8,-1);return i==="Object"&&t.constructor&&(i=t.constructor.name),i==="Map"||i==="Set"?Array.from(t):i==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?ro(t,r):void 0}})(n,e)||(function(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
8In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function $m(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var io,ir={exports:{}},rs=(function(){if(io)return ir.exports;io=1;var n,e=typeof Reflect=="object"?Reflect:null,t=e&&typeof e.apply=="function"?e.apply:function(v,E,C){return Function.prototype.apply.call(v,E,C)};n=e&&typeof e.ownKeys=="function"?e.ownKeys:Object.getOwnPropertySymbols?function(v){return Object.getOwnPropertyNames(v).concat(Object.getOwnPropertySymbols(v))}:function(v){return Object.getOwnPropertyNames(v)};var r=Number.isNaN||function(v){return v!=v};function i(){i.init.call(this)}ir.exports=i,ir.exports.once=function(v,E){return new Promise(function(C,O){function j(x){v.removeListener(E,S),O(x)}function S(){typeof v.removeListener=="function"&&v.removeListener("error",j),C([].slice.call(arguments))}b(v,E,S,{once:!0}),E!=="error"&&(function(x,T,I){typeof x.on=="function"&&b(x,"error",T,I)})(v,j,{once:!0})})},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var s=10;function a(v){if(typeof v!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof v)}function o(v){return v._maxListeners===void 0?i.defaultMaxListeners:v._maxListeners}function l(v,E,C,O){var j,S,x,T;if(a(C),(S=v._events)===void 0?(S=v._events=Object.create(null),v._eventsCount=0):(S.newListener!==void 0&&(v.emit("newListener",E,C.listener?C.listener:C),S=v._events),x=S[E]),x===void 0)x=S[E]=C,++v._eventsCount;else if(typeof x=="function"?x=S[E]=O?[C,x]:[x,C]:O?x.unshift(C):x.push(C),(j=o(v))>0&&x.length>j&&!x.warned){x.warned=!0;var I=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+String(E)+" listeners added. Use emitter.setMaxListeners() to increase limit");I.name="MaxListenersExceededWarning",I.emitter=v,I.type=E,I.count=x.length,T=I,console&&console.warn&&console.warn(T)}return v}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function f(v,E,C){var O={fired:!1,wrapFn:void 0,target:v,type:E,listener:C},j=u.bind(O);return j.listener=C,O.wrapFn=j,j}function g(v,E,C){var O=v._events;if(O===void 0)return[];var j=O[E];return j===void 0?[]:typeof j=="function"?C?[j.listener||j]:[j]:C?(function(S){for(var x=new Array(S.length),T=0;T<x.length;++T)x[T]=S[T].listener||S[T];return x})(j):k(j,j.length)}function _(v){var E=this._events;if(E!==void 0){var C=E[v];if(typeof C=="function")return 1;if(C!==void 0)return C.length}return 0}function k(v,E){for(var C=new Array(E),O=0;O<E;++O)C[O]=v[O];return C}function b(v,E,C,O){if(typeof v.on=="function")O.once?v.once(E,C):v.on(E,C);else{if(typeof v.addEventListener!="function")throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof v);v.addEventListener(E,function j(S){O.once&&v.removeEventListener(E,j),C(S)})}}return Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(v){if(typeof v!="number"||v<0||r(v))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");s=v}}),i.init=function(){this._events!==void 0&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(v){if(typeof v!="number"||v<0||r(v))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+v+".");return this._maxListeners=v,this},i.prototype.getMaxListeners=function(){return o(this)},i.prototype.emit=function(v){for(var E=[],C=1;C<arguments.length;C++)E.push(arguments[C]);var O=v==="error",j=this._events;if(j!==void 0)O=O&&j.error===void 0;else if(!O)return!1;if(O){var S;if(E.length>0&&(S=E[0]),S instanceof Error)throw S;var x=new Error("Unhandled error."+(S?" ("+S.message+")":""));throw x.context=S,x}var T=j[v];if(T===void 0)return!1;if(typeof T=="function")t(T,this,E);else{var I=T.length,F=k(T,I);for(C=0;C<I;++C)t(F[C],this,E)}return!0},i.prototype.addListener=function(v,E){return l(this,v,E,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(v,E){return l(this,v,E,!0)},i.prototype.once=function(v,E){return a(E),this.on(v,f(this,v,E)),this},i.prototype.prependOnceListener=function(v,E){return a(E),this.prependListener(v,f(this,v,E)),this},i.prototype.removeListener=function(v,E){var C,O,j,S,x;if(a(E),(O=this._events)===void 0)return this;if((C=O[v])===void 0)return this;if(C===E||C.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete O[v],O.removeListener&&this.emit
8("removeListener",v,C.listener||E));else if(typeof C!="function"){for(j=-1,S=C.length-1;S>=0;S--)if(C[S]===E||C[S].listener===E){x=C[S].listener,j=S;break}if(j<0)return this;j===0?C.shift():(function(T,I){for(;I+1<T.length;I++)T[I]=T[I+1];T.pop()})(C,j),C.length===1&&(O[v]=C[0]),O.removeListener!==void 0&&this.emit("removeListener",v,x||E)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(v){var E,C,O;if((C=this._events)===void 0)return this;if(C.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):C[v]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete C[v]),this;if(arguments.length===0){var j,S=Object.keys(C);for(O=0;O<S.length;++O)(j=S[O])!=="removeListener"&&this.removeAllListeners(j);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(typeof(E=C[v])=="function")this.removeListener(v,E);else if(E!==void 0)for(O=E.length-1;O>=0;O--)this.removeListener(v,E[O]);return this},i.prototype.listeners=function(v){return g(this,v,!0)},i.prototype.rawListeners=function(v){return g(this,v,!1)},i.listenerCount=function(v,E){return typeof v.listenerCount=="function"?v.listenerCount(E):_.call(v,E)},i.prototype.listenerCount=_,i.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]},ir.exports})(),sr=$m(rs),so=Object.prototype.hasOwnProperty;function ao(n,e,t){for(t of n.keys())if(Je(t,e))return t}function Je(n,e){var t,r,i;if(n===e)return!0;if(n&&e&&(t=n.constructor)===e.constructor){if(t===Date)return n.getTime()===e.getTime();if(t===RegExp)return n.toString()===e.toString();if(t===Array){if((r=n.length)===e.length)for(;r--&&Je(n[r],e[r]););return r===-1}if(t===Set){if(n.size!==e.size)return!1;for(r of n)if((i=r)&&typeof i=="object"&&!(i=ao(e,i))||!e.has(i))return!1;return!0}if(t===Map){if(n.size!==e.size)return!1;for(r of n)if((i=r[0])&&typeof i=="object"&&!(i=ao(e,i))||!Je(r[1],e.get(i)))return!1;return!0}if(t===ArrayBuffer)n=new Uint8Array(n),e=new Uint8Array(e);else if(t===DataView){if((r=n.byteLength)===e.byteLength)for(;r--&&n.getInt8(r)===e.getInt8(r););return r===-1}if(ArrayBuffer.isView(n)){if((r=n.byteLength)===e.byteLength)for(;r--&&n[r]===e[r];);return r===-1}if(!t||typeof n=="object"){for(t in r=0,n)if(so.call(n,t)&&++r&&!so.call(e,t)||!(t in e)||!Je(n[t],e[t]))return!1;return Object.keys(e).length===r}}return n!=n&&e!=e}const Um={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},Nu={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},G={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},Ve={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},$t={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"};class A{static getFirstMatch(e,t){const r=t.match(e);return r&&r.length>0&&r[1]||""}static getSecondMatch(e,t){const r=t.match(e);return r&&r.length>1&&r[2]||""}static matchAndReturnConst(e,t,r){if(e.test(t))return r}
8static getWindowsVersionName(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(e){const t=e.split(".").splice(0,2).map(s=>parseInt(s,10)||0);t.push(0);const r=t[0],i=t[1];if(r===10)switch(i){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(r){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}}static getAndroidVersionName(e){const t=e.split(".").splice(0,2).map(r=>parseInt(r,10)||0);if(t.push(0),!(t[0]===1&&t[1]<5))return t[0]===1&&t[1]<6?"Cupcake":t[0]===1&&t[1]>=6?"Donut":t[0]===2&&t[1]<2?"Eclair":t[0]===2&&t[1]===2?"Froyo":t[0]===2&&t[1]>2?"Gingerbread":t[0]===3?"Honeycomb":t[0]===4&&t[1]<1?"Ice Cream Sandwich":t[0]===4&&t[1]<4?"Jelly Bean":t[0]===4&&t[1]>=4?"KitKat":t[0]===5?"Lollipop":t[0]===6?"Marshmallow":t[0]===7?"Nougat":t[0]===8?"Oreo":t[0]===9?"Pie":void 0}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,t,r=!1){const i=A.getVersionPrecision(e),s=A.getVersionPrecision(t);let a=Math.max(i,s),o=0;const l=A.map([e,t],u=>{const f=a-A.getVersionPrecision(u),g=u+new Array(f+1).join(".0");return A.map(g.split("."),_=>new Array(20-_.length).join("0")+_).reverse()});for(r&&(o=a-Math.min(i,s)),a-=1;a>=o;){if(l[0][a]>l[1][a])return 1;if(l[0][a]===l[1][a]){if(a===o)return 0;a-=1}else if(l[0][a]<l[1][a])return-1}}static map(e,t){const r=[];let i;if(Array.prototype.map)return Array.prototype.map.call(e,t);for(i=0;i<e.length;i+=1)r.push(t(e[i]));return r}static find(e,t){let r,i;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,i=e.length;r<i;r+=1){const s=e[r];if(t(s,r))return s}}static assign(e,...t){const r=e;let i,s;if(Object.assign)return Object.assign(e,...t);for(i=0,s=t.length;i<s;i+=1){const a=t[i];typeof a=="object"&&a!==null&&Object.keys(a).forEach(o=>{r[o]=a[o]})}return e}static getBrowserAlias(e){return Um[e]}static getBrowserTypeByAlias(e){return Nu[e]||""}}const K=/version\/(\d+(\.?_?\d+)+)/i,Vm=[{test:[/gptbot/i],describe(n){const e={name:"GPTBot"},t=A.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/chatgpt-user/i],describe(n){const e={name:"ChatGPT-User"},t=A.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/oai-searchbot/i],describe(n){const e={name:"OAI-SearchBot"},t=A.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(n){const e={name:"ClaudeBot"},t=A.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/omgilibot/i,/webzio-extended/i],describe(n){const e={name:"Omgilibot"},t=A.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/diffbot/i],describe(n){const e={name:"Diffbot"},t=A.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/perplexitybot/i],describe(n){const e={name:"PerplexityBot"},t=A.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/perplexity-user/i],describe(n){const e={name:"Perplexity-User"},t=A.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/youbot/i],describe(n){const e={name:"YouBot"},t=A.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/meta-webindexer/i],describe(n){const e={name:"Meta-WebIndexer"},t=A.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/meta-externalads/i],describe(n){const e={name:"Meta-ExternalAds"},t=A.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/meta-externalagent/i],describe(n){const e={name:"Meta-ExternalAgent"},t=A.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/meta-externalfetcher/i],describe(n){const e={name:"Meta-ExternalFetcher"},t=A.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/googlebot/i],describe(n){const e={name:"Googlebot"},t=A.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/linespider/i],describe(n){const e={name:"Linespider"},t=A.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/amazonbot/i],describe(n){const e={name:"AmazonBot"},t=A.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/bingbot/i],describe(n){const e={name:"BingCrawler"},t=A.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/baiduspider/i],describe(n){const e={name:"BaiduSpider"},t=A.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/duckduckbot/i],describe(n){const e={name:"DuckDuckBot"},t=A.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/ia_archiver/i],describe(n){const e={name:"InternetArchiveCrawler"},t=A.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:()=>({name:"FacebookExternalHit"})},{test:[/slackbot/i,/slack-imgProxy/i],describe(n){const e={name:"SlackBot"},t=A.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/yahoo!?[\s/]*slurp/i],describe:()=>({name:"YahooSlurp"})},{test:[/yandexbot/i,/yandexmobilebot/i],describe:()=>({name:"YandexBot"})},{test:[/pingdom/i],describe:()=>({name:"PingdomBot"})},{test:[/opera/i],describe(n){const e={name:"Opera"},t=A.getFirstMatch(K,n)||A.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/opr\/|opios/i],describe(n){const e={name:"Opera"},t=A.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/SamsungBrowser/i],describe(n){const e={name:"Samsung Internet for Android"},t=A.getFirstMatch(K,n)||A.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/Whale/i],describe(n){const e={name:"NAVER Whale Browser"},t=A.getFirstMatch(K,n)||A.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/PaleMoon/i],describe(n){const e={name:"Pale Moon"},t=A.getFirstMatch(K,n)||A.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/MZBrowser/i],describe(n){const e={name:"MZ Browser"},t=A.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/focus/i],describe(n){const e={name:"Focus"},t=A.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/swing/i],describe(n){const e={name:"Swing"},t=A.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/coast/i],describe(n){const e={name:"Opera Coast"},t=A.getFirstMatch(K,n)||A.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(n){const e={name:"Opera Touch"},t=A.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/yabrowser/i],describe(n){const e={name:"Yandex Browser"},t=A.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/ucbrowser/i],describe(n){const e={name:"UC Browser"},t=A.getFirstMatch(K,n)||A.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/Maxthon|mxios/i],describe(n){const e={name:"Maxthon"}
vendor: 4,546 bytes, line 8
8,t=A.getFirstMatch(K,n)||A.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/epiphany/i],describe(n){const e={name:"Epiphany"},t=A.getFirstMatch(K,n)||A.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/puffin/i],describe(n){const e={name:"Puffin"},t=A.getFirstMatch(K,n)||A.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/sleipnir/i],describe(n){const e={name:"Sleipnir"},t=A.getFirstMatch(K,n)||A.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/k-meleon/i],describe(n){const e={name:"K-Meleon"},t=A.getFirstMatch(K,n)||A.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/micromessenger/i],describe(n){const e={name:"WeChat"},t=A.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/qqbrowser/i],describe(n){const e={name:/qqbrowserlite/i.test(n)?"QQ Browser Lite":"QQ Browser"},t=A.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/msie|trident/i],describe(n){const e={name:"Internet Explorer"},t=A.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/\sedg\//i],describe(n){const e={name:"Microsoft Edge"},t=A.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/edg([ea]|ios)/i],describe(n){const e={name:"Microsoft Edge"},t=A.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/vivaldi/i],describe(n){const e={name:"Vivaldi"},t=A.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/seamonkey/i],describe(n){const e={name:"SeaMonkey"},t=A.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/sailfish/i],describe(n){const e={name:"Sailfish"},t=A.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,n);return t&&(e.version=t),e}},{test:[/silk/i],describe(n){const e={name:"Amazon Silk"},t=A.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/phantom/i],describe(n){const e={name:"PhantomJS"},t=A.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/slimerjs/i],describe(n){const e={name:"SlimerJS"},t=A.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(n){const e={name:"BlackBerry"},t=A.getFirstMatch(K,n)||A.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/(web|hpw)[o0]s/i],describe(n){const e={name:"WebOS Browser"},t=A.getFirstMatch(K,n)||A.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/bada/i],describe(n){const e={name:"Bada"},t=A.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/tizen/i],describe(n){const e={name:"Tizen"},t=A.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/qupzilla/i],describe(n){const e={name:"QupZilla"},t=A.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/librewolf/i],describe(n){const e={name:"LibreWolf"},t=A.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/firefox|iceweasel|fxios/i],describe(n){const e={name:"Firefox"},t=A.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/electron/i],describe(n){const e={name:"Electron"},t=A.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe(n){const e={name:"Sogou Browser"},t=A.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,n),r=A.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),i=A.getFirstMatch(/se ([\d.]+)x/i,n),s=t||r||i;return s&&(e.version=s),e}},{test:[/MiuiBrowser/i],describe(n){const e={name:"Miui"},t=A.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:n=>!!n.hasBrand("DuckDuckGo")||n.test(/\sDdg\/[\d.]+$/i),describe(n,e){const t={name:"DuckDuckGo"};if(e){const i=e.getBrandVersion("DuckDuckGo");if(i)return t.version=i,t}const r=A.getFirstMatch(/\sDdg\/([\d.]+)$/i,n);return r&&(t.version=r),t}},{test:n=>n.hasBrand("Brave"),describe(n,e){const t={name:"Brave"};if(e){const r=e.getBrandVersion("Brave");
8if(r)return t.version=r,t}return t}},{test:[/chromium/i],describe(n){const e={name:"Chromium"},t=A.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,n)||A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/chrome|crios|crmo/i],describe(n){const e={name:"Chrome"},t=A.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/GSA/i],describe(n){const e={name:"Google Search"},t=A.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test(n){const e=!n.test(/like android/i),t=n.test(/android/i);return e&&t},describe(n){const e={name:"Android Browser"},t=A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/playstation 4/i],describe(n){const e={name:"PlayStation 4"},t=A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/safari|applewebkit/i],describe(n){const e={name:"Safari"},t=A.getFirstMatch(K,n);return t&&(e.version=t),e}},{test:[/.*/i],describe(n){const e=n.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:A.getFirstMatch(e,n),version:A.getSecondMatch(e,n)}}}];var zm=[{test:[/Roku\/DVP/],describe(n){const e=A.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,n);return{name:Ve.Roku,version:e}}},{test:[/windows phone/i],describe(n){const e=A.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,n);return{name:Ve.WindowsPhone,version:e}}},{test:[/windows /i],describe(n){const e=A.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,n),t=A.getWindowsVersionName(e);return{name:Ve.Windows,version:e,versionName:t}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(n){const e={name:Ve.iOS},t=A.getSecondMatch(/(Version\/)(\d[\d.]+)/,n);return t&&(e.version=t),e}},{test:[/macintosh/i],describe(n){const e=A.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,n).replace(/[_\s]/g,"."),t=A.getMacOSVersionName(e),r={name:Ve.MacOS,version:e};return t&&(r.versionName=t),r}},{test:[/(ipod|iphone|ipad)/i],describe(n){const e=A.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,n).replace(/[_\s]/g,".");return{name:Ve.iOS,version:e}}},{test:[/OpenHarmony/i],describe(n){const e=A.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,n);return{name:Ve.HarmonyOS,version:e}}},{test(n){const e=!n.test(/like android/i),t=n.test(/android/i);return e&&t},describe(n){const e=A.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,n),t=A.getAndroidVersionName(e),r={name:Ve.Android,version:e};return t&&(r.versionName=t),r}},{test:[/(web|hpw)[o0]s/i],describe(n){const e=A.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,n),t={name:Ve.WebOS};return e&&e.length&&(t.version=e),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(n){const e=A.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,n)||A.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,n)||A.getFirstMatch(/\bbb(\d+)/i,n);return{name:Ve.BlackBerry,version:e}}},{test:[/bada/i],describe(n){const e=A.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,n);return{name:Ve.Bada,version:e}}},{test:[/tizen/i],describe(n){const e=A.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,n);return{name:Ve.Tizen,version:e}}},{test:[/linux/i],describe:()=>({name:Ve.Linux})},{test:[/CrOS/],describe:()=>({name:Ve.ChromeOS})},{test:[/PlayStation 4/],describe(n){const e=A.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,n);return{name:Ve.PlayStation4,version:e}}}],Wm=[{test:[/googlebot/i],describe:()=>({type:G.bot,vendor:"Google"})},{test:[/linespider/i],describe:()=>({type:G.bot,vendor:"Line"})},{test:[/amazonbot/i],describe:()=>({type:G.bot,vendor:"Amazon"})},{test:[/gptbot/i],describe:()=>({type:G.bot,vendor:"OpenAI"})},{test:[/chatgpt-user/i],describe:()=>({type:G.bot,vendor:"OpenAI"})},{test:[/oai-searchbot/i],describe:()=>({type:G.bot,vendor:"OpenAI"})},{test:[/baiduspider/i],describe:()=>({type:G.bot,vendor:"Baidu"})},{test:[/bingbot/i],describe:()=>({type:G.bot,vendor:"Bing"})},{test:[/duckduckbot/i],describe:()=>({type:G.bot,vendor:"DuckDuckGo"})},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:()=>({type:G.bot,vendor:"Anthropic"})},{test:[/omgilibot/i,/webzio-extended/i],describe:()=>({type:G.bot,vendor:"Webz.io"})},{test:[/diffbot/i],describe:()=>({type:G.bot,vendor:"Diffbot"})},{test:[/perplexitybot/i],describe:()=>({type:G.bot,vendor:"Perplexity AI"})},{test:[/perplexity-user/i],describe:()=>({type:G.bot,vendor:"Perplexity AI"})},{test:[/youbot/i],describe:()=>({type:G.bot,vendor:"You.com"})},{test:[/ia_archiver/i],describe:()=>({type:G.bot,vendor:"Internet Archive"})},{test:[/meta-webindexer/i],describe:()=>({type:G.bot,vendor:"Meta"})},{test:[/meta-externalads/i],describe:()=>({type:G.bot,vendor:"Meta"})},{test:[/meta-externalagent/i],describe:()=>({type:G.bot,vendor:"Meta"})},{test:[/meta-externalfetcher/i],describe:()=>({type:G.bot,vendor:"Meta"})},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:()=>({type:G.bot,vendor:"Meta"})},{test:[/slackbot/i,/slack-imgProxy/i],describe:()=>({type:G.bot,vendor:"Slack"})},{test:[/yahoo/i],describe:()=>({type:G.bot,vendor:"Yahoo"})},{test:[/yandexbot/i,/yandexmobilebot/i],describe:()=>({type:G.bot,vendor:"Yandex"})},{test:[/pingdom/i],describe:()=>({type:G.bot,vendor:"Pingdom"})},{test:[/huawei/i],describe(n){const e=A.getFirstMatch(/(can-l01)/i,n)&&"Nova",t={type:G.mobile,vendor:"Huawei"};return e&&(t.model=e),t}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:()=>({type:G.tablet,vendor:"Nexus"})},{test:[/ipad/i],describe:()=>({type:G.tablet,vendor:"Apple",model:"iPad"})},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:()=>({type:G.tablet,vendor:"Apple",model:"iPad"})},{test:[/kftt build/i],describe:()=>({type:G.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"})},{test:[/silk/i],describe:()=>({type:G.tablet,vendor:"Amazon"})},{test:[/tablet(?! pc)/i],describe:()=>({type:G.tablet})},{test(n){const e=n.test(/ipod|iphone/i),t=n.test(/like (ipod|iphone)/i);return e&&!t},describe(n){const e=A.getFirstMatch(/(ipod|iphone)/i,n);return{type:G.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:()=>({type:G.mobile,vendor:"Nexus"})},{test:[/Nokia/i],describe(n){const e=A.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,n),t={type:G.mobile,vendor:"Nokia"};return e&&(t.model=e),t}},{test:[/[^-]mobi/i],describe:()=>({type:G.mobile})},{test:n=>n.getBrowserName(!0)==="blackberry",describe:()=>({type:G.mobile,vendor:"BlackBerry"})},{test:n=>n.getBrowserName(!0)==="bada",describe:()=>({type:G.mobile})},{test:n=>n.getBrowserName()==="windows phone",describe:()=>({type:G.mobile,vendor:"Microsoft"})},{test(n){const e=Number(String(n.getOSVersion()).split(".")[0]);return n.getOSName(!0)==="android"&&e>=3},describe:()=>({type:G.tablet})},{test:n=>n.getOSName(!0)==="android",describe:()=>({type:G.mobile})},{test:[/smart-?tv|smarttv/i],describe:()=>({type:G.tv})},{test:[/netcast/i],describe:()=>({type:G.tv})},{test:n=>n.getOSName(!0)==="macos",describe:()=>({type:G.desktop,vendor:"Apple"})},{test:n=>n.getOSName(!0)==="windows",describe:()=>({type:G.desktop})},{test:n=>n.getOSName(!0)==="linux",describe:()=>({type:G.desktop})},{test:n=>n.getOSName(!0)==="playstation 4",describe:()=>({type:G.tv})},{test:n=>n.getOSName(!0)==="roku",describe:()=>({type:G.tv})}],qm=[{test:n=>n.getBrowserName(!0)==="microsoft edge",describe(n){if(/\sedg\//i.test(n))return{name:$t.Blink};const e=A.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,n);return{name:$t.EdgeHTML,version:e}}},{test:[/trident/i],describe(n){const e={name:$t.Trident},t=A.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:n=>n.test(/presto/i),describe(n){const e={name:$t.Presto},t=A.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test(n){const e=n.test(/gecko/i),t=n.test(/like gecko/i);return e&&!t},describe(n){const e={name:$t.Gecko},t=A.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:$t.Blink})},{test:[/(apple)?webkit/i],describe(n){const e={name:$t.WebKit},t=A.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,n);return t&&(e.version=t),e}}];class oo{constructor(e,t=!1,r=null){if(e==null||e==="")throw new Error("UserAgent parameter can't be empty");this._ua=e;let i=!1;typeof t=="boolean"?(i=t,this._hints=r):this._hints=t!=null&&typeof t=="object"?t:null,this.parsedResult={},i!==!0&&this.parse()}getHints(){return this._hints}hasBrand(e){if(!this._hints||!Array.isArray(this._hints.brands))return!1;const t=e.toLowerCase();return this._hints.brands.some(r=>r.brand&&r.brand.toLowerCase()===t)}getBrandVersion(e){if(!this._hints||!Array.isArray(this._hints.brands))return;const t=e.toLowerCase(),r=this._hints.brands.find(i=>i.brand&&i.brand.toLowerCase()===t);return r?r.version:void 0}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=A.find(Vm,t=>{if(typeof t.test=="function")return t.test(this);if(Array.isArray(t.test))return t.test.some(r=>this.test(r));
8throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.browser=e.describe(this.getUA(),this)),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const e=A.find(zm,t=>{if(typeof t.test=="function")return t.test(this);if(Array.isArray(t.test))return t.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.os=e.describe(this.getUA())),this.parsedResult.os}getOSName(e){const{name:t}=this.getOS();return e?String(t).toLowerCase()||"":t||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:t}=this.getPlatform();return e?String(t).toLowerCase()||"":t||""}parsePlatform(){this.parsedResult.platform={};const e=A.find(Wm,t=>{if(typeof t.test=="function")return t.test(this);if(Array.isArray(t.test))return t.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.platform=e.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const e=A.find(qm,t=>{if(typeof t.test=="function")return t.test(this);if(Array.isArray(t.test))return t.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.engine=e.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return A.assign({},this.parsedResult)}satisfies(e){const t={};let r=0;const i={};let s=0;if(Object.keys(e).forEach(a=>{const o=e[a];typeof o=="string"?(i[a]=o,s+=1):typeof o=="object"&&(t[a]=o,r+=1)}),r>0){const a=Object.keys(t),o=A.find(a,u=>this.isOS(u));if(o){const u=this.satisfies(t[o]);if(u!==void 0)return u}const l=A.find(a,u=>this.isPlatform(u));if(l){const u=this.satisfies(t[l]);if(u!==void 0)return u}}if(s>0){const a=Object.keys(i),o=A.find(a,l=>this.isBrowser(l,!0));if(o!==void 0)return this.compareVersion(i[o])}}isBrowser(e,t=!1){const r=this.getBrowserName().toLowerCase();let i=e.toLowerCase();const s=A.getBrowserTypeByAlias(i);return t&&s&&(i=s.toLowerCase()),i===r}compareVersion(e){let t=[0],r=e,i=!1;const s=this.getBrowserVersion();if(typeof s=="string")return e[0]===">"||e[0]==="<"?(r=e.substr(1),e[1]==="="?(i=!0,r=e.substr(2)):t=[],e[0]===">"?t.push(1):t.push(-1)):e[0]==="="?r=e.substr(1):e[0]==="~"&&(i=!0,r=e.substr(1)),t.indexOf(A.compareVersions(s,r,i))>-1}isOS(e){return this.getOSName(!0)===String(e).toLowerCase()}isPlatform(e){return this.getPlatformType(!0)===String(e).toLowerCase()}isEngine(e){return this.getEngineName(!0)===String(e).toLowerCase()}is(e,t=!1){return this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some(t=>this.is(t))}}class Jm{static getParser(e,t=!1,r=null){if(typeof e!="string")throw new Error("UserAgent should be a string");return new oo(e,t,r)}static parse(e,t=null){return new oo(e,t).getResult()}static get BROWSER_MAP(){return Nu}static get ENGINE_MAP(){return $t}static get OS_MAP(){return Ve}static get PLATFORMS_MAP(){return G}}function ei(){return Date.now()+Math.random().toString()}function Fn(){throw new Error("Method must be implemented in subclass")}function Ou(n,e){return e!=null&&e.proxyUrl?e.proxyUrl+(e.proxyUrl.slice(-1)==="/"?"":"/")+n.substring(8):n}function Rr(n){if(n!=null&&n.callObjectBundleUrlOverride)return console.warn("The callObjectBundleUrlOverride property is deprecated and will be removed. Please use bundlePathOverride instead. When providing a bundlePathOverride, the URL should point to the directory containing all Daily bundles (call-machine-object-bundle.js and audio-processor-bundle.js)."),n.callObjectBundleUrlOverride;var e=(function(t){if(t!=null&&t.bundlePathOverride){var r=t.bundlePathOverride;return r.endsWith("/")?r.slice(0,-1):r}if(t!=null&&t.callObjectBundleUrlOverride){var i=t.callObjectBundleUrlOverride,s=i.substring(0,i.lastIndexOf("/"));return s.endsWith("/")?s.slice(0,-1):s}var a=Ou("https://c.daily.co/call-machine/versioned/".concat("0.90.0","/static"),t);return a.endsWith("/")?a.slice(0,-1):a})(n)+"/call-machine-object-bundle.js";return e}function Lr(n){try{new URL(n)}catch{return!1}return!0}const we=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,sn="8.55.2",he=globalThis;function Dr(n,e,t){const r=he,i=r.__SENTRY__=r.__SENTRY__||{},s=i[sn]=i[sn]||{};return s[n]||(s[n]=e())}const mn=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,is=["debug","info","warn","error","log","assert","trace"],Fr={};function Xn(n){if(!("console"in he))return n();const e=he.console,t={},r=Object.keys(Fr);r.forEach(i=>
8{const s=Fr[i];t[i]=e[i],e[i]=s});try{return n()}finally{r.forEach(i=>{e[i]=t[i]})}}const Q=Dr("logger",function(){let n=!1;const e={enable:()=>{n=!0},disable:()=>{n=!1},isEnabled:()=>n};return mn?is.forEach(t=>{e[t]=(...r)=>{n&&Xn(()=>{he.console[t](`Sentry Logger [${t}]:`,...r)})}}):is.forEach(t=>{e[t]=()=>{}}),e}),tn="?",co=/\(error: (.*)\)/,lo=/captureMessage|captureException/;function ar(n){return n[n.length-1]||{}}const uo="<anonymous>";function qt(n){try{return n&&typeof n=="function"&&n.name||uo}catch{return uo}}function ho(n){const e=n.exception;if(e){const t=[];try{return e.values.forEach(r=>{r.stacktrace.frames&&t.push(...r.stacktrace.frames)}),t}catch{return}}}const Er={},fo={};function an(n,e){Er[n]=Er[n]||[],Er[n].push(e)}function on(n,e){if(!fo[n]){fo[n]=!0;try{e()}catch(t){mn&&Q.error(`Error while instrumenting ${n}`,t)}}}function mt(n,e){const t=n&&Er[n];if(t)for(const r of t)try{r(e)}catch(i){mn&&Q.error(`Error while triggering instrumentation handler.
9Type: ${n}
10Name: ${qt(r)}
11Error:`,i)}}let Ei=null;function Gm(){Ei=he.onerror,he.onerror=function(n,e,t,r,i){return mt("error",{column:r,error:i,line:t,msg:n,url:e}),!!Ei&&Ei.apply(this,arguments)},he.onerror.__SENTRY_INSTRUMENTED__=!0}let Ci=null;function Hm(){Ci=he.onunhandledrejection,he.onunhandledrejection=function(n){return mt("unhandledrejection",n),!Ci||Ci.apply(this,arguments)},he.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}function ti(){return Vs(he),he}function Vs(n){const e=n.__SENTRY__=n.__SENTRY__||{};return e.version=e.version||sn,e[sn]=e[sn]||{}}const Pu=Object.prototype.toString;function zs(n){switch(Pu.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return cn(n,Error)}}function In(n,e){return Pu.call(n)===`[object ${e}]`}function ju(n){return In(n,"ErrorEvent")}function po(n){return In(n,"DOMError")}function Tt(n){return In(n,"String")}function Ws(n){return typeof n=="object"&&n!==null&&"__sentry_template_string__"in n&&"__sentry_template_values__"in n}function ss(n){return n===null||Ws(n)||typeof n!="object"&&typeof n!="function"}function An(n){return In(n,"Object")}function ni(n){return typeof Event<"u"&&cn(n,Event)}function ri(n){return!!(n&&n.then&&typeof n.then=="function")}function cn(n,e){try{return n instanceof e}catch{return!1}}function Iu(n){return!(typeof n!="object"||n===null||!n.__isVue&&!n._isVue)}const qs=he;function Ru(n,e={}){if(!n)return"<unknown>";try{let t=n;const r=5,i=[];let s=0,a=0;const o=" > ",l=o.length;let u;const f=Array.isArray(e)?e:e.keyAttrs,g=!Array.isArray(e)&&e.maxStringLength||80;for(;t&&s++<r&&(u=Km(t,f),!(u==="html"||s>1&&a+i.length*l+u.length>=g));)i.push(u),a+=u.length,t=t.parentNode;return i.reverse().join(o)}catch{return"<unknown>"}}function Km(n,e){const t=n,r=[];if(!t||!t.tagName)return"";if(qs.HTMLElement&&t instanceof HTMLElement&&t.dataset){if(t.dataset.sentryComponent)return t.dataset.sentryComponent;if(t.dataset.sentryElement)return t.dataset.sentryElement}r.push(t.tagName.toLowerCase());const i=e&&e.length?e.filter(a=>t.getAttribute(a)).map(a=>[a,t.getAttribute(a)]):null;if(i&&i.length)i.forEach(a=>{r.push(`[${a[0]}="${a[1]}"]`)});else{t.id&&r.push(`#${t.id}`);const a=t.className;if(a&&Tt(a)){const o=a.split(/\s+/);for(const l of o)r.push(`.${l}`)}}const s=["aria-label","type","name","title","alt"];for(const a of s){const o=t.getAttribute(a);o&&r.push(`[${a}="${o}"]`)}return r.join("")}function Sn(n,e=0){return typeof n!="string"||e===0||n.length<=e?n:`${n.slice(0,e)}...`}function mo(n,e){if(!Array.isArray(n))return"";const t=[];for(let r=0;r<n.length;r++){const i=n[r];try{Iu(i)?t.push("[VueViewModel]"):t.push(String(i))}catch{t.push("[value cannot be serialized]")}}return t.join(e)}function Ym(n,e,t=!1){return!!Tt(n)&&(In(e,"RegExp")?e.test(n):!!Tt(e)&&(t?n===e:n.includes(e)))}function or(n,e=[],t=!1){return e.some(r=>Ym(n,r,t))}function Ze(n,e,t){if(!(e in n))return;const r=n[e],i=t(r);typeof i=="function"&&Lu(i,r);try{n[e]=i}catch{mn&&Q.log(`Failed to replace method "${e}" in object`,n)}}function ln(n,e,t){try{Object.defineProperty(n,e,{value:t,writable:!0,configurable:!0})}catch{mn&&Q.log(`Failed to add non-enumerable property "${e}" to object`,n)}}function Lu(n,e){try{const t=e.prototype||{};n.prototype=e.prototype=t,ln(n,"__sentry_original__",e)}catch{}}function Js(n){return n.__sentry_original__}function Du(n){if(zs(n))return{message:n.message,name:n.name,stack:n.stack,...vo(n)};if(ni(n)){const e={type:n.type,target:go(n.target),currentTarget:go(n.
11currentTarget),...vo(n)};return typeof CustomEvent<"u"&&cn(n,CustomEvent)&&(e.detail=n.detail),e}return n}function go(n){try{return e=n,typeof Element<"u"&&cn(e,Element)?Ru(n):Object.prototype.toString.call(n)}catch{return"<unknown>"}var e}function vo(n){if(typeof n=="object"&&n!==null){const e={};for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=n[t]);return e}return{}}function it(n){return as(n,new Map)}function as(n,e){if((function(t){if(!An(t))return!1;try{const r=Object.getPrototypeOf(t).constructor.name;return!r||r==="Object"}catch{return!0}})(n)){const t=e.get(n);if(t!==void 0)return t;const r={};e.set(n,r);for(const i of Object.getOwnPropertyNames(n))n[i]!==void 0&&(r[i]=as(n[i],e));return r}if(Array.isArray(n)){const t=e.get(n);if(t!==void 0)return t;const r=[];return e.set(n,r),n.forEach(i=>{r.push(as(i,e))}),r}return n}function Qn(){return Date.now()/1e3}const Ot=(function(){const{performance:n}=he;if(!n||!n.now)return Qn;const e=Date.now()-n.now(),t=n.timeOrigin==null?e:n.timeOrigin;return()=>(t+n.now())/1e3})();function st(){const n=he,e=n.crypto||n.msCrypto;let t=()=>16*Math.random();try{if(e&&e.randomUUID)return e.randomUUID().replace(/-/g,"");e&&e.getRandomValues&&(t=()=>{const r=new Uint8Array(1);return e.getRandomValues(r),r[0]})}catch{}return("10000000100040008000"+1e11).replace(/[018]/g,r=>(r^(15&t())>>r/4).toString(16))}function Fu(n){return n.exception&&n.exception.values?n.exception.values[0]:void 0}function Ut(n){const{message:e,event_id:t}=n;if(e)return e;const r=Fu(n);return r?r.type&&r.value?`${r.type}: ${r.value}`:r.type||r.value||t||"<unknown>":t||"<unknown>"}function os(n,e,t){const r=n.exception=n.exception||{},i=r.values=r.values||[],s=i[0]=i[0]||{};s.value||(s.value=e||""),s.type||(s.type="Error")}function Tn(n,e){const t=Fu(n);if(!t)return;const r=t.mechanism;if(t.mechanism={type:"generic",handled:!0,...r,...e},e&&"data"in e){const i={...r&&r.data,...e.data};t.mechanism.data=i}}function bo(n){if((function(e){try{return e.__sentry_captured__}catch{}})(n))return!0;try{ln(n,"__sentry_captured__",!0)}catch{}return!1}var Ct;function un(n){return new rt(e=>{e(n)})}function Br(n){return new rt((e,t)=>{t(n)})}(()=>{const{performance:n}=he;!n||!n.now||(n.now(),n.timing&&n.timing.navigationStart)})(),(function(n){n[n.PENDING=0]="PENDING",n[n.RESOLVED=1]="RESOLVED",n[n.REJECTED=2]="REJECTED"})(Ct||(Ct={}));class rt{constructor(e){rt.prototype.__init.call(this),rt.prototype.__init2.call(this),rt.prototype.__init3.call(this),rt.prototype.__init4.call(this),this._state=Ct.PENDING,this._handlers=[];try{e(this._resolve,this._reject)}catch(t){this._reject(t)}}then(e,t){return new rt((r,i)=>{this._handlers.push([!1,s=>{if(e)try{r(e(s))}catch(a){i(a)}else r(s)},s=>{if(t)try{r(t(s))}catch(a){i(a)}else i(s)}]),this._executeHandlers()})}catch(e){return this.then(t=>t,e)}finally(e){return new rt((t,r)=>{let i,s;return this.then(a=>{s=!1,i=a,e&&e()},a=>{s=!0,i=a,e&&e()}).then(()=>{s?r(i):t(i)})})}__init(){this._resolve=e=>{this._setResult(Ct.RESOLVED,e)}}__init2(){this._reject=e=>{this._setResult(Ct.REJECTED,e)}}__init3(){this._setResult=(e,t)=>{this._state===Ct.PENDING&&(ri(t)?t.then(this._resolve,this._reject):(this._state=e,this._value=t,this._executeHandlers()))}}__init4(){this._executeHandlers=()=>{if(this._state===Ct.PENDING)return;const e=this._handlers.slice();this._handlers=[],e.forEach(t=>{t[0]||(this._state===Ct.RESOLVED&&t[1](this._value),this._state===Ct.REJECTED&&t[2](this._value),t[0]=!0)})}}}function Xm(n){const e=Ot(),t={sid:st(),init:!0,timestamp:e,started:e,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>(function(r){return it({sid:`${r.sid}`,init:r.init,started:new Date(1e3*r.started).toISOString(),timestamp:new Date(1e3*r.timestamp).toISOString(),status:r.status,errors:r.errors,did:typeof r.did=="number"||typeof r.did=="string"?`${r.did}`:void 0,duration:r.duration,abnormal_mechanism:r.abnormal_mechanism,attrs:{release:r.release,environment:r.environment,ip_address:r.ipAddress,user_agent:r.userAgent}})})(t)};return n&&Nn(t,n),t}function Nn(n,e={}){if(e.user&&(!n.ipAddress&&e.user.ip_address&&(n.ipAddress=e.user.ip_address),n.did||e.did||(n.did=e.user.id||e.user.email||e.user.username)),n.timestamp=e.timestamp||Ot(),e.abnormal_mechanism&&(n.abnormal_mechanism=e.abnormal_mechanism),e.ignoreDuration&&(n.ignoreDuration=e.ignoreDuration),e.sid&&(n.sid=e.sid.length===32?e.sid:st(
11)),e.init!==void 0&&(n.init=e.init),!n.did&&e.did&&(n.did=`${e.did}`),typeof e.started=="number"&&(n.started=e.started),n.ignoreDuration)n.duration=void 0;else if(typeof e.duration=="number")n.duration=e.duration;else{const t=n.timestamp-n.started;n.duration=t>=0?t:0}e.release&&(n.release=e.release),e.environment&&(n.environment=e.environment),!n.ipAddress&&e.ipAddress&&(n.ipAddress=e.ipAddress),!n.userAgent&&e.userAgent&&(n.userAgent=e.userAgent),typeof e.errors=="number"&&(n.errors=e.errors),e.status&&(n.status=e.status)}function yo(){return st()}function cs(){return st().substring(16)}function ii(n,e,t=2){if(!e||typeof e!="object"||t<=0)return e;if(n&&e&&Object.keys(e).length===0)return n;const r={...n};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=ii(r[i],e[i],t-1));return r}const ls="_sentrySpan";function wo(n,e){e?ln(n,ls,e):delete n[ls]}function _o(n){return n[ls]}class Gs{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:yo(),spanId:cs()}}clone(){const e=new Gs;return e._breadcrumbs=[...this._breadcrumbs],e._tags={...this._tags},e._extra={...this._extra},e._contexts={...this._contexts},this._contexts.flags&&(e._contexts.flags={values:[...this._contexts.flags.values]}),e._user=this._user,e._level=this._level,e._session=this._session,e._transactionName=this._transactionName,e._fingerprint=this._fingerprint,e._eventProcessors=[...this._eventProcessors],e._requestSession=this._requestSession,e._attachments=[...this._attachments],e._sdkProcessingMetadata={...this._sdkProcessingMetadata},e._propagationContext={...this._propagationContext},e._client=this._client,e._lastEventId=this._lastEventId,wo(e,_o(this)),e}setClient(e){this._client=e}setLastEventId(e){this._lastEventId=e}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(e){this._scopeListeners.push(e)}addEventProcessor(e){return this._eventProcessors.push(e),this}setUser(e){return this._user=e||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&Nn(this._session,{user:e}),this._notifyScopeListeners(),this}getUser(){return this._user}getRequestSession(){return this._requestSession}setRequestSession(e){return this._requestSession=e,this}setTags(e){return this._tags={...this._tags,...e},this._notifyScopeListeners(),this}setTag(e,t){return this._tags={...this._tags,[e]:t},this._notifyScopeListeners(),this}setExtras(e){return this._extra={...this._extra,...e},this._notifyScopeListeners(),this}setExtra(e,t){return this._extra={...this._extra,[e]:t},this._notifyScopeListeners(),this}setFingerprint(e){return this._fingerprint=e,this._notifyScopeListeners(),this}setLevel(e){return this._level=e,this._notifyScopeListeners(),this}setTransactionName(e){return this._transactionName=e,this._notifyScopeListeners(),this}setContext(e,t){return t===null?delete this._contexts[e]:this._contexts[e]=t,this._notifyScopeListeners(),this}setSession(e){return e?this._session=e:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(e){if(!e)return this;const t=typeof e=="function"?e(this):e,[r,i]=t instanceof Jt?[t.getScopeData(),t.getRequestSession()]:An(t)?[e,e.requestSession]:[],{tags:s,extra:a,user:o,contexts:l,level:u,fingerprint:f=[],propagationContext:g}=r||{};return this._tags={...this._tags,...s},this._extra={...this._extra,...a},this._contexts={...this._contexts,...l},o&&Object.keys(o).length&&(this._user=o),u&&(this._level=u),f.length&&(this._fingerprint=f),g&&(this._propagationContext=g),i&&(this._requestSession=i),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._session=void 0,wo(this,void 0),this._attachments=[],this.setPropagationContext({traceId:yo()}),this._notifyScopeListeners(),this}addBreadcrumb(e,t){const r=typeof t=="number"?t:100;if(r<=0)return this;const i={timestamp:Qn(),...e};return this._breadcrumbs.push(i),this._breadcrumbs.length>r&&(this._breadcrumbs=this._breadcrumbs.slice(-r),this._client&&this._client.re
11cordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(e){return this._attachments.push(e),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:_o(this)}}setSDKProcessingMetadata(e){return this._sdkProcessingMetadata=ii(this._sdkProcessingMetadata,e,2),this}setPropagationContext(e){return this._propagationContext={spanId:cs(),...e},this}getPropagationContext(){return this._propagationContext}captureException(e,t){const r=t&&t.event_id?t.event_id:st();if(!this._client)return Q.warn("No client configured on scope - will not capture exception!"),r;const i=new Error("Sentry syntheticException");return this._client.captureException(e,{originalException:e,syntheticException:i,...t,event_id:r},this),r}captureMessage(e,t,r){const i=r&&r.event_id?r.event_id:st();if(!this._client)return Q.warn("No client configured on scope - will not capture message!"),i;const s=new Error(e);return this._client.captureMessage(e,t,{originalException:e,syntheticException:s,...r,event_id:i},this),i}captureEvent(e,t){const r=t&&t.event_id?t.event_id:st();return this._client?(this._client.captureEvent(e,{...t,event_id:r},this),r):(Q.warn("No client configured on scope - will not capture event!"),r)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(e=>{e(this)}),this._notifyingListeners=!1)}}const Jt=Gs;class Qm{constructor(e,t){let r,i;r=e||new Jt,i=t||new Jt,this._stack=[{scope:r}],this._isolationScope=i}withScope(e){const t=this._pushScope();let r;try{r=e(t)}catch(i){throw this._popScope(),i}return ri(r)?r.then(i=>(this._popScope(),i),i=>{throw this._popScope(),i}):(this._popScope(),r)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const e=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:e}),e}_popScope(){return!(this._stack.length<=1)&&!!this._stack.pop()}}function On(){const n=Vs(ti());return n.stack=n.stack||new Qm(Dr("defaultCurrentScope",()=>new Jt),Dr("defaultIsolationScope",()=>new Jt))}function Zm(n){return On().withScope(n)}function eg(n,e){const t=On();return t.withScope(()=>(t.getStackTop().scope=n,e(n)))}function ko(n){return On().withScope(()=>n(On().getIsolationScope()))}function Hs(n){const e=Vs(n);return e.acs?e.acs:{withIsolationScope:ko,withScope:Zm,withSetScope:eg,withSetIsolationScope:(t,r)=>ko(r),getCurrentScope:()=>On().getScope(),getIsolationScope:()=>On().getIsolationScope()}}function gn(){return Hs(ti()).getCurrentScope()}function Zn(){return Hs(ti()).getIsolationScope()}function ze(){return gn().getClient()}function tg(n){const e=n.getPropagationContext(),{traceId:t,spanId:r,parentSpanId:i}=e;return it({trace_id:t,span_id:r,parent_span_id:i})}function ng(n){const e=n._sentryMetrics;if(!e)return;const t={};for(const[,[r,i]]of e)(t[r]||(t[r]=[])).push(it(i));return t}const rg=/^sentry-/;function ig(n){const e=(function(r){if(!(!r||!Tt(r)&&!Array.isArray(r)))return Array.isArray(r)?r.reduce((i,s)=>{const a=So(s);return Object.entries(a).forEach(([o,l])=>{i[o]=l}),i},{}):So(r)})(n);if(!e)return;const t=Object.entries(e).reduce((r,[i,s])=>(i.match(rg)&&(r[i.slice(7)]=s),r),{});return Object.keys(t).length>0?t:void 0}function So(n){return n.split(",").map(e=>e.split("=").map(t=>decodeURIComponent(t.trim()))).reduce((e,[t,r])=>(t&&r&&(e[t]=r),e),{})}let xo=!1;function sg(n){const{spanId:e,traceId:t,isRemote:r}=n.spanContext();return it({parent_span_id:r?e:Ks(n).parent_span_id,span_id:r?cs():e,trace_id:t})}function Eo(n){return typeof n=="number"?Co(n):Array.isArray(n)?n[0]+n[1]/1e9:n instanceof Date?Co(n.getTime()):Ot()}function Co(n){return n>9999999999?n/1e3:n}function Ks(n){if((function(e){return typeof e.getSpanJSON=="function"})(n))return n.getSpanJSON();try{const{spanId:e,traceId:t}=n.spanContext();if((function(r){const i=r;return!!(i.attributes&&i.startTime&&i.name&&i.endTime&&i.status)})(n)){const{attributes:r,startTime:i,name:s,endTime:a,parentSpanId:o,status:l}=n;return it({span_id:e,trace_id:t,data:r,description:s,parent_span_id:o,start_timestamp:Eo(i),timestamp:Eo(a)||void 0,status:ag(l),op:r["sentry.op"],origin:r["sentry.origin"],_metrics_summary:ng(n)})}return{span_id:e,trace_id:t}}catch{return{}}}
11function ag(n){if(n&&n.code!==0)return n.code===1?"ok":n.message||"unknown_error"}function Bu(n){return n._sentryRootSpan||n}function og(){xo||(Xn(()=>{console.warn("[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly.")}),xo=!0)}const Ys="production";function $u(n,e){const t=e.getOptions(),{publicKey:r}=e.getDsn()||{},i=it({environment:t.environment||Ys,release:t.release,public_key:r,trace_id:n});return e.emit("createDsc",i),i}function cg(n){const e=ze();if(!e)return{};const t=Bu(n),r=t._frozenDsc;if(r)return r;const i=t.spanContext().traceState,s=i&&i.get("sentry.dsc"),a=s&&ig(s);if(a)return a;const o=$u(n.spanContext().traceId,e),l=Ks(t),u=l.data||{},f=u["sentry.sample_rate"];f!=null&&(o.sample_rate=`${f}`);const g=u["sentry.source"],_=l.description;return g!=="url"&&_&&(o.transaction=_),(function(k){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;const b=ze(),v=b&&b.getOptions();return!!v&&(v.enableTracing||"tracesSampleRate"in v||"tracesSampler"in v)})()&&(o.sampled=String((function(k){const{traceFlags:b}=k.spanContext();return b===1})(t))),e.emit("createDsc",o,t),o}const lg=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function $r(n,e=!1){const{host:t,path:r,pass:i,port:s,projectId:a,protocol:o,publicKey:l}=n;return`${o}://${l}${e&&i?`:${i}`:""}@${t}${s?`:${s}`:""}/${r&&`${r}/`}${a}`}function Mo(n){return{protocol:n.protocol,publicKey:n.publicKey||"",pass:n.pass||"",host:n.host,port:n.port||"",path:n.path||"",projectId:n.projectId}}function ug(n){const e=typeof n=="string"?(function(t){const r=lg.exec(t);if(!r)return void Xn(()=>{console.error(`Invalid Sentry Dsn: ${t}`)});const[i,s,a="",o="",l="",u=""]=r.slice(1);let f="",g=u;const _=g.split("/");if(_.length>1&&(f=_.slice(0,-1).join("/"),g=_.pop()),g){const k=g.match(/^\d+/);k&&(g=k[0])}return Mo({host:o,pass:a,path:f,projectId:g,port:l,protocol:i,publicKey:s})})(n):Mo(n);if(e&&(function(t){if(!mn)return!0;const{port:r,projectId:i,protocol:s}=t;return!(["protocol","publicKey","host","projectId"].find(a=>!t[a]&&(Q.error(`Invalid Sentry Dsn: ${a} missing`),!0))||(i.match(/^\d+$/)?(function(a){return a==="http"||a==="https"})(s)?r&&isNaN(parseInt(r,10))&&(Q.error(`Invalid Sentry Dsn: Invalid port ${r}`),1):(Q.error(`Invalid Sentry Dsn: Invalid protocol ${s}`),1):(Q.error(`Invalid Sentry Dsn: Invalid projectId ${i}`),1)))})(e))return e}function Mt(n,e=100,t=1/0){try{return us("",n,e,t)}catch(r){return{ERROR:`**non-serializable** (${r})`}}}function Uu(n,e=3,t=102400){const r=Mt(n,e);return i=r,(function(s){return~-encodeURI(s).split(/%..|./).length})(JSON.stringify(i))>t?Uu(n,e-1,t):r;var i}function us(n,e,t=1/0,r=1/0,i=(function(){const s=typeof WeakSet=="function",a=s?new WeakSet:[];return[function(o){if(s)return!!a.has(o)||(a.add(o),!1);for(let l=0;l<a.length;l++)if(a[l]===o)return!0;return a.push(o),!1},function(o){if(s)a.delete(o);else for(let l=0;l<a.length;l++)if(a[l]===o){a.splice(l,1);break}}]})()){const[s,a]=i;
11if(e==null||["boolean","string"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e))return e;const o=(function(k,b){try{if(k==="domain"&&b&&typeof b=="object"&&b._events)return"[Domain]";if(k==="domainEmitter")return"[DomainEmitter]";if(typeof global<"u"&&b===global)return"[Global]";if(typeof window<"u"&&b===window)return"[Window]";if(typeof document<"u"&&b===document)return"[Document]";if(Iu(b))return"[VueViewModel]";if(An(v=b)&&"nativeEvent"in v&&"preventDefault"in v&&"stopPropagation"in v)return"[SyntheticEvent]";if(typeof b=="number"&&!Number.isFinite(b))return`[${b}]`;if(typeof b=="function")return`[Function: ${qt(b)}]`;if(typeof b=="symbol")return`[${String(b)}]`;if(typeof b=="bigint")return`[BigInt: ${String(b)}]`;const E=(function(C){const O=Object.getPrototypeOf(C);return O?O.constructor.name:"null prototype"})(b);return/^HTML(\w*)Element$/.test(E)?`[HTMLElement: ${E}]`:`[object ${E}]`}catch(E){return`**non-serializable** (${E})`}var v})(n,e);if(!o.startsWith("[object "))return o;if(e.__sentry_skip_normalization__)return e;const l=typeof e.__sentry_override_normalization_depth__=="number"?e.__sentry_override_normalization_depth__:t;if(l===0)return o.replace("object ","");if(s(e))return"[Circular ~]";const u=e;if(u&&typeof u.toJSON=="function")try{return us("",u.toJSON(),l-1,r,i)}catch{}const f=Array.isArray(e)?[]:{};let g=0;const _=Du(e);
11for(const k in _){if(!Object.prototype.hasOwnProperty.call(_,k))continue;if(g>=r){f[k]="[MaxProperties ~]";break}const b=_[k];f[k]=us(k,b,l-1,r,i),g++}return a(e),f}function Kn(n,e=[]){return[n,e]}function dg(n,e){const[t,r]=n;return[t,[...r,e]]}function Ao(n,e){const t=n[1];for(const r of t)if(e(r,r[0].type))return!0;return!1}function ds(n){return he.__SENTRY__&&he.__SENTRY__.encodePolyfill?he.__SENTRY__.encodePolyfill(n):new TextEncoder().encode(n)}function hg(n){const[e,t]=n;let r=JSON.stringify(e);function i(s){typeof r=="string"?r=typeof s=="string"?r+s:[ds(r),s]:r.push(typeof s=="string"?ds(s):s)}for(const s of t){const[a,o]=s;if(i(`
12${JSON.stringify(a)}
13`),typeof o=="string"||o instanceof Uint8Array)i(o);else{let l;try{l=JSON.stringify(o)}catch{l=JSON.stringify(Mt(o))}i(l)}}return typeof r=="string"?r:(function(s){const a=s.reduce((u,f)=>u+f.length,0),o=new Uint8Array(a);let l=0;for(const u of s)o.set(u,l),l+=u.length;return o})(r)}function fg(n){const e=typeof n.data=="string"?ds(n.data):n.data;return[it({type:"attachment",length:e.length,filename:n.filename,content_type:n.contentType,attachment_type:n.attachmentType}),e]}const pg={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",statsd:"metric_bucket",raw_security:"security"};function To(n){return pg[n]}function Vu(n){if(!n||!n.sdk)return;const{name:e,version:t}=n.sdk;return{name:e,version:t}}function mg(n,e,t,r){const i=Vu(t),s=n.type&&n.type!=="replay_event"?n.type:"event";(function(o,l){l&&(o.sdk=o.sdk||{},o.sdk.name=o.sdk.name||l.name,o.sdk.version=o.sdk.version||l.version,o.sdk.integrations=[...o.sdk.integrations||[],...l.integrations||[]],o.sdk.packages=[...o.sdk.packages||[],...l.packages||[]])})(n,t&&t.sdk);const a=(function(o,l,u,f){const g=o.sdkProcessingMetadata&&o.sdkProcessingMetadata.dynamicSamplingContext;return{event_id:o.event_id,sent_at:new Date().toISOString(),...l&&{sdk:l},...!!u&&f&&{dsn:$r(f)},...g&&{trace:it({...g})}}})(n,i,r,e);return delete n.sdkProcessingMetadata,Kn(a,[[{type:s},n]])}function hs(n,e,t,r=0){return new rt((i,s)=>{const a=n[r];if(e===null||typeof a!="function")i(e);else{const o=a({...e},t);we&&a.id&&o===null&&Q.log(`Event processor "${a.id}" dropped event`),ri(o)?o.then(l=>hs(n,l,t,r+1).then(i)).then(null,s):hs(n,o,t,r+1).then(i).then(null,s)}})}let cr,No,Mi;function gg(n,e){const{fingerprint:t,span:r,breadcrumbs:i,sdkProcessingMetadata:s}=e;(function(a,o){const{extra:l,tags:u,user:f,contexts:g,level:_,transactionName:k}=o,b=it(l);b&&Object.keys(b).length&&(a.extra={...b,...a.extra});const v=it(u);v&&Object.keys(v).length&&(a.tags={...v,...a.tags});const E=it(f);E&&Object.keys(E).length&&(a.user={...E,...a.user});const C=it(g);C&&Object.keys(C).length&&(a.contexts={...C,...a.contexts}),_&&(a.level=_),k&&a.type!=="transaction"&&(a.transaction=k)})(n,e),r&&(function(a,o){a.contexts={trace:sg(o),...a.contexts},a.sdkProcessingMetadata={dynamicSamplingContext:cg(o),...a.sdkProcessingMetadata};const l=Bu(o),u=Ks(l).description;u&&!a.transaction&&a.type==="transaction"&&(a.transaction=u)})(n,r),(function(a,o){a.fingerprint=a.fingerprint?Array.isArray(a.fingerprint)?a.fingerprint:[a.fingerprint]:[],o&&(a.fingerprint=a.fingerprint.concat(o)),a.fingerprint&&!a.fingerprint.length&&delete a.fingerprint})(n,t),(function(a,o){const l=[...a.breadcrumbs||[],...o];a.breadcrumbs=l.length?l:void 0})(n,i),(function(a,o){a.sdkProcessingMetadata={...a.sdkProcessingMetadata,...o}})(n,s)}function Oo(n,e){const{extra:t,tags:r,user:i,contexts:s,level:a,sdkProcessingMetadata:o,breadcrumbs:l,fingerprint:u,eventProcessors:f,attachments:g,propagationContext:_,transactionName:k,span:b}=e;lr(n,"extra",t),lr(n,"tags",r),lr(n,"user",i),lr(n,"contexts",s),n.sdkProcessingMetadata=ii(n.sdkProcessingMetadata,o,2),a&&(n.level=a),k&&(n.transactionName=k),b&&(n.span=b),l.length&&(n.breadcrumbs=[...n.breadcrumbs,...l]),u.length&&(n.fingerprint=[...n.fingerprint,...u]),f.length&&(n.eventProcessors=[...n.eventProcessors,...f]),g.length&&(n.attachments=[...n.attachments,...g]),n.propagationContext={...n.propagationContext,..._}}function lr(n,e,t){n[e]=ii(n[e],t,1)}function vg(n,e,t,r,i,s){const{normalizeDepth:a=3,normalizeMaxBreadth:o=1e3}=n,l={...e,event_id:e.event_id||t.event_id||st(),timestamp:e.timestamp||Qn()},u=t.integrations||n.integrations.map(b=>b.name);(function(b,v){const{environment:E,release:C,dist:O,maxValueLength:j=250}=v;b.environment=b.environment||E||Ys,!b.release&&C&&(b.release=C),!b.dist&&O&&(b.dist=O),b.message&&(b.message=Sn(b.message,j));const S=b.exception&&b.exception.values&&b.exception.values[0];
13S&&S.value&&(S.value=Sn(S.value,j));const x=b.request;x&&x.url&&(x.url=Sn(x.url,j))})(l,n),(function(b,v){v.length>0&&(b.sdk=b.sdk||{},b.sdk.integrations=[...b.sdk.integrations||[],...v])})(l,u),i&&i.emit("applyFrameMetadata",e),e.type===void 0&&(function(b,v){const E=(function(C){const O=he._sentryDebugIds;if(!O)return{};const j=Object.keys(O);return Mi&&j.length===No||(No=j.length,Mi=j.reduce((S,x)=>{cr||(cr={});const T=cr[x];if(T)S[T[0]]=T[1];else{const I=C(x);for(let F=I.length-1;F>=0;F--){const $=I[F],z=$&&$.filename,fe=O[x];if(z&&fe){S[z]=fe,cr[x]=[z,fe];break}}}return S},{})),Mi})(v);try{b.exception.values.forEach(C=>{C.stacktrace.frames.forEach(O=>{E&&O.filename&&(O.debug_id=E[O.filename])})})}catch{}})(l,n.stackParser);const f=(function(b,v){if(!v)return b;const E=b?b.clone():new Jt;return E.update(v),E})(r,t.captureContext);t.mechanism&&Tn(l,t.mechanism);const g=i?i.getEventProcessors():[],_=Dr("globalScope",()=>new Jt).getScopeData();s&&Oo(_,s.getScopeData()),f&&Oo(_,f.getScopeData());const k=[...t.attachments||[],..._.attachments];return k.length&&(t.attachments=k),gg(l,_),hs([...g,..._.eventProcessors],l,t).then(b=>(b&&(function(v){const E={};try{v.exception.values.forEach(O=>{O.stacktrace.frames.forEach(j=>{j.debug_id&&(j.abs_path?E[j.abs_path]=j.debug_id:j.filename&&(E[j.filename]=j.debug_id),delete j.debug_id)})})}catch{}if(Object.keys(E).length===0)return;v.debug_meta=v.debug_meta||{},v.debug_meta.images=v.debug_meta.images||[];const C=v.debug_meta.images;Object.entries(E).forEach(([O,j])=>{C.push({type:"sourcemap",code_file:O,debug_id:j})})})(b),typeof a=="number"&&a>0?(function(v,E,C){if(!v)return null;const O={...v,...v.breadcrumbs&&{breadcrumbs:v.breadcrumbs.map(j=>({...j,...j.data&&{data:Mt(j.data,E,C)}}))},...v.user&&{user:Mt(v.user,E,C)},...v.contexts&&{contexts:Mt(v.contexts,E,C)},...v.extra&&{extra:Mt(v.extra,E,C)}};return v.contexts&&v.contexts.trace&&O.contexts&&(O.contexts.trace=v.contexts.trace,v.contexts.trace.data&&(O.contexts.trace.data=Mt(v.contexts.trace.data,E,C))),v.spans&&(O.spans=v.spans.map(j=>({...j,...j.data&&{data:Mt(j.data,E,C)}}))),v.contexts&&v.contexts.flags&&O.contexts&&(O.contexts.flags=Mt(v.contexts.flags,3,C)),O})(b,a,o):b))}function Po(n,e){return gn().captureEvent(n,e)}function jo(n){const e=ze(),t=Zn(),r=gn(),{release:i,environment:s=Ys}=e&&e.getOptions()||{},{userAgent:a}=he.navigator||{},o=Xm({release:i,environment:s,user:r.getUser()||t.getUser(),...a&&{userAgent:a},...n}),l=t.getSession();return l&&l.status==="ok"&&Nn(l,{status:"exited"}),zu(),t.setSession(o),r.setSession(o),o}function zu(){const n=Zn(),e=gn(),t=e.getSession()||n.getSession();t&&(function(r,i){let s={};r.status==="ok"&&(s={status:"exited"}),Nn(r,s)})(t),Wu(),n.setSession(),e.setSession()}function Wu(){const n=Zn(),e=gn(),t=ze(),r=e.getSession()||n.getSession();r&&t&&t.captureSession(r)}function Io(n=!1){n?zu():Wu()}function bg(n,e,t){return e||`${(function(r){return`${(function(i){const s=i.protocol?`${i.protocol}:`:"",a=i.port?`:${i.port}`:"";return`${s}//${i.host}${a}${i.path?`/${i.path}`:""}/api/`})(r)}${r.projectId}/envelope/`})(n)}?${(function(r,i){const s={sentry_version:"7"};return r.publicKey&&(s.sentry_key=r.publicKey),i&&(s.sentry_client=`${i.name}/${i.version}`),new URLSearchParams(s).toString()})(n,t)}`}const Ro=[];function Lo(n,e){for(const t of e)t&&t.afterAllSetup&&t.afterAllSetup(n)}function Do(n,e,t){if(t[e.name])we&&Q.log(`Integration skipped because it was already installed: ${e.name}`);else{if(t[e.name]=e,Ro.indexOf(e.name)===-1&&typeof e.setupOnce=="function"&&(e.setupOnce(),Ro.push(e.name)),e.setup&&typeof e.setup=="function"&&e.setup(n),typeof e.preprocessEvent=="function"){const r=e.preprocessEvent.bind(e);n.on("preprocessEvent",(i,s)=>r(i,s,n))}if(typeof e.processEvent=="function"){const r=e.processEvent.bind(e),i=Object.assign((s,a)=>r(s,a,n),{id:e.name});n.addEventProcessor(i)}we&&Q.log(`Integration installed: ${e.name}`)}}class ht extends Error{constructor(e,t="warn"){super(e),this.message=e,this.logLevel=t}}const Fo="Not capturing exception because it's already been captured.";class yg{constructor(e){if(this._options=e,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],e.dsn?this._dsn=ug(e.dsn):we&&Q.warn("No DSN provided, client will not send events."),this._dsn){const r=bg(this._dsn,e.tunnel,e._metadata?e._metadata.sdk:void 0);this._transport=e.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...e.transportOptions,url:r})}const t=["enableTracing","tracesSampleRate","tracesSampler"].find(r=>r in e&&e[r]==null);t&&Xn(()=>{console.warn(`[Sentry] Deprecation warning: \`${t}\` is set to undefined, which leads to tracing being enabled. In v9, a value of \`undefined\` will result in tracing being disabled.`)})}captureException(e,t,r){const i=st();if(bo(e))return we&&Q.log(Fo),i;const s={event_id:i,...t};return this._process(this.eventFromException(e,s).then(a=>this._captureEvent(a,s,r))),s.event_id}
13captureMessage(e,t,r,i){const s={event_id:st(),...r},a=Ws(e)?e:String(e),o=ss(e)?this.eventFromMessage(a,t,s):this.eventFromException(e,s);return this._process(o.then(l=>this._captureEvent(l,s,i))),s.event_id}captureEvent(e,t,r){const i=st();if(t&&t.originalException&&bo(t.originalException))return we&&Q.log(Fo),i;const s={event_id:i,...t},a=(e.sdkProcessingMetadata||{}).capturedSpanScope;return this._process(this._captureEvent(e,s,a||r)),s.event_id}captureSession(e){typeof e.release!="string"?we&&Q.warn("Discarded session because of missing or non-string release"):(this.sendSession(e),Nn(e,{init:!1}))}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}flush(e){const t=this._transport;return t?(this.emit("flush"),this._isClientDoneProcessing(e).then(r=>t.flush(e).then(i=>r&&i))):un(!0)}close(e){return this.flush(e).then(t=>(this.getOptions().enabled=!1,this.emit("close"),t))}getEventProcessors(){return this._eventProcessors}addEventProcessor(e){this._eventProcessors.push(e)}init(){(this._isEnabled()||this._options.integrations.some(({name:e})=>e.startsWith("Spotlight")))&&this._setupIntegrations()}getIntegrationByName(e){return this._integrations[e]}addIntegration(e){const t=this._integrations[e.name];Do(this,e,this._integrations),t||Lo(this,[e])}sendEvent(e,t={}){this.emit("beforeSendEvent",e,t);let r=mg(e,this._dsn,this._options._metadata,this._options.tunnel);for(const s of t.attachments||[])r=dg(r,fg(s));const i=this.sendEnvelope(r);i&&i.then(s=>this.emit("afterSendEvent",e,s),null)}sendSession(e){const t=(function(r,i,s,a){const o=Vu(s);return Kn({sent_at:new Date().toISOString(),...o&&{sdk:o},...!!a&&i&&{dsn:$r(i)}},["aggregates"in r?[{type:"sessions"},r]:[{type:"session"},r.toJSON()]])})(e,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(t)}recordDroppedEvent(e,t,r){if(this._options.sendClientReports){const i=typeof r=="number"?r:1,s=`${e}:${t}`;we&&Q.log(`Recording outcome: "${s}"${i>1?` (${i} times)`:""}`),this._outcomes[s]=(this._outcomes[s]||0)+i}}on(e,t){const r=this._hooks[e]=this._hooks[e]||[];return r.push(t),()=>{const i=r.indexOf(t);i>-1&&r.splice(i,1)}}emit(e,...t){const r=this._hooks[e];r&&r.forEach(i=>i(...t))}sendEnvelope(e){return this.emit("beforeEnvelope",e),this._isEnabled()&&this._transport?this._transport.send(e).then(null,t=>(we&&Q.error("Error while sending envelope:",t),t)):(we&&Q.error("Transport disabled"),un({}))}_setupIntegrations(){const{integrations:e}=this._options;this._integrations=(function(t,r){const i={};return r.forEach(s=>{s&&Do(t,s,i)}),i})(this,e),Lo(this,e)}_updateSessionFromEvent(e,t){let r=t.level==="fatal",i=!1;const s=t.exception&&t.exception.values;if(s){i=!0;for(const o of s){const l=o.mechanism;if(l&&l.handled===!1){r=!0;break}}}const a=e.status==="ok";(a&&e.errors===0||a&&r)&&(Nn(e,{...r&&{status:"crashed"},errors:e.errors||Number(i||r)}),this.captureSession(e))}_isClientDoneProcessing(e){return new rt(t=>{let r=0;const i=setInterval(()=>{this._numProcessing==0?(clearInterval(i),t(!0)):(r+=1,e&&r>=e&&(clearInterval(i),t(!1)))},1)})}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(e,t,r=gn(),i=Zn()){const s=this.getOptions(),a=Object.keys(this._integrations);return!t.integrations&&a.length>0&&(t.integrations=a),this.emit("preprocessEvent",e,t),e.type||i.setLastEventId(e.event_id||t.event_id),vg(s,e,t,r,this,i).then(o=>{if(o===null)return o;o.contexts={trace:tg(r),...o.contexts};const l=(function(u,f){const g=f.getPropagationContext();return g.dsc||$u(g.traceId,u)})(this,r);return o.sdkProcessingMetadata={dynamicSamplingContext:l,...o.sdkProcessingMetadata},o})}_captureEvent(e,t={},r){return this._processEvent(e,t,r).then(i=>i.event_id,i=>{we&&(i instanceof ht&&i.logLevel==="log"?Q.log(i.message):Q.warn(i))})}_processEvent(e,t,r){const i=this.getOptions(),{sampleRate:s}=i,a=$o(e),o=Bo(e),l=e.type||"error",u=`before send for type \`${l}\``,f=s===void 0?void 0:(function(k){if(typeof k=="boolean")return Number(k);const b=typeof k=="string"?parseFloat(k):k;if(!(typeof b!="number"||isNaN(b)||b<0||b>1))return b;
13we&&Q.warn(`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(k)} of type ${JSON.stringify(typeof k)}.`)})(s);if(o&&typeof f=="number"&&Math.random()>f)return this.recordDroppedEvent("sample_rate","error",e),Br(new ht(`Discarding event because it's not included in the random sample (sampling rate = ${s})`,"log"));const g=l==="replay_event"?"replay":l,_=(e.sdkProcessingMetadata||{}).capturedSpanIsolationScope;return this._prepareEvent(e,t,r,_).then(k=>{if(k===null)throw this.recordDroppedEvent("event_processor",g,e),new ht("An event processor returned `null`, will not send event.","log");if(t.data&&t.data.__sentry__===!0)return k;const b=(function(v,E,C,O){const{beforeSend:j,beforeSendTransaction:S,beforeSendSpan:x}=E;if(Bo(C)&&j)return j(C,O);if($o(C)){if(C.spans&&x){const T=[];for(const I of C.spans){const F=x(I);F?T.push(F):(og(),v.recordDroppedEvent("before_send","span"))}C.spans=T}if(S){if(C.spans){const T=C.spans.length;C.sdkProcessingMetadata={...C.sdkProcessingMetadata,spanCountBeforeProcessing:T}}return S(C,O)}}return C})(this,i,k,t);return(function(v,E){const C=`${E} must return \`null\` or a valid event.`;if(ri(v))return v.then(O=>{if(!An(O)&&O!==null)throw new ht(C);return O},O=>{throw new ht(`${E} rejected with ${O}`)});if(!An(v)&&v!==null)throw new ht(C);return v})(b,u)}).then(k=>{if(k===null){if(this.recordDroppedEvent("before_send",g,e),a){const E=1+(e.spans||[]).length;this.recordDroppedEvent("before_send","span",E)}throw new ht(`${u} returned \`null\`, will not send event.`,"log")}const b=r&&r.getSession();if(!a&&b&&this._updateSessionFromEvent(b,k),a){const E=(k.sdkProcessingMetadata&&k.sdkProcessingMetadata.spanCountBeforeProcessing||0)-(k.spans?k.spans.length:0);E>0&&this.recordDroppedEvent("before_send","span",E)}const v=k.transaction_info;if(a&&v&&k.transaction!==e.transaction){const E="custom";k.transaction_info={...v,source:E}}return this.sendEvent(k,t),k}).then(null,k=>{throw k instanceof ht?k:(this.captureException(k,{data:{__sentry__:!0},originalException:k}),new ht(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
14Reason: ${k}`))})}_process(e){this._numProcessing++,e.then(t=>(this._numProcessing--,t),t=>(this._numProcessing--,t))}_clearOutcomes(){const e=this._outcomes;return this._outcomes={},Object.entries(e).map(([t,r])=>{const[i,s]=t.split(":");return{reason:i,category:s,quantity:r}})}_flushOutcomes(){we&&Q.log("Flushing outcomes...");const e=this._clearOutcomes();if(e.length===0)return void(we&&Q.log("No outcomes to send"));if(!this._dsn)return void(we&&Q.log("No dsn provided, will not send outcomes"));we&&Q.log("Sending outcomes:",e);const t=(r=e,Kn((i=this._options.tunnel&&$r(this._dsn))?{dsn:i}:{},[[{type:"client_report"},{timestamp:s||Qn(),discarded_events:r}]]));var r,i,s;this.sendEnvelope(t)}}function Bo(n){return n.type===void 0}function $o(n){return n.type==="transaction"}function wg(n){const e=[];function t(r){return e.splice(e.indexOf(r),1)[0]||Promise.resolve(void 0)}return{$:e,add:function(r){if(!(n===void 0||e.length<n))return Br(new ht("Not adding Promise because buffer limit was reached."));const i=r();return e.indexOf(i)===-1&&e.push(i),i.then(()=>t(i)).then(null,()=>t(i).then(null,()=>{})),i},drain:function(r){return new rt((i,s)=>{let a=e.length;if(!a)return i(!0);const o=setTimeout(()=>{r&&r>0&&i(!1)},r);e.forEach(l=>{un(l).then(()=>{--a||(clearTimeout(o),i(!0))},s)})})}}}function _g(n,{statusCode:e,headers:t},r=Date.now()){const i={...n},s=t&&t["x-sentry-rate-limits"],a=t&&t["retry-after"];if(s)for(const o of s.trim().split(",")){const[l,u,,,f]=o.split(":",5),g=parseInt(l,10),_=1e3*(isNaN(g)?60:g);if(u)for(const k of u.split(";"))k==="metric_bucket"&&f&&!f.split(";").includes("custom")||(i[k]=r+_);else i.all=r+_}else a?i.all=r+(function(o,l=Date.now()){const u=parseInt(`${o}`,10);if(!isNaN(u))return 1e3*u;const f=Date.parse(`${o}`);return isNaN(f)?6e4:f-l})(a,r):e===429&&(i.all=r+6e4);return i}function kg(n,e,t=wg(n.bufferSize||64)){let r={};return{send:function(i){const s=[];if(Ao(i,(l,u)=>{const f=To(u);if((function(g,_,k=Date.now()){return(function(b,v){return b[v]||b.all||0})(g,_)>k})(r,f)){const g=Uo(l,u);n.recordDroppedEvent("ratelimit_backoff",f,g)}else s.push(l)}),s.length===0)return un({});const a=Kn(i[0],s),o=l=>{Ao(a,(u,f)=>{const g=Uo(u,f);n.recordDroppedEvent(l,To(f),g)})};return t.add(()=>e({body:hg(a)}).then(l=>(l.statusCode!==void 0&&(l.statusCode<200||l.statusCode>=300)&&we&&Q.warn(`Sentry responded with status code ${l.statusCode} to sent event.`),r=_g(r,l),l),l=>{throw o("network_error"),l})).then(l=>l,l=>{if(l instanceof ht)return we&&Q.error("Skipped sending event because buffer is full."),o("queue_overflow"),un({});throw l})},flush:i=>t.drain(i)}}function Uo(n,e){if(e==="event"||e==="transaction")return Array.isArray(n)?n[1]:void 0}const Sg=100;function Kt(n,e){const t=ze(),r=Zn();if(!t)return;const{beforeBreadcrumb:i=null,maxBreadcrumbs:s=Sg}=t.getOptions();if(s<=0)return;const a={timestamp:Qn(),...n},o=i?Xn(()=>i(a,e)):a;o!==null&&(t.emit&&t.emit("beforeAddBreadcrumb",o,e),r.addBreadcrumb(o,s))}let Vo;const zo=new WeakMap,xg=()=>({name:"FunctionToString",setupOnce(){Vo=Function.prototype.toString;try{Function.prototype.toString=function(...n){const e=Js(this),t=zo.has(ze())&&e!==void 0?e:this;return Vo.apply(t,n)}}catch{}},setup(n){zo.set(n,!0)}}),Eg=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/,/^Can't find variable: gmo$/,"undefined is not an object (evaluating 'a.L')",`can't redefine non-configurable property "solana"`,"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)","Can't find variable: _AutofillCallbackHandler",/^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/,/^Java exception was raised during method invocation$/],Cg=(n={})=>({name:"InboundFilters",processEvent(e,t,r){const i=r.getOptions(),s=(function(a={},o={}){return{allowUrls:[...a.allowUrls||[],...o.allowUrls||[]],denyUrls:[...a.denyUrls||[],...o.denyUrls||[]],ignoreErrors:[...a.ignoreErrors||[],...o.ignoreErrors||[],...a.disableErrorDefaults?[]:Eg],ignoreTransactions:[...a.ignoreTransactions||[],...o.ignoreTransactions||[]],ignoreInternal:a.ignoreInternal===void 0||a.ignoreInternal}})(n,i);return(function(a,o){return o.ignoreInternal&&(function(l){try{return l.exception.values[0].type==="SentryError"}catch{}return!1})(a)?(we&&Q.warn(`Event dropped due to being internal Sentry Error.
15Event: ${Ut(a)}`),!0):(function(l,u){return l.type||!u||!u.length?!1:(function(f){const g=[];f.message&&g.push(f.message);let _;try{_=f.exception.values[f.exception.values.length-1]}catch{}return _&&_.value&&(g.push(_.value),_.type&&g.push(`${_.type}: ${_.value}`)),g})(l).some(f=>or(f,u))})(a,o.ignoreErrors)?(we&&Q.warn(`Event dropped due to being matched by \`ignoreErrors\` option.
16Event: ${Ut(a)}`),!0):(function(l){return l.type||!l.exception||!l.exception.values||l.exception.values.length===0?!1:!l.message&&!l.exception.values.some(u=>u.stacktrace||u.type&&u.type!=="Error"||u.value)})(a)?(we&&Q.warn(`Event dropped due to not having an error message, error type or stacktrace.
17Event: ${Ut(a)}`),!0):(function(l,u){if(l.type!=="transaction"||!u||!u.length)return!1;const f=l.transaction;return!!f&&or(f,u)})(a,o.ignoreTransactions)?(we&&Q.warn(`Event dropped due to being matched by \`ignoreTransactions\` option.
18Event: ${Ut(a)}`),!0):(function(l,u){if(!u||!u.length)return!1;const f=ur(l);return!!f&&or(f,u)})(a,o.denyUrls)?(we&&Q.warn(`Event dropped due to being matched by \`denyUrls\` option.
19Event: ${Ut(a)}.
20Url: ${ur(a)}`),!0):(function(l,u){if(!u||!u.length)return!0;const f=ur(l);return!f||or(f,u)})(a,o.allowUrls)?!1:(we&&Q.warn(`Event dropped due to not being matched by \`allowUrls\` option.
21Event: ${Ut(a)}.
22Url: ${ur(a)}`),!0)})(e,s)?null:e}});function ur(n){try{let e;try{e=n.exception.values[0].stacktrace.frames}catch{}return e?(function(t=[]){for(let r=t.length-1;r>=0;r--){const i=t[r];
22if(i&&i.filename!=="<anonymous>"&&i.filename!=="[native code]")return i.filename||null}return null})(e):null}catch{return we&&Q.error(`Cannot extract url for event ${Ut(n)}`),null}}function Mg(n,e,t=250,r,i,s,a){if(!(s.exception&&s.exception.values&&a&&cn(a.originalException,Error)))return;const o=s.exception.values.length>0?s.exception.values[s.exception.values.length-1]:void 0;var l,u;o&&(s.exception.values=(l=fs(n,e,i,a.originalException,r,s.exception.values,o,0),u=t,l.map(f=>(f.value&&(f.value=Sn(f.value,u)),f))))}function fs(n,e,t,r,i,s,a,o){if(s.length>=t+1)return s;let l=[...s];if(cn(r[i],Error)){Wo(a,o);const u=n(e,r[i]),f=l.length;qo(u,i,f,o),l=fs(n,e,t,r[i],i,[u,...l],u,f)}return Array.isArray(r.errors)&&r.errors.forEach((u,f)=>{if(cn(u,Error)){Wo(a,o);const g=n(e,u),_=l.length;qo(g,`errors[${f}]`,_,o),l=fs(n,e,t,u,i,[g,...l],g,_)}}),l}function Wo(n,e){n.mechanism=n.mechanism||{type:"generic",handled:!0},n.mechanism={...n.mechanism,...n.type==="AggregateError"&&{is_exception_group:!0},exception_id:e}}function qo(n,e,t,r){n.mechanism=n.mechanism||{type:"generic",handled:!0},n.mechanism={...n.mechanism,type:"chained",source:e,exception_id:t,parent_id:r}}function Ai(n){if(!n)return{};const e=n.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};const t=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],search:t,hash:r,relative:e[5]+t+r}}function Ag(){"console"in he&&is.forEach(function(n){n in he.console&&Ze(he.console,n,function(e){return Fr[n]=e,function(...t){mt("console",{args:t,level:n});const r=Fr[n];r&&r.apply(he.console,t)}})})}function Tg(n){return n==="warn"?"warning":["fatal","error","warning","log","info","debug"].includes(n)?n:"log"}const Ng=()=>{let n;return{name:"Dedupe",processEvent(e){if(e.type)return e;try{if((function(t,r){return r?!!((function(i,s){const a=i.message,o=s.message;return!(!a&&!o||a&&!o||!a&&o||a!==o||!Go(i,s)||!Jo(i,s))})(t,r)||(function(i,s){const a=Ho(s),o=Ho(i);return!(!a||!o||a.type!==o.type||a.value!==o.value||!Go(i,s)||!Jo(i,s))})(t,r)):!1})(e,n))return we&&Q.warn("Event dropped due to being a duplicate of previously captured event."),null}catch{}return n=e}}};function Jo(n,e){let t=ho(n),r=ho(e);if(!t&&!r)return!0;if(t&&!r||!t&&r||r.length!==t.length)return!1;for(let i=0;i<r.length;i++){const s=r[i],a=t[i];if(s.filename!==a.filename||s.lineno!==a.lineno||s.colno!==a.colno||s.function!==a.function)return!1}return!0}function Go(n,e){let t=n.fingerprint,r=e.fingerprint;if(!t&&!r)return!0;if(t&&!r||!t&&r)return!1;try{return t.join("")===r.join("")}catch{return!1}}function Ho(n){return n.exception&&n.exception.values&&n.exception.values[0]}function Ko(n){return n===void 0?void 0:n>=400&&n<500?"warning":n>=500?"error":void 0}const Ti=he;function ps(n){return n&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(n.toString())}function Og(){if(typeof EdgeRuntime=="string")return!0;if(!(function(){if(!("fetch"in Ti))return!1;try{return new Headers,new Request("http://www.example.com"),new Response,!0}catch{return!1}})())return!1;if(ps(Ti.fetch))return!0;let n=!1;const e=Ti.document;if(e&&typeof e.createElement=="function")try{const t=e.createElement("iframe");t.hidden=!0,e.head.appendChild(t),t.contentWindow&&t.contentWindow.fetch&&(n=ps(t.contentWindow.fetch)),e.head.removeChild(t)}catch(t){mn&&Q.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",t)}return n}function Pg(n,e){const t="fetch";an(t,n),on(t,()=>(function(r,i=!1){i&&!Og()||Ze(he,"fetch",function(s){return function(...a){const o=new Error,{method:l,url:u}=(function(g){if(g.length===0)return{method:"GET",url:""};if(g.length===2){const[k,b]=g;return{url:Yo(k),method:ms(b,"method")?String(b.method).toUpperCase():"GET"}}const _=g[0];return{url:Yo(_),method:ms(_,"method")?String(_.method).toUpperCase():"GET"}})(a),f={args:a,fetchData:{method:l,url:u},startTimestamp:1e3*Ot(),virtualError:o};return r||mt("fetch",{...f}),s.apply(he,a).then(async g=>(r?r(g):mt("fetch",{...f,endTimestamp:1e3*Ot(),response:g}),g),g=>{throw mt("fetch",{...f,endTimestamp:1e3*Ot(),error:g}),zs(g)&&g.stack===void 0&&(g.stack=o.stack,ln(g,"framesToPop",1)),g})}})})(void 0,e))}function ms(n,e){return!!n&&typeof n=="object"&&!!n[e]}function Yo(n){return typeof n=="string"?n:n?ms(n,"url")?n.url:n.toString?n.toString():"":""}const dr=he,Oe=he;let gs=0;function Xo(){return gs>0}function Pn(n,e={}){if(!(function(r){return typeof r=="function"})(n))return n;try{const r=n.__sentry_wrapped__;if(r)return typeof r=="function"?r:n;if(Js(n))return n}catch{return n}const t=function(...r){try{const i=r.map(s=>Pn(s,e));return n.apply(this,i)}catch(i){throw gs++,setTimeout(()=>{gs--}),(function(...s){const a=Hs(ti());if(s.length===2){const[o,l]=s;return o?a.withSetScope(o,l):a.withScope(l)}a.withScope(s[0])})(s=>{var a;s.addEventProcessor(o=>(e.mechanism&&(os(o,void 0),Tn(o,e.mechanism)),o.extra={...o.extra,arguments:r},o)),a=i,gn().captureException(a,void 0)}),i}};try{for(const r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}catch{}Lu(t,n),ln(n,"__sentry_wrapped__",t);try{Object.getOwnPropertyDescriptor(t,"name").configurable&&Object.defineProperty(t,"name",{get:()=>n.name})}catch{}return t}const si=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function Xs(n,e){const t=Qs(n,e),r={type:Rg(e),value:Lg(e)};return t.length&&(r.stacktrace={frames:t}),r.type===void 0&&r.value===""&&(r.value="Unrecoverable error caught"),r}function jg(n,e,t,r){const i=ze(),s=i&&i.getOptions().normalizeDepth,a=(function(u){for(const f in u)if(Object.prototype.hasOwnProperty.call(u,f)){const g=u[f];if(g instanceof Error)return g}})(e),o={__serialized__:Uu(e,s)};if(a)return{exception:{values:[Xs(n,a)]},extra:o};const l={exception:{values:[{type:ni(e)?e.constructor.name:r?"UnhandledRejection":"Error",value:Dg(e,{isUnhandledRejection:r})}]},extra:o};if(t){const u=Qs(n,t);u.length&&(l.exception.values[0].stacktrace={frames:u})}return l}function Ni(n,e){return{exception:{values:[Xs(n,e)]}}}function Qs(n,e){const t=e.stacktrace||e.stack||"",r=(function(s){return s&&Ig.test(s.message)?1:0})(e),i=(function(s){return typeof s.framesToPop=="number"?s.framesToPop:0})(e);try{return n(t,r,i)}catch{}return[]}const Ig=/Minified React error #\d+;/i;function qu(n){return typeof WebAssembly<"u"&&WebAssembly.Exception!==void 0&&n instanceof WebAssembly.Exception}function Rg(n){const e=n&&n.name;return!e&&qu(n)?n.message&&Array.isArray(n.message)&&n.message.length==2?n.message[0]:"WebAssembly.Exception":e}function Lg(n){const e=n&&n.message;return e?e.error&&typeof e.error.message=="string"?e.error.message:qu(n)&&Array.isArray(n.message)&&n.message.length==2?n.message[1]:e:"No error message"}function vs(n,e,t,r,i){let s;if(ju(e)&&e.error)return Ni(n,e.error);if(po(e)||In(e,"DOMException")){const a=e;if("stack"in e)s=Ni(n,e);else{const o=a.name||(po(a)?"DOMError":"DOMException"),l=a.message?`${o}: ${a.message}`:o;s=bs(n,l,t,r),os(s,l)}return"code"in a&&(s.tags={...s.tags,"DOMException.code":`${a.code}`}),s}return zs(e)?Ni(n,e):An(e)||ni(e)?(s=jg(n,e,t,i),Tn(s,{synthetic:!0}),s):(s=bs(n,e,t,r),os(s,`${e}`),Tn(s,{synthetic:!0}),s)}function bs(n,e,t,r){const i={};if(r&&t){const s=Qs(n,t);s.length&&(i.exception={values:[{value:e,stacktrace:{frames:s}}]}),Tn(i,{synthetic:!0})}
22if(Ws(e)){const{__sentry_template_string__:s,__sentry_template_values__:a}=e;return i.logentry={message:s,params:a},i}return i.message=e,i}function Dg(n,{isUnhandledRejection:e}){const t=(function(i,s=40){const a=Object.keys(Du(i));a.sort();const o=a[0];if(!o)return"[object has no keys]";if(o.length>=s)return Sn(o,s);for(let l=a.length;l>0;l--){const u=a.slice(0,l).join(", ");if(!(u.length>s))return l===a.length?u:Sn(u,s)}return""})(n),r=e?"promise rejection":"exception";return ju(n)?`Event \`ErrorEvent\` captured as ${r} with message \`${n.message}\``:ni(n)?`Event \`${(function(i){try{const s=Object.getPrototypeOf(i);return s?s.constructor.name:void 0}catch{}})(n)}\` (type=${n.type}) captured as ${r}`:`Object captured as ${r} with keys: ${t}`}class Fg extends yg{constructor(e){const t={parentSpanIsAlwaysRootSpan:!0,...e};(function(r,i,s=[i],a="npm"){const o=r._metadata||{};o.sdk||(o.sdk={name:`sentry.javascript.${i}`,packages:s.map(l=>({name:`${a}:@sentry/${l}`,version:sn})),version:sn}),r._metadata=o})(t,"browser",["browser"],Oe.SENTRY_SDK_SOURCE||"npm"),super(t),t.sendClientReports&&Oe.document&&Oe.document.addEventListener("visibilitychange",()=>{Oe.document.visibilityState==="hidden"&&this._flushOutcomes()})}eventFromException(e,t){return(function(r,i,s,a){const o=vs(r,i,s&&s.syntheticException||void 0,a);return Tn(o),o.level="error",s&&s.event_id&&(o.event_id=s.event_id),un(o)})(this._options.stackParser,e,t,this._options.attachStacktrace)}eventFromMessage(e,t="info",r){return(function(i,s,a="info",o,l){const u=bs(i,s,o&&o.syntheticException||void 0,l);return u.level=a,o&&o.event_id&&(u.event_id=o.event_id),un(u)})(this._options.stackParser,e,t,r,this._options.attachStacktrace)}captureUserFeedback(e){if(!this._isEnabled())return void(si&&Q.warn("SDK not enabled, will not capture user feedback."));const t=(function(r,{metadata:i,tunnel:s,dsn:a}){const o={event_id:r.event_id,sent_at:new Date().toISOString(),...i&&i.sdk&&{sdk:{name:i.sdk.name,version:i.sdk.version}},...!!s&&!!a&&{dsn:$r(a)}};return Kn(o,[(function(u){return[{type:"user_report"},u]})(r)])})(e,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this.sendEnvelope(t)}_prepareEvent(e,t,r){return e.platform=e.platform||"javascript",super._prepareEvent(e,t,r)}}const Bg=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Ge=he;let Qo,Oi,Pi,hr;function $g(){if(!Ge.document)return;const n=mt.bind(null,"dom"),e=Zo(n,!0);Ge.document.addEventListener("click",e,!1),Ge.document.addEventListener("keypress",e,!1),["EventTarget","Node"].forEach(t=>{const r=Ge[t],i=r&&r.prototype;i&&i.hasOwnProperty&&i.hasOwnProperty("addEventListener")&&(Ze(i,"addEventListener",function(s){return function(a,o,l){if(a==="click"||a=="keypress")try{const u=this.__sentry_instrumentation_handlers__=this.__sentry_instrumentation_handlers__||{},f=u[a]=u[a]||{refCount:0};if(!f.handler){const g=Zo(n);f.handler=g,s.call(this,a,g,l)}f.refCount++}catch{}return s.call(this,a,o,l)}}),Ze(i,"removeEventListener",function(s){return function(a,o,l){if(a==="click"||a=="keypress")try{const u=this.__sentry_instrumentation_handlers__||{},f=u[a];f&&(f.refCount--,f.refCount<=0&&(s.call(this,a,f.handler,l),f.handler=void 0,delete u[a]),Object.keys(u).length===0&&delete this.__sentry_instrumentation_handlers__)}catch{}return s.call(this,a,o,l)}}))})}function Zo(n,e=!1){return t=>{if(!t||t._sentryCaptured)return;const r=(function(s){try{return s.target}catch{return null}})(t);if((function(s,a){return s==="keypress"&&(!a||!a.tagName||a.tagName!=="INPUT"&&a.tagName!=="TEXTAREA"&&!a.isContentEditable)})(t.type,r))return;ln(t,"_sentryCaptured",!0),r&&!r._sentryId&&ln(r,"_sentryId",st());const i=t.type==="keypress"?"input":t.type;(function(s){if(s.type!==Oi)return!1;try{if(!s.target||s.target._sentryId!==Pi)return!1}catch{}return!0})(t)||(n({event:t,name:i,global:e}),Oi=t.type,Pi=r?r._sentryId:void 0),clearTimeout(Qo),Qo=Ge.setTimeout(()=>{Pi=void 0,Oi=void 0},1e3)}}function Ju(n){const e="history";an(e,n),on(e,Ug)}function Ug(){if(!(function(){const t=dr.chrome,r=t&&t.app&&t.app.runtime,i="history"in dr&&!!dr.history.pushState&&!!dr.history.replaceState;return!r&&i})())return;const n=Ge.onpopstate;function e(t){return function(...r){const i=r.length>2?r[2]:void 0;if(i){const s=hr,a=String(i);hr=a,mt("history",{from:s,to:a})}return t.apply(this,r)}}Ge.onpopstate=function(...t){const r=Ge.location.href,i=hr;if(hr=r,mt("history",{from:i,to:r}),n)try{return n.apply(this,t)}catch{}},Ze(Ge.history,"pushState",e),Ze(Ge.history,"replaceState",e)}const Cr={};function ec(n){Cr[n]=void 0}const Vn="__sentry_xhr_v3__";function Vg(){if(!Ge.XMLHttpRequest)return;const n=XMLHttpRequest.prototype;n.open=new Proxy(n.open,{apply(e,t,r){const i=new Error,s=1e3*Ot(),a=Tt(r[0])?r[0].toUpperCase():void 0,o=(function(u){if(Tt(u))return u;try{return u.toString()}catch{}})(r[1]);if(!a||!o)return e.apply(t,r);t[Vn]={method:a,url:o,request_headers:{}}
22,a==="POST"&&o.match(/sentry_key/)&&(t.__sentry_own_request__=!0);const l=()=>{const u=t[Vn];if(u&&t.readyState===4){try{u.status_code=t.status}catch{}mt("xhr",{endTimestamp:1e3*Ot(),startTimestamp:s,xhr:t,virtualError:i})}};return"onreadystatechange"in t&&typeof t.onreadystatechange=="function"?t.onreadystatechange=new Proxy(t.onreadystatechange,{apply:(u,f,g)=>(l(),u.apply(f,g))}):t.addEventListener("readystatechange",l),t.setRequestHeader=new Proxy(t.setRequestHeader,{apply(u,f,g){const[_,k]=g,b=f[Vn];return b&&Tt(_)&&Tt(k)&&(b.request_headers[_.toLowerCase()]=k),u.apply(f,g)}}),e.apply(t,r)}}),n.send=new Proxy(n.send,{apply(e,t,r){const i=t[Vn];return i?(r[0]!==void 0&&(i.body=r[0]),mt("xhr",{startTimestamp:1e3*Ot(),xhr:t}),e.apply(t,r)):e.apply(t,r)}})}function zg(n,e=(function(t){const r=Cr[t];if(r)return r;let i=Ge[t];if(ps(i))return Cr[t]=i.bind(Ge);const s=Ge.document;if(s&&typeof s.createElement=="function")try{const a=s.createElement("iframe");a.hidden=!0,s.head.appendChild(a);const o=a.contentWindow;o&&o[t]&&(i=o[t]),s.head.removeChild(a)}catch(a){Bg&&Q.warn(`Could not create sandbox iframe for ${t} check, bailing to window.${t}: `,a)}return i&&(Cr[t]=i.bind(Ge))})("fetch")){let t=0,r=0;return kg(n,function(i){const s=i.body.length;t+=s,r++;const a={body:i.body,method:"POST",referrerPolicy:"origin",headers:n.headers,keepalive:t<=6e4&&r<15,...n.fetchOptions};if(!e)return ec("fetch"),Br("No fetch implementation available");try{return e(n.url,a).then(o=>(t-=s,r--,{statusCode:o.status,headers:{"x-sentry-rate-limits":o.headers.get("X-Sentry-Rate-Limits"),"retry-after":o.headers.get("Retry-After")}}))}catch(o){return ec("fetch"),t-=s,r--,Br(o)}})}function ji(n,e,t,r){const i={filename:n,function:e==="<anonymous>"?tn:e,in_app:!0};return t!==void 0&&(i.lineno=t),r!==void 0&&(i.colno=r),i}const Wg=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,qg=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Jg=/\((\S*)(?::(\d+))(?::(\d+))\)/,Gg=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Hg=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Kg=(function(...n){const e=n.sort((t,r)=>t[0]-r[0]).map(t=>t[1]);return(t,r=0,i=0)=>{const s=[],a=t.split(`
23`);for(let o=r;o<a.length;o++){const l=a[o];if(l.length>1024)continue;const u=co.test(l)?l.replace(co,"$1"):l;if(!u.match(/\S*Error: /)){for(const f of e){const g=f(u);if(g){s.push(g);break}}if(s.length>=50+i)break}}return(function(o){if(!o.length)return[];const l=Array.from(o);return/sentryWrapped/.test(ar(l).function||"")&&l.pop(),l.reverse(),lo.test(ar(l).function||"")&&(l.pop(),lo.test(ar(l).function||"")&&l.pop()),l.slice(0,50).map(u=>({...u,filename:u.filename||ar(l).filename,function:u.function||tn}))})(s.slice(i))}})([30,n=>{const e=Wg.exec(n);if(e){const[,r,i,s]=e;return ji(r,tn,+i,+s)}const t=qg.exec(n);if(t){if(t[2]&&t[2].indexOf("eval")===0){const s=Jg.exec(t[2]);s&&(t[2]=s[1],t[3]=s[2],t[4]=s[3])}const[r,i]=tc(t[1]||tn,t[2]);return ji(i,r,t[3]?+t[3]:void 0,t[4]?+t[4]:void 0)}}],[50,n=>{const e=Gg.exec(n);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const i=Hg.exec(e[3]);i&&(e[1]=e[1]||"eval",e[3]=i[1],e[4]=i[2],e[5]="")}let t=e[3],r=e[1]||tn;return[r,t]=tc(r,t),ji(t,r,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]),tc=(n,e)=>{const t=n.indexOf("safari-extension")!==-1,r=n.indexOf("safari-web-extension")!==-1;return t||r?[n.indexOf("@")!==-1?n.split("@")[0]:tn,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[n,e]},nc=1024,Yg=(n={})=>{const e={console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0,...n};return{name:"Breadcrumbs",setup(t){var r;e.console&&(function(i){const s="console";an(s,i),on(s,Ag)})((function(i){return function(s){if(ze()!==i)return;const a={category:"console",data:{arguments:s.args,logger:"console"},level:Tg(s.level),message:mo(s.args," ")};if(s.level==="assert"){if(s.args[0]!==!1)return;a.message=`Assertion failed: ${mo(s.args.slice(1)," ")||"console.assert"}`,a.data.arguments=s.args.slice(1)}Kt(a,{input:s.args,level:s.level})}}
23)(t)),e.dom&&(r=(function(i,s){return function(a){if(ze()!==i)return;let o,l,u=typeof s=="object"?s.serializeAttribute:void 0,f=typeof s=="object"&&typeof s.maxStringLength=="number"?s.maxStringLength:void 0;f&&f>nc&&(si&&Q.warn(`\`dom.maxStringLength\` cannot exceed 1024, but a value of ${f} was configured. Sentry will use 1024 instead.`),f=nc),typeof u=="string"&&(u=[u]);try{const _=a.event,k=(function(b){return!!b&&!!b.target})(_)?_.target:_;o=Ru(k,{keyAttrs:u,maxStringLength:f}),l=(function(b){if(!qs.HTMLElement)return null;let v=b;for(let E=0;E<5;E++){if(!v)return null;if(v instanceof HTMLElement){if(v.dataset.sentryComponent)return v.dataset.sentryComponent;if(v.dataset.sentryElement)return v.dataset.sentryElement}v=v.parentNode}return null})(k)}catch{o="<unknown>"}if(o.length===0)return;const g={category:`ui.${a.name}`,message:o};l&&(g.data={"ui.component_name":l}),Kt(g,{event:a.event,name:a.name,global:a.global})}})(t,e.dom),an("dom",r),on("dom",$g)),e.xhr&&(function(i){an("xhr",i),on("xhr",Vg)})((function(i){return function(s){if(ze()!==i)return;const{startTimestamp:a,endTimestamp:o}=s,l=s.xhr[Vn];if(!a||!o||!l)return;const{method:u,url:f,status_code:g,body:_}=l,k={method:u,url:f,status_code:g},b={xhr:s.xhr,input:_,startTimestamp:a,endTimestamp:o};Kt({category:"xhr",data:k,type:"http",level:Ko(g)},b)}})(t)),e.fetch&&Pg((function(i){return function(s){if(ze()!==i)return;const{startTimestamp:a,endTimestamp:o}=s;if(o&&(!s.fetchData.url.match(/sentry_key/)||s.fetchData.method!=="POST"))if(s.error)Kt({category:"fetch",data:s.fetchData,level:"error",type:"http"},{data:s.error,input:s.args,startTimestamp:a,endTimestamp:o});else{const l=s.response,u={...s.fetchData,status_code:l&&l.status},f={input:s.args,response:l,startTimestamp:a,endTimestamp:o};Kt({category:"fetch",data:u,type:"http",level:Ko(u.status_code)},f)}}})(t)),e.history&&Ju((function(i){return function(s){if(ze()!==i)return;let a=s.from,o=s.to;const l=Ai(Oe.location.href);let u=a?Ai(a):void 0;const f=Ai(o);u&&u.path||(u=l),l.protocol===f.protocol&&l.host===f.host&&(o=f.relative),l.protocol===u.protocol&&l.host===u.host&&(a=u.relative),Kt({category:"navigation",data:{from:a,to:o}})}})(t)),e.sentry&&t.on("beforeSendEvent",(function(i){return function(s){ze()===i&&Kt({category:"sentry."+(s.type==="transaction"?"transaction":"event"),event_id:s.event_id,level:s.level,message:Ut(s)},{event:s})}})(t))}}},Xg=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","BroadcastChannel","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","SharedWorker","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],Qg=(n={})=>{const e={XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0,...n};return{name:"BrowserApiErrors",setupOnce(){e.setTimeout&&Ze(Oe,"setTimeout",rc),e.setInterval&&Ze(Oe,"setInterval",rc),e.requestAnimationFrame&&Ze(Oe,"requestAnimationFrame",Zg),e.XMLHttpRequest&&"XMLHttpRequest"in Oe&&Ze(XMLHttpRequest.prototype,"send",ev);const t=e.eventTarget;t&&(Array.isArray(t)?t:Xg).forEach(tv)}}};function rc(n){return function(...e){const t=e[0];return e[0]=Pn(t,{mechanism:{data:{function:qt(n)},handled:!1,type:"instrument"}}),n.apply(this,e)}}function Zg(n){return function(e){return n.apply(this,[Pn(e,{mechanism:{data:{function:"requestAnimationFrame",handler:qt(n)},handled:!1,type:"instrument"}})])}}function ev(n){return function(...e){const t=this;return["onload","onerror","onprogress","onreadystatechange"].forEach(r=>{r in t&&typeof t[r]=="function"&&Ze(t,r,function(i){const s={mechanism:{data:{function:r,handler:qt(i)},handled:!1,type:"instrument"}},a=Js(i);return a&&(s.mechanism.data.handler=qt(a)),Pn(i,s)})}),n.apply(this,e)}}function tv(n){const e=Oe[n],t=e&&e.prototype;t&&t.hasOwnProperty&&t.hasOwnProperty("addEventListener")&&(Ze(t,"addEventListener",function(r){return function(i,s,a){try{typeof s.handleEvent=="function"&&(s.handleEvent=Pn(s.handleEvent,{mechanism:{data:{function:"handleEvent",handler:qt(s),target:n},handled:!1,type:"instrument"}}))}catch{}return r.apply(this,[i,Pn(s,{mechanism:{data:{function:"addEventListener",handler:qt(s),target:n},handled:!1,type:"instrument"}}),a])}}),Ze(t,"removeEventListener",function(r){return function(i,s,a){try{const o=s.__sentry_wrapped__;o&&r.call(this,i,o,a)}catch{}return r.call(this,i,s,a)}}))}const nv=()=>({name:"BrowserSession",setupOnce(){Oe.document!==void 0?(jo({ignoreDuration:!0}),Io(),Ju(({from:n,to:e})=>{n!==void 0&&n!==e&&(jo({ignoreDuration:!0}),Io())})):si&&Q.warn("Using the `browserSessionIntegration` in non-browser environments is not supported.")}}),rv=(n={})=>{const e={onerror:!0,onunhandledrejection:!0,...n};return{name:"GlobalHandlers",setupOnce(){Error.stackTraceLimit=50},setup(t){e.onerror&&((function(r){(function(i){const s="error";an(s,i),on(s,Gm)})(i=>{const{stackParser:s,attachStacktrace:a}=sc();if(ze()!==r||Xo())return;const{msg:o,url:l,line:u,column:f,error:g}=i,_=(function(k,b,v,E){const C=k.exception=k.exception||{},O=C.values=C.values||[],j=O[0]=O[0]||{},S=j.stacktrace=j.stacktrace||{},x=S.frames=S.frames||[],T=E,I=v,F=Tt(b)&&b.length>0?b:(function(){try{return qs.document.location.href}catch{return""}})();return x.length===0&&x.push({colno:T,filename:F,function:tn,in_app:!0,lineno:I}),k})(vs(s,g||o,void 0,a,!1),l,u,f);_.level="error",Po(_,{originalException:g,mechanism:{handled:!1,type:"onerror"}})})})(t),ic("onerror")),e.onunhandledrejection&&((function(r){(function(i){const s="unhandledrejection";an(s,i),on(s,Hm)})(i=>{const{stackParser:s,attachStacktrace:a}=sc();if(ze()!==r||Xo())return;const o=(function(u){if(ss(u))return u;try{if("reason"in u)return u.reason;if("detail"in u&&"reason"in u.detail)return u.detail.reason}catch{}return u})(i),l=ss(o)?{exception:{values:[{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(o)}`}]}}:vs(s,o,void 0,a,!0);l.level="error",Po(l,{originalException:o,mechanism:{handled:!1,type:"onunhandledrejection"}})})})(t),ic("onunhandledrejection"))}}};function ic(n){si&&Q.log(`Global Handler attached: ${n}`)}function sc(){const n=ze();return n&&n.getOptions()||{stackParser:()=>[],attachStacktrace:!1}}const iv=()=>({name:"HttpContext",preprocessEvent(n){if(!Oe.navigator&&!Oe.location&&!Oe.document)return;const e=n.request&&n.request.url||Oe.location&&Oe.location.href,{referrer:t}=Oe.document||{},{userAgent:r}=Oe.navigator||{},i={...n.request&&n.request.headers,...t&&{Referer:t},...r&&{"User-Agent":r}},s={...n.request,...e&&{url:e},headers:i};n.request=s}}),sv=(n={})=>{const e=n.limit||5,t=n.key||"cause";return{name:"LinkedErrors",preprocessEvent(r,i,s){const a=s.getOptions();Mg(Xs,a.stackParser,a.maxValueLength,t,e,r,i)}}};var ac="new",oc="loading",cc="loaded",ys="joining-meeting",en="joined-meeting",It="left-meeting",Rt="error",av="playable",Ii="unknown",ov
23="full",cv="base",lc="no-room",lv="end-of-life",uv="connection-error",dv="iframe-ready-for-launch-config",hv="iframe-launch-config",fv="theme-updated",pv="loading",mv="load-attempt-failed",uc="loaded",gv="started-camera",vv="camera-error",bv="joining-meeting",yv="joined-meeting",wv="left-meeting",_v="participant-joined",kv="participant-updated",Sv="participant-left",xv="participant-counts-updated",Ev="access-state-updated",Cv="meeting-session-summary-updated",Mv="meeting-session-state-updated",Av="waiting-participant-added",Tv="waiting-participant-updated",Nv="waiting-participant-removed",Ov="track-started",Pv="track-stopped",jv="transcription-started",Iv="transcription-stopped",Rv="transcription-error",dc="recording-started",hc="recording-stopped",Lv="recording-stats",Dv="recording-error",Fv="recording-upload-completed",Bv="recording-data",$v="app-message",Uv="transcription-message",Vv="remote-media-player-started",zv="remote-media-player-updated",Wv="remote-media-player-stopped",qv="local-screen-share-started",Jv="local-screen-share-stopped",Gv="local-screen-share-canceled",Hv="active-speaker-change",Kv="active-speaker-mode-change",Yv="network-quality-change",Xv="network-connection",Qv="cpu-load-change",Zv="face-counts-updated",fr="fullscreen",pr="exited-fullscreen",eb="live-streaming-started",tb="live-streaming-updated",nb="live-streaming-stopped",rb="live-streaming-error",ib="lang-updated",sb="receive-settings-updated",fc="input-settings-updated",pc="nonfatal-error",mc="error",Ri=4096,gc=102400,Li="iframe-call-message",vc="local-screen-start",bc="daily-method-update-live-streaming-endpoints",mr="transmit-log",Nt="daily-custom-track",Mr={NONE:"none",BGBLUR:"background-blur",BGIMAGE:"background-image",FACE_DETECTION:"face-detection"},Gu={NONE:"none",NOISE_CANCELLATION:"noise-cancellation"},ws={PLAY:"play",PAUSE:"pause"},gr="daily",Di="signalwire",Fi=["jpg","png","jpeg"],ab="add-endpoints",ob="remove-endpoints",yc="sip-call-transfer";function at(){return!ce()&&typeof window<"u"&&window.navigator&&window.navigator.userAgent?window.navigator.userAgent:""}function ce(){return typeof navigator<"u"&&navigator.product&&navigator.product==="ReactNative"}function Hu(){return navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function cb(){return!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)&&((function(n,e){if(!n||!e)return!0;switch(n){case"Chrome":return e.major>=75;case"Safari":return RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")&&!(e.major===13&&e.minor===0&&e.point===0);case"Firefox":return e.major>=67}return!0})(dn(),Ur())||ce())}function wc(){if(ce()||!document)return!1;var n=document.createElement("iframe");return!!n.requestFullscreen||!!n.webkitRequestFullscreen}var _s="none",lb="software",ub="hardware",db=(function(){try{var n,e=document.createElement("canvas"),t=!1;(n=e.getContext("webgl2",{failIfMajorPerformanceCaveat:!0}))||(t=!0,n=e.getContext("webgl2"));var r=n!=null;return e.remove(),r?t?lb:ub:_s}catch{return _s}})();function Ku(){var n=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return!ce()&&db!==_s&&(n?(function(){return _c()?!1:["Chrome","Firefox"].includes(dn())})():(function(){if(_c())return!1;var e=dn();if(e==="Safari"){var t=ea();if(t.major<15||t.major===15&&t.minor<4)return!1}return e==="Chrome"?Zs().major>=77:e==="Firefox"?ta().major>=97:["Chrome","Firefox","Safari"].includes(e)})())}function Yu(){if(ce()||Xu()||typeof AudioWorkletNode>"u")return!1;switch(dn()){case"Chrome":case"Firefox":return!0;case"Safari":var n=Ur();return n.major>17||n.major===17&&n.minor>=4}return!1}function Bi(){return Hu()&&typeof MediaStreamTrack<"u"&&!(function(){var n,e=dn();if(!at())return!0;switch(e){case"Chrome":return(n=Zs()).major&&n.major>0&&n.major<75;case"Firefox":return(n=ta()).major<91;case"Safari":return(n=ea()).major<13||n.major===13&&n.minor<1;default:return!0}})()}function Xu(){return at().match(/Linux; Android/)}function _c(){var n,e=at(),t=e.match(/Mac/)&&(!ce()&&typeof window<"u"&&(n=window)!==null&&n!==void 0&&(n=n.navigator)!==null&&n!==void 0&&n.maxTouchPoints?window.navigator.maxTouchPoints:0)>=5;return!!(e.match(/Mobi/)||e.match(/Android/)||t)||!!at().match(/DailyAnd\//)||void 0}function dn(){if(typeof window<"u"){var n=at();return Qu()?"Safari":n.indexOf("Edge")>-1?"Edge":n.match(/Chrome\//)?"Chrome":n.indexOf("Safari")>-1||Zu()?"Safari":n.indexOf("Firefox")>-1?"Firefox":n.indexOf("MSIE")>-1||n.indexOf(".NET")>-1?"IE":"Unknown Browser"}}function Ur(){switch(dn()){case"Chrome":return Zs();case"Safari":return ea();case"Firefox":return ta();case"Edge":return(function(){var n=0,e=0;if(typeof window<"u"){var t=at().match(/Edge\/(\d+).(\d+)/);if(t)try{n=parseInt(t[1]),e=parseInt(t[2])}catch{}}return{major:n,minor:e}})()}}function Zs(){var n=0,e=0,t=0,r=0,i=!1;if(typeof window<"u"){var s=at(),a=s.match(/Chrome\/(\d+).(\d+).(\d+).(\d+)/);if(a)try{n=parseInt(a[1]),e=parseInt(a[2]),t=parseInt(a[3]),r=parseInt(a[4]),i=s.indexOf("OPR/")>-1}catch{}}return{major:n,minor:e,build:t,patch:r,opera:i}}function Qu(){return!!at().match(/\((iPad|iPhone|iPod)/i)&&Hu()}function Zu(){return at().indexOf("AppleWebKit/605.1.15")>-1}function ea(){var n=0,e=0,t=0;if(typeof window<"u"){var r=at().match(/Version\/(\d+).(\d+)(.(\d+))?/);if(r)try{n=parseInt(r[1]),e=parseInt(r[2]),t=parseInt(r[4])}catch{}else(Qu()||Zu())&&(n=14,e=0,t=3)}return{major:n,minor:e,point:t}}function ta(){var n=0,e=0;if(typeof window<"u"){var t=at().match(/Firefox\/(\d+).(\d+)/);if(t)try{n=parseInt(t[1]),e=parseInt(t[2])}catch{}}return{major:n,minor:e}}var ed=(function(){return tt(function n(){et(this,n)},[{key:"addListenerForMessagesFromCallMachine",value:function(n,e,t){Fn()}},{key:"addListenerForMessagesFromDailyJs",value:function(n,e,t){Fn()}},{key:"sendMessageToCallMachine",value:function(n,e,t,r){Fn()}},{key:"sendMessageToDailyJs",value:function(n,e){Fn()}},{key:"removeListener",value:function(n){Fn()}}])})();function kc(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function $i(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};
23e%2?kc(Object(t),!0).forEach(function(r){wt(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):kc(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}function td(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(td=function(){return!!n})()}var hb=(function(){function n(){var e,t,r,i;return et(this,n),t=this,r=gt(r=n),(e=Qr(t,td()?Reflect.construct(r,[],gt(t).constructor):r.apply(t,i)))._wrappedListeners={},e._messageCallbacks={},e}return Zr(n,ed),tt(n,[{key:"addListenerForMessagesFromCallMachine",value:function(e,t,r){var i=this,s=function(a){if(a.data&&a.data.what==="iframe-call-message"&&(!a.data.callClientId||a.data.callClientId===t)&&(!a.data.from||a.data.from!=="module")){var o=$i({},a.data);if(delete o.from,o.callbackStamp&&i._messageCallbacks[o.callbackStamp]){var l=o.callbackStamp;i._messageCallbacks[l].call(r,o),delete i._messageCallbacks[l]}delete o.what,delete o.callbackStamp,e.call(r,o)}};this._wrappedListeners[e]=s,window.addEventListener("message",s)}},{key:"addListenerForMessagesFromDailyJs",value:function(e,t,r){var i=function(s){var a;if(!(!s.data||s.data.what!==Li||!s.data.action||s.data.from&&s.data.from!=="module"||s.data.callClientId&&t&&s.data.callClientId!==t||s!=null&&(a=s.data)!==null&&a!==void 0&&a.callFrameId)){var o=s.data;e.call(r,o)}};this._wrappedListeners[e]=i,window.addEventListener("message",i)}},{key:"sendMessageToCallMachine",value:function(e,t,r,i){if(!r)throw new Error("undefined callClientId. Are you trying to use a DailyCall instance previously destroyed?");var s=$i({},e);if(s.what=Li,s.from="module",s.callClientId=r,t){var a=ei();this._messageCallbacks[a]=t,s.callbackStamp=a}var o=i?i.contentWindow:window,l=this._callMachineTargetOrigin(i);l&&o.postMessage(s,l)}},{key:"sendMessageToDailyJs",value:function(e,t){e.what=Li,e.callClientId=t,e.from="embedded",window.postMessage(e,this._targetOriginFromWindowLocation())}},{key:"removeListener",value:function(e){var t=this._wrappedListeners[e];t&&(window.removeEventListener("message",t),delete this._wrappedListeners[e])}},{key:"forwardPackagedMessageToCallMachine",value:function(e,t,r){var i=$i({},e);i.callClientId=r;var s=t?t.contentWindow:window,a=this._callMachineTargetOrigin(t);a&&s.postMessage(i,a)}},{key:"addListenerForPackagedMessagesFromCallMachine",value:function(e,t){var r=function(i){if(i.data&&i.data.what==="iframe-call-message"&&(!i.data.callClientId||i.data.callClientId===t)&&(!i.data.from||i.data.from!=="module")){var s=i.data;e(s)}};return this._wrappedListeners[e]=r,window.addEventListener("message",r),e}},{key:"removeListenerForPackagedMessagesFromCallMachine",value:function(e){var t=this._wrappedListeners[e];t&&(window.removeEventListener("message",t),delete this._wrappedListeners[e])}},{key:"_callMachineTargetOrigin",value:function(e){return e?e.src?new URL(e.src).origin:void 0:this._targetOriginFromWindowLocation()}},{key:"_targetOriginFromWindowLocation",value:function(){return window.location.protocol==="file:"?"*":window.location.origin}}])})();function Sc(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function nd(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(nd=function(){return!!n})()}var fb=(function(){function n(){var e,t,r,i;return et(this,n),t=this,r=gt(r=n),e=Qr(t,nd()?Reflect.construct(r,[],gt(t).constructor):r.apply(t,i)),global.callMachineToDailyJsEmitter=global.callMachineToDailyJsEmitter||new rs.EventEmitter,global.dailyJsToCallMachineEmitter=global.dailyJsToCallMachineEmitter||new rs.EventEmitter,e._wrappedListeners={},e._messageCallbacks={},e}return Zr(n,ed),tt(n,[{key:"addListenerForMessagesFromCallMachine",value:function(e,t,r){this._addListener(e,global.callMachineToDailyJsEmitter,t,r,"received call machine message")}},{key:"addListenerForMessagesFromDailyJs",value:function(e,t,r){this._addListener(e,global.dailyJsToCallMachineEmitter,t,r,"received daily-js message")}},{key:"sendMessageToCallMachine",value:function(e,t,r){this._sendMessage(e,global.dailyJsToCallMachineEmitter,r,t,"sending message to call machine")}},{key:"sendMessageToDailyJs",value:function(e,t){this._sendMessage(e,global.callMachineToDailyJsEmitter,t,null,"sending message to daily-js")}},{key:"removeListener",value:function(e){var t=this._wrappedListeners[e];t&&(global.callMachineToDailyJsEmitter.removeListener("message",t),global.dailyJsToCallMachineEmitter.removeListener("message",t),delete this._wrappedListeners[e])}},{key:"_addListener",value:function(e,t,r,i,s){var a=this,o=function(l){if(l.callClientId===r){if(l.callbackStamp&&a._messageCallbacks[l.callbackStamp]){var u=l.callbackStamp;a._messageCallbacks[u].call(i,l),delete a._messageCallbacks[u]}e.call(i,l)}};this._wrappedListeners[e]=o,t.addListener("message",o)}},{key:"_sendMessage",value:function(e,t,r,i,s){var a=(function(l){for(var u=1;u<arguments.length;u++){var f=arguments[u]!=null?arguments[u]:{};
23u%2?Sc(Object(f),!0).forEach(function(g){wt(l,g,f[g])}):Object.getOwnPropertyDescriptors?Object.defineProperties(l,Object.getOwnPropertyDescriptors(f)):Sc(Object(f)).forEach(function(g){Object.defineProperty(l,g,Object.getOwnPropertyDescriptor(f,g))})}return l})({},e);if(a.callClientId=r,i){var o=ei();this._messageCallbacks[o]=i,a.callbackStamp=o}t.emit("message",a)}}])})(),ks="replace",Ss="shallow-merge",xc=[ks,Ss],pb=(function(){function n(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=e.data,r=e.mergeStrategy,i=r===void 0?ks:r;et(this,n),n._validateMergeStrategy(i),n._validateData(t,i),this.mergeStrategy=i,this.data=t}return tt(n,[{key:"isNoOp",value:function(){return n.isNoOpUpdate(this.data,this.mergeStrategy)}}],[{key:"isNoOpUpdate",value:function(e,t){return Object.keys(e).length===0&&t===Ss}},{key:"_validateMergeStrategy",value:function(e){if(!xc.includes(e))throw Error("Unrecognized mergeStrategy provided. Options are: [".concat(xc,"]"))}},{key:"_validateData",value:function(e,t){if(!(function(o){if(o==null||le(o)!=="object")return!1;var l=Object.getPrototypeOf(o);return l==null||l===Object.prototype})(e))throw Error("Meeting session data must be a plain (map-like) object");var r;try{if(r=JSON.stringify(e),t===ks){var i=JSON.parse(r);Je(i,e)||console.warn("The meeting session data provided will be modified when serialized.",i,e)}else if(t===Ss){for(var s in e)if(Object.hasOwnProperty.call(e,s)&&e[s]!==void 0){var a=JSON.parse(JSON.stringify(e[s]));Je(e[s],a)||console.warn("At least one key in the meeting session data provided will be modified when serialized.",a,e[s])}}}catch(o){throw Error("Meeting session data must be serializable to JSON: ".concat(o))}if(r.length>gc)throw Error("Meeting session data is too large (".concat(r.length," characters). Maximum size suppported is ").concat(gc,"."))}}])})();function rd(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(rd=function(){return!!n})()}function xs(n){var e=typeof Map=="function"?new Map:void 0;return xs=function(t){if(t===null||!(function(i){try{return Function.toString.call(i).indexOf("[native code]")!==-1}catch{return typeof i=="function"}})(t))return t;if(typeof t!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return(function(i,s,a){if(rd())return Reflect.construct.apply(null,arguments);var o=[null];o.push.apply(o,s);var l=new(i.bind.apply(i,o));return a&&Hn(l,a.prototype),l})(t,arguments,gt(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),Hn(r,t)},xs(n)}function id(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(id=function(){return!!n})()}function Ec(n){var e,t=(e=window._daily)===null||e===void 0?void 0:e.pendings;if(t){var r=t.indexOf(n);r!==-1&&t.splice(r,1)}}var mb=(function(){return tt(function n(e){et(this,n),this._currentLoad=null,this._callClientId=e,this._publicPath=null},[{key:"load",value:function(){var n,e=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;if(this.loaded)return window._daily.instances[this._callClientId].callMachine.reset(),window._daily.instances[this._callClientId].publicPath=this._publicPath,void r(!0);n=this._callClientId,window._daily.pendings.push(n),this._currentLoad&&this._currentLoad.cancel(),this._currentLoad=new gb(t,function(s){var a=s.substring(0,s.lastIndexOf("/"));a.length&&a.slice(-1)!=="/"&&(a+="/"),e._publicPath=a,window._daily.instances[e._callClientId].publicPath=a,r(!1)},function(s,a){a||Ec(e._callClientId),i(s,a)}),this._currentLoad.start()}},{key:"cancel",value:function(){this._currentLoad&&this._currentLoad.cancel(),Ec(this._callClientId)}},{key:"loaded",get:function(){return this._currentLoad&&this._currentLoad.succeeded}}])})(),gb=(function(){return tt(function n(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2?arguments[2]:void 0;et(this,n),this._attemptsRemaining=3,this._currentAttempt=null,this._dailyConfig=e,this._successCallback=t,this._failureCallback=r},[{key:"start",value:function(){var n=this;if(!this._currentAttempt){var e=function(t){n._currentAttempt.cancelled||(n._attemptsRemaining--,n._failureCallback(t,n._attemptsRemaining>0),n._attemptsRemaining<=0||setTimeout(function(){n._currentAttempt.cancelled||(n._currentAttempt=new Cc(n._dailyConfig,n._successCallback,e),n._currentAttempt.start())},3e3))};this._currentAttempt=new Cc(this._dailyConfig,this._successCallback,e),this._currentAttempt.start()}}},{key:"cancel",value:function(){this._currentAttempt&&this._currentAttempt.cancel()}},{key:"cancelled",get:function(){return this._currentAttempt&&this._currentAttempt.cancelled}},{key:"succeeded",get:function(){return this._currentAttempt&&this._currentAttempt.succeeded}}])})(),Ui=(function(){function n(){return et(this,n),e=this,r=arguments,t=gt(t=n),Qr(e,id()?Reflect.construct(t,r||[],gt(e).constructor):t.apply(e,r));var e,t,r}return Zr(n,xs(Error)),tt(n)})(),Vr=2e4,Cc=(function(){return tt(function e(t,r,i){et(this,e),this._loadAttemptImpl=ce()||!t.avoidEval?new vb(t,r,i):new bb(t,r,i)},[{key:"start",value:(n=X(function*(){return this._loadAttemptImpl.start()}),function(){return n.apply(this,arguments)})},{key:"cancel",value:function(){this._loadAttemptImpl.cancel()}},{key:"cancelled",get:function(){return this._loadAttemptImpl.cancelled}},{key:"succeeded",get:function(){return this._loadAttemptImpl.succeeded}}]);var n})(),vb=(function(){return tt(function i(s,a,o){et(this,i),this.cancelled=!1,this.succeeded=!1,this._networkTimedOut=!1,this._networkTimeout=null,this._iosCache=typeof iOSCallObjectBundleCache<"u"&&iOSCallObjectBundleCache,this._refetchHeaders=null,this._dailyConfig=s,this._successCallback=a,this._failureCallback=o},[{key:"start",value:(r=X(function*(){var i=Rr(this._dailyConfig);!(yield this._tryLoadFromIOSCache(i))&&this._loadFromNetwork(i)}),function(){return r.apply(this,arguments)})},{key:"cancel",value:function(){clearTimeout(this._networkTimeout),this.cancelled=!0}}
23,{key:"_tryLoadFromIOSCache",value:(t=X(function*(i){if(!this._iosCache)return!1;try{var s=yield this._iosCache.get(i);return!!this.cancelled||!!s&&(s.code?(Function('"use strict";'+s.code)(),this.succeeded=!0,this._successCallback(i),!0):(this._refetchHeaders=s.refetchHeaders,!1))}catch{return!1}}),function(i){return t.apply(this,arguments)})},{key:"_loadFromNetwork",value:(e=X(function*(i){var s=this;this._networkTimeout=setTimeout(function(){s._networkTimedOut=!0,s._failureCallback({msg:"Timed out (>".concat(Vr," ms) when loading call object bundle ").concat(i),type:"timeout"})},Vr);try{var a=this._refetchHeaders?{headers:this._refetchHeaders}:{},o=yield fetch(i,a);if(clearTimeout(this._networkTimeout),this.cancelled||this._networkTimedOut)throw new Ui;var l=yield this._getBundleCodeFromResponse(i,o);if(this.cancelled)throw new Ui;Function('"use strict";'+l)(),this._iosCache&&this._iosCache.set(i,l,o.headers),this.succeeded=!0,this._successCallback(i)}catch(u){if(clearTimeout(this._networkTimeout),u instanceof Ui||this.cancelled||this._networkTimedOut)return;this._failureCallback({msg:"Failed to load call object bundle ".concat(i,": ").concat(u),type:u.message})}}),function(i){return e.apply(this,arguments)})},{key:"_getBundleCodeFromResponse",value:(n=X(function*(i,s){if(s.ok)return yield s.text();if(this._iosCache&&s.status===304)return(yield this._iosCache.renew(i,s.headers)).code;throw new Error("Received ".concat(s.status," response"))}),function(i,s){return n.apply(this,arguments)})}]);var n,e,t,r})(),bb=(function(){return tt(function n(e,t,r){et(this,n),this.cancelled=!1,this.succeeded=!1,this._dailyConfig=e,this._successCallback=t,this._failureCallback=r,this._attemptId=ei(),this._networkTimeout=null,this._scriptElement=null},[{key:"start",value:function(){window._dailyCallMachineLoadWaitlist||(window._dailyCallMachineLoadWaitlist=new Set);var n=Rr(this._dailyConfig);(typeof document>"u"?"undefined":le(document))==="object"?this._startLoading(n):this._failureCallback({msg:"Call object bundle must be loaded in a DOM/web context",type:"missing context"})}},{key:"cancel",value:function(){this._stopLoading(),this.cancelled=!0}},{key:"_startLoading",value:function(n){var e=this;this._signUpForCallMachineLoadWaitlist(),this._networkTimeout=setTimeout(function(){e._stopLoading(),e._failureCallback({msg:"Timed out (>".concat(Vr," ms) when loading call object bundle ").concat(n),type:"timeout"})},Vr);var t=document.getElementsByTagName("head")[0],r=document.createElement("script");this._scriptElement=r,r.onload=function(){e._stopLoading(),e.succeeded=!0,e._successCallback(n)},r.onerror=function(i){e._stopLoading(),e._failureCallback({msg:"Failed to load call object bundle ".concat(i.target.src),type:i.message})},r.src=n,t.appendChild(r)}},{key:"_stopLoading",value:function(){this._withdrawFromCallMachineLoadWaitlist(),clearTimeout(this._networkTimeout),this._scriptElement&&(this._scriptElement.onload=null,this._scriptElement.onerror=null)}},{key:"_signUpForCallMachineLoadWaitlist",value:function(){window._dailyCallMachineLoadWaitlist.add(this._attemptId)}},{key:"_withdrawFromCallMachineLoadWaitlist",value:function(){window._dailyCallMachineLoadWaitlist.delete(this._attemptId)}}])})(),vr=function(n,e,t){return wb(n.local,e,t)===!0},yb=function(n,e,t){return n.local.streams&&n.local.streams[e]&&n.local.streams[e].stream&&n.local.streams[e].stream["get".concat(t==="video"?"Video":"Audio","Tracks")]()[0]},wn=function(n,e,t,r){var i=_b(n,e,t,r);return i&&i.pendingTrack},wb=function(n,e,t){if(!n)return!1;var r=function(s){switch(s){case"avatar":return!0;case"staged":return s;default:return!!s}},i=n.public.subscribedTracks;return i&&i[e]?["cam-audio","cam-video","screen-video","screen-audio","rmpAudio","rmpVideo"].indexOf(t)===-1&&i[e].custom?[!0,"staged"].includes(i[e].custom)?r(i[e].custom):r(i[e].custom[t]):r(i[e][t]):!i||r(i.ALL)},_b=function(n,e,t,r){var i=Object.values(n.streams||{}).filter(function(s){return s.participantId===e&&s.type===t&&s.pendingTrack&&s.pendingTrack.kind===r}).sort(function(s,a){return new Date(a.starttime)-new Date(s.starttime)});return i&&i[0]},kb=function(n,e){var t=n.local.public.customTracks;
23if(t&&t[e])return t[e].track};function Mc(n,e){for(var t=e.getState(),r=0,i=["cam","screen"];r<i.length;r++)for(var s=i[r],a=0,o=["video","audio"];a<o.length;a++){var l=o[a],u=s==="cam"?l:"screen".concat(l.charAt(0).toUpperCase()+l.slice(1)),f=n.tracks[u];if(f){var g=n.local?yb(t,s,l):wn(t,n.session_id,s,l);f.state==="playable"&&(f.track=g),f.persistentTrack=g}}}function Ac(n,e){try{var t=e.getState();for(var r in n.tracks)if(!Sb(r)){var i=n.tracks[r].kind;if(i){var s=n.tracks[r];if(s){var a=n.local?kb(t,r):wn(t,n.session_id,r,i);s.state==="playable"&&(n.tracks[r].track=a),s.persistentTrack=a}}else console.error("unknown type for custom track")}}catch(o){console.error(o)}}function Sb(n){return["video","audio","screenVideo","screenAudio"].includes(n)}function Tc(n,e,t){var r=t.getState();if(n.local){if(n.audio)try{n.audioTrack=r.local.streams.cam.stream.getAudioTracks()[0],n.audioTrack||(n.audio=!1)}catch{}if(n.video)try{n.videoTrack=r.local.streams.cam.stream.getVideoTracks()[0],n.videoTrack||(n.video=!1)}catch{}if(n.screen)try{n.screenVideoTrack=r.local.streams.screen.stream.getVideoTracks()[0],n.screenAudioTrack=r.local.streams.screen.stream.getAudioTracks()[0],n.screenVideoTrack||n.screenAudioTrack||(n.screen=!1)}catch{}}else{var i=!0;try{var s=r.participants[n.session_id];s&&s.public&&s.public.rtcType&&s.public.rtcType.impl==="peer-to-peer"&&s.private&&!["connected","completed"].includes(s.private.peeringState)&&(i=!1)}catch(f){console.error(f)}if(!i)return n.audio=!1,n.audioTrack=!1,n.video=!1,n.videoTrack=!1,n.screen=!1,void(n.screenTrack=!1);try{if(r.streams,n.audio&&vr(r,n.session_id,"cam-audio")){var a=wn(r,n.session_id,"cam","audio");a&&(e&&e.audioTrack&&e.audioTrack.id===a.id?n.audioTrack=a:a.muted||(n.audioTrack=a)),n.audioTrack||(n.audio=!1)}if(n.video&&vr(r,n.session_id,"cam-video")){var o=wn(r,n.session_id,"cam","video");o&&(e&&e.videoTrack&&e.videoTrack.id===o.id?n.videoTrack=o:o.muted||(n.videoTrack=o)),n.videoTrack||(n.video=!1)}if(n.screen&&vr(r,n.session_id,"screen-audio")){var l=wn(r,n.session_id,"screen","audio");l&&(e&&e.screenAudioTrack&&e.screenAudioTrack.id===l.id?n.screenAudioTrack=l:l.muted||(n.screenAudioTrack=l))}if(n.screen&&vr(r,n.session_id,"screen-video")){var u=wn(r,n.session_id,"screen","video");u&&(e&&e.screenVideoTrack&&e.screenVideoTrack.id===u.id?n.screenVideoTrack=u:u.muted||(n.screenVideoTrack=u))}n.screenVideoTrack||n.screenAudioTrack||(n.screen=!1)}catch(f){console.error("unexpected error matching up tracks",f)}}}function xb(n,e){var t=typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(!t){if(Array.isArray(n)||(t=(function(l,u){if(l){if(typeof l=="string")return Nc(l,u);var f={}.toString.call(l).slice(8,-1);return f==="Object"&&l.constructor&&(f=l.constructor.name),f==="Map"||f==="Set"?Array.from(l):f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f)?Nc(l,u):void 0}})(n))||e){t&&(n=t);var r=0,i=function(){};return{s:i,n:function(){return r>=n.length?{done:!0}:{done:!1,value:n[r++]}},e:function(l){throw l},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
24In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s,a=!0,o=!1;return{s:function(){t=t.call(n)},n:function(){var l=t.next();return a=l.done,l},e:function(l){o=!0,s=l},f:function(){try{a||t.return==null||t.return()}finally{if(o)throw s}}}}function Nc(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,r=Array(e);t<e;t++)r[t]=n[t];return r}var bt=new Map,xn=null;function Eb(n,e){var t=typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(!t){if(Array.isArray(n)||(t=(function(l,u){if(l){if(typeof l=="string")return Oc(l,u);var f={}.toString.call(l).slice(8,-1);return f==="Object"&&l.constructor&&(f=l.constructor.name),f==="Map"||f==="Set"?Array.from(l):f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f)?Oc(l,u):void 0}})(n))||e){t&&(n=t);var r=0,i=function(){};return{s:i,n:function(){return r>=n.length?{done:!0}:{done:!1,value:n[r++]}},e:function(l){throw l},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
25In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s,a=!0,o=!1;return{s:function(){t=t.call(n)},n:function(){var l=t.next();return a=l.done,l},e:function(l){o=!0,s=l},f:function(){try{a||t.return==null||t.return()}finally{if(o)throw s}}}}function Oc(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,r=Array(e);t<e;t++)r[t]=n[t];return r}
25var yt=new Map,qn=null;function Cb(n){sd()?(function(e){bt.has(e)||(bt.set(e,{}),navigator.mediaDevices.enumerateDevices().then(function(t){bt.has(e)&&(bt.get(e).lastDevicesString=JSON.stringify(t),xn||(xn=(function(){var r=X(function*(){var i,s=yield navigator.mediaDevices.enumerateDevices(),a=xb(bt.keys());try{for(a.s();!(i=a.n()).done;){var o=i.value,l=JSON.stringify(s);l!==bt.get(o).lastDevicesString&&(bt.get(o).lastDevicesString=l,o(s))}}catch(u){a.e(u)}finally{a.f()}});return function(){return r.apply(this,arguments)}})(),navigator.mediaDevices.addEventListener("devicechange",xn)))}).catch(function(){}))})(n):(function(e){yt.has(e)||(yt.set(e,{}),navigator.mediaDevices.enumerateDevices().then(function(t){yt.has(e)&&(yt.get(e).lastDevicesString=JSON.stringify(t),qn||(qn=setInterval(X(function*(){var r,i=yield navigator.mediaDevices.enumerateDevices(),s=Eb(yt.keys());try{for(s.s();!(r=s.n()).done;){var a=r.value,o=JSON.stringify(i);o!==yt.get(a).lastDevicesString&&(yt.get(a).lastDevicesString=o,a(i))}}catch(l){s.e(l)}finally{s.f()}}),3e3)))}))})(n)}function Mb(n){sd()?(function(e){bt.has(e)&&(bt.delete(e),bt.size===0&&xn&&(navigator.mediaDevices.removeEventListener("devicechange",xn),xn=null))})(n):(function(e){yt.has(e)&&(yt.delete(e),yt.size===0&&qn&&(clearInterval(qn),qn=null))})(n)}function sd(){var n;return ce()||((n=navigator.mediaDevices)===null||n===void 0?void 0:n.ondevicechange)!==void 0}var Ab=new Set;function Tb(n,e){return n&&n.readyState==="live"&&!(function(t,r){return t.muted&&!Ab.has(t.id)})(n)}function Pc(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function Lt(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Pc(Object(t),!0).forEach(function(r){wt(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):Pc(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}var zn=Object.freeze({VIDEO:"video",AUDIO:"audio",SCREEN_VIDEO:"screenVideo",SCREEN_AUDIO:"screenAudio",CUSTOM_VIDEO:"customVideo",CUSTOM_AUDIO:"customAudio"}),Nb=Object.freeze({PARTICIPANTS:"participants",STREAMING:"streaming",TRANSCRIPTION:"transcription"}),Jn=Object.values(zn),jc=["v","a","sv","sa","cv","ca"];Object.freeze(Jn.reduce(function(n,e,t){return n[e]=jc[t],n},{})),Object.freeze(jc.reduce(function(n,e,t){return n[e]=Jn[t],n},{}));var Ob=[zn.VIDEO,zn.AUDIO,zn.SCREEN_VIDEO,zn.SCREEN_AUDIO],Ic=Object.values(Nb),Rc=["p","s","t"];Object.freeze(Ic.reduce(function(n,e,t){return n[e]=Rc[t],n},{})),Object.freeze(Rc.reduce(function(n,e,t){return n[e]=Ic[t],n},{}));var ad=(function(){function n(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=e.base,r=e.byUserId,i=e.byParticipantId;et(this,n),this.base=t,this.byUserId=r,this.byParticipantId=i}return tt(n,[{key:"clone",value:function(){var e=new n;if(this.base instanceof Le?e.base=this.base.clone():e.base=this.base,this.byUserId!==void 0)for(var t in e.byUserId={},this.byUserId){var r=this.byUserId[t];e.byUserId[t]=r instanceof Le?r.clone():r}if(this.byParticipantId!==void 0)for(var i in e.byParticipantId={},this.byParticipantId){var s=this.byParticipantId[i];e.byParticipantId[i]=s instanceof Le?s.clone():s}return e}},{key:"toJSONObject",value:function(){var e={};if(typeof this.base=="boolean"?e.base=this.base:this.base instanceof Le&&(e.base=this.base.toJSONObject()),this.byUserId!==void 0)for(var t in e.byUserId={},this.byUserId){var r=this.byUserId[t];e.byUserId[t]=r instanceof Le?r.toJSONObject():r}if(this.byParticipantId!==void 0)for(var i in e.byParticipantId={},this.byParticipantId){var s=this.byParticipantId[i];e.byParticipantId[i]=s instanceof Le?s.toJSONObject():s}return e}},{key:"toMinifiedJSONObject",value:function(){var e={};if(this.base!==void 0&&(typeof this.base=="boolean"?e.b=this.base:e.b=this.base.toMinifiedJSONObject()),this.byUserId!==void 0)for(var t in e.u={},this.byUserId){var r=this.byUserId[t];e.u[t]=typeof r=="boolean"?r:r.toMinifiedJSONObject()}if(this.byParticipantId!==void 0)for(var i in e.p={},this.byParticipantId){var s=this.byParticipantId[i];e.p[i]=typeof s=="boolean"?s:s.toMinifiedJSONObject()}return e}},{key:"normalize",value:function(){return this.base instanceof Le&&(this.base=this.base.normalize()),this.byUserId&&(this.byUserId=Object.fromEntries(Object.entries(this.byUserId).map(function(e){var t=Pe(e,2),r=t[0],i=t[1];return[r,i instanceof Le?i.normalize():i]}))),this.byParticipantId&&(this.byParticipantId=Object.fromEntries(Object.entries(this.byParticipantId).map(function(e){var t=Pe(e,2),r=t[0],i=t[1];return[r,i instanceof Le?i.normalize():i]}))),this}}],[{key:"fromJSONObject",value:function(e){var t,r,i;if(e.base!==void 0&&(t=typeof e.base=="boolean"?e.base:Le.fromJSONObject(e.base)),e.byUserId!==void 0)for(var s in r={},e.byUserId){var a=e.byUserId[s];r[s]=typeof a=="boolean"?a:Le.fromJSONObject(a)}if(e.byParticipantId!==void 0)for(var o in i={},e.byParticipantId){var l=e.byParticipantId[o];i[o]=typeof l=="boolean"?l:Le.fromJSONObject(l)}return new n({base:t,byUserId:r,byParticipantId:i})}},{key:"fromMinifiedJSONObject",value:function(e){var t,r,i;if(e.b!==void 0&&(t=typeof e.b=="boolean"?e.b:Le.fromMinifiedJSONObject(e.b)),e.u!==void 0)for(var s in r={},e.u){var a=e.u[s];r[s]=typeof a=="boolean"?a:Le.fromMinifiedJSONObject(a)}if(e.p!==void 0)for(var o in i={},e.p){var l=e.p[o];i[o]=typeof l=="boolean"?l:Le.fromMinifiedJSONObject(l)}return new n({base:t,byUserId:r,byParticipantId:i})}},{key:"validateJSONObject",value:function(e){if(le(e)!=="object")return[!1,"canReceive must be an object"];for(var t=["base","byUserId","byParticipantId"],r=0,i=Object.keys(e);r<i.length;r++){var s=i[r];if(!t.includes(s))return[!1,"canReceive can only contain keys (".concat(t.join(", "),")")];if(s==="base"){var a=Pe(Le.validateJSONObject(e.base,!0),2),o=a[0],l=a[1];if(!o)return[!1,l]}
25else{if(le(e[s])!=="object")return[!1,"invalid (non-object) value for field '".concat(s,"' in canReceive")];for(var u=0,f=Object.values(e[s]);u<f.length;u++){var g=f[u],_=Pe(Le.validateJSONObject(g),2),k=_[0],b=_[1];if(!k)return[!1,b]}}}return[!0]}}])})(),Le=(function(){function n(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=e.video,r=e.audio,i=e.screenVideo,s=e.screenAudio,a=e.customVideo,o=e.customAudio;et(this,n),this.video=t,this.audio=r,this.screenVideo=i,this.screenAudio=s,this.customVideo=a,this.customAudio=o}return tt(n,[{key:"clone",value:function(){var e=new n;return this.video!==void 0&&(e.video=this.video),this.audio!==void 0&&(e.audio=this.audio),this.screenVideo!==void 0&&(e.screenVideo=this.screenVideo),this.screenAudio!==void 0&&(e.screenAudio=this.screenAudio),this.customVideo!==void 0&&(e.customVideo=Lt({},this.customVideo)),this.customAudio!==void 0&&(e.customAudio=Lt({},this.customAudio)),e}},{key:"toJSONObject",value:function(){var e={};return this.video!==void 0&&(e.video=this.video),this.audio!==void 0&&(e.audio=this.audio),this.screenVideo!==void 0&&(e.screenVideo=this.screenVideo),this.screenAudio!==void 0&&(e.screenAudio=this.screenAudio),this.customVideo!==void 0&&(e.customVideo=Lt({},this.customVideo)),this.customAudio!==void 0&&(e.customAudio=Lt({},this.customAudio)),e}},{key:"toMinifiedJSONObject",value:function(){var e={};return this.video!==void 0&&(e.v=this.video),this.audio!==void 0&&(e.a=this.audio),this.screenVideo!==void 0&&(e.sv=this.screenVideo),this.screenAudio!==void 0&&(e.sa=this.screenAudio),this.customVideo!==void 0&&(e.cv=Lt({},this.customVideo)),this.customAudio!==void 0&&(e.ca=Lt({},this.customAudio)),e}},{key:"normalize",value:function(){function e(t,r){return t&&Object.keys(t).length===1&&t["*"]===r}return!(this.video!==!0||this.audio!==!0||this.screenVideo!==!0||this.screenAudio!==!0||!e(this.customVideo,!0)||!e(this.customAudio,!0))||(this.video!==!1||this.audio!==!1||this.screenVideo!==!1||this.screenAudio!==!1||!e(this.customVideo,!1)||!e(this.customAudio,!1))&&this}}],[{key:"fromBoolean",value:function(e){return new n({video:e,audio:e,screenVideo:e,screenAudio:e,customVideo:{"*":e},customAudio:{"*":e}})}},{key:"fromJSONObject",value:function(e){return new n({video:e.video,audio:e.audio,screenVideo:e.screenVideo,screenAudio:e.screenAudio,customVideo:e.customVideo!==void 0?Lt({},e.customVideo):void 0,customAudio:e.customAudio!==void 0?Lt({},e.customAudio):void 0})}},{key:"fromMinifiedJSONObject",value:function(e){return new n({video:e.v,audio:e.a,screenVideo:e.sv,screenAudio:e.sa,customVideo:e.cv,customAudio:e.ca})}},{key:"validateJSONObject",value:function(e,t){if(typeof e=="boolean")return[!0];if(le(e)!=="object")return[!1,"invalid (non-object, non-boolean) value in canReceive"];for(var r=Object.keys(e),i=0,s=r;i<s.length;i++){var a=s[i];if(!Jn.includes(a))return[!1,"invalid media type '".concat(a,"' in canReceive")];if(Ob.includes(a)){if(typeof e[a]!="boolean")return[!1,"invalid (non-boolean) value for media type '".concat(a,"' in canReceive")]}else{if(le(e[a])!=="object")return[!1,"invalid (non-object) value for media type '".concat(a,"' in canReceive")];for(var o=0,l=Object.values(e[a]);o<l.length;o++)if(typeof l[o]!="boolean")return[!1,"invalid (non-boolean) value for entry within '".concat(a,"' in canReceive")];if(t&&e[a]["*"]===void 0)return[!1,`canReceive "base" permission must specify "*" as an entry within '`.concat(a,"'")]}}return t&&r.length!==Jn.length?[!1,'canReceive "base" permission must specify all media types: '.concat(Jn.join(", ")," (or be set to a boolean shorthand)")]:[!0]}}])})(),Pb=["result"],jb=["preserveIframe"];function Lc(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function W(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Lc(Object(t),!0).forEach(function(r){wt(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):Lc(Object(t)).forEac
25h(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}function od(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(od=function(){return!!n})()}function Es(n,e){var t=typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(!t){if(Array.isArray(n)||(t=(function(l,u){if(l){if(typeof l=="string")return Dc(l,u);var f={}.toString.call(l).slice(8,-1);return f==="Object"&&l.constructor&&(f=l.constructor.name),f==="Map"||f==="Set"?Array.from(l):f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f)?Dc(l,u):void 0}})(n))||e){t&&(n=t);var r=0,i=function(){};return{s:i,n:function(){return r>=n.length?{done:!0}:{done:!1,value:n[r++]}},e:function(l){throw l},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
26In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s,a=!0,o=!1;return{s:function(){t=t.call(n)},n:function(){var l=t.next();return a=l.done,l},e:function(l){o=!0,s=l},f:function(){try{a||t.return==null||t.return()}finally{if(o)throw s}}}}function Dc(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,r=Array(e);t<e;t++)r[t]=n[t];return r}var Yt={},Fc="video",Ib="voice",Bc=ce()?{data:{}}:{data:{},topology:"none"},$c={present:0,hidden:0},cd={maxBitrate:{min:1e5,max:25e5},maxFramerate:{min:1,max:30},scaleResolutionDownBy:{min:1,max:8}},Vi=Object.keys(cd),Uc=["state","volume","simulcastEncodings"],Vc={androidInCallNotification:{title:"string",subtitle:"string",iconName:"string",disableForCustomOverride:"boolean"},disableAutoDeviceManagement:{audio:"boolean",video:"boolean"}},zr={id:{iconPath:"string",iconPathDarkMode:"string",label:"string",tooltip:"string",visualState:"'default' | 'sidebar-open' | 'active'"}},Cs={id:{allow:"string",controlledBy:"'*' | 'owners' | string[]",csp:"string",iconURL:"string",label:"string",loading:"'eager' | 'lazy'",location:"'main' | 'sidebar'",name:"string",referrerPolicy:"string",sandbox:"string",src:"string",srcdoc:"string",shared:"string[] | 'owners' | boolean"}},ld=/^[a-zA-Z0-9_-]+$/;function zc(n){if(n!=null&&le(n)==="object"&&!Array.isArray(n)){var e,t={},r=Es(Object.entries(n).slice(0,10));try{for(r.s();!(e=r.n()).done;){var i=Pe(e.value,2),s=i[0],a=i[1];typeof s!="string"||s.length>64||ld.test(s)&&typeof a=="string"&&(t[s]=a.slice(0,256))}}catch(o){r.e(o)}finally{r.f()}return Object.keys(t).length?t:void 0}}var Xt={customIntegrations:{validate:vd,help:md()},customTrayButtons:{validate:gd,help:"customTrayButtons should be a dictionary of the type ".concat(JSON.stringify(zr))},url:{validate:function(n){return typeof n=="string"},help:"url should be a string"},baseUrl:{validate:function(n){return console.warn("baseUrl is deprecated and has no effect"),typeof n=="string"},help:"baseUrl should be a string"},token:{validate:function(n){return typeof n=="string"},help:"token should be a string",queryString:"t"},dailyConfig:{validate:function(n,e){try{return e.validateDailyConfig(n),!0}catch(t){console.error("Failed to validate dailyConfig",t)}return!1},help:"Unsupported dailyConfig. Check error logs for detailed info."},reactNativeConfig:{validate:function(n){return bd(n,Vc)},help:"reactNativeConfig should look like ".concat(JSON.stringify(Vc),", all fields optional")},lang:{validate:function(n){return["da","de","en-us","en","es","fi","fr","it","jp","ka","nl","no","pl","pt","pt-BR","ru","sv","tr","user"].includes(n)},help:"language not supported. Options are: da, de, en-us, en, es, fi, fr, it, jp, ka, nl, no, pl, pt, pt-BR, ru, sv, tr, user"},userName:!0,userData:{validate:function(n){try{return ud(n),!0}catch(e){return console.error(e),!1}},help:"invalid userData type provided"},startVideoOff:!0,startAudioOff:!0,allowLocalVideo:!0,allowLocalAudio:!0,activeSpeakerMode:!0,showLeaveButton:!0,showLocalVideo:!0,showParticipantsBar:!0,showFullscreenButton:!0,showUserNameChangeUI:!0,iframeStyle:!0,customLayout:!0,cssFile:!0,cssText:!0,bodyClass:!0,videoSource:{validate:function(n,e){if(typeof n=="boolean")return e._preloadCache.allowLocalVideo=n,!0;var t;if(n instanceof MediaStreamTrack)e._sharedTracks.videoTrack=n,t={customTrack:Nt};
26else{if(delete e._sharedTracks.videoTrack,typeof n!="string")return console.error("videoSource must be a MediaStreamTrack, boolean, or a string"),!1;t={deviceId:n}}return e._updatePreloadCacheInputSettings({video:{settings:t}},!1),!0}},audioSource:{validate:function(n,e){if(typeof n=="boolean")return e._preloadCache.allowLocalAudio=n,!0;var t;if(n instanceof MediaStreamTrack)e._sharedTracks.audioTrack=n,t={customTrack:Nt};else{if(delete e._sharedTracks.audioTrack,typeof n!="string")return console.error("audioSource must be a MediaStreamTrack, boolean, or a string"),!1;t={deviceId:n}}return e._updatePreloadCacheInputSettings({audio:{settings:t}},!1),!0}},subscribeToTracksAutomatically:{validate:function(n,e){return e._preloadCache.subscribeToTracksAutomatically=n,!0}},theme:{validate:function(n){var e=["accent","accentText","background","backgroundAccent","baseText","border","mainAreaBg","mainAreaBgAccent","mainAreaText","supportiveText"],t=function(r){for(var i=0,s=Object.keys(r);i<s.length;i++){var a=s[i];if(!e.includes(a))return console.error('unsupported color "'.concat(a,'". Valid colors: ').concat(e.join(", "))),!1;if(!r[a].match(/^#[0-9a-f]{6}|#[0-9a-f]{3}$/i))return console.error("".concat(a,' theme color should be provided in valid hex color format. Received: "').concat(r[a],'"')),!1}return!0};return le(n)==="object"&&("light"in n&&"dark"in n||"colors"in n)?"light"in n&&"dark"in n?"colors"in n.light?"colors"in n.dark?t(n.light.colors)&&t(n.dark.colors):(console.error('Dark theme is missing "colors" property.',n),!1):(console.error('Light theme is missing "colors" property.',n),!1):t(n.colors):(console.error('Theme must contain either both "light" and "dark" properties, or "colors".',n),!1)},help:"unsupported theme configuration. Check error logs for detailed info."},layoutConfig:{validate:function(n){if("grid"in n){var e=n.grid;if("maxTilesPerPage"in e){if(!Number.isInteger(e.maxTilesPerPage))return console.error("grid.maxTilesPerPage should be an integer. You passed ".concat(e.maxTilesPerPage,".")),!1;if(e.maxTilesPerPage>49)return console.error("grid.maxTilesPerPage can't be larger than 49 without sacrificing browser performance. Please contact us at https://www.daily.co/contact to talk about your use case."),!1}if("minTilesPerPage"in e){if(!Number.isInteger(e.minTilesPerPage))return console.error("grid.minTilesPerPage should be an integer. You passed ".concat(e.minTilesPerPage,".")),!1;if(e.minTilesPerPage<1)return console.error("grid.minTilesPerPage can't be lower than 1."),!1;if("maxTilesPerPage"in e&&e.minTilesPerPage>e.maxTilesPerPage)return console.error("grid.minTilesPerPage can't be higher than grid.maxTilesPerPage."),!1}}return!0},help:"unsupported layoutConfig. Check error logs for detailed info."},receiveSettings:{validate:function(n){return dd(n,{allowAllParticipantsKey:!1})},help:pd({allowAllParticipantsKey:!1})},sendSettings:{validate:function(n,e){return!!(function(t,r){try{return r.validateUpdateSendSettings(t),!0}catch(i){return console.error("Failed to validate send settings",i),!1}})(n,e)&&(e._preloadCache.sendSettings=n,!0)},help:"Invalid sendSettings provided. Check error logs for detailed info."},inputSettings:{validate:function(n,e){var t;return!!hd(n)&&(e._inputSettings||(e._inputSettings={}),fd(n,(t=e.properties)===null||t===void 0?void 0:t.dailyConfig,e._sharedTracks),e._updatePreloadCacheInputSettings(n,!0),!0)},help:Ms()},layout:{validate:function(n){return n==="custom-v1"||n==="browser"||n==="none"},help:'layout may only be set to "custom-v1"',queryString:"layout"},emb:{queryString:"emb"},embHref:{queryString:"embHref"},dailyJsVersion:{queryString:"dailyJsVersion"},aboutClient:{validate:function(n){if(n==null)return!0;if(le(n)!=="object"||Array.isArray(n))return!1;var e=Object.entries(n);if(e.length>10)return!1;for(var t=0,r=e;t<r.length;t++){var i=Pe(r[t],2),s=i[0],a=i[1];if(typeof s!="string"||s.length>64||!ld.test(s)||typeof a!="string"||a.length>256)return!1}return!0},help:"aboutClient must be an object with up to ".concat(10," entries; keys must be strings made up of characters (a-z, 0-9, _, -) and a max length of ").concat(64,"; values must be strings with a max length of ").concat(256)},proxy:{queryString:"proxy"},strictMode:!0,allowMultipleCallInstances:!0},br={styles:{validate:function(n){for(var e in n)if(e!=="cam"&&e!=="screen")return!1;if(n.cam){for(var t in n.cam)if(t!=="div"&&t!=="video")return!1}if(n.screen){for(var r in n.screen)if(r!=="div"&&r!=="video")return!1}return!0},help:"styles format should be a subset of: { cam: {div: {}, video: {}}, screen: {div: {}, video: {}} }"},setSubscribedTracks:{validate:function(n,e){if(e._preloadCache.subscribeToTracksAutomatically)return!1;var t=[!0,!1,"staged"];if(t.includes(n)||!ce()&&n==="avatar")return!0;var r=["audio","video","screenAudio","screenVideo","rmpAudio","rmpVideo"],i=function(s){var a=arguments.length>1&&arguments[1]!==void 0&&arguments[1];for(var o in s)if(o==="custom"){if(!t.includes(s[o])&&!i(s[o],!0))return!1}else{var l=!a&&!r.includes(o),u=!t.includes(s[o]);if(l||u)return!1}return!0};return i(n)},help:"setSubscribedTracks cannot be used when setSubscribeToTracksAutomatically is enabled, and should be of the form: "+"true".concat(ce()?"":" | 'avatar'"," | false | 'staged' | { [audio: true|false|'staged'], [video: true|false|'staged'], [screenAudio: true|false|'staged'], [screenVideo: true|false|'staged'] }")},setAudio:!0,setVideo:!0,setScreenShare:{validate:function(n){return n===!1},help:"setScreenShare must be false, as it's only meant for stopping remote participants' screen shares"},eject:!0,updatePermissions:{validate:function(n){for(var e=0,t=Object.entries(n);e<t.length;e++){var r=Pe(t[e],2),i=r[0],s=r[1];switch(i){case"hasPresence":if(typeof s!="boolean")return!1;break;case"canSend":if(s instanceof Set||s instanceof Array||Array.isArray(s)){var a,o=["video","audio","screenVideo","screenAudio","customVideo","customAudio"],l=Es(s);try{for(l.s();!(a=l.n()).done;){var u=a.value;if(!o.includes(u))return!1}}catch(C){l.e(C)}finally{l.f()}}else if(typeof s!="boolean")return!1;(s instanceof Array||Array.isArray(s))&&(n.canSend=new Set(s));break;case"canReceive":var f=Pe(ad.validateJSONObject(s),2),g=f[0],_=f[1];if(!g)return console.error(_),!1;break;case"canAdmin":if(s instanceof Set||s instanceof Array||Array.isArray(s)){var k,b=["participants","streaming","transcription"],v=Es(s);try{for(v.s();!(k=v.n()).done;){var E=k.value;if(!b.includes(E))return!1}}catch(C){v.e(C)}finally{v.f()}}else if(typeof s!="boolean")return!1;(s instanceof Array||Array.isArray(s))&&(n.canAdmin=new Set(s));break;default:return!1}}return!0},help:"updatePermissions can take hasPresence, canSend, canReceive, and canAdmin permissions. hasPresence must be a boolean. canSend can be a boolean or an Array or Set of media types (video, audio, screenVideo, screenAudio, customVideo, customAudio). canReceive must be an object specifying base, byUserId, and/or byParticipantId fields (see documentation for more details). canAdmin can be a boolean or an Array or Set of admin types (participants, streaming, transcription)."}};Promise.any||(Promise.any=(function(){var n=X(function*(e){return new Promise(function(t,r){var i=[];e.forEach(function(s){return Promise.resolve(s).then(function(a){t(a)}).catch(function(a){i.push(a),i.length===e.length&&r(i)})})})});return function(e){return n.apply(this,arguments)}})());var Wc=(function(){function n(c){var p,h,m,y,N,P,R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(et(this,n),m=this,y=gt(y=n),wt(h=Qr(m,od()?Reflect.construct(y,[],gt(m).constructor):y.apply(m,N)),"startListeningForDeviceChanges",function(){Cb(h.handleDeviceChange)}),wt(h,"stopListeningForDeviceChanges",function(){Mb(h.handleDeviceChange)}),wt(h,"handleDeviceChange",function(V){V=V.map(function(U){return JSON.parse(JSON.stringify(U))}),h.emitDailyJSEvent({action:"available-devices-updated",availableDevices:V})}),wt(h,"handleNativeAppStateChange",(function(){var V=X(function*(U){if(U==="destroyed")return console.warn("App has been destroyed before leaving the meeting. Cleaning up all the resources!"),void(yield h.destroy());var ye=U==="active";h.disableReactNativeAutoDeviceManagement("video")||(ye?h.camUnmutedBeforeLosingNativeActiveState&&h.setLocalVideo(!0):(h.camUnmutedBeforeLosingNativeActiveState=h.localVideo(),h.camUnmutedBeforeLosingNativeActiveState&&h.setLocalVideo(!1)))});return function(U){return V.apply(this,arguments)}})()),wt(h,"handleNativeAudioFocusChange",function(V){h.disableReactNativeAutoDeviceManagement("audio")||(h._hasNativeAudioFocus=V,h.toggleParticipantAudioBasedOnNativeAudioFocus(),h._hasNativeAudioFocus?h.micUnmutedBeforeLosingNativeAudioFocus&&h.setLocalAudio(!0):(h.micUnmutedBeforeLosingNativeAudioFocus=h.localAudio(),h.setLocalAudio(!1)))}),wt(h,"handleNativeSystemScreenCaptureStop",function(){h.stopScreenShare()}),!Bi()&&!ce())throw new Error("WebRTC not supported or suppressed");if(h.strictMode=R.strictMode===void 0||R.strictMode,h.allowMultipleCallInstances=(p=R.allowMultipleCallInstances)!==null&&p!==void 0&&p,Object.keys(Yt).length&&(h._logDuplicateInstanceAttempt(),!h.allowMultipleCallInstances)){if(h.strictMode)throw new Error("Duplicate DailyIframe instances are not allowed");
26console.warn("Using strictMode: false to allow multiple call instances is now deprecated. Set `allowMultipleCallInstances: true`")}if(window._daily||(window._daily={pendings:[],instances:{}}),h.callClientId=ei(),Yt[(P=h).callClientId]=P,window._daily.instances[h.callClientId]={},h._sharedTracks={},window._daily.instances[h.callClientId].tracks=h._sharedTracks,R.dailyJsVersion=n.version(),R.aboutClient!==void 0&&(R.aboutClient=zc(R.aboutClient)),h._iframe=c,h._callObjectMode=R.layout==="none"&&!h._iframe,h._preloadCache={subscribeToTracksAutomatically:!0,outputDeviceId:null,inputSettings:null,sendSettings:null,videoTrackForNetworkConnectivityTest:null,videoTrackForConnectionQualityTest:null},R.showLocalVideo!==void 0?h._callObjectMode?console.error("showLocalVideo is not available in call object mode"):h._showLocalVideo=!!R.showLocalVideo:h._showLocalVideo=!0,R.showParticipantsBar!==void 0?h._callObjectMode?console.error("showParticipantsBar is not available in call object mode"):h._showParticipantsBar=!!R.showParticipantsBar:h._showParticipantsBar=!0,R.customIntegrations!==void 0?h._callObjectMode?console.error("customIntegrations is not available in call object mode"):h._customIntegrations=R.customIntegrations:h._customIntegrations={},R.customTrayButtons!==void 0?h._callObjectMode?console.error("customTrayButtons is not available in call object mode"):h._customTrayButtons=R.customTrayButtons:h._customTrayButtons={},R.activeSpeakerMode!==void 0?h._callObjectMode?console.error("activeSpeakerMode is not available in call object mode"):h._activeSpeakerMode=!!R.activeSpeakerMode:h._activeSpeakerMode=!1,R.receiveSettings?h._callObjectMode?h._receiveSettings=R.receiveSettings:console.error("receiveSettings is only available in call object mode"):h._receiveSettings={},h.validateProperties(R),h.properties=W({},R),h.properties.aboutClient!==void 0&&(h.properties.aboutClient=zc(h.properties.aboutClient)),h._inputSettings||(h._inputSettings={}),h._callObjectLoader=h._callObjectMode?new mb(h.callClientId):null,h._callState=ac,h._isPreparingToJoin=!1,h._accessState={access:Ii},h._meetingSessionSummary={},h._finalSummaryOfPrevSession={},h._meetingSessionState=qi(Bc,h._callObjectMode),h._nativeInCallAudioMode=Fc,h._participants={},h._isScreenSharing=!1,h._participantCounts=$c,h._rmpPlayerState={},h._waitingParticipants={},h._network={threshold:"good",quality:100,networkState:"unknown",stats:{}},h._activeSpeaker={},h._localAudioLevel=0,h._isLocalAudioLevelObserverRunning=!1,h._remoteParticipantsAudioLevel={},h._isRemoteParticipantsAudioLevelObserverRunning=!1,h._maxAppMessageSize=Ri,h._messageChannel=ce()?new fb:new hb,h._iframe&&(h._iframe.requestFullscreen?h._iframe.addEventListener("fullscreenchange",function(){document.fullscreenElement===h._iframe?(h.emitDailyJSEvent({action:fr}),h.sendMessageToCallMachine({action:fr})):(h.emitDailyJSEvent({action:pr}),h.sendMessageToCallMachine({action:pr}))}):h._iframe.webkitRequestFullscreen&&h._iframe.addEventListener("webkitfullscreenchange",function(){document.webkitFullscreenElement===h._iframe?(h.emitDailyJSEvent({action:fr}),h.sendMessageToCallMachine({action:fr})):(h.emitDailyJSEvent({action:pr}),h.sendMessageToCallMachine({action:pr}))})),ce()){var B=h.nativeUtils();B.addAudioFocusChangeListener&&B.removeAudioFocusChangeListener&&B.addAppStateChangeListener&&B.removeAppStateChangeListener&&B.addSystemScreenCaptureStopListener&&B.removeSystemScreenCaptureStopListener||console.warn("expected (add|remove)(AudioFocusChange|AppActiveStateChange|SystemScreenCaptureStop)Listener to be available in React Native"),h._hasNativeAudioFocus=!0,B.addAudioFocusChangeListener(h.handleNativeAudioFocusChange),B.addAppStateChangeListener(h.handleNativeAppStateChange),B.addSystemScreenCaptureStopListener(h.handleNativeSystemScreenCaptureStop)}return h._callObjectMode&&h.startListeningForDeviceChanges(),h._messageChannel.addListenerForMessagesFromCallMachine(h.handleMessageFromCallMachine,h.callClientId,h),h}return Zr(n,sr),tt(n,[{key:"destroy",value:(Be=X(function*(){var c;try{yield this.leave()}catch{}var p=this._iframe;if(p){var h=p.parentElement;h&&h.removeChild(p)}if(this._messageChannel.removeListener(this.handleMessageFromCallMachine),ce()){var m=this.nativeUtils();m.removeAudioFocusChangeListener(this.handleNativeAudioFocusChange),m.removeAppStateChangeListener(this.handleNativeAppStateChange),m.removeSystemScreenCaptureStopListener(this.handleNativeSystemScreenCaptureStop)}this._callObjectMode&&this.stopListeningForDeviceChanges(),this.resetMeetingDependentVars(),this._destroyed=!0,this.emitDailyJSEvent({action:"call-instance-destroyed"}),delete Yt[this.callClientId],!((c=window)===null||c===void 0||(c=c._daily)===null||c===void 0)&&c.instances&&delete window._daily.instances[this.callClientId],this.strictMode&&(this.callClientId=void 0)}),function(){return Be.apply(this,arguments)})},{key:"isDestroyed",value:function(){return!!this._destroyed}},{key:"loadCss",value:function(c){var p=c.bodyClass,h=c.cssFile,m=c.cssText;return oe(),this.sendMessageToCallMachine({action:"load-css",cssFile:this.absoluteUrl(h),bodyClass:p,cssText:m}),this}},{key:"iframe",value:function(){return oe(),this._iframe}},{key:"meetingState",value:function(){return this._callState}},{key:"accessState",value:function(){return lt(this._callObjectMode,"accessState()"),this._accessState}},{key:"participants",value:function(){return this._participants}},{key:"participantCounts",value:function(){return this._participantCounts}},{key:"waitingParticipants",value:function(){return lt(this._callObjectMode,"waitingParticipants()"),this._waitingParticipants}},{key:"validateParticipantProperties",value:function(c,p){for(var h in p){if(!br[h])throw new Error("unrecognized updateParticipant property ".concat(h));if(br[h].validate&&!br[h].validate(p[h],this,this._participants[c]))throw new Error(br[h].help)}}},{key:"updateParticipant",value:function(c,p){return this._participants.local&&this._participants.local.session_id===c&&(c="local"),c&&p&&(this.validateParticipantProperties(c,p),this.sendMessageToCallMachine({action:"update-participant",id:c,properties:p})),this}},{key:"updateParticipants",value:function(c){var p=this._participants.local&&this._participants.local.session_id;for(var h in c)h===p&&(h="local"),h&&c[h]&&this.validateParticipantProperties(h,c[h]);return this.sendMessageToCallMachine({action:"update-participants",participants:c}),this}},{key:"updateWaitingParticipant",value:(Ne=X(function*(){var c=this,p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(lt(this._callObjectMode,"updateWaitingParticipant()"),ve(this._callState,"updateWaitingParticipant()"),typeof p!="string"||le(h)!=="object")throw new Error("updateWaitingParticipant() must take an id string and a updates object");return new Promise(function(m,y){c.sendMessageToCallMachine({action:"daily-method-update-waiting-participant",id:p,updates:h},function(N){N.error&&y(N.error),N.id||y(new Error("unknown error in updateWaitingParticipant()")),m({id:N.id})})})}),function(){return Ne.apply(this,arguments)})},{key:"updateWaitingParticipants",value:(Se=X(function*(){var c=this,p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(lt(this._callObjectMode,"updateWaitingParticipants()"),ve(this._callState,"updateWaitingParticipants()"),le(p)!=="object")throw new Error("updateWaitingParticipants() must take a mapping between ids and update objects");return new Promise(function(h,m){c.sendMessageToCallMachine({action:"daily-method-update-waiting-participants",updates
26ById:p},function(y){y.error&&m(y.error),y.ids||m(new Error("unknown error in updateWaitingParticipants()")),h({ids:y.ids})})})}),function(){return Se.apply(this,arguments)})},{key:"requestAccess",value:(ie=X(function*(){var c=this,p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},h=p.access,m=h===void 0?{level:ov}:h,y=p.name,N=y===void 0?"":y;return lt(this._callObjectMode,"requestAccess()"),ve(this._callState,"requestAccess()"),new Promise(function(P,R){c.sendMessageToCallMachine({action:"daily-method-request-access",access:m,name:N},function(B){B.error&&R(B.error),B.access||R(new Error("unknown error in requestAccess()")),P({access:B.access,granted:B.granted})})})}),function(){return ie.apply(this,arguments)})},{key:"localAudio",value:function(){return this._participants.local?!["blocked","off"].includes(this._participants.local.tracks.audio.state):null}},{key:"localVideo",value:function(){return this._participants.local?!["blocked","off"].includes(this._participants.local.tracks.video.state):null}},{key:"setLocalAudio",value:function(c){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return"forceDiscardTrack"in p&&(ce()?(console.warn("forceDiscardTrack option not supported in React Native; ignoring"),p={}):c&&(console.warn("forceDiscardTrack option only supported when calling setLocalAudio(false); ignoring"),p={})),this.sendMessageToCallMachine({action:"local-audio",state:c,options:p}),this}},{key:"localScreenAudio",value:function(){return this._participants.local?!["blocked","off"].includes(this._participants.local.tracks.screenAudio.state):null}},{key:"localScreenVideo",value:function(){return this._participants.local?!["blocked","off"].includes(this._participants.local.tracks.screenVideo.state):null}},{key:"updateScreenShare",value:function(c){if(this._isScreenSharing)return this.sendMessageToCallMachine({action:"local-screen-update",options:c}),this;console.warn("There is no screen share in progress. Try calling startScreenShare first.")}},{key:"setLocalVideo",value:function(c){return this.sendMessageToCallMachine({action:"local-video",state:c}),this}},{key:"_setAllowLocalAudio",value:function(c){if(this._preloadCache.allowLocalAudio=c,this._callMachineInitialized)return this.sendMessageToCallMachine({action:"set-allow-local-audio",state:c}),this}},{key:"_setAllowLocalVideo",value:function(c){if(this._preloadCache.allowLocalVideo=c,this._callMachineInitialized)return this.sendMessageToCallMachine({action:"set-allow-local-video",state:c}),this}},{key:"getReceiveSettings",value:(ke=X(function*(c){var p=this,h=(arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}).showInheritedValues,m=h!==void 0&&h;if(lt(this._callObjectMode,"getReceiveSettings()"),!this._callMachineInitialized)return this._receiveSettings;switch(le(c)){case"string":return new Promise(function(y){p.sendMessageToCallMachine({action:"get-single-participant-receive-settings",id:c,showInheritedValues:m},function(N){y(N.receiveSettings)})});case"undefined":return this._receiveSettings;default:throw new Error('first argument to getReceiveSettings() must be a participant id (or "base"), or there should be no arguments')}}),function(c){return ke.apply(this,arguments)})},{key:"updateReceiveSettings",value:(Re=X(function*(c){var p=this;if(lt(this._callObjectMode,"updateReceiveSettings()"),!dd(c,{allowAllParticipantsKey:!0}))throw new Error(pd({allowAllParticipantsKey:!0}));return ve(this._callState,"updateReceiveSettings()","To specify receive settings earlier, use the receiveSettings config property."),new Promise(function(h){p.sendMessageToCallMachine({action:"update-receive-settings",receiveSettings:c},function(m){h({receiveSettings:m.receiveSettings})})})}),function(c){return Re.apply(this,arguments)})},{key:"_prepInputSettingsForSharing",value:function(c,p){if(c){var h={};if(c.audio){var m,y,N;c.audio.settings&&(!Object.keys(c.audio.settings).length&&p||(h.audio={settings:W({},c.audio.settings)})),p&&(m=h.audio)!==null&&m!==void 0&&(m=m.settings)!==null&&m!==void 0&&m.customTrack&&(h.audio.settings={customTrack:this._sharedTracks.audioTrack});var P=((y=c.audio.processor)===null||y===void 0?void 0:y.type)==="none"&&((N=c.audio.processor)===null||N===void 0?void 0:N._isDefaultWhenNone);if(c.audio.processor&&!P){var R=W({},c.audio.processor);delete R._isDefaultWhenNone,h.audio=W(W({},h.audio),{},{processor:R})}}if(c.video){var B,V,U;c.video.settings&&(!Object.keys(c.video.settings).length&&p||(h.video={settings:W({},c.video.settings)})),p&&(B=h.video)!==null&&B!==void 0&&(B=B.settings)!==null&&B!==void 0&&B.customTrack&&(h.video.settings={customTrack:this._sharedTracks.videoTrack});var ye=((V=c.video.processor)===null||V===void 0?void 0:V.type)==="none"&&((U=c.video.processor)===null||U===void 0?void 0:U._isDefaultWhenNone);if(c.video.processor&&!ye){var ge=W({},c.video.processor);delete ge._isDefaultWhenNone,h.video=W(W({},h.video),{},{processor:ge})}}return h}}},{key:"getInputSettings",value:function(){var c=this;return oe(),new Promise(function(p){p(c._getInputSettings())})}},{key:"_getInputSettings",value:function(){var c,p,h,m,y,N,P={processor:{type:"none",_isDefaultWhenNone:!0}};this._inputSettings?(c=((h=this._inputSettings)===null||h===void 0?void 0:h.video)||P,p=((m=this._inputSettings)===null||m===void 0?void 0:m.audio)||P):(c=((y=this._preloadCache)===null||y===void 0||(y=y.inputSettings)===null||y===void 0?void 0:y.video)||P,p=((N=this._preloadCache)===null||N===void 0||(N=N.inputSettings)===null||N===void 0?void 0:N.audio)||P);var R={audio:p,video:c};return this._prepInputSettingsForSharing(R,!0)}},{key:"_updatePreloadCacheInputSettings",value:function(c,p){var h=this._inputSettings||{},m={};if(c.video){var y,N,P;m.video={},c.video.settings?(m.video.settings={},p||c.video.settings.customTrack||(P=h.video)===null||P===void 0||!P.settings?m.video.settings=c.video.settings:m.video.settings=W(W({},h.video.settings),c.video.settings),Object.keys(m.video.settings).length||delete m.video.settings):(y=h.video)!==null&&y!==void 0&&y.settings&&(m.video.settings=h.video.settings),c.video.processor?m.video.processor=c.video.processor:(N=h.video)!==null&&N!==void 0&&N.processor&&(m.video.processor=h.video.processor)}else h.video&&(m.video=h.video);if(c.audio){var R,B,V;m.audio={},c.audio.settings?(m.audio.settings={},p||c.audio.settings.customTrack||(V=h.audio)===null||V===void 0||!V.settings?m.audio.settings=c.audio.settings:m.audio.settings=W(W({},h.audio.settings),c.audio.settings),Object.keys(m.audio.settings).length||delete m.audio.settings):(R=h.audio)!==null&&R!==void 0&&R.settings&&(m.audio.settings=h.audio.settings),c.audio.processor?m.audio.processor=c.audio.processor:(B=h.audio)!==null&&B!==void 0&&B.processor&&(m.audio.processor=h.audio.processor)}else h.audio&&(m.audio=h.audio);this._maybeUpdateInputSettings(m)}},{key:"_devicesFromInputSettings",value:function(c){var p,h,m=(c==null||(p=c.video)===null||p===void 0||(p=p.settings)===null||p===void 0?void 0:p.deviceId)||null,y=(c==null||(h=c.audio)===null||h===void 0||(h=h.settings)===null||h===void 0?void 0:h.deviceId)||null,N=this._preloadCache.outputDeviceId||null;return{camera:m?{deviceId:m}:{},mic:y?{deviceId:y}:{},speaker:N?{deviceId:N}:{}}}},{key:"updateInputSettings",value:(Ie=X(function*(c){var p=this;return oe(),hd(c)?c.video||c.audio?(fd(c,this.properties.dailyConfig,this._sharedTracks),this._callObjectMode&&!this._callMachineInitialized?(this._updatePreloadCacheInputSettings(c,!0),this._getInputSettings()):new Promise(function(h,m){p.sendMessageToCallMachine({action:"update-input-sett
26ings",inputSettings:c},function(y){if(y.error)m(y.error);else{if(y.returnPreloadCache)return p._updatePreloadCacheInputSettings(c,!0),void h(p._getInputSettings());p._maybeUpdateInputSettings(y.inputSettings),h(p._prepInputSettingsForSharing(y.inputSettings,!0))}})})):this._getInputSettings():(console.error(Ms()),Promise.reject(Ms()))}),function(c){return Ie.apply(this,arguments)})},{key:"setBandwidth",value:function(c){var p=c.kbs,h=c.trackConstraints;if(oe(),this._callMachineInitialized)return this.sendMessageToCallMachine({action:"set-bandwidth",kbs:p,trackConstraints:h}),this}},{key:"getDailyLang",value:function(){var c=this;if(oe(),this._callMachineInitialized)return new Promise(function(p){c.sendMessageToCallMachine({action:"get-daily-lang"},function(h){delete h.action,delete h.callbackStamp,p(h)})})}},{key:"setDailyLang",value:function(c){return oe(),this.sendMessageToCallMachine({action:"set-daily-lang",lang:c}),this}},{key:"setProxyUrl",value:function(c){return this.sendMessageToCallMachine({action:"set-proxy-url",proxyUrl:c}),this}},{key:"setIceConfig",value:function(c){return this.sendMessageToCallMachine({action:"set-ice-config",iceConfig:c}),this}},{key:"meetingSessionSummary",value:function(){return[It,Rt].includes(this._callState)?this._finalSummaryOfPrevSession:this._meetingSessionSummary}},{key:"getMeetingSession",value:(Te=X(function*(){var c=this;return console.warn("getMeetingSession() is deprecated: use meetingSessionSummary(), which will return immediately"),ve(this._callState,"getMeetingSession()"),new Promise(function(p){c.sendMessageToCallMachine({action:"get-meeting-session"},function(h){delete h.action,delete h.callbackStamp,p(h)})})}),function(){return Te.apply(this,arguments)})},{key:"meetingSessionState",value:function(){return ve(this._callState,"meetingSessionState"),this._meetingSessionState}},{key:"setMeetingSessionData",value:function(c){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"replace";lt(this._callObjectMode,"setMeetingSessionData()"),ve(this._callState,"setMeetingSessionData");try{(function(h,m){new pb({data:h,mergeStrategy:m})})(c,p)}catch(h){throw console.error(h),h}try{this.sendMessageToCallMachine({action:"set-session-data",data:c,mergeStrategy:p})}catch(h){throw new Error("Error setting meeting session data: ".concat(h))}}},{key:"setUserName",value:function(c,p){var h=this;return this.properties.userName=c,new Promise(function(m){h.sendMessageToCallMachine({action:"set-user-name",name:c??"",thisMeetingOnly:ce()||!!p&&!!p.thisMeetingOnly},function(y){delete y.action,delete y.callbackStamp,m(y)})})}},{key:"setUserData",value:(_e=X(function*(c){var p=this;try{ud(c)}catch(h){throw console.error(h),h}if(this.properties.userData=c,this._callMachineInitialized)return new Promise(function(h){try{p.sendMessageToCallMachine({action:"set-user-data",userData:c},function(m){delete m.action,delete m.callbackStamp,h(m)})}catch(m){throw new Error("Error setting user data: ".concat(m))}})}),function(c){return _e.apply(this,arguments)})},{key:"validateAudioLevelInterval",value:function(c){if(c&&(c<100||typeof c!="number"))throw new Error("The interval must be a number greater than or equal to 100 milliseconds.")}},{key:"startLocalAudioLevelObserver",value:function(c){var p=this;if(typeof AudioWorkletNode>"u"&&!ce())throw new Error("startLocalAudioLevelObserver() is not supported on this browser");if(this.validateAudioLevelInterval(c),this._callMachineInitialized)return this._isLocalAudioLevelObserverRunning=!0,new Promise(function(h,m){p.sendMessageToCallMachine({action:"start-local-audio-level-observer",interval:c},function(y){p._isLocalAudioLevelObserverRunning=!y.error,y.error?m({error:y.error}):h()})});this._preloadCache.localAudioLevelObserver={enabled:!0,interval:c}}},{key:"isLocalAudioLevelObserverRunning",value:function(){return this._isLocalAudioLevelObserverRunning}},{key:"stopLocalAudioLevelObserver",value:function(){this._preloadCache.localAudioLevelObserver=null,this._localAudioLevel=0,this._isLocalAudioLevelObserverRunning=!1,this.sendMessageToCallMachine({action:"stop-local-audio-level-observer"})}},{key:"startRemoteParticipantsAudioLevelObserver",value:function(c){var p=this;if(this.validateAudioLevelInterval(c),this._callMachineInitialized)return this._isRemoteParticipantsAudioLevelObserverRunning=!0,new Promise(function(h,m){p.sendMessageToCallMachine({action:"start-remote-participants-audio-level-observer",interval:c},function(y){p._isRemoteParticipantsAudioLevelObserverRunning=!y.error,y.error?m({error:y.error}):h()})});this._preloadCache.remoteParticipantsAudioLevelObserver={enabled:!0,interval:c}}},{key:"isRemoteParticipantsAudioLevelObserverRunning",value:function(){return this._isRemoteParticipantsAudioLevelObserverRunning}},{key:"stopRemoteParticipantsAudioLevelObserver",value:function(){this._preloadCache.remoteParticipantsAudioLevelObserver=null,this._remoteParticipantsAudioLevel={},this._isRemoteParticipantsAudioLevelObserverRunning=!1,this.sendMessageToCallMachine({action:"stop-remote-participants-audio-level-observer"})}},{key:"startCamera",value:(je=X(function*(){var c=this,p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(lt(this._callObjectMode,"startCamera()"),zi(this._callState,this._isPreparingToJoin,"startCamera()","Did you mean to use setLocalAudio() and/or set
26LocalVideo() instead?"),this.needsLoad())try{yield this.load(p)}catch(h){return Promise.reject(h)}else{if(this._didPreAuth){if(p.url&&p.url!==this.properties.url)return console.error("url in startCamera() is different than the one used in preAuth()"),Promise.reject();if(p.token&&p.token!==this.properties.token)return console.error("token in startCamera() is different than the one used in preAuth()"),Promise.reject()}this.validateProperties(p),this.properties=W(W({},this.properties),p)}return new Promise(function(h,m){c._preloadCache.inputSettings=c._prepInputSettingsForSharing(c._inputSettings,!1),c.sendMessageToCallMachine({action:"start-camera",properties:vn(c.properties,c.callClientId),preloadCache:vn(c._preloadCache,c.callClientId)},function(y){y.error?m(y.error):h({camera:y.camera,mic:y.mic,speaker:y.speaker})})})}),function(){return je.apply(this,arguments)})},{key:"validateCustomTrack",value:function(c,p,h){if(h&&h.length>50)throw new Error("Custom track `trackName` must not be more than 50 characters");if(p&&p!=="music"&&p!=="speech"&&!(p instanceof Object))throw new Error("Custom track `mode` must be either `music` | `speech` | `DailyMicAudioModeSettings` or `undefined`");if(h&&["cam-audio","cam-video","screen-video","screen-audio","rmpAudio","rmpVideo","customVideoDefaults"].includes(h))throw new Error("Custom track `trackName` must not match a track name already used by daily: cam-audio, cam-video, customVideoDefaults, screen-video, screen-audio, rmpAudio, rmpVideo");if(!(c instanceof MediaStreamTrack))throw new Error("Custom tracks provided must be instances of MediaStreamTrack")}},{key:"startCustomTrack",value:function(){var c=this,p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{track,mode,trackName,ignoreAudioLevel};return oe(),ve(this._callState,"startCustomTrack()"),this.validateCustomTrack(p.track,p.mode,p.trackName),new Promise(function(h,m){c._sharedTracks.customTrack=p.track,p.track=Nt,c.sendMessageToCallMachine({action:"start-custom-track",properties:p},function(y){y.error?m({error:y.error}):h(y.mediaTag)})})}},{key:"stopCustomTrack",value:function(c){var p=this;return oe(),ve(this._callState,"stopCustomTrack()"),new Promise(function(h){p.sendMessageToCallMachine({action:"stop-custom-track",mediaTag:c},function(m){h(m.mediaTag)})})}},{key:"setCamera",value:function(c){var p=this;return Bn(),yr(this._callMachineInitialized,"setCamera()"),new Promise(function(h){p.sendMessageToCallMachine({action:"set-camera",cameraDeviceId:c},function(m){h({device:m.device})})})}},{key:"setAudioDevice",value:(me=X(function*(c){return Bn(),this.nativeUtils().setAudioDevice(c),{deviceId:yield this.nativeUtils().getAudioDevice()}}),function(c){return me.apply(this,arguments)})},{key:"cycleCamera",value:function(){var c=this,p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return new Promise(function(h){c.sendMessageToCallMachine({action:"cycle-camera",properties:p},function(m){h({device:m.device})})})}},{key:"cycleMic",value:function(){var c=this;return oe(),new Promise(function(p){c.sendMessageToCallMachine({action:"cycle-mic"},function(h){p({device:h.device})})})}},{key:"getCameraFacingMode",value:function(){var c=this;return Bn(),new Promise(function(p){c.sendMessageToCallMachine({action:"get-camera-facing-mode"},function(h){p(h.facingMode)})})}},{key:"setInputDevicesAsync",value:(fe=X(function*(c){var p=this,h=c.audioDeviceId,m=c.videoDeviceId,y=c.audioSource,N=c.videoSource;if(oe(),y!==void 0&&(h=y),N!==void 0&&(m=N),typeof h=="boolean"&&(this._setAllowLocalAudio(h),h=void 0),typeof m=="boolean"&&(this._setAllowLocalVideo(m),m=void 0),!h&&!m)return yield this.getInputDevices();var P={};return h&&(h instanceof MediaStreamTrack?(this._sharedTracks.audioTrack=h,h=Nt,P.audio={settings:{customTrack:h}}):(delete this._sharedTracks.audioTrack,P.audio={settings:{deviceId:h}})),m&&(m instanceof MediaStreamTrack?(this._sharedTracks.videoTrack=m,m=Nt,P.video={settings:{customTrack:m}}):(delete this._sharedTracks.videoTrack,P.video={settings:{deviceId:m}})),this._callObjectMode&&this.needsLoad()?(this._updatePreloadCacheInputSettings(P,!1),this._devicesFromInputSettings(this._inputSettings)):new Promise(function(R){p.sendMessageToCallMachine({action:"set-input-devices",audioDeviceId:h,videoDeviceId:m},function(B){if(delete B.action,delete B.callbackStamp,B.returnPreloadCache)return p._updatePreloadCacheInputSettings(P,!1),void R(p._devicesFromInputSettings(p._inputSettings));R(B)})})}),function(c){return fe.apply(this,arguments)})},{key:"setOutputDeviceAsync",value:(z=X(function*(c){var p=this,h=c.outputDeviceId;if(oe(),!h||typeof h!="string")throw new Error("outputDeviceId must be provided and must be a valid device id");return this._preloadCache.outputDeviceId=h,this._callObjectMode&&this.needsLoad()?this._devicesFromInputSettings(this._inputSettings):new Promise(function(m,y){p.sendMessageToCallMachine({action:"set-output-device",outputDeviceId:h},function(N){if(delete N.action,delete N.callbackStamp,N.error){var P=new Error(N.error.message);return P.type=N.error.type,void y(P)}N.returnPreloadCache?m(p._devicesFromInputSettings(p._inputSettings)):m(N)})})}),function(c){return z.apply(this,arguments)})},{key:"getInputDevices",value:($=X(function*(){var c=this;return this._callObjectMode&&this.needsLoad()?this._devicesFromInputSettings(this._inputSettings):new Promise(function(p){c.sendMessageToCallMachine({action:"get-input-devices"},function(h){h.returnPreloadCache?p(c._devicesFromInputSettings(c._inputSettings)):p({camera:h.camera,mic:h.mic,speaker:h.speaker})})})}),function(){return $.apply(this,arguments)})},{key:"nativeInCallAudioMode",value:function(){return Bn(),this._nativeInCallAudioMode}},{key:"setNativeInCallAudioMode",value:function(c){if(Bn(),[Fc,Ib].includes(c)){if(c!==this._nativeInCallAudioMode)return this._nativeInCallAudioMode=c,!this.disableReactNativeAutoDeviceManagement("audio")&&Ar(this._callState,this._isPreparingToJoin)&&this.nativeUtils().setAudioMo
26de(this._nativeInCallAudioMode),this}else console.error("invalid in-call audio mode specified: ",c)}},{key:"preAuth",value:(F=X(function*(){var c=this,p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(lt(this._callObjectMode,"preAuth()"),zi(this._callState,this._isPreparingToJoin,"preAuth()"),this.needsLoad()&&(yield this.load(p)),!p.url)throw new Error("preAuth() requires at least a url to be provided");return this.validateProperties(p),this.properties=W(W({},this.properties),p),new Promise(function(h,m){c._preloadCache.inputSettings=c._prepInputSettingsForSharing(c._inputSettings,!1),c.sendMessageToCallMachine({action:"daily-method-preauth",properties:vn(c.properties,c.callClientId),preloadCache:vn(c._preloadCache,c.callClientId)},function(y){return y.error?m(y.error):y.access?(c._didPreAuth=!0,void h({access:y.access})):m(new Error("unknown error in preAuth()"))})})}),function(){return F.apply(this,arguments)})},{key:"load",value:(I=X(function*(c){var p=this;if(this.needsLoad()){if(this._destroyed&&(this._logUseAfterDestroy(),this.strictMode))throw new Error("Use after destroy");if(c&&(this.validateProperties(c),this.properties=W(W({},this.properties),c)),!this._callObjectMode&&!this.properties.url)throw new Error("can't load iframe meeting because url property isn't set");return this._updateCallState(oc),this.emitDailyJSEvent({action:pv}),this._callObjectMode?new Promise(function(h,m){p._callObjectLoader.cancel();var y=Date.now();p._callObjectLoader.load(p.properties.dailyConfig,function(N){p._bundleLoadTime=N?"no-op":Date.now()-y,p._updateCallState(cc),N&&p.emitDailyJSEvent({action:uc}),h()},function(N,P){if(p.emitDailyJSEvent({action:mv}),!P){p._updateCallState(Rt),p.resetMeetingDependentVars();var R={action:mc,errorMsg:N.msg,error:{type:"connection-error",msg:"Failed to load call object bundle.",details:{on:"load",sourceError:N,bundleUrl:Rr(p.properties.dailyConfig)}}};p._maybeSendToSentry(R),p.emitDailyJSEvent(R),m(N.msg)}})}):(this._iframe.src=Ou(this.assembleMeetingUrl(),this.properties.dailyConfig),new Promise(function(h,m){p._loadedCallback=function(y){p._callState!==Rt?(p._updateCallState(cc),(p.properties.cssFile||p.properties.cssText)&&p.loadCss(p.properties),h()):m(y)}}))}}),function(c){return I.apply(this,arguments)})},{key:"join",value:(T=X(function*(){var c=this,p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this._testCallInProgress&&this.stopTestCallQuality(),!p.url&&!this.properties.url){var h="No room URL has been provided";return console.error(h),Promise.reject(new Error(h))}var m=!1;if(this.needsLoad()){this.updateIsPreparingToJoin(!0);try{yield this.load(p)}catch(y){return this.updateIsPreparingToJoin(!1),Promise.reject(y)}}else{if(m=!(!this.properties.cssFile&&!this.properties.cssText),this._didPreAuth){if(p.url&&p.url!==this.properties.url)return console.error("url in join() is different than the one used in preAuth()"),this.updateIsPreparingToJoin(!1),Promise.reject();if(p.token&&p.token!==this.properties.token)return console.error("token in join() is different than the one used in preAuth()"),this.updateIsPreparingToJoin(!1),Promise.reject()}if(p.url&&!this._callObjectMode&&p.url&&p.url!==this.properties.url)return console.error("url in join() is different than the one used in load() (".concat(this.properties.url," -> ").concat(p.url,")")),this.updateIsPreparingToJoin(!1),Promise.reject();this.validateProperties(p),this.properties=W(W({},this.properties),p)}return p.showLocalVideo!==void 0&&(this._callObjectMode?console.error("showLocalVideo is not available in callObject mode"):this._showLocalVideo=!!p.showLocalVideo),p.showParticipantsBar!==void 0&&(this._callObjectMode?console.error("showParticipantsBar is not available in callObject mode"):this._showParticipantsBar=!!p.showParticipantsBar),this._callState===en||this._callState===ys?(console.warn("already joined meeting, call leave() before joining again"),void this.updateIsPreparingToJoin(!1)):(this._updateCallState(ys,!1),this.emitDailyJSEvent({action:bv}),this._preloadCache.inputSettings=this._prepInputSettingsForSharing(this._inputSettings||{},!1),this.sendMessageToCallMachine({action:"join-meeting",properties:vn(this.properties,this.callClientId),preloadCache:vn(this._preloadCache,this.callClientId)},function(y){y.error&&c._joinedCallback&&(c._joinedCallback(null,y.error),c._joinedCallback=null)}),new Promise(function(y,N){c._joinedCallback=function(P,R){if(c._callState!==Rt){if(R)return c._updateCallState(It),void N(R);if(c._updateCallState(en),P)for(var B in P){if(c._callObjectMode){var V=c._callMachine().store;Mc(P[B],V),Ac(P[B],V),Tc(P[B],c._participants[B],V)}c._participants[B]=W({},P[B]),c.toggleParticipantAudioBasedOnNativeAudioFocus()}m&&c.loadCss(c.properties),y(P)}else N(R)}}))}),function(){return T.apply(this,arguments)})},{key:"leave",value:(x=X(function*(){var c=this;return this._testCallInProgress&&this.stopTestCallQuality(),new Promise(function(p){c._callState===It||c._callState===Rt?p():c._callObjectLoader&&!c._callObjectLoader.loaded?(c._callObjectLoader.cancel(),c._updateCallState(It),c.resetMeetingDependentVars(),c.emitDailyJSEvent({action:It}),p()):(c._resolveLeave=p,c.sendMessageToCallMachine({action:"leave-meeting"}))})}),function(){return x.apply(this,arguments)})},{key:"startScreenShare",value:(S=X(function*(){var c=this,p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(yr(this._callMachineInitialized,"startScreenShare()"),p.screenVideoSendSettings&&this._val
26idateVideoSendSettings("screenVideo",p.screenVideoSendSettings),p.mediaStream&&(this._sharedTracks.screenMediaStream=p.mediaStream,p.mediaStream=Nt),typeof DailyNativeUtils<"u"&&DailyNativeUtils.isIOS!==void 0&&DailyNativeUtils.isIOS){var h=this.nativeUtils();if(yield h.isScreenBeingCaptured())return void this.emitDailyJSEvent({action:pc,type:"screen-share-error",errorMsg:"Could not start the screen sharing. The screen is already been captured!"});h.setSystemScreenCaptureStartCallback(function(){h.setSystemScreenCaptureStartCallback(null),c.sendMessageToCallMachine({action:vc,captureOptions:p})}),h.presentSystemScreenCapturePrompt()}else this.sendMessageToCallMachine({action:vc,captureOptions:p})}),function(){return S.apply(this,arguments)})},{key:"stopScreenShare",value:function(){yr(this._callMachineInitialized,"stopScreenShare()"),this.sendMessageToCallMachine({action:"local-screen-stop"})}},{key:"startRecording",value:function(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},p=c.type;if(p&&p!=="cloud"&&p!=="cloud-audio-only"&&p!=="raw-tracks"&&p!=="local")throw new Error("invalid type: ".concat(p,", allowed values 'cloud', 'cloud-audio-only', 'raw-tracks', or 'local'"));this.sendMessageToCallMachine(W({action:"local-recording-start"},c))}},{key:"updateRecording",value:function(c){var p=c.layout,h=p===void 0?{preset:"default"}:p,m=c.instanceId;this.sendMessageToCallMachine({action:"daily-method-update-recording",layout:h,instanceId:m})}},{key:"stopRecording",value:function(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.sendMessageToCallMachine(W({action:"local-recording-stop"},c))}},{key:"startLiveStreaming",value:function(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.sendMessageToCallMachine(W({action:"daily-method-start-live-streaming"},c))}},{key:"updateLiveStreaming",value:function(c){var p=c.layout,h=p===void 0?{preset:"default"}:p,m=c.instanceId;this.sendMessageToCallMachine({action:"daily-method-update-live-streaming",layout:h,instanceId:m})}},{key:"addLiveStreamingEndpoints",value:function(c){var p=c.endpoints,h=c.instanceId;this.sendMessageToCallMachine({action:bc,endpointsOp:ab,endpoints:p,instanceId:h})}},{key:"removeLiveStreamingEndpoints",value:function(c){var p=c.endpoints,h=c.instanceId;this.sendMessageToCallMachine({action:bc,endpointsOp:ob,endpoints:p,instanceId:h})}},{key:"stopLiveStreaming",value:function(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};
26this.sendMessageToCallMachine(W({action:"daily-method-stop-live-streaming"},c))}},{key:"validateDailyConfig",value:function(c){c.camSimulcastEncodings&&(console.warn("camSimulcastEncodings is deprecated. Use sendSettings, found in DailyCallOptions, to provide camera simulcast settings."),this.validateSimulcastEncodings(c.camSimulcastEncodings)),c.screenSimulcastEncodings&&console.warn("screenSimulcastEncodings is deprecated. Use sendSettings, found in DailyCallOptions, to provide screen simulcast settings."),Xu()&&c.noAutoDefaultDeviceChange&&console.warn("noAutoDefaultDeviceChange is not supported on Android, and will be ignored.")}},{key:"validateSimulcastEncodings",value:function(c){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,h=arguments.length>2&&arguments[2]!==void 0&&arguments[2];if(c){if(!(c instanceof Array||Array.isArray(c)))throw new Error("encodings must be an Array");if(!Kc(c.length,1,3))throw new Error("encodings must be an Array with between 1 to ".concat(3," layers"));for(var m=0;m<c.length;m++){var y=c[m];for(var N in this._validateEncodingLayerHasValidProperties(y),y)if(Vi.includes(N)){if(typeof y[N]!="number")throw new Error("".concat(N," must be a number"));if(p){var P=p[N],R=P.min,B=P.max;if(!Kc(y[N],R,B))throw new Error("".concat(N," value not in range. valid range: ").concat(R," to ").concat(B))}}else if(!["active","scalabilityMode"].includes(N))throw new Error("Invalid key ".concat(N,", valid keys are:")+Object.values(Vi));if(h&&!y.hasOwnProperty("maxBitrate"))throw new Error("maxBitrate is not specified")}}}},{key:"startRemoteMediaPlayer",value:(j=X(function*(c){var p=this,h=c.url,m=c.settings,y=m===void 0?{state:ws.PLAY}:m;try{(function(N){if(typeof N!="string")throw new Error('url parameter must be "string" type')})(h),Hc(y),(function(N){for(var P in N)if(!Uc.includes(P))throw new Error("Invalid key ".concat(P,", valid keys are: ").concat(Uc));N.simulcastEncodings&&this.validateSimulcastEncodings(N.simulcastEncodings,cd,!0)})(y)}catch(N){throw console.error("invalid argument Error: ".concat(N)),console.error(`startRemoteMediaPlayer arguments must be of the form:
27  { url: "playback url",
28  settings?:
29  {state: "play"|"pause", simulcastEncodings?: [{}] } }`),N}return new Promise(function(N,P){p.sendMessageToCallMachine({action:"daily-method-start-remote-media-player",url:h,settings:y},function(R){R.error?P({error:R.error,errorMsg:R.errorMsg}):N({session_id:R.session_id,remoteMediaPlayerState:{state:R.state,settings:R.settings}})})})}),function(c){return j.apply(this,arguments)})},{key:"stopRemoteMediaPlayer",value:(O=X(function*(c){var p=this;if(typeof c!="string")throw new Error(" remotePlayerID must be of type string");return new Promise(function(h,m){p.sendMessageToCallMachine({action:"daily-method-stop-remote-media-player",session_id:c},function(y){y.error?m({error:y.error,errorMsg:y.errorMsg}):h()})})}),function(c){return O.apply(this,arguments)})},{key:"updateRemoteMediaPlayer",value:(C=X(function*(c){var p=this,h=c.session_id,m=c.settings;try{Hc(m)}catch(y){throw console.error("invalid argument Error: ".concat(y)),console.error(`updateRemoteMediaPlayer arguments must be of the form:
30  session_id: "participant session",
31  { settings?: {state: "play"|"pause"} }`),y}return new Promise(function(y,N){p.sendMessageToCallMachine({action:"daily-method-update-remote-media-player",session_id:h,settings:m},function(P){P.error?N({error:P.error,errorMsg:P.errorMsg}):y({session_id:P.session_id,remoteMediaPlayerState:{state:P.state,settings:P.settings}})})})}),function(c){return C.apply(this,arguments)})},{key:"startTranscription",value:function(c){ve(this._callState,"startTranscription()"),this.sendMessageToCallMachine(W({action:"daily-method-start-transcription"},c))}},{key:"updateTranscription",value:function(c){if(ve(this._callState,"updateTranscription()"),!c)throw new Error("updateTranscription Error: options is mandatory");if(le(c)!=="object")throw new Error("updateTranscription Error: options must be object type");if(c.participants&&!Array.isArray(c.participants))throw new Error("updateTranscription 
31Error: participants must be an array");this.sendMessageToCallMachine(W({action:"daily-method-update-transcription"},c))}},{key:"stopTranscription",value:function(c){if(ve(this._callState,"stopTranscription()"),c&&le(c)!=="object")throw new Error("stopTranscription Error: options must be object type");if(c&&!c.instanceId)throw new Error('"instanceId" not provided');this.sendMessageToCallMachine(W({action:"daily-method-stop-transcription"},c))}},{key:"startDialOut",value:(E=X(function*(c){var p=this;ve(this._callState,"startDialOut()");var h=function(P){if(P){if(!Array.isArray(P))throw new Error("Error starting dial out: audio codec must be an array");if(P.length<=0)throw new Error("Error starting dial out: audio codec array specified but empty");P.forEach(function(R){if(typeof R!="string")throw new Error("Error starting dial out: audio codec must be a string");if(R!=="OPUS"&&R!=="PCMU"&&R!=="PCMA"&&R!=="G722")throw new Error("Error starting dial out: audio codec must be one of OPUS, PCMU, PCMA, G722")})}};if(!c.sipUri&&!c.phoneNumber)throw new Error("Error starting dial out: either a sip uri or phone number must be provided");if(c.sipUri&&c.phoneNumber)throw new Error("Error starting dial out: only one of sip uri or phone number must be provided");
31if(c.sipUri){if(typeof c.sipUri!="string")throw new Error("Error starting dial out: sipUri must be a string");if(!c.sipUri.startsWith("sip:"))throw new Error("Error starting dial out: Invalid SIP URI, must start with 'sip:'");if(c.video&&typeof c.video!="boolean")throw new Error("Error starting dial out: video must be a boolean value");(function(P){if(P&&(h(P.audio),P.video)){if(!Array.isArray(P.video))throw new Error("Error starting dial out: video codec must be an array");if(P.video.length<=0)throw new Error("Error starting dial out: video codec array specified but empty");P.video.forEach(function(R){if(typeof R!="string")throw new Error("Error starting dial out: video codec must be a string");if(R!=="H264"&&R!=="VP8")throw new Error("Error starting dial out: video codec must be H264 or VP8")})}})(c.codecs)}if(c.phoneNumber){if(typeof c.phoneNumber!="string")throw new Error("Error starting dial out: phoneNumber must be a string");if(!/^\+\d{1,}$/.test(c.phoneNumber))throw new Error("Error starting dial out: Invalid phone number, must be valid phone number as per E.164");c.codecs&&h(c.codecs.audio)}if(c.callerId){if(typeof c.callerId!="string")throw new Error("Error starting dial out: callerId must be a string");if(c.sipUri)throw new Error("Error starting dial out: callerId not allowed with sipUri")}if(c.displayName){if(typeof c.displayName!="string")throw new Error("Error starting dial out: displayName must be a string");if(c.displayName.length>=200)throw new Error("Error starting dial out: displayName length must be less than 200")}if(c.userId){if(typeof c.userId!="string")throw new Error("Error starting dial out: userId must be a string");if(c.userId.length>36)throw new Error("Error starting dial out: userId length must be less than or equal to 36")}if(qc(c),c.permissions&&c.permissions.canReceive){var m=Pe(ad.validateJSONObject(c.permissions.canReceive),2),y=m[0],N=m[1];if(!y)throw new Error(N)}if(c.provider){if(c.provider!==gr&&c.provider!==Di)throw new Error("Error: provider can be set only to '".concat(gr,"' or '").concat(Di,"', got: ").concat(c.provider));if(c.phoneNumber)throw new Error("Error starting dial out: provider valid only for sipUri, not phoneNumber");c.provider===gr&&console.warn("(pre-beta) provider=".concat(gr," is currently in pre-beta, things might break!"))}else c.provider=Di;return new Promise(function(P,R){p.sendMessageToCallMachine(W({action:"dialout-start"},c),function(B){B.error?R(B.error):P(B)})})}),function(c){return E.apply(this,arguments)})},{key:"stopDialOut",value:function(c){var p=this;return ve(this._callState,"stopDialOut()"),new Promise(function(h,m){p.sendMessageToCallMachine(W({action:"dialout-stop"},c),function(y){y.error?m(y.error):h(y)})})}},{key:"sipCallTransfer",value:(v=X(function*(c){var p=this;if(ve(this._callState,"sipCallTransfer()"),!c)throw new Error("sipCallTransfer() requires a sessionId and toEndPoint");return c.useSipRefer=!1,Gc(c,"sipCallTransfer"),qc(c),new Promise(function(h,m){p.sendMessageToCallMachine(W({action:yc},c),function(y){y.error?m(y.error):h(y)})})}),function(c){return v.apply(this,arguments)})},{key:"sipRefer",value:(b=X(function*(c){var p=this;if(ve(this._callState,"sipRefer()"),!c)throw new Error("sessionId and toEndPoint are mandatory parameter");return c.useSipRefer=!0,Gc(c,"sipRefer"),new Promise(function(h,m){p.sendMessageToCallMachine(W({action:yc},c),function(y){y.error?m(y.error):h(y)})})}),function(c){return b.apply(this,arguments)})},{key:"sendDTMF",value:(k=X(function*(c){var p=this;return ve(this._callState,"sendDTMF()"),(function(h){var m=h.sessionId,y=h.tones,N=h.method,P=h.digitDurationMs;if(!m||!y)throw new Error("sessionId and tones are mandatory parameter");if(typeof m!="string"||typeof y!="string")throw new Error("sessionId and tones should be of string type");if(y.length>20)throw new Error("tones string must be upto 20 characters");var R=/[^0-9A-D*#]/g,B=y.match(R);if(B&&B[0])throw new Error("".concat(B[0]," is not valid DTMF tone"));if(N&&!["sip-info","telephone-event","auto"].includes(N))throw new Error("method must be one of 'sip-info', 'telephone-event', or 'auto'");if(P!==void 0){if(typeof P!="number")throw new Error("digitDurationMs must be a number");if(!Number.isFinite(P)||!Number.isInteger(P))throw new Error("digitDurationMs must be a finite integer number");if(P<50||P>2e3)throw new Error("digitDurationMs must be between 50ms and 2000ms")}})(c),c.method=c.method||"auto",c.digitDurationMs=c.digitDurationMs||500,new Promise(function(h,m){p.sendMessageToCallMachine(W({action:"send-dtmf"},c),function(y){y.error?m(y.error):h(y)})})}),function(c){return k.apply(this,arguments)})},{key:"getNetworkStats",value:function(){var c=this;return this._callState!==en?Promise.resolve(W({stats:{latest:{}}},this._network)):new Promise(function(p){c.sendMessageToCallMachine({action:"get-calc-stats"},function(h){p(W(W({},c._network),{},{stats:h.stats}))})})}},{key:"testWebsocketConnectivity",value:(_=X(function*(){var c=this;if(Wi(this._testCallInProgress,"testWebsocketConnectivity()"),this.needsLoad())try{yield this.load()}catch(p){return Promise.reject(p)}return new Promise(function(p,h){c.sendMessageToCallMachine({action:"test-websocket-connectivity"},function(m){m.error?h(m.error):p(m.results)})})}),function(){return _.apply(this,arguments)})},{key:"abortTestWebsocketConnectivity",value:function(){this.sendMessageToCallMachine({action:"abort-test-websocket-connectivity"})}},{key:"_validateVideoTrackForNetworkTests",value:function(c){return c?c instanceof MediaStreamTrack?!!Tb(c)||(console.error("Video track is not playable. This test needs a live video track."),!1):(console.error("Video track needs to be of type `MediaStreamTrack`."),!1):(console.error("Missing video track. You must provide a video track in order to run this test."),!1)}},{key:"testCallQuality",value:(g=X(function*(){var c=this;oe(),lt(this._callObjectMode,"testCallQuality()"),yr(this._callMachineInitialized,"testCallQuality()",null,!0),zi(this._callState,this._isPreparingToJoin,"testCallQuality()");var p=this._testCallAlreadyInProgress,h=function(y){p||(c._testCallInProgress=y)};if(h(!0),this.needsLoad())try{var m=this._callState;yield this.load(),this._callState=m}catch(y){return h(!1),Promise.reject(y)}return new Promise(function(y){c.sendMessageToCallMachine({action:"test-call-quality",dailyJsVersion:c.properties.dailyJsVersion},function(N){var P=N.results,R=P.result,B=eo(P,Pb);if(R==="failed"){var V,U=W({},B);(V=B.error)!==null&&V!==void 0&&V.details?(B.error.details=JSON.parse(B.error.details),U.error=W(W({},U.error),{},{details:W({},U.error.details)}),U.error.details.duringTest="testCallQuality"):(U.error=U.error?W({},U.error):{},U.error.details={duringTest:"testCallQuality"}),c._maybeSendToSentry(U)}h(!1),y(W({result:R},B))})})}),function(){return g.apply(this,arguments)})},{key:"stopTestCallQuality",value:function(){this.sendMessageToCallMachine({action:"stop-test-call-quality"})}},{key:"testConnectionQuality",value:(f=X(function*(c){var p;
31ce()?(console.warn("testConnectionQuality() is deprecated: use testPeerToPeerCallQuality() instead"),p=yield this.testPeerToPeerCallQuality(c)):(console.warn("testConnectionQuality() is deprecated: use testCallQuality() instead"),p=yield this.testCallQuality());var h={result:p.result,secondsElapsed:p.secondsElapsed};return p.data&&(h.data={maxRTT:p.data.maxRoundTripTime,packetLoss:p.data.avgRecvPacketLoss}),h}),function(c){return f.apply(this,arguments)})},{key:"testPeerToPeerCallQuality",value:(u=X(function*(c){var p=this;if(Wi(this._testCallInProgress,"testPeerToPeerCallQuality()"),this.needsLoad())try{yield this.load()}catch(y){return Promise.reject(y)}var h=c.videoTrack,m=c.duration;if(!this._validateVideoTrackForNetworkTests(h))throw new Error("Video track error");return this._sharedTracks.videoTrackForConnectionQualityTest=h,new Promise(function(y,N){p.sendMessageToCallMachine({action:"test-p2p-call-quality",duration:m},function(P){P.error?N(P.error):y(P.results)})})}),function(c){return u.apply(this,arguments)})},{key:"stopTestConnectionQuality",value:function(){ce()?(console.warn("stopTestConnectionQuality() is deprecated: use testPeerToPeerCallQuality() and stopTestPeerToPeerCallQuality() instead"),this.stopTestPeerToPeerCallQuality()):(console.warn("stopTestConnectionQuality() is deprecated: use testCallQuality() and stopTestCallQuality() instead"),this.stopTestCallQuality())}},{key:"stopTestPeerToPeerCallQuality",value:function(){this.sendMessageToCallMachine({action:"stop-test-p2p-call-quality"})}},{key:"testNetworkConnectivity",value:(l=X(function*(c){var p=this;if(Wi(this._testCallInProgress,"testNetworkConnectivity()"),this.needsLoad())try{yield this.load()}catch(h){return Promise.reject(h)}if(!this._validateVideoTrackForNetworkTests(c))throw new Error("Video track error");return this._sharedTracks.videoTrackForNetworkConnectivityTest=c,new Promise(function(h,m){p.sendMessageToCallMachine({action:"test-network-connectivity"},function(y){y.error?m(y.error):h(y.results)})})}),function(c){return l.apply(this,arguments)})},{key:"abortTestNetworkConnectivity",value:function(){this.sendMessageToCallMachine({action:"abort-test-network-connectivity"})}},{key:"getCpuLoadStats",value:function(){var c=this;return new Promise(function(p){c._callState===en?c.sendMessageToCallMachine({action:"get-cpu-load-stats"},function(h){p(h.cpuStats)}):p({cpuLoadState:void 0,cpuLoadStateReason:void 0,stats:{}})})}},{key:"_validateEncodingLayerHasValidProperties",value:function(c){var p;if(!(((p=Object.keys(c))===null||p===void 0?void 0:p.length)>0))throw new Error("Empty encoding is not allowed. At least one of these valid keys should be specified:"+Object.values(Vi))}},{key:"_validateVideoSendSettings",value:function(c,p){var h=c==="screenVideo"?["default-screen-video","detail-optimized","motion-optimized","motion-and-detail-balanced"]:["default-video","bandwidth-optimized","bandwidth-and-quality-balanced","quality-optimized","adaptive-2-layers","adaptive-3-layers"],m="Video send settings should be either an object or one of the supported presets: ".concat(h.join());if(typeof p=="string"){if(!h.includes(p))throw new Error(m)}else{if(le(p)!=="object")throw new Error(m);if(!p.maxQuality&&!p.encodings&&p.allowAdaptiveLayers===void 0)throw new Error("Video send settings must contain at least maxQuality, allowAdaptiveLayers or encodings attribute");if(p.maxQuality&&["low","medium","high"].indexOf(p.maxQuality)===-1)throw new Error("maxQuality must be either low, medium or high");if(p.encodings){var y=!1;switch(Object.keys(p.encodings).length){case 1:y=!p.encodings.low;break;case 2:y=!p.encodings.low||!p.encodings.medium;break;case 3:y=!p.encodings.low||!p.encodings.medium||!p.encodings.high;break;default:y=!0}if(y)throw new Error("Encodings must be defined as: low, low and medium, or low, medium and high.");p.encodings.low&&this._validateEncodingLayerHasValidProperties(p.encodings.low),p.encodings.medium&&this._validateEncodingLayerHasValidProperties(p.encodings.medium),p.encodings.high&&this._validateEncodingLayerHasValidProperties(p.encodings.high)}}}},{key:"validateUpdateSendSettings",value:function(c){var p=this;if(!c||Object.keys(c).length===0)throw new Error("Send settings must contain at least information for one track!");
31Object.entries(c).forEach(function(h){var m=Pe(h,2),y=m[0],N=m[1];p._validateVideoSendSettings(y,N)})}},{key:"updateSendSettings",value:function(c){var p=this;return this.validateUpdateSendSettings(c),this.needsLoad()?(this._preloadCache.sendSettings=c,{sendSettings:this._preloadCache.sendSettings}):new Promise(function(h,m){p.sendMessageToCallMachine({action:"update-send-settings",sendSettings:c},function(y){y.error?m(y.error):h(y.sendSettings)})})}},{key:"getSendSettings",value:function(){return this._sendSettings||this._preloadCache.sendSettings}},{key:"getLocalAudioLevel",value:function(){return this._localAudioLevel}},{key:"getRemoteParticipantsAudioLevel",value:function(){return this._remoteParticipantsAudioLevel}},{key:"getActiveSpeaker",value:function(){return oe(),this._activeSpeaker}},{key:"setActiveSpeakerMode",value:function(c){return oe(),this.sendMessageToCallMachine({action:"set-active-speaker-mode",enabled:c}),this}},{key:"activeSpeakerMode",value:function(){return oe(),this._activeSpeakerMode}},{key:"subscribeToTracksAutomatically",value:function(){return this._preloadCache.subscribeToTracksAutomatically}},{key:"setSubscribeToTracksAutomatically",value:function(c){return ve(this._callState,"setSubscribeToTracksAutomatically()","Use the subscribeToTracksAutomatically configuration property."),this._preloadCache.subscribeToTracksAutomatically=c,this.sendMessageToCallMachine({action:"daily-method-subscribe-to-tracks-automatically",enabled:c}),this}},{key:"enumerateDevices",value:(o=X(function*(){var c=this;if(this._callObjectMode){var p=yield navigator.mediaDevices.enumerateDevices();return dn()==="Firefox"&&Ur().major>115&&Ur().major<123&&(p=p.filter(function(h){return h.kind!=="audiooutput"})),{devices:p.map(function(h){var m=JSON.parse(JSON.stringify(h));if(!ce()&&h.kind==="videoinput"&&h.getCapabilities){var y,N=h.getCapabilities();m.facing=(N==null||(y=N.facingMode)===null||y===void 0?void 0:y.length)>=1?N.facingMode[0]:void 0}return m})}}return new Promise(function(h){c.sendMessageToCallMachine({action:"enumerate-devices"},function(m){h({devices:m.devices})})})}),function(){return o.apply(this,arguments)})},{key:"sendAppMessage",value:function(c){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"*";if(ve(this._callState,"sendAppMessage()"),JSON.stringify(c).length>this._maxAppMessageSize)throw new Error("Message data too large. Max size is "+this._maxAppMessageSize);return this.sendMessageToCallMachine({action:"app-msg",data:c,to:p}),this}},{key:"addFakeParticipant",value:function(c){return oe(),ve(this._callState,"addFakeParticipant()"),this.sendMessageToCallMachine(W({action:"add-fake-participant"},c)),this}},{key:"setShowNamesMode",value:function(c){return Qe(this._callObjectMode,"setShowNamesMode()"),oe(),c&&c!=="always"&&c!=="never"?(console.error('setShowNamesMode argument should be "always", "never", or false'),this):(this.sendMessageToCallMachine({action:"set-show-names",mode:c}),this)}},{key:"setShowLocalVideo",value:function(){var c=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return Qe(this._callObjectMode,"setShowLocalVideo()"),oe(),ve(this._callState,"setShowLocalVideo()"),typeof c!="boolean"?(console.error("setShowLocalVideo only accepts a boolean value"),this):(this.sendMessageToCallMachine({action:"set-show-local-video",show:c}),this._showLocalVideo=c,this)}},{key:"showLocalVideo",value:function(){return Qe(this._callObjectMode,"showLocalVideo()"),oe(),this._showLocalVideo}},{key:"setShowParticipantsBar",value:function(){var c=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return Qe(this._callObjectMode,"setShowParticipantsBar()"),oe(),ve(this._callState,"setShowParticipantsBar()"),typeof c!="boolean"?(console.error("setShowParticipantsBar only accepts a boolean value"),this):(this.sendMessageToCallMachine({action:"set-show-participants-bar",show:c}),this._showParticipantsBar=c,this)}},{key:"showParticipantsBar",value:function(){return Qe(this._callObjectMode,"showParticipantsBar()"),oe(),this._showParticipantsBar}},{key:"customIntegrations",value:function(){return oe(),Qe(this._callObjectMode,"customIntegrations()"),this._customIntegrations}},{key:"setCustomIntegrations",value:function(c){return oe(),Qe(this._callObjectMode,"setCustomIntegrations()"),ve(this._callState,"setCustomIntegrations()"),vd(c)?(this.sendMessageToCallMachine({action:"set-custom-integrations",integrations:c}),this._customIntegrations=c,this):this}},{key:"startCustomIntegrations",value:function(c){var p=this;if(oe(),Qe(this._callObjectMode,"startCustomIntegrations()"),ve(this._callState,"startCustomIntegrations()"),Array.isArray(c)&&c.some(function(y){return typeof y!="str
31ing"})||!Array.isArray(c)&&typeof c!="string")return console.error("startCustomIntegrations() only accepts string | string[]"),this;var h=typeof c=="string"?[c]:c,m=h.filter(function(y){return!(y in p._customIntegrations)});return m.length?(console.error(`Can't find custom integration(s): "`.concat(m.join(", "),'"')),this):(this.sendMessageToCallMachine({action:"start-custom-integrations",ids:h}),this)}},{key:"stopCustomIntegrations",value:function(c){var p=this;if(oe(),Qe(this._callObjectMode,"stopCustomIntegrations()"),ve(this._callState,"stopCustomIntegrations()"),Array.isArray(c)&&c.some(function(y){return typeof y!="string"})||!Array.isArray(c)&&typeof c!="string")return console.error("stopCustomIntegrations() only accepts string | string[]"),this;var h=typeof c=="string"?[c]:c,m=h.filter(function(y){return!(y in p._customIntegrations)});return m.length?(console.error(`Can't find custom integration(s): "`.concat(m.join(", "),'"')),this):(this.sendMessageToCallMachine({action:"stop-custom-integrations",ids:h}),this)}},{key:"customTrayButtons",value:function(){return Qe(this._callObjectMode,"customTrayButtons()"),oe(),this._customTrayButtons}},{key:"updateCustomTrayButtons",value:function(c){return Qe(this._callObjectMode,"updateCustomTrayButtons()"),oe(),ve(this._callState,"updateCustomTrayButtons()"),gd(c)?(this.sendMessageToCallMachine({action:"update-custom-tray-buttons",btns:c}),this._customTrayButtons=c,this):(console.error("updateCustomTrayButtons only accepts a dictionary of the type ".concat(JSON.stringify(zr))),this)}},{key:"theme",value:function(){return Qe(this._callObjectMode,"theme()"),this.properties.theme}},{key:"setTheme",value:function(c){var p=this;return Qe(this._callObjectMode,"setTheme()"),new Promise(function(h,m){try{p.validateProperties({theme:c}),p.properties.theme=W({},c),p.sendMessageToCallMachine({action:"set-theme",theme:p.properties.theme});try{p.emitDailyJSEvent({action:fv,theme:p.properties.theme})}catch(y){console.log("could not emit 'theme-updated'",y)}h(p.properties.theme)}catch(y){m(y)}})}},{key:"requestFullscreen",value:(a=X(function*(){if(oe(),this._iframe&&!document.fullscreenElement&&wc())try{(yield this._iframe.requestFullscreen)?this._iframe.requestFullscreen():this._iframe.webkitRequestFullscreen()}catch(c){console.log("could not make video call fullscreen",c)}}),function(){return a.apply(this,arguments)})},{key:"exitFullscreen",value:function(){oe(),document.fullscreenElement?document.exitFullscreen():document.webkitFullscreenElement&&document.webkitExitFullscreen()}},{key:"getSidebarView",value:(s=X(function*(){var c=this;return this._callObjectMode?(console.error("getSidebarView is not available in callObject mode"),Promise.resolve(null)):new Promise(function(p){c.sendMessageToCallMachine({action:"get-sidebar-view"},function(h){p(h.view)})})}),function(){return s.apply(this,arguments)})},{key:"setSidebarView",value:function(c){return this._callObjectMode?(console.error("setSidebarView is not available in callObject mode"),this):(this.sendMessageToCallMachine({action:"set-sidebar-view",view:c}),this)}},{key:"room",value:(i=X(function*(){var c=this,p=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}).includeRoomConfigDefaults,h=p===void 0||p;return this._accessState.access===Ii||this.needsLoad()?this.properties.url?{roomUrlPendingJoin:this.properties.url}:null:new Promise(function(m){c.sendMessageToCallMachine({action:"lib-room-info",includeRoomConfigDefaults:h},function(y){delete y.action,delete y.callbackStamp,m(y)})})}),function(){return i.apply(this,arguments)})},{key:"geo",value:(r=X(function*(){return console.error("The geo() function is no longer supported. Geographical decisions now depend upon domain and room settings."),{current:""}}),function(){return r.apply(this,arguments)})},{key:"setNetworkTopology",value:(t=X(function*(c){var p=this;return oe(),ve(this._callState,"setNetworkTopology()"),new Promise(function(h,m){p.sendMessageToCallMachine({action:"set-network-topology",opts:c},function(y){y.error?m({error:y.error}):h({workerId:y.workerId})})})}),function(c){return t.apply(this,arguments)})},{key:"getNetworkTopology",value:(e=X(function*(){var c=this;return new Promise(function(p,h){c.needsLoad()&&p({topology:"none"}),c.sendMessageToCallMachine({action:"get-network-topology"},function(m){m.error?h({error:m.error}):p({topology:m.topology})})})}),function(){return e.apply(this,arguments)})},{key:"setPlayNewParticipantSound",value:function(c){if(oe(),typeof c!="number"&&c!==!0&&c!==!1)throw new Error("argument to setShouldPlayNewParticipantSound should be true, false, or a number, but is ".concat(c));this.sendMessageToCallMachine({action:"daily-method-set-play-ding",arg:c})}},{key:"on",value:function(c,p){return sr.prototype.on.call(this,c,p)}},{key:"once",value:function(c,p){return sr.prototype.once.call(this,c,p)}},{key:"off",value:function(c,p){return sr.prototype.off.call(this,c,p)}},{key:"validateProperties",value:function(c){var p,h;if(c!=null&&(p=c.dailyConfig)!==null&&p!==void 0&&p.userMediaAudioConstraints){var m,y;ce()||console.warn("userMediaAudioConstraints is deprecated. You can override constraints with inputSettings.audio.settings, found in DailyCallOptions.");var N=c.inputSettings||{};N.audio=((m=c.inputSettings)===null||m===void 0?void 0:m.audio)||{},N.audio.settings=((y=c.inputSettings)===null||y===void 0||(y=y.audio)===null||y===void 0?void 0:y.settings)||{},N.audio.settings=W(W({},N.audio.settings),c.dailyConfig.userMediaAudioConstraints),c.inputSettings=N,delete c.dailyConfig.userMediaAudioConstraints}if(c!=null&&(h=c.dailyConfig)!==null&&h!==void 0&&h.userMediaVideoConstraints){var P,R;ce()||console.warn("userMediaVideoConstraints is deprecated. You can override constraints with inputSettings.video.settings, found in DailyCallOptions.");var B=c.inputSettings||{};B.video=((P=c.inputSettings)===null||P===void 0?void 0:P.video)||{},B.video.settings=((R=c.inputSettings)===null||R===void 0||(R=R.video)===null||R===void 0?void 0:R.settings)||{},B.video.settings=W(W({},B.video.settings),c.dailyConfig.userMediaVideoConstraints),c.inputSettings=B,delete c.dailyConfig.userMediaVideoConstraints}for(var V in c)if(Xt[V]){if(Xt[V].validate&&!Xt[V].validate(c[V],this))throw new Error("property '".concat(V,"': ").concat(Xt[V].help))}else console.warn("Ignoring unrecognized property '".concat(V,"'")),delete c[V]}},{key:"assembleMeetingUrl",value:function(){var c,p,h=W(W({},this.properties),{},{emb:this.callClientId,embHref:encodeURIComponent(window.location.href),proxy:(c=this.properties.dailyConfig)!==null&&c!==void 0&&c.proxyUrl?encodeURIComponent((p=this.properties.dailyConfig)===null||p===void 0?void 0:p.proxyUrl):void 0}),m=h.url.match(/\?/)?"&":"?";return h.url+m+Object.keys(Xt).filter(function(y){return Xt[y].queryString&&h[y]!==void 0}
31).map(function(y){return"".concat(Xt[y].queryString,"=").concat(h[y])}).join("&")}},{key:"needsLoad",value:function(){return[ac,oc,It,Rt].includes(this._callState)}},{key:"sendMessageToCallMachine",value:function(c,p){if(this._destroyed&&(this._logUseAfterDestroy(),this.strictMode))throw new Error("Use after destroy");this._messageChannel.sendMessageToCallMachine(c,p,this.callClientId,this._iframe)}},{key:"forwardPackagedMessageToCallMachine",value:function(c){this._messageChannel.forwardPackagedMessageToCallMachine(c,this._iframe,this.callClientId)}},{key:"addListenerForPackagedMessagesFromCallMachine",value:function(c){return this._messageChannel.addListenerForPackagedMessagesFromCallMachine(c,this.callClientId)}},{key:"removeListenerForPackagedMessagesFromCallMachine",value:function(c){this._messageChannel.removeListenerForPackagedMessagesFromCallMachine(c)}},{key:"handleMessageFromCallMachine",value:function(c){switch(c.action){case dv:this.sendMessageToCallMachine(W({action:hv},this.properties));break;case"call-machine-initialized":this._callMachineInitialized=!0;var p={action:mr,level:"log",code:1011,stats:{event:"bundle load",time:this._bundleLoadTime==="no-op"?0:this._bundleLoadTime,preLoaded:this._bundleLoadTime==="no-op",url:Rr(this.properties.dailyConfig)}};this.sendMessageToCallMachine(p),this._delayDuplicateInstanceLog&&this._logDuplicateInstanceAttempt();break;case uc:this._loadedCallback&&(this._loadedCallback(),this._loadedCallback=null),this.emitDailyJSEvent(c);break;case yv:var h,m=W({},c);delete m.internal,this._maxAppMessageSize=((h=c.internal)===null||h===void 0?void 0:h._maxAppMessageSize)||Ri,this._joinedCallback&&(this._joinedCallback(c.participants),this._joinedCallback=null),this.emitDailyJSEvent(m);break;case _v:case kv:if(this._callState===It)return;if(c.participant&&c.participant.session_id){var y=c.participant.local?"local":c.participant.session_id;if(this._callObjectMode){var N=this._callMachine().store;Mc(c.participant,N),Ac(c.participant,N),Tc(c.participant,this._participants[y],N)}try{this.maybeParticipantTracksStopped(this._participants[y],c.participant),this.maybeParticipantTracksStarted(this._participants[y],c.participant),this.maybeEventRecordingStopped(this._participants[y],c.participant),this.maybeEventRecordingStarted(this._participants[y],c.participant)}catch(ci){console.error("track events error",ci)}this.compareEqualForParticipantUpdateEvent(c.participant,this._participants[y])||(this._participants[y]=W({},c.participant),this.toggleParticipantAudioBasedOnNativeAudioFocus(),this.emitDailyJSEvent(c))}break;case Sv:if(c.participant&&c.participant.session_id){var P=this._participants[c.participant.session_id];P&&this.maybeParticipantTracksStopped(P,null),delete this._participants[c.participant.session_id],this.emitDailyJSEvent(c)}break;case xv:Je(this._participantCounts,c.participantCounts)||(this._participantCounts=c.participantCounts,this.emitDailyJSEvent(c));break;case Ev:var R={access:c.access}
vendor: 4,553 bytes, line 31
31;c.awaitingAccess&&(R.awaitingAccess=c.awaitingAccess),Je(this._accessState,R)||(this._accessState=R,this.emitDailyJSEvent(c));break;case Cv:if(c.meetingSession){this._meetingSessionSummary=c.meetingSession,this.emitDailyJSEvent(c);var B=W(W({},c),{},{action:"meeting-session-updated"});this.emitDailyJSEvent(B)}break;case mc:var V;this._iframe&&!c.preserveIframe&&(this._iframe.src=""),this._updateCallState(Rt),this.resetMeetingDependentVars(),this._loadedCallback&&(this._loadedCallback(c.errorMsg),this._loadedCallback=null),c.preserveIframe;var U=eo(c,jb);U!=null&&(V=U.error)!==null&&V!==void 0&&V.details&&(U.error.details=JSON.parse(U.error.details)),this._maybeSendToSentry(c),this._joinedCallback&&(this._joinedCallback(null,U),this._joinedCallback=null),this.emitDailyJSEvent(U);break;case wv:this._callState!==Rt&&this._updateCallState(It),this.resetMeetingDependentVars(),this._resolveLeave&&(this._resolveLeave(),this._resolveLeave=null),this.emitDailyJSEvent(c);break;case"selected-devices-updated":c.devices&&this.emitDailyJSEvent(c);break;case Yv:var ye=c.state,ge=c.threshold,$e=c.quality,xe=ye.state,pe=ye.reasons;xe===this._network.networkState&&Je(pe,this._network.networkStateReasons)&&ge===this._network.threshold&&$e===this._network.quality||(this._network.networkState=xe,this._network.networkStateReasons=pe,this._network.quality=$e,this._network.threshold=ge,c.networkState=xe,pe.length&&(c.networkStateReasons=pe),delete c.state,this.emitDailyJSEvent(c));break;case Qv:c&&c.cpuLoadState&&this.emitDailyJSEvent(c);break;case Zv:c&&c.faceCounts!==void 0&&this.emitDailyJSEvent(c);break;case Hv:var Ee=c.activeSpeaker;this._activeSpeaker.peerId!==Ee.peerId&&(this._activeSpeaker.peerId=Ee.peerId,this.emitDailyJSEvent({action:c.action,activeSpeaker:this._activeSpeaker}));break;case"show-local-video-changed":if(this._callObjectMode)return;var Z=c.show;this._showLocalVideo=Z,this.emitDailyJSEvent({action:c.action,show:Z});break;case Kv:var te=c.enabled;this._activeSpeakerMode!==te&&(this._activeSpeakerMode=te,this.emitDailyJSEvent({action:c.action,enabled:this._activeSpeakerMode}));break;case Av:case Tv:case Nv:this._waitingParticipants=c.allWaitingParticipants,this.emitDailyJSEvent({action:c.action,participant:c.participant});break;case sb:Je(this._receiveSettings,c.receiveSettings)||(this._receiveSettings=c.receiveSettings,this.emitDailyJSEvent({action:c.action,receiveSettings:c.receiveSettings}));break;case fc:this._maybeUpdateInputSettings(c.inputSettings);break;case"send-settings-updated":Je(this._sendSettings,c.sendSettings)||(this._sendSettings=c.sendSettings,this._preloadCache.sendSettings=null,this.emitDailyJSEvent({action:c.action,sendSettings:c.sendSettings}));break;case"local-audio-level":this._localAudioLevel=c.audioLevel,this._preloadCache.localAudioLevelObserver=null,this.emitDailyJSEvent(c);break;case"remote-participants-audio-level":this._remoteParticipantsAudioLevel=c.participantsAudioLevel,this._preloadCache.remoteParticipantsAudioLevelObserver=null,this.emitDailyJSEvent(c);break;case Vv:var se=c.session_id;this._rmpPlayerState[se]=c.playerState,this.emitDailyJSEvent(c);break;case Wv:delete this._rmpPlayerState[c.session_id],this.emitDailyJSEvent(c);break;case zv:var Ae=c.session_id,nt=this._rmpPlayerState[Ae];nt&&this.compareEqualForRMPUpdateEvent(nt,c.remoteMediaPlayerState)||(this._rmpPlayerState[Ae]=c.remoteMediaPlayerState,this.emitDailyJSEvent(c));break;case"custom-button-click":case"sidebar-view-changed":case"pip-started":case"pip-stopped":this.emitDailyJSEvent(c);break;case Mv:var St=this._meetingSessionState.topology!==(c.meetingSessionState&&c.meetingSessionState.topology);this._meetingSessionState=qi(c.meetingSessionState,this._callObjectMode),(this._callObjectMode||St)&&this.emitDailyJSEvent(c);break;case qv:this._isScreenSharing=!0,this.emitDailyJSEvent(c);break;case Jv:case Gv:this._isScreenSharing=!1,this.emitDailyJSEvent(c);break;case dc:case hc:case Lv:case Dv:case Fv:case jv:case Iv:case Rv:case gv:case vv:case $v:case Uv:case"test-completed":case Xv:case Bv:case eb:case tb:case nb:case rb:case pc:case ib:case"dialin-ready":case"dialin-connected":case"dialin-error":case"dialin-stopped":case"dialin-warning":case"dialout-connected":case"dtmf-event":case"dialout-answered":case"dialout-error":case"dialout-stopped":case"dialout-warning":this.emitDailyJSEvent(c);break;case"request-fullscreen":this.requestFullscreen();break;case"request-exit-fullscreen":this.exitFullscreen()}}},{key:"maybeEventRecordingStopped",value:function(c,p){var h="record";
31c&&(p.local||p[h]!==!1||c[h]===p[h]||this.emitDailyJSEvent({action:hc}))}},{key:"maybeEventRecordingStarted",value:function(c,p){var h="record";c&&(p.local||p[h]!==!0||c[h]===p[h]||this.emitDailyJSEvent({action:dc}))}},{key:"_trackStatePlayable",value:function(c){return!(!c||c.state!==av)}},{key:"_trackChanged",value:function(c,p){return c?.id!==p?.id}},{key:"maybeEventTrackStopped",value:function(c,p,h){var m,y,N=(m=p?.tracks[c])!==null&&m!==void 0?m:null,P=(y=h?.tracks[c])!==null&&y!==void 0?y:null,R=N?.track;if(R){var B=this._trackStatePlayable(N),V=this._trackStatePlayable(P),U=this._trackChanged(R,P?.track);B&&(V&&!U||this.emitDailyJSEvent({action:Pv,track:R,participant:h??p,type:c}))}}},{key:"maybeEventTrackStarted",value:function(c,p,h){var m,y,N=(m=p?.tracks[c])!==null&&m!==void 0?m:null,P=(y=h?.tracks[c])!==null&&y!==void 0?y:null,R=P?.track;if(R){var B=this._trackStatePlayable(N),V=this._trackStatePlayable(P),U=this._trackChanged(N?.track,R);V&&(B&&!U||this.emitDailyJSEvent({action:Ov,track:R,participant:h,type:c}))}}},{key:"maybeParticipantTracksStopped",value:function(c,p){if(c)for(var h in c.tracks)this.maybeEventTrackStopped(h,c,p)}},{key:"maybeParticipantTracksStarted",value:function(c,p){if(p)for(var h in p.tracks)this.maybeEventTrackStarted(h,c,p)}},{key:"compareEqualForRMPUpdateEvent",value:function(c,p){var h,m;return c.state===p.state&&((h=c.settings)===null||h===void 0?void 0:h.volume)===((m=p.settings)===null||m===void 0?void 0:m.volume)}},{key:"emitDailyJSEvent",value:function(c){try{c.callClientId=this.callClientId,this.emit(c.action,c)}catch(p){console.log("could not emit",c,p)}}},{key:"compareEqualForParticipantUpdateEvent",value:function(c,p){return!!Je(c,p)&&(!c.videoTrack||!p.videoTrack||c.videoTrack.id===p.videoTrack.id&&c.videoTrack.muted===p.videoTrack.muted&&c.videoTrack.enabled===p.videoTrack.enabled)&&(!c.audioTrack||!p.audioTrack||c.audioTrack.id===p.audioTrack.id&&c.audioTrack.muted===p.audioTrack.muted&&c.audioTrack.enabled===p.audioTrack.enabled)}},{key:"nativeUtils",value:function(){return ce()?typeof DailyNativeUtils>"u"?(console.warn("in React Native, DailyNativeUtils is expected to be available"),null):DailyNativeUtils:null}},{key:"updateIsPreparingToJoin",value:function(c){this._updateCallState(this._callState,c)}},{key:"_updateCallState",value:function(c){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._isPreparingToJoin;if(c!==this._callState||p!==this._isPreparingToJoin){var h=this._callState,m=this._isPreparingToJoin;this._callState=c,this._isPreparingToJoin=p;var y=this._callState===en;this.updateShowAndroidOngoingMeetingNotification(y);var N=Ar(h,m),P=Ar(this._callState,this._isPreparingToJoin);N!==P&&(this.updateKeepDeviceAwake(P),this.updateDeviceAudioMode(P),this.updateNoOpRecordingEnsuringBackgroun
vendor: 1,530 bytes, line 31
31dContinuity(P))}}},{key:"resetMeetingDependentVars",value:function(){this._participants={},this._participantCounts=$c,this._waitingParticipants={},this._activeSpeaker={},this._activeSpeakerMode=!1,this._didPreAuth=!1,this._accessState={access:Ii},this._finalSummaryOfPrevSession=this._meetingSessionSummary,this._meetingSessionSummary={},this._meetingSessionState=qi(Bc,this._callObjectMode),this._isScreenSharing=!1,this._receiveSettings={},this._inputSettings=void 0,this._sendSettings={},this._localAudioLevel=0,this._isLocalAudioLevelObserverRunning=!1,this._remoteParticipantsAudioLevel={},this._isRemoteParticipantsAudioLevelObserverRunning=!1,this._maxAppMessageSize=Ri,this._callMachineInitialized=!1,this._bundleLoadTime=void 0,this._preloadCache}},{key:"updateKeepDeviceAwake",value:function(c){ce()&&this.nativeUtils().setKeepDeviceAwake(c,this.callClientId)}},{key:"updateDeviceAudioMode",value:function(c){if(ce()&&!this.disableReactNativeAutoDeviceManagement("audio")){var p=c?this._nativeInCallAudioMode:"idle";this.nativeUtils().setAudioMode(p)}}},{key:"updateShowAndroidOngoingMeetingNotification",value:function(c){if(ce()&&this.nativeUtils().setShowOngoingMeetingNotification){var p,h,m,y;if(this.properties.reactNativeConfig&&this.properties.reactNativeConfig.androidInCallNotification){var N=this.properties.reactNativeConfig.androidInCallNotification;p=N.title,h=N.subtitle,m=N.iconName,y=N.disableForCustomOverride}y&&(c=!1),this.nativeUtils().setShowOngoingMeetingNotification(c,p,h,m,this.callClientId)}}}
31,{key:"updateNoOpRecordingEnsuringBackgroundContinuity",value:function(c){ce()&&this.nativeUtils().enableNoOpRecordingEnsuringBackgroundContinuity&&this.nativeUtils().enableNoOpRecordingEnsuringBackgroundContinuity(c)}},{key:"toggleParticipantAudioBasedOnNativeAudioFocus",value:function(){var c;if(ce()){var p=(c=this._callMachine())===null||c===void 0||(c=c.store)===null||c===void 0?void 0:c.getState();for(var h in p?.streams){var m=p.streams[h];m&&m.pendingTrack&&m.pendingTrack.kind==="audio"&&(m.pendingTrack.enabled=this._hasNativeAudioFocus)}}}},{key:"disableReactNativeAutoDeviceManagement",value:function(c){return this.properties.reactNativeConfig&&this.properties.reactNativeConfig.disableAutoDeviceManagement&&this.properties.reactNativeConfig.disableAutoDeviceManagement[c]}},{key:"absoluteUrl",value:function(c){if(c!==void 0){var p=document.createElement("a");return p.href=c,p.href}}},{key:"sayHello",value:function(){var c="hello, world.";return console.log(c),c}},{key:"_logUseAfterDestroy",value:function(){var c=Object.values(Yt)[0];if(this.needsLoad())if(c&&!c.needsLoad()){var p={action:mr,level:"error",code:this.strictMode?9995:9997};c.sendMessageToCallMachine(p)}else this.strictMode||console.error("You are are attempting to use a call instance that was previously destroyed, which is unsupported. Please remove `strictMode: false` from your constructor properties to enable strict mode to track down and fix this unsupported usage.");else{var h={action:mr,level:"error",code:this.strictMode?9995:9997};this._messageChannel.sendMessageToCallMachine(h,null,this.callClientId,this._iframe)}}},{key:"_logDuplicateInstanceAttempt",value:function(){for(var c=0,p=Object.values(Yt);c<p.length;c++){var h=p[c];h._callMachineInitialized?(h.sendMessageToCallMachine({action:mr,level:"warn",code:this.allowMultipleCallInstances?9993:9992}),h._delayDuplicateInstanceLog=!1):h._delayDuplicateInstanceLog=!0}}},{key:"_maybeSendToSentry",value:function(c){var p,h,m,y,N;if(!((p=c.error)!==null&&p!==void 0&&p.type&&(![uv,lv,lc].includes(c.error.type)||c.error.type===lc&&c.error.msg.includes("deleted")))){var P=(h=this.properties)!==null&&h!==void 0&&h.url?new URL(this.properties.url):void 0,R="production";P&&P.host.includes(".staging.daily")&&(R="staging");var B,V,U,ye,ge,$e=(function(Ae){const nt=[Cg(),xg(),Qg(),Yg(),rv(),sv(),Ng(),iv()];return Ae.autoSessionTracking!==!1&&nt.push(nv()),nt})({}).filter(function(Ae){return!["BrowserApiErrors","Breadcrumbs","GlobalHandlers"].includes(Ae.name)}),xe=new Fg({dsn:"https://[email protected]/168844",transport:zg,stackParser:Kg,integrations:$e,environment:R}),pe=new Jt;if(pe.setClient(xe),xe.init(),!((m=this._participants)===null||m===void 0||(m=m.local)===null||m===void 0)&&m.session_id&&pe.setExtra("sessionId",this._participants.local.session_id),this.properties){var Ee=W({},this.properties);Ee.userName=Ee.userName?"[Filtered]":void 0,Ee.userData=Ee.userData?"[Filtered]":void 0,Ee.token=Ee.token?"[Filtered]":void 0,pe.setExtra("properties",Ee)}if(P){var Z=P.searchParams.get("domain");if(!Z){var te=P.host.match(/(.*?)\./);Z=te&&te[1]||""}Z&&pe.setTag("domain",Z)}c.error&&(pe.setTag("fatalErrorType",c.error.type),pe.setExtra("errorDetails",c.error.details),!((B=c.error.details)===null||B===void 0)&&B.uri&&pe.setTag("serverAddress",c.error.details.uri),!((V=c.error.details)===null||V===void 0)&&V.workerGroup&&pe.setTag("workerGroup",c.error.details.workerGroup),!((U=c.error.details)===null||U===void 0)&&U.geoGroup&&pe.setTag("geoGroup",c.error.details.geoGroup),!((ye=c.error.details)===null||ye===void 0)&&ye.on&&pe.setTag("connectionAttempt",c.error.details.on),(ge=c.error.details)!==null&&ge!==void 0&&ge.bundleUrl&&(pe.setTag("bundleUrl",c.error.details.bundleUrl),pe.setTag("bundleError",c.error.details.sourceError.type))),pe.setTags({callMode:this._callObjectMode?ce()?"reactNative":(y=this.properties)!==null&&y!==void 0&&(y=y.dailyConfig)!==null&&y!==void 0&&(y=y.callMode)!==null&&y!==void 0&&y.includes("prebuilt")?this.properties.dailyConfig.callMode:"custom":"prebuilt-frame",version:n.version()});var se=((N=c.error)===null||N===void 0?void 0:N.msg)||c.errorMsg;pe.captureException(new Error(se))}}},{key:"_callMachine",value:function(){var c;return(c=window._daily)===null||c===void 0||(c=c.instances)===null||c===void 0||(c=c[this.callClientId])===null||c===void 0?void 0:c.callMachine}},{key:"_maybeUpdateInputSettings",value:function(c){if(!Je(this._inputSettings,c)){var p=this._getInputSettings();this._inputSettings=c;var h=this._getInputSettings();Je(p,h)||this.emitDailyJSEvent({action:fc,inputSettings:h})}}}],[{key:"supportedBrowser",value:function(){if(ce())return{supported:!0,mobile:!0,name:"React Native",version:null,supportsScreenShare:!0,supportsSfu:!0,supportsVideoProcessing:!1,supportsAudioProcessing:!1};var c=Jm.getParser(at());return{supported:!!Bi(),mobile:c.getPlatformType()==="mobile",name:c.getBrowserName(),version:c.getBrowserVersion(),supportsFullscreen:!!wc(),supportsScreenShare:!!cb(),supportsSfu:!!Bi(),supportsVideoProcessing:Ku(),supportsAudioProcessing:Yu()}}},{key:"version",value:function(){return"0.90.0"}},{key:"createCallObject",value:function(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return c.layout="none",new n(null,c)}},{key:"wrap",value:function(c){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(oe(),!c||!c.contentWindow||typeof c.src!="string")throw new Error("DailyIframe::Wrap needs an iframe-like first argument");return p.layout||(p.customLayout?p.layout="custom-v1":p.layout="browser"),new n(c,p)}},{key:"createFrame",value:function(c,p){var h,m;oe(),c&&p?(h=c,m=p):c&&c.append?(h=c,m={}):(h=document.body,m=c||{});var y=m.iframeStyle;y||(y=h===document.body?{position:"fixed",border:"1px solid black",backgroundColor:"white",width:"375px",height:"450px",right:"1em",bottom:"1em"}:{border:0,width:"100%",height:"100%"});var N=document.createElement("iframe");window.navigator&&window.navigator.userAgent.match(/Chrome\/61\./)?N.allow="microphone, camera":N.allow="microphone; camera; autoplay; display-capture; screen-wake-lock; compute-pressure;",N.style.visibility="hidden",h.appendChild(N),N.style.visibility=null,Object.keys(y).forEac
31h(function(P){return N.style[P]=y[P]}),m.layout||(m.customLayout?m.layout="custom-v1":m.layout="browser");try{return new n(N,m)}catch(P){throw h.removeChild(N),P}}},{key:"createTransparentFrame",value:function(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};oe();var p=document.createElement("iframe");return p.allow="microphone; camera; autoplay",p.style.cssText=`
32      position: fixed;
33      top: 0;
34      left: 0;
35      width: 100%;
36      height: 100%;
37      border: 0;
38      pointer-events: none;
39    `,document.body.appendChild(p),c.layout||(c.layout="custom-v1"),n.wrap(p,c)}},{key:"getCallInstance",value:function(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;return c?Yt[c]:Object.values(Yt)[0]}}]);var e,t,r,i,s,a,o,l,u,f,g,_,k,b,v,E,C,O,j,S,x,T,I,F,$,z,fe,me,je,_e,Te,Ie,Re,ke,ie,Se,Ne,Be})();function qc(n){if(n.extension){if(typeof n.extension!="string")throw new Error("Error starting dial out: extension must be a string");if(n.extension.length>20)throw new Error("Error starting dial out: extension length must be less than or equal to 20")}if(n.waitBeforeExtensionDialSec){if(typeof n.waitBeforeExtensionDialSec!="number")throw new Error("Error starting dial out: waitBeforeExtensionDialSec must be a number");if(n.waitBeforeExtensionDialSec>60)throw new Error("Error starting dial out: waitBeforeExtensionDialSec must be less than or equal to 60");if(!n.extension)throw new Error("Error starting dial out: waitBeforeExtensionDialSec requires a phoneNumber and extension")}}function vn(n,e){var t={};for(var r in n)if(n[r]instanceof MediaStreamTrack)console.warn("MediaStreamTrack found in props or cache.",r),t[r]=Nt;else if(r==="dailyConfig"){if(n[r].modifyLocalSdpHook){var i=window._daily.instances[e].customCallbacks||{};i.modifyLocalSdpHook=n[r].modifyLocalSdpHook,window._daily.instances[e].customCallbacks=i,delete n[r].modifyLocalSdpHook}if(n[r].modifyRemoteSdpHook){var s=window._daily.instances[e].customCallbacks||{};s.modifyRemoteSdpHook=n[r].modifyRemoteSdpHook,window._daily.instances[e].customCallbacks=s,delete n[r].modifyRemoteSdpHook}t[r]=n[r]}else t[r]=n[r];return t}function ve(n){var e=arguments.length>2?arguments[2]:void 0;if(n!==en){var t="".concat(arguments.length>1&&arguments[1]!==void 0?arguments[1]:"This daily-js method"," only supported after join.");throw e&&(t+=" ".concat(e)),console.error(t),new Error(t)}}function Ar(n,e){return[ys,en].includes(n)||e}function zi(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"This daily-js method",r=arguments.length>3?arguments[3]:void 0;if(Ar(n,e)){var i="".concat(t," not supported after joining a meeting.");throw r&&(i+=" ".concat(r)),console.error(i),new Error(i)}}function yr(n){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"This daily-js method",t=arguments.length>2?arguments[2]:void 0;if(!n){var r="".concat(e,arguments.length>3&&arguments[3]!==void 0&&arguments[3]?" requires preAuth() or startCamera() to initialize call state.":" requires preAuth(), startCamera(), or join() to initialize call state.");throw t&&(r+=" ".concat(t)),console.error(r),new Error(r)}}function Wi(n){if(n){var e="A pre-call quality test is in progress. Please try ".concat(arguments.length>1&&arguments[1]!==void 0?arguments[1]:"This daily-js method"," again once testing has completed. Use stopTestCallQuality() to end it early.");throw console.error(e),new Error(e)}}function lt(n){if(!n){var e="".concat(arguments.length>1&&arguments[1]!==void 0?arguments[1]:"This daily-js method"," is only supported on custom callObject instances");throw console.error(e),new Error(e)}}function Qe(n){if(n){var e="".concat(arguments.length>1&&arguments[1]!==void 0?arguments[1]:"This daily-js method"," is only supported as part of Daily's Prebuilt");throw console.error(e),new Error(e)}}function oe(){if(ce())throw new Error("This daily-js method is not currently supported in React Native")}function Bn(){if(!ce())throw new Error("This daily-js method is only supported in React Native")}function ud(n){if(n===void 0)return!0;var e;if(typeof n=="string")e=n;else try{e=JSON.stringify(n),Je(JSON.parse(e),n)||console.warn("The userData provided will be modified when serialized.")}catch(t){throw Error("userData must be serializable to JSON: ".concat(t))}if(e.length>4096)throw Error("userData is too large (".concat(e.length," characters). Maximum size suppported is ").concat(4096,"."));return!0}
39function dd(n,e){for(var t=e.allowAllParticipantsKey,r=function(g){var _=["local"];return t||_.push("*"),g&&!_.includes(g)},i=function(g){return!!(g.layer===void 0||Number.isInteger(g.layer)&&g.layer>=0||g.layer==="inherit")},s=function(g){return!!g&&!(g.video&&!i(g.video))&&!(g.screenVideo&&!i(g.screenVideo))},a=0,o=Object.entries(n);a<o.length;a++){var l=Pe(o[a],2),u=l[0],f=l[1];if(!r(u)||!s(f))return!1}return!0}function hd(n){if(le(n)!=="object")return!1;for(var e=0,t=Object.entries(n);e<t.length;e++){var r=Pe(t[e],2),i=r[0],s=r[1];switch(i){case"video":if(le(s)!=="object")return!1;for(var a=0,o=Object.entries(s);a<o.length;a++){var l=Pe(o[a],2),u=l[0],f=l[1];switch(u){case"processor":if(!Lb(f))return!1;break;case"settings":if(!Jc(f))return!1;break;default:return!1}}break;case"audio":if(le(s)!=="object")return!1;for(var g=0,_=Object.entries(s);g<_.length;g++){var k=Pe(_[g],2),b=k[0],v=k[1];switch(b){case"processor":if(!Rb(v))return!1;break;case"settings":if(!Jc(v))return!1;break;default:return!1}}break;default:return!1}}return!0}function fd(n,e,t){var r,i=[];n.video&&n.video.processor&&(Ku((r=e?.useLegacyVideoProcessor)!==null&&r!==void 0&&r)||(n.video.settings?delete n.video.processor:delete n.video,i.push("video"))),n.audio&&n.audio.processor&&(Yu()||(n.audio.settings?delete n.audio.processor:delete n.audio,i.push("audio"))),i.length>0&&console.error("Ignoring settings for browser- or platform-unsupported input processor(s): ".concat(i.join(", "))),n.audio&&n.audio.settings&&(n.audio.settings.customTrack?(t.audioTrack=n.audio.settings.customTrack,n.audio.settings={customTrack:Nt}):delete t.audioTrack),n.video&&n.video.settings&&(n.video.settings.customTrack?(t.videoTrack=n.video.settings.customTrack,n.video.settings={customTrack:Nt}):delete t.videoTrack)}function Rb(n){if(ce())return console.warn("Video processing is not yet supported in React Native"),!1;var e=["type"];return!!n&&le(n)==="object"&&(Object.keys(n).filter(function(t){return!e.includes(t)}).forEach(function(t){console.warn("invalid key inputSettings -> audio -> processor : ".concat(t)),delete n[t]}),!!(function(t){return typeof t!="string"?!1:Object.values(Gu).includes(t)?!0:(console.error("inputSettings audio processor type invalid"),!1)})(n.type))}function Lb(n){if(ce())return console.warn("Video processing is not yet supported in React Native"),!1;var e=["type","config"];return!n||le(n)!=="object"||!(function(t){return typeof t!="string"?!1:Object.values(Mr).includes(t)?!0:(console.error("inputSettings video processor type invalid"),!1)})(n.type)||n.config&&(le(n.config)!=="object"||!(function(t,r){var i=Object.keys(r);if(i.length===0)return!0;var s="invalid object in inputSettings -> video -> processor -> config";switch(t){case Mr.BGBLUR:return i.length>1||i[0]!=="strength"?(console.error(s),!1):!(typeof r.strength!="number"||r.strength<=0||r.strength>1||isNaN(r.strength))||(console.error("".concat(s,"; expected: {0 < strength <= 1}, got: ").concat(r.strength)),!1);case Mr.BGIMAGE:return!(r.source!==void 0&&!(function(a){if(a.source==="default")return a.type="default",!0;if(a.source instanceof ArrayBuffer)return!0;if(Lr(a.source))return a.type="url",!!(function(u){var f=new URL(u),g=f.pathname;if(f.protocol==="data:")try{var _=g.substring(g.indexOf(":")+1,g.indexOf(";")).split("/")[1];return Fi.includes(_)}catch(b){return console.error("failed to deduce blob content type",b),!1}var k=g.split(".").at(-1).toLowerCase().trim();return Fi.includes(k)})(a.source)||(console.error("invalid image type; supported types: [".concat(Fi.join(", "),"]")),!1);return o=a.source,l=Number(o),isNaN(l)||!Number.isInteger(l)||l<=0||l>10?(console.error("invalid image selection; must be an int, > 0, <= ".concat(10)),!1):(a.type="daily-preselect",!0);var o,l})(r));default:return!0}})(n.type,n.config))?!1:(Object.keys(n).filter(function(t){return!e.includes(t)}).forEach(function(t){console.warn("invalid key inputSettings -> video -> processor : ".concat(t)),delete n[t]}),!0)}function Jc(n){return le(n)==="object"&&(!n.customTrack||n.customTrack instanceof MediaStreamTrack)}function Ms(){var n=Object.values(Mr).join(" | "),e=Object.values(Gu).join(" | ");return"inputSettings must be of the form: { video?: { processor?: { type: [ ".concat(n," ], config?: {} } }, audio?: { processor: {type: [ ").concat(e," ] } } }")}function pd(n){var e=n.allowAllParticipantsKey;return"receiveSettings must be of the form { [<remote participant id> | ".concat(cv).concat(e?' | "'.concat("*",'"'):"","]: ")+'{ [video: [{ layer: [<non-negative integer> | "inherit"] } | "inherit"]], [screenVideo: [{ layer: [<non-negative integer> | "inherit"] } | "inherit"]] }}}'}function md(){return"customIntegrations should be an object of type ".concat(JSON.stringify(Cs),".")}function gd(n){if(n&&le(n)!=="object"||Array.isArray(n))return console.error("customTrayButtons should be an Object of the type ".concat(JSON.stringify(zr),".")),!1;if(n)for(var e=0,t=Object.entries(n);e<t.length;e++)for(var r=Pe(t[e],1)[0],i=0,s=Object.entries(n[r]);i<s.length;i++){var a=Pe(s[i],2),o=a[0],l=a[1],u=zr.id[o];if(!u)return console.error("customTrayButton does not support key ".concat(o)),!1;switch(o){case"iconPath":case"iconPathDarkMode":if(!Lr(l))return console.error("customTrayButton ".concat(o," should be a url.")),!1;break;case"visualState":if(!["default","sidebar-open","active"].includes(l))return console.error("customTrayButton ".concat(o," should be ").concat(u,". Got: ").concat(l)),!1;break;default:if(le(l)!==u)return console.error("customTrayButton ".concat(o," should be a ").concat(u,".")),!1}}return!0}function vd(n){if(!n||n&&le(n)!=="object"||Array.isArray(n))return console.error(md()),!1;for(var e=function(g){return"".concat(g," should be ").concat(Cs.id[g])},t=function(g,_){return console.error("customIntegration ".concat(g,": ").concat(_))},r=0,i=Object.entries(n);r<i.length;r++){var s=Pe(i[r],1)[0];if(!("label"in n[s]))return t(s,"label is required"),!1;if(!("location"in n[s]))return t(s,"location is required"),!1;if(!("src"in n[s])&&!("srcdoc"in n[s]))return t(s,"src or srcdoc is required"),!1;for(var a=0,o=Object.entries(n[s]);a<o.length;a++){var l=Pe(o[a],2),u=l[0],f=l[1];switch(u){case"allow":case"csp":case"name":case"referrerPolicy":case"sandbox":if(typeof f!="string")return t(s,e(u)),!1;break;case"iconURL":if(!Lr(f))return t(s,"".concat(u," should be a url")),!1;break;case"src":if("srcdoc"in n[s])return t(s,"cannot have both src and srcdoc"),!1;if(!Lr(f))return t(s,'src "'.concat(f,'" is not a valid URL')),!1;break;case"srcdoc":if("src"in n[s])return t(s,"cannot have both src and srcdoc"),!1;if(typeof f!="string")return t(s,e(u)),!1;break;case"location":if(!["main","sidebar"].includes(f))return t(s,e(u)),!1;break;case"controlledBy":if(f!=="*"&&f!=="owners"&&(!Array.isArray(f)||f.some(function(g){return typeof g!="string"})))return t(s,e(u)),!1;break;case"shared":if((!Array.isArray(f)||f.some(function(g){return typeof g!="string"}))&&f!=="owners"&&typeof f!="boolean")return t(s,e(u)),!1;break;default:if(!Cs.id[u])return console.error("customIntegration does not support key ".concat(u)),!1}}}return!0}function bd(n,e){if(e===void 0)return!1;switch(le(e)){case"string":return le(n)===e;case"object":if(le(n)!=="object")return!1;for(var t in n)if(!bd(n[t],e[t]))return!1;return!0;default:return!1}}function Gc(n,e){var t=n.sessionId,r=n.toEndPoint,i=n.callerId,s=n.useSipRefer;if(!t||!r)throw new Error("".concat(e,"() requires a sessionId and toEndPoint"));if(typeof t!="string"||typeof r!="string")throw new Error("Invalid paramater: sessionId and toEndPoint must be of type string");if(s&&!r.startsWith("sip:"))throw new Error('"toEndPoint" must be a "sip" address');
39if(!r.startsWith("sip:")&&!r.startsWith("+"))throw new Error("toEndPoint: ".concat(r,' must starts with either "sip:" or "+"'));if(i&&typeof i!="string")throw new Error("callerId must be of type string");if(i&&!r.startsWith("+"))throw new Error("callerId is only valid when transferring to a PSTN number")}function Hc(n){if(le(n)!=="object")throw new Error('RemoteMediaPlayerSettings: must be "object" type');if(n.state&&!Object.values(ws).includes(n.state))throw new Error("Invalid value for RemoteMediaPlayerSettings.state, valid values are: "+JSON.stringify(ws));if(n.volume){if(typeof n.volume!="number")throw new Error('RemoteMediaPlayerSettings.volume: must be "number" type');if(n.volume<0||n.volume>2)throw new Error("RemoteMediaPlayerSettings.volume: must be between 0.0 - 2.0")}}function Kc(n,e,t){return!(typeof n!="number"||n<e||n>t)}function qi(n,e){return n&&!e&&delete n.data,n}function yd(n){let e=typeof n;if(e=="object"){if(Array.isArray(n))return"array";if(n===null)return"null"}return e}function Db(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}let At="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ai=[];for(let n=0;n<At.length;n++)ai[At[n].charCodeAt(0)]=n;ai[45]=At.indexOf("+");ai[95]=At.indexOf("/");function Fb(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),r=0,i=0,s,a=0;for(let o=0;o<n.length;o++){if(s=ai[n.charCodeAt(o)],s===void 0)switch(n[o]){case"=":i=0;case`
40`:case"\r":case"	":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:a=s,i=1;break;case 1:t[r++]=a<<2|(s&48)>>4,a=s,i=2;break;case 2:t[r++]=(a&15)<<4|(s&60)>>2,a=s,i=3;break;case 3:t[r++]=(a&3)<<6|s,i=0;break}}if(i==1)throw Error("invalid base64 string.");return t.subarray(0,r)}function Bb(n){let e="",t=0,r,i=0;for(let s=0;s<n.length;s++)switch(r=n[s],t){case 0:e+=At[r>>2],i=(r&3)<<4,t=1;break;case 1:e+=At[i|r>>4],i=(r&15)<<2,t=2;break;case 2:e+=At[i|r>>6],e+=At[r&63],t=0;break}return t&&(e+=At[i],e+="=",t==1&&(e+="=")),e}var Xe;(function(n){n.symbol=Symbol.for("protobuf-ts/unknown"),n.onRead=(t,r,i,s,a)=>{(e(r)?r[n.symbol]:r[n.symbol]=[]).push({no:i,wireType:s,data:a})},n.onWrite=(t,r,i)=>{for(let{no:s,wireType:a,data:o}of n.list(r))i.tag(s,a).raw(o)},n.list=(t,r)=>{if(e(t)){let i=t[n.symbol];return r?i.filter(s=>s.no==r):i}return[]},n.last=(t,r)=>n.list(t,r).slice(-1)[0];const e=t=>t&&Array.isArray(t[n.symbol])})(Xe||(Xe={}));var ne;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(ne||(ne={}));function $b(){let n=0,e=0;for(let r=0;r<28;r+=7){let i=this.buf[this.pos++];if(n|=(i&127)<<r,(i&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let r=3;r<=31;r+=7){let i=this.buf[this.pos++];if(e|=(i&127)<<r,(i&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Ji(n,e,t){for(let s=0;s<28;s=s+7){const a=n>>>s,o=!(!(a>>>7)&&e==0),l=(o?a|128:a)&255;if(t.push(l),!o)return}const r=n>>>28&15|(e&7)<<4,i=e>>3!=0;if(t.push((i?r|128:r)&255),!!i){for(let s=3;s<31;s=s+7){const a=e>>>s,o=!!(a>>>7),l=(o?a|128:a)&255;if(t.push(l),!o)return}t.push(e>>>31&1)}}const Tr=65536*65536;function wd(n){let e=n[0]=="-";e&&(n=n.slice(1));const t=1e6;let r=0,i=0;function s(a,o){const l=Number(n.slice(a,o));i*=t,r=r*t+l,r>=Tr&&(i=i+(r/Tr|0),r=r%Tr)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),[e,r,i]}function As(n,e){if(e>>>0<=2097151)return""+(Tr*e+(n>>>0));let t=n&16777215,r=(n>>>24|e<<8)>>>0&16777215,i=e>>16&65535,s=t+r*6777216+i*6710656,a=r+i*8147497,o=i*2,l=1e7;s>=l&&(a+=Math.floor(s/l),s%=l),a>=l&&(o+=Math.floor(a/l),a%=l);function u(f,g){let _=f?String(f):"";return g?"0000000".slice(_.length)+_:_}return u(o,0)+u(a,o)+u(s,1)}function Yc(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function Ub(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}let be;function Vb(){const n=new DataView(new ArrayBuffer(8));be=globalThis.BigInt!==void 0&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:n}:void 0}Vb();function _d(n){if(!n)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const kd=/^-?[0-9]+$/,Wr=4294967296,wr=2147483648;class Sd{constructor(e,t){this.lo=e|0,this.hi=t|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*Wr+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class We extends Sd{static from(e){if(be)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=be.C(e);case"number":if(e===0)return this.ZERO;e=be.C(e);case"bigint":if(!e)return this.ZERO;if(e<be.UMIN)throw new Error("signed value for ulong");if(e>be.UMAX)throw new Error("ulong too large");return be.V.setBigUint64(0,e,!0),new We(be.V.getInt32(0,!0),be.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!kd.test(e))throw new Error("string is no integer");let[t,r,i]=wd(e);if(t)throw new Error("signed value for ulong");return new We(r,i);case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");if(e<0)throw new Error("signed value for ulong");return new We(e,e/Wr)}throw new Error("unknown value "+typeof e)}toString(){return be?this.toBigInt().toString():As(this.lo,this.hi)}toBigInt(){return _d(be),be.V.setInt32(0,this.lo,!0),be.V.setInt32(4,this.hi,!0),be.V.getBigUint64(0,!0)}}We.ZERO=new We(0,0);class Me extends Sd{static from(e){if(be)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=be.C(e);case"number":if(e===0)return this.ZERO;e=be.C(e);case"bigint":if(!e)return this.ZERO;if(e<be.MIN)throw new Error("signed long too small");
vendor: 26,800 bytes, line 40
40if(e>be.MAX)throw new Error("signed long too large");return be.V.setBigInt64(0,e,!0),new Me(be.V.getInt32(0,!0),be.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!kd.test(e))throw new Error("string is no integer");let[t,r,i]=wd(e);if(t){if(i>wr||i==wr&&r!=0)throw new Error("signed long too small")}else if(i>=wr)throw new Error("signed long too large");let s=new Me(r,i);return t?s.negate():s;case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new Me(e,e/Wr):new Me(-e,-e/Wr).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&wr)!==0}negate(){let e=~this.hi,t=this.lo;return t?t=~t+1:e+=1,new Me(t,e)}toString(){if(be)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+As(e.lo,e.hi)}return As(this.lo,this.hi)}toBigInt(){return _d(be),be.V.setInt32(0,this.lo,!0),be.V.setInt32(4,this.hi,!0),be.V.getBigInt64(0,!0)}}Me.ZERO=new Me(0,0);const Xc={readUnknownField:!0,readerFactory:n=>new Wb(n)};function zb(n){return n?Object.assign(Object.assign({},Xc),n):Xc}class Wb{constructor(e,t){this.varint64=$b,this.uint32=Ub,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),t=e>>>3,r=e&7;if(t<=0||r<0||r>5)throw new Error("illegal tag: field no "+t+" wire type "+r);return[t,r]}skip(e){let t=this.pos;switch(e){case ne.Varint:for(;this.buf[this.pos++]&128;);break;case ne.Bit64:this.pos+=4;case ne.Bit32:this.pos+=4;break;case ne.LengthDelimited:let r=this.uint32();this.pos+=r;break;case ne.StartGroup:let i;for(;(i=this.tag()[1])!==ne.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return new Me(...this.varint64())}uint64(){return new We(...this.varint64())}sint64(){let[e,t]=this.varint64(),r=-(e&1);return e=(e>>>1|(t&1)<<31)^r,t=t>>>1^r,new Me(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new We(this.sfixed32(),this.sfixed32())}sfixed64(){return new Me(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function de(n,e){if(!n)throw new Error(e)}const qb=34028234663852886e22,Jb=-34028234663852886e22,Gb=4294967295,Hb=2147483647,Kb=-2147483648;function Gn(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>Hb||n<Kb)throw new Error("invalid int 32: "+n)}function qr(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>Gb||n<0)throw new Error("invalid uint 32: "+n)}function na(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>qb||n<Jb))throw new Error("invalid float 32: "+n)}const Qc={writeUnknownFields:!0,writerFactory:()=>new Xb};function Yb(n){return n?Object.assign(Object.assign({},Qc),n):Qc}class Xb{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let t=new Uint8Array(e),r=0;for(let i=0;i<this.chunks.length;i++)t.set(this.chunks[i],r),r+=this.chunks[i].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(qr(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Gn(e),Yc(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){na(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){qr(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Gn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Gn(e),e=(e<<1^e>>31)>>>0,Yc(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),i=Me.from(e);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),i=We.from(e);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=Me.from(e);return Ji(t.lo,t.hi,this.buf),this}sint64(e){let t=Me.from(e),r=t.hi>>31,i=t.lo<<1^r,s=(t.hi<<1|t.lo>>>31)^r;return Ji(i,s,this.buf),this}uint64(e){let t=We.from(e);return Ji(t.lo,t.hi,this.buf),this}}const Zc={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},el={ignoreUnknownFields:!1};function Qb(n){return n?Object.assign(Object.assign({},el),n):el}function Zb(n){return n?Object.assign(Object.assign({},Zc),n):Zc}const xd=Symbol.for("protobuf-ts/message-type");function tl(n){let e=!1;const t=[];for(let r=0;r<n.length;r++){let i=n.charAt(r);i=="_"?e=!0:/\d/.test(i)?(t.push(i),e=!0):e?(t.push(i.toUpperCase()),e=!1):r==0?t.push(i.toLowerCase()):t.push(i)}return t.join("")}var L;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(L||(L={}));var _t;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING",n[n.NUMBER=2]="NUMBER"})(_t||(_t={}));var Jr;(function(n){n[n.NO=0]="NO",n[n.PACKED=1]="PACKED",n[n.UNPACKED=2]="UNPACKED"})(Jr||(Jr={}));function ey(n){var e,t,r,i;return n.localName=(e=n.localName)!==null&&e!==void 0?e:tl(n.name),n.jsonName=(t=n.jsonName)!==null&&t!==void 0?t:tl(n.name),n.repeat=(r=n.repeat)!==null&&r!==void 0?r:Jr.NO,n.opt=(i=n.opt)!==null&&i!==void 0?i:n.repeat||n.oneof?!1:n.kind=="message",n}function ty(n){if(typeof n!="object"||n===null||!n.hasOwnProperty("oneofKind"))return!1;switch(typeof n.oneofKind){case"string":return n[n.oneofKind]===void 0?!1:Object.keys(n).length==2;case"undefined":return Object.keys(n).length==1;default:return!1}}class ny{constructor(e){var t;this.fields=(t=e.fields)!==null&&t!==void 0?t:[]}prepare(){if(this.data)return;const e=[],t=[],r=[];for(let i of this.fields)if(i.oneof)r.includes(i.oneof)||(r.push(i.oneof),e.push(i.oneof),t.push(i.oneof));else switch(t.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&e.push(i.localName);break;case"message":i.repeat&&e.push(i.localName);break;case"map":e.push(i.localName);break}this.data={req:e,known:t,oneofs:Object.values(r)}}is(e,t,r=!1){if(t<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let i=Object.keys(e),s=this.data;if(i.length<s.req.length||s.req.some(a=>!i.includes(a))||!r&&i.some(a=>!s.known.includes(a)))return!1;if(t<1)return!0;for(const a of s.oneofs){const o=e[a];if(!ty(o))return!1;if(o.oneofKind===void 0)continue;const l=this.fields.find(u=>u.localName===o.oneofKind);if(!l||!this.field(o[o.oneofKind],l,r,t))return!1}for(const a of this.fields)if(a.oneof===void 0&&!this.field(e[a.localName],a,r,t))return!1;return!0}field(e,t,r,i){let s=t.repeat;switch(t.kind){case"scalar":return e===void 0?t.opt:s?this.scalars(e,t.T,i,t.L):this.scalar(e,t.T,t.L);case"enum":return e===void 0?t.opt:s?this.scalars(e,L.INT32,i):this.scalar(e,L.INT32);case"message":return e===void 0?!0:s?this.messages(e,t.T(),r,i):this.message(e,t.T(),r,i);case"map":if(typeof e!="object"||e===null)return!1;if(i<2)return!0;if(!this.mapKeys(e,t.K,i))return!1;switch(t.V.kind){case"scalar":return this.scalars(Object.values(e),t.V.T,i,t.V.L);case"enum":return this.scalars(Object.values(e),L.INT32,i);case"message":return this.messages(Object.values(e),t.V.T(),r,i)}break}return!0}message(e,t,r,i){return r?t.isAssignable(e,i):t.is(e,i)}messages(e,t,r,i){if(!Array.isArray(e))return!1;if(i<2)return!0;if(r){for(let s=0;s<e.length&&s<i;s++)if(!t.isAssignable(e[s],i-1))return!1}else for(let s=0;s<e.length&&s<i;s++)if(!t.is(e[s],i-1))return!1;return!0}scalar(e,t,r){let i=typeof e;switch(t){case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:switch(r){case _t.BIGINT:return i=="bigint";case _t.NUMBER:return i=="number"&&!isNaN(e);default:return i=="string"}case L.BOOL:return i=="boolean";case L.STRING:return i=="string";case L.BYTES:return e instanceof Uint8Array;case L.DOUBLE:case L.FLOAT:return i=="number"&&!isNaN(e);default:return i=="number"&&Number.isInteger(e)}}scalars(e,t,r,i){if(!Array.isArray(e))return!1;if(r<2)return!0;if(Array.isArray(e)){for(let s=0;s<e.length&&s<r;s++)if(!this.scalar(e[s],t,i))return!1}return!0}mapKeys(e,t,r){let i=Object.keys(e);switch(t){case L.INT32:case L.FIXED32:case L.SFIXED32:case L.SINT32:case L.UINT32:return this.scalars(i.slice(0,r).map(s=>parseInt(s)),t,r);case L.BOOL:return this.scalars(i.slice(0,r).map(s=>s=="true"?!0:s=="false"?!1:s),t,r);default:return this.scalars(i,t,r,_t.STRING)}}}function pt(n,e){switch(e){case _t.BIGINT:return n.toBigInt();case _t.NUMBER:return n.toNumber();default:return n.toString()}}class ry{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};const t=(e=this.info.fields)!==null&&e!==void 0?e:[];for(const r of t)this.fMap[r.name]=r,this.fMap[r.jsonName]=r,this.fMap[r.localName]=r}}assert(e,t,r){if(!e){let i=yd(r);throw(i=="number"||i=="boolean")&&(i=r.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${t}`)}}read(e,t,r){this.prepare();const i=[];for(const[s,a]of Object.entries(e)){const o=this.fMap[s];if(!o){if(!r.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${s}`);continue}const l=o.localName;let u;if(o.oneof){if(a===null&&(o.kind!=="enum"||o.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(o.oneof))throw new Error(`Multiple members of the oneof group "${o.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(o.oneof),u=t[o.oneof]={oneofKind:l}}else u=t;if(o.kind=="map"){if(a===null)continue;this.assert(Db(a),o.name,a);const f=u[l];for(const[g,_]of Object.entries(a)){this.assert(_!==null,o.name+" map value",null);let k;switch(o.V.kind){case"message":k=o.V.T().internalJsonRead(_,r);break;case"enum":if(k=this.enum(o.V.T(),_,o.name,r.ignoreUnknownFields),k===!1)continue;break;case"scalar":k=this.scalar(_,o.V.T,o.V.L,o.name);break}this.assert(k!==void 0,o.name+" map value",_);let b=g;o.K==L.BOOL&&(b=b=="true"?!0:b=="false"?!1:b),b=this.scalar(b,o.K,_t.STRING,o.name).toString(),f[b]=k}}else if(o.repeat){if(a===null)continue;this.assert(Array.isArray(a),o.name,a);const f=u[l];for(const g of a){this.assert(g!==null,o.name,null);let _;switch(o.kind){case"message":_=o.T().internalJsonRead(g,r);break;case"enum":if(_=this.enum(o.T(),g,o.name,r.ignoreUnknownFields),_===!1)continue;break;case"scalar":_=this.scalar(g,o.T,o.L,o.name);break}this.assert(_!==void 0,o.name,a),f.push(_)}}else switch(o.kind){case"message":if(a===null&&o.T().typeName!="google.protobuf.Value"){this.assert(o.oneof===void 0,o.name+" (oneof member)",null);continue}u[l]=o.T().internalJsonRead(a,r,u[l]);break;case"enum":if(a===null)continue;let f=this.enum(o.T(),a,o.name,r.ignoreUnknownFields);if(f===!1)continue;u[l]=f;break;case"scalar":if(a===null)continue;u[l]=this.scalar(a,o.T,o.L,o.name);break}}}enum(e,t,r,i){if(e[0]=="google.protobuf.NullValue"&&de(t===null||t==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${r}, enum ${e[0]} only accepts null.`),t===null)return 0;switch(typeof t){case"number":return de(Number.isInteger(t),`Unable to parse field ${this.info.typeName}#${r}, enum can only be integral number, got ${t}.`),t;case"string":let s=t;e[2]&&t.substring(0,e[2].length)===e[2]&&(s=t.substring(e[2].length));let a=e[1][s];return typeof a>"u"&&i?!1:(de(typeof a=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${e[0]} has no value for "${t}".`),a)}de(!1,`Unable to parse field ${this.info.typeName}#${r}, cannot parse enum value from ${typeof t}".`)}scalar(e,t,r,i){let s;try{switch(t){case L.DOUBLE:case L.FLOAT:if(e===null)return 0;if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""){s="empty string";break}if(typeof e=="string"&&e.trim().length!==e.length){s="extra whitespace";break}if(typeof e!="string"&&typeof e!="number")break;let a=Number(e);if(Number.isNaN(a)){s="not a number";break}if(!Number.isFinite(a)){s="too large or small";break}return t==L.FLOAT&&na(a),a;case L.INT32:case L.FIXED32:case L.SFIXED32:case L.SINT32:case L.UINT32:if(e===null)return 0;let o;if(typeof e=="number"?o=e:e===""?s="empty string":typeof e=="string"&&(e.trim().length!==e.length?s="extra whitespace":o=Number(e)),o===void 0)break;return t==L.UINT32?qr(o):Gn(o),o;case L.INT64:case L.SFIXED64:case L.SINT64:if(e===null)return pt(Me.ZERO,r);if(typeof e!="number"&&typeof e!="string")break;return pt(Me.from(e),r);case L.FIXED64:case L.UINT64:if(e===null)return pt(We.ZERO,r);if(typeof e!="number"&&typeof e!="string")break;return pt(We.from(e),r);case L.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case L.STRING:if(e===null)return"";if(typeof e!="string"){s="extra whitespace";break}try{encodeURIComponent(e)}catch(l){l="invalid UTF8";break}return e;case L.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return Fb(e)}}catch(a){s=a.message}this.assert(!1,i+(s?" - "+s:""),e)}}class iy{constructor(e){var t;this.fields=(t=e.fields)!==null&&t!==void 0?t:[]}write(e,t){const r={},i=e;for(const s of this.fields){if(!s.oneof){let u=this.field(s,i[s.localName],t);u!==void 0&&(r[t.useProtoFieldName?s.name:s.jsonName]=u);continue}const a=i[s.oneof];if(a.oneofKind!==s.localName)continue;const o=s.kind=="scalar"||s.kind=="enum"?Object.assign(Object.assign({},t),{emitDefaultValues:!0}):t;let l=this.field(s,a[s.localName],o);de(l!==void 0),r[t.useProtoFieldName?s.name:s.jsonName]=l}return r}field(e,t,r){let i;if(e.kind=="map"){de(typeof t=="object"&&t!==null);const s={};switch(e.V.kind){case"scalar":for(const[l,u]of Object.entries(t)){const f=this.scalar(e.V.T,u,e.name,!1,!0);de(f!==void 0),s[l.toString()]=f}break;case"message":const a=e.V.T();for(const[l,u]of Object.entries(t)){const f=this.message(a,u,e.name,r);de(f!==void 0),s[l.toString()]=f}break;case"enum":const o=e.V.T();for(const[l,u]of Object.entries(t)){de(u===void 0||typeof u=="number");const f=this.enum(o,u,e.name,!1,!0,r.enumAsInteger);de(f!==void 0),s[l.toString()]=f}break}(r.emitDefaultValues||Object.keys(s).length>0)&&(i=s)}else if(e.repeat){de(Array.isArray(t));const s=[];switch(e.kind){case"scalar":for(let l=0;l<t.length;l++){const u=this.scalar(e.T,t[l],e.name,e.opt,!0);de(u!==void 0),s.push(u)}break;case"enum":const a=e.T();for(let l=0;l<t.length;l++){de(t[l]===void 0||typeof t[l]=="number");const u=this.enum(a,t[l],e.name,e.opt,!0,r.enumAsInteger);de(u!==void 0),s.push(u)}break;case"message":const o=e.T();for(let l=0;l<t.length;l++){const u=this.message(o,t[l],e.name,r);de(u!==void 0),s.push(u)}break}(r.emitDefaultValues||s.length>0||r.emitDefaultValues)&&(i=s)}else switch(e.kind){case"scalar":i=this.scalar(e.T,t,e.name,e.opt,r.emitDefaultValues);break;case"enum":i=this.enum(e.T(),t,e.name,e.opt,r.emitDefaultValues,r.enumAsInteger);break;case"message":i=this.message(e.T(),t,e.name,r);break}return i}enum(e,t,r,i,s,a){if(e[0]=="google.protobuf.NullValue")return!s&&!i?void 0:null;if(t===void 0){de(i);return}if(!(t===0&&!s&&!i))return de(typeof t=="number"),de(Number.isInteger(t)),a||!e[1].hasOwnProperty(t)?t:e[2]?e[2]+e[1][t]:e[1][t]}message(e,t,r,i){return t===void 0?i.emitDefaultValues?null:void 0:e.internalJsonWrite(t,i)}scalar(e,t,r,i,s){if(t===void 0){de(i);return}const a=s||i;switch(e){case L.INT32:case L.SFIXED32:case L.SINT32:return t===0?a?0:void 0:(Gn(t),t);case L.FIXED32:case L.UINT32:return t===0?a?0:void 0:(qr(t),t);case L.FLOAT:na(t);case L.DOUBLE:return t===0?a?0:void 0:(de(typeof t=="number"),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t);case L.STRING:return t===""?a?"":void 0:(de(typeof t=="string"),t);case L.BOOL:return t===!1?a?!1:void 0:(de(typeof t=="boolean"),t);case L.UINT64:case L.FIXED64:de(typeof t=="number"||typeof t=="string"||typeof t=="bigint");let o=We.from(t);return o.isZero()&&!a?void 0:o.toString();case L.INT64:case L.SFIXED64:case L.SINT64:de(typeof t=="number"||typeof t=="string"||typeof t=="bigint");let l=Me.from(t);return l.isZero()&&!a?void 0:l.toString();case L.BYTES:return de(t instanceof Uint8Array),t.byteLength?Bb(t):a?"":void 0}}}function Ts(n,e=_t.STRING){switch(n){case L.BOOL:return!1;case L.UINT64:case L.FIXED64:return pt(We.ZERO,e);case L.INT64:case L.SFIXED64:case L.SINT64:return pt(Me.ZERO,e);case L.DOUBLE:case L.FLOAT:return 0;case L.BYTES:return new Uint8Array(0);case L.STRING:return"";default:return 0}}class sy{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const t=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(t.map(r=>[r.no,r]))}}read(e,t,r,i){this.prepare();const s=i===void 0?e.len:e.pos+i;for(;e.pos<s;){const[a,o]=e.tag(),l=this.fieldNoToField.get(a);if(!l){let _=r.readUnknownField;if(_=="throw")throw new Error(`Unknown field ${a} (wire type ${o}) for ${this.info.typeName}`);let k=e.skip(o);_!==!1&&(_===!0?Xe.onRead:_)(this.info.typeName,t,a,o,k);continue}let u=t,f=l.repeat,g=l.localName;switch(l.oneof&&(u=u[l.oneof],u.oneofKind!==g&&(u=t[l.oneof]={oneofKind:g})),l.kind){case"scalar":case"enum":let _=l.kind=="enum"?L.INT32:l.T,k=l.kind=="scalar"?l.L:void 0;if(f){let E=u[g];if(o==ne.LengthDelimited&&_!=L.STRING&&_!=L.BYTES){let C=e.uint32()+e.pos;for(;e.pos<C;)E.push(this.scalar(e,_,k))}else E.push(this.scalar(e,_,k))}else u[g]=this.scalar(e,_,k);break;case"message":if(f){let E=u[g],C=l.T().internalBinaryRead(e,e.uint32(),r);E.push(C)}else u[g]=l.T().internalBinaryRead(e,e.uint32(),r,u[g]);break;case"map":let[b,v]=this.mapEntry(l,e,r);u[g][b]=v;break}}}mapEntry(e,t,r){let i=t.uint32(),s=t.pos+i,a,o;for(;t.pos<s;){let[l,u]=t.tag();switch(l){case 1:e.K==L.BOOL?a=t.bool().toString():a=this.scalar(t,e.K,_t.STRING);break;case 2:switch(e.V.kind){case"scalar":o=this.scalar(t,e.V.T,e.V.L);break;case"enum":o=t.int32();break;case"message":o=e.V.T().internalBinaryRead(t,t.uint32(),r);break}break;default:throw new Error(`Unknown field ${l} (wire type ${u}) in map entry for ${this.info.typeName}#${e.name}`)}}if(a===void 0){let l=Ts(e.K);a=e.K==L.BOOL?l.toString():l}if(o===void 0)switch(e.V.kind){case"scalar":o=Ts(e.V.T,e.V.L);break;case"enum":o=0;break;case"message":o=e.V.T().create();break}return[a,o]}scalar(e,t,r){switch(t){case L.INT32:return e.int32();case L.STRING:return e.string();case L.BOOL:return e.bool();case L.DOUBLE:return e.double();case L.FLOAT:return e.float();case L.INT64:return pt(e.int64(),r);case L.UINT64:return pt(e.uint64(),r);case L.FIXED64:return pt(e.fixed64(),r);case L.FIXED32:return e.fixed32();case L.BYTES:return e.bytes();case L.UINT32:return e.uint32();case L.SFIXED32:return e.sfixed32();case L.SFIXED64:return pt(e.sfixed64(),r);case L.SINT32:return e.sint32();case L.SINT64:return pt(e.sint64(),r)}}}class ay{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((t,r)=>t.no-r.no)}}write(e,t,r){this.prepare();for(const s of this.fields){let a,o,l=s.repeat,u=s.localName;if(s.oneof){const f=e[s.oneof];if(f.oneofKind!==u)continue;a=f[u],o=!0}else a=e[u],o=!1;switch(s.kind){case"scalar":case"enum":let f=s.kind=="enum"?L.INT32:s.T;if(l)if(de(Array.isArray(a)),l==Jr.PACKED)this.packed(t,f,s.no,a);else for(const g of a)this.scalar(t,f,s.no,g,!0);else a===void 0?de(s.opt):this.scalar(t,f,s.no,a,o||s.opt);break;case"message":if(l){de(Array.isArray(a));for(const g of a)this.message(t,r,s.T(),s.no,g)}else this.message(t,r,s.T(),s.no,a);break;case"map":de(typeof a=="object"&&a!==null);for(const[g,_]of Object.entries(a))this.mapEntry(t,r,s,g,_);break}}let i=r.writeUnknownFields;i!==!1&&(i===!0?Xe.onWrite:i)(this.info.typeName,e,t)}mapEntry(e,t,r,i,s){e.tag(r.no,ne.LengthDelimited),e.fork();let a=i;switch(r.K){case L.INT32:case L.FIXED32:case L.UINT32:case L.SFIXED32:case L.SINT32:a=Number.parseInt(i);break;case L.BOOL:de(i=="true"||i=="false"),a=i=="true";break}switch(this.scalar(e,r.K,1,a,!0),r.V.kind){case"scalar":this.scalar(e,r.V.T,2,s,!0);break;case"enum":this.scalar(e,L.INT32,2,s,!0);break;case"message":this.message(e,t,r.V.T(),2,s);break}e.join()}message(e,t,r,i,s){s!==void 0&&(r.internalBinaryWrite(s,e.tag(i,ne.LengthDelimited).fork(),t),e.join())}scalar(e,t,r,i,s){let[a,o,l]=this.scalarInfo(t,i);(!l||s)&&(e.tag(r,a),e[o](i))}packed(e,t,r,i){if(!i.length)return;de(t!==L.BYTES&&t!==L.STRING),e.tag(r,ne.LengthDelimited),e.fork();let[,s]=this.scalarInfo(t);for(let a=0;a<i.length;a++)e[s](i[a]);e.join()}scalarInfo(e,t){let r=ne.Varint,i,s=t===void 0,a=t===0;switch(e){case L.INT32:i="int32";break;case L.STRING:a=s||!t.length,r=ne.LengthDelimited,i="string";break;case L.BOOL:a=t===!1,i="bool";break;case L.UINT32:i="uint32";break;case L.DOUBLE:r=ne.Bit64,i="double";break;case L.FLOAT:r=ne.Bit32,i="float";break;case L.INT64:a=s||Me.from(t).isZero(),i="int64";break;case L.UINT64:a=s||We.from(t).isZero(),i="uint64";break;case L.FIXED64:a=s||We.from(t).isZero(),r=ne.Bit64,i="fixed64";break;case L.BYTES:a=s||!t.byteLength,r=ne.LengthDelimited,i="bytes";break;case L.FIXED32:r=ne.Bit32,i="fixed32";break;case L.SFIXED32:r=ne.Bit32,i="sfixed32";break;case L.SFIXED64:a=s||Me.from(t).isZero(),r=ne.Bit64,i="sfixed64";break;case L.SINT32:i="sint32";break;case L.SINT64:a=s||Me.from(t).isZero(),i="sint64";break}return[r,i,s||a]}}function oy(n){const e=n.messagePrototype?Object.create(n.messagePrototype):Object.defineProperty({},xd,{value:n});for(let t of n.fields){let r=t.localName;if(!t.opt)if(t.oneof)e[t.oneof]={oneofKind:void 0};else if(t.repeat)e[r]=[];else switch(t.kind){case"scalar":e[r]=Ts(t.T,t.L);break;case"enum":e[r]=0;break;case"map":e[r]={};break}}return e}function zt(n,e,t){let r,i=t,s;for(let a of n.fields){let o=a.localName;if(a.oneof){const l=i[a.oneof];if(l?.oneofKind==null)continue;if(r=l[o],s=e[a.oneof],s.oneofKind=l.oneofKind,r==null){delete s[o];continue}}else if(r=i[o],s=e,r==null)continue;switch(a.repeat&&(s[o].length=r.length),a.kind){case"scalar":case"enum":if(a.repeat)for(let u=0;u<r.length;u++)s[o][u]=r[u];else s[o]=r;break;case"message":let l=a.T();if(a.repeat)for(let u=0;u<r.length;u++)s[o][u]=l.create(r[u]);else s[o]===void 0?s[o]=l.create(r):l.mergePartial(s[o],r);break;case"map":switch(a.V.kind){case"scalar":case"enum":Object.assign(s[o],r);break;case"message":let u=a.V.T();for(let f of Object.keys(r))s[o][f]=u.create(r[f]);break}break}}}function cy(n,e,t){if(e===t)return!0;if(!e||!t)return!1;for(let r of n.fields){let i=r.localName,s=r.oneof?e[r.oneof][i]:e[i],a=r.oneof?t[r.oneof][i]:t[i];switch(r.kind){case"enum":case"scalar":let o=r.kind=="enum"?L.INT32:r.T;if(!(r.repeat?nl(o,s,a):Ed(o,s,a)))return!1;break;case"map":if(!(r.V.kind=="message"?rl(r.V.T(),_r(s),_r(a)):nl(r.V.kind=="enum"?L.INT32:r.V.T,_r(s),_r(a))))return!1;break;case"message":let l=r.T();if(!(r.repeat?rl(l,s,a):l.equals(s,a)))return!1;break}}return!0}const _r=Object.values;function Ed(n,e,t){if(e===t)return!0;if(n!==L.BYTES)return!1;let r=e,i=t;if(r.length!==i.length)return!1;for(let s=0;s<r.length;s++)if(r[s]!=i[s])return!1;return!0}function nl(n,e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ed(n,e[r],t[r]))return!1;return!0}function rl(n,e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!n.equals(e[r],t[r]))return!1;return!0}const Cd=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),ly=Cd[xd]={};class er{constructor(e,t,r){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(ey),this.options=r??{},ly.value=this,this.messagePrototype=Object.create(null,Cd),this.refTypeCheck=new ny(this),this.refJsonReader=new ry(this),this.refJsonWriter=new iy(this),this.refBinReader=new sy(this),this.refBinWriter=new ay(this)}create(e){let t=oy(this);return e!==void 0&&zt(this,t,e),t}clone(e){let t=this.create();return zt(this,t,e),t}equals(e,t){return cy(this,e,t)}is(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!1)}isAssignable(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!0)}mergePartial(e,t){zt(this,e,t)}fromBinary(e,t){let r=zb(t);return this.internalBinaryRead(r.readerFactory(e),e.byteLength,r)}fromJson(e,t){return this.internalJsonRead(e,Qb(t))}fromJsonString(e,t){let r=JSON.parse(e);return this.fromJson(r,t)}toJson(e,t){return this.internalJsonWrite(e,Zb(t))}toJsonString(e,t){var r;let i=this.toJson(e,t);return JSON.stringify(i,null,(r=t?.prettySpaces)!==null&&r!==void 0?r:0)}toBinary(e,t){let r=Yb(t);return this.internalBinaryWrite(e,r.writerFactory(),r).finish()}internalJsonRead(e,t,r){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let i=r??this.create();return this.refJsonReader.read(e,i,t),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${yd(e)}.`)}internalJsonWrite(e,t){return this.refJsonWriter.write(e,t)}internalBinaryWrite(e,t,r){return this.refBinWriter.write(e,t,r),t}internalBinaryRead(e,t,r,i){let s=i??this.create();return this.refBinReader.read(e,s,r,t),s}}var Md=Object.defineProperty,Ke=(n,e)=>Md(n,"name",{value:e,configurable:!0}),ra=(n,e)=>{for(var t in e)Md(n,t,{get:e[t],enumerable:!0})},uy={};ra(uy,{decode:()=>oa,decodeBuffer:()=>Td,decodeSample:()=>sa,encode:()=>aa,encodeBuffer:()=>Ad,encodeSample:()=>ia});var dy=[1,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
406,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7];function ia(n){let e;n=n==-32768?-32767:n;let t=~n>>8&128;if(t||(n=n*-1),n>32635&&(n=32635),n>=256){let r=dy[n>>8&127],i=n>>r+3&15;e=r<<4|i}else e=n>>4;return e^(t^85)}Ke(ia,"encodeSample");function sa(n){let e=0;n^=85,n&128&&(n&=-129,e=-1);let t=((n&240)>>4)+4,r=0;return t!=4?r=1<<t|(n&15)<<t-4|1<<t-5:r=n<<1|1,r=e===0?r:-r,r*8*-1}Ke(sa,"decodeSample");function aa(n){let e=new Uint8Array(n.length);for(let t=0;t<n.length;t++)e[t]=ia(n[t]);return e}Ke(aa,"encode");function oa(n){let e=new Int16Array(n.length);for(let t=0;t<n.length;t++)e[t]=sa(n[t]);return e}Ke(oa,"decode");function Ad(n){const e=Math.floor(n.length/2),t=new Int16Array(e);for(let r=0;r<e;r++)t[r]=n.readInt16LE(r*2);return Buffer.from(aa(t).buffer)}Ke(Ad,"encodeBuffer");function Td(n){const e=oa(new Uint8Array(n));return Buffer.from(e.buffer)}Ke(Td,"decodeBuffer");var hy={};ra(hy,{decode:()=>da,decodeBuffer:()=>Od,decodeSample:()=>la,encode:()=>ua,encodeBuffer:()=>Nd,encodeSample:()=>ca});var fy=132,il=32635,py=[0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],my=[0,132,396,924,1980,4092,8316,16764];function ca(n){const e=n<0?128:0;n=Math.abs(n),n+=fy,n>il&&(n=il);const t=py[n>>7&255],r=n>>t+3&15;return~(e|t<<4|r)&255}Ke(ca,"encodeSample");function la(n){n=~n&255;const e=n&128?-1:1,t=n>>4&7,r=n&15,i=my[t]+(r<<t+3);return e*i}Ke(la,"decodeSample");function ua(n){const e=new Uint8Array(n.length);for(let t=0;t<n.length;t++)e[t]=ca(n[t]);return e}Ke(ua,"encode");function da(n){const e=new Int16Array(n.length);for(let t=0;t<n.length;t++)e[t]=la(n[t]);return e}Ke(da,"decode");function Nd(n){const e=Math.floor(n.length/2),t=new Int16Array(e);for(let r=0;r<e;r++)t[r]=n.readInt16LE(r*2);return Buffer.from(ua(t).buffer)}Ke(Nd,"encodeBuffer");function Od(n){const e=da(new Uint8Array(n));return Buffer.from(e.buffer)}Ke(Od,"decodeBuffer");var gy={};ra(gy,{calculateLoudness:()=>Pd,createWavHeader:()=>jd,resample:()=>vy});var Ns=[8,16,24,32,48];function Pd(n,e){if(!(n instanceof Buffer)||n.length===0)throw new Error("Invalid buffer, must be a non-empty Buffer.");if(!Ns.includes(e))throw new Error("Invalid bit depth, supported values are 8, 16, 24, 32, and 48.");if(e===48)throw new Error("48-bit audio is not yet implemented.");const t=Math.ceil(e/8);if(n.length%t!==0)throw new Error(`Invalid buffer length ${n.length}. Must be a multiple of ${t} bytes for ${e}-bit audio.`);const r=Math.pow(2,e-1)-1,i=n.length/t;let s=0;for(let o=0;o<i;o++){const l=o*t;let u;switch(e){case 8:u=n[l],u&128&&(u=u-256);break;case 16:u=n[l]|n[l+1]<<8,u&32768&&(u=u-65536);break;case 24:u=n[l]|n[l+1]<<8|n[l+2]<<16,u&8388608&&(u=u|-16777216);break;case 32:u=n[l]|n[l+1]<<8|n[l+2]<<16|n[l+3]<<24;break;default:throw new Error(`Unsupported bit depth: ${e}`)}const f=u/r;s+=f*f}const a=Math.sqrt(s/i);return a<=1e-10?-100:20*Math.log10(a)}Ke(Pd,"calculateLoudness");function jd(n,e,t,r){const i=[{value:"RIFF",type:"string"},{value:36+n,type:"uint32"},{value:"WAVE",type:"string"},{value:"fmt ",type:"string"},{value:16,type:"uint32"},{value:1,type:"uint16"},{value:t,type:"uint16"},{value:e,type:"uint32"},{value:e*t*r/8,type:"uint32"},{value:t*r/8,type:"uint16"},{value:r,type:"uint16"},{value:"data",type:"string"},{value:n,type:"uint32"}],s=Buffer.alloc(44);let a=0;return i.forEach(({value:o,type:l})=>{l==="string"?(s.write(o,a),a+=4):l==="uint32"?(s.writeUInt32LE(o,a),a+=4):l==="uint16"&&(s.writeUInt16LE(o,a),a+=2)}),s}Ke(jd,"createWavHeader");var vy=Ke((n,e,t,r)=>{if(e<=0||t<=0)throw new Error("Sample rates must be positive.");if(!Ns.includes(r))throw new Error(`Invalid bit depth. Allowed values are: ${Ns.join(", ")}`);const i=t/e,s=Math.round(n.length*i),a=new Array(s),o=(1<<r-1)-1,l=-1<<r-1;for(let u=0;u<s;u++){const f=u/i,g=Math.floor(f),_=Math.min(g+1,n.length-1),k=f-g,b=n[g]*(1-k)+n[_]*k,v=Math.round(b);a[u]=Math.max(l,Math.min(o,v))}return a},"resample");class ft{static floatTo16BitPCM(e){const t=new ArrayBuffer(e.length*2),r=new DataView(t);let i=0;for(let s=0;s<e.length;s++,i+=2){let a=Math.max(-1,Math.min(1,e[s]));r.setInt16(i,a<0?a*32768:a*32767,!0)}return t}
40static mergeBuffers(e,t){const r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e),0),r.set(new Uint8Array(t),e.byteLength),r.buffer}_packData(e,t){return[new Uint8Array([t,t>>8]),new Uint8Array([t,t>>8,t>>16,t>>24])][e]}pack(e,t){if(t?.bitsPerSample)if(t?.channels){if(!t?.data)throw new Error('Missing "data"')}else throw new Error('Missing "channels"');else throw new Error('Missing "bitsPerSample"');const{bitsPerSample:r,channels:i,data:s}=t,a=["RIFF",this._packData(1,52),"WAVE","fmt ",this._packData(1,16),this._packData(0,1),this._packData(0,i.length),this._packData(1,e),this._packData(1,e*i.length*r/8),this._packData(0,i.length*r/8),this._packData(0,r),"data",this._packData(1,i[0].length*i.length*r/8),s],o=new Blob(a,{type:"audio/mpeg"}),l=URL.createObjectURL(o);return{blob:o,url:l,channelCount:i.length,sampleRate:e,duration:s.byteLength/(i.length*e*2)}}}globalThis.WavPacker=ft;const sl=[4186.01,4434.92,4698.63,4978.03,5274.04,5587.65,5919.91,6271.93,6644.88,7040,7458.62,7902.13],by=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Wt=[],ha=[];for(let n=1;n<=8;n++)for(let e=0;e<sl.length;e++){const t=sl[e];Wt.push(t/Math.pow(2,8-n)),ha.push(by[e]+n)}const Gr=[32,2e3],al=Wt.filter((n,e)=>Wt[e]>Gr[0]&&Wt[e]<Gr[1]),yy=ha.filter((n,e)=>Wt[e]>Gr[0]&&Wt[e]<Gr[1]);class Rn{static getFrequencies(e,t,r,i="frequency",s=-100,a=-30){r||(r=new Float32Array(e.frequencyBinCount),e.getFloatFrequencyData(r));const o=t/2,l=1/r.length*o;let u,f,g;if(i==="music"||i==="voice"){const b=i==="voice"?al:Wt,v=Array(b.length).fill(s);for(let E=0;E<r.length;E++){const C=E*l,O=r[E];for(let j=b.length-1;j>=0;j--)if(C>b[j]){v[j]=Math.max(v[j],O);break}}u=v,f=i==="voice"?al:Wt,g=i==="voice"?yy:ha}else u=Array.from(r),f=u.map((b,v)=>l*v),g=f.map(b=>`${b.toFixed(2)} Hz`);const _=u.map(b=>Math.max(0,Math.min((b-s)/(a-s),1)));return{values:new Float32Array(_),frequencies:f,labels:g}}constructor(e,t=null){if(this.fftResults=[],t){const{length:r,sampleRate:i}=t,s=new OfflineAudioContext({length:r,sampleRate:i}),a=s.createBufferSource();a.buffer=t;const o=s.createAnalyser();o.fftSize=8192,o.smoothingTimeConstant=.1,a.connect(o);const l=1/60,u=r/i,f=g=>{const _=l*g;_<u&&s.suspend(_).then(()=>{const k=new Float32Array(o.frequencyBinCount);o.getFloatFrequencyData(k),this.fftResults.push(k),f(g+1)}),g===1?s.startRendering():s.resume()};a.start(0),f(1),this.audio=e,this.context=s,this.analyser=o,this.sampleRate=i,this.audioBuffer=t}else{const r=new AudioContext,i=r.createMediaElementSource(e),s=r.createAnalyser();s.fftSize=8192,s.smoothingTimeConstant=.1,i.connect(s),s.connect(r.destination),this.audio=e,this.context=r,this.analyser=s,this.sampleRate=this.context.sampleRate,this.audioBuffer=null}}getFrequencies(e="frequency",t=-100,r=-30){let i=null;if(this.audioBuffer&&this.fftResults.length){const s=this.audio.currentTime/this.audio.duration,a=Math.min(s*this.fftResults.length|0,this.fftResults.length-1);i=this.fftResults[a]}return Rn.getFrequencies(this.analyser,this.sampleRate,i,e,t,r)}async resumeIfSuspended(){return this.context.state==="suspended"&&await this.context.resume(),!0}}globalThis.AudioAnalysis=Rn;const wy=`
41class StreamProcessor extends AudioWorkletProcessor {
42  constructor() {
43    super();
44    this.hasStarted = false;
45    this.hasInterrupted = false;
46    this.outputBuffers = [];
47    this.bufferLength = 128;
48    this.write = { buffer: new Float32Array(this.bufferLength), trackId: null };
49    this.writeOffset = 0;
50    this.trackSampleOffsets = {};
51    this.port.onmessage = (event) => {
52      if (event.data) {
53        const payload = event.data;
54        if (payload.event === 'write') {
55          const int16Array = payload.buffer;
56          const float32Array = new Float32Array(int16Array.length);
57          for (let i = 0; i < int16Array.length; i++) {
58            float32Array[i] = int16Array[i] / 0x8000; // Convert Int16 to Float32
59          }
60          this.writeData(float32Array, payload.trackId);
61        } else if (
62          payload.event === 'offset' ||
63          payload.event === 'interrupt'
64        ) {
65          const requestId = payload.requestId;
66          const trackId = this.write.trackId;
67          const offset = this.trackSampleOffsets[trackId] || 0;
68          this.port.postMessage({
69            event: 'offset',
70            requestId,
71            trackId,
72            offset,
73          });
74          if (payload.event === 'interrupt') {
75            this.hasInterrupted = true;
76          }
77        } else {
78          throw new Error(\`Unhandled event "\${payload.event}"\`);
79        }
80      }
81    };
82  }
83
84  writeData(float32Array, trackId = null) {
85    let { buffer } = this.write;
86    let offset = this.writeOffset;
87    for (let i = 0; i < float32Array.length; i++) {
88      buffer[offset++] = float32Array[i];
89      if (offset >= buffer.length) {
90        this.outputBuffers.push(this.write);
91        this.write = { buffer: new Float32Array(this.bufferLength), trackId };
92        buffer = this.write.buffer;
93        offset = 0;
94      }
95    }
96    this.writeOffset = offset;
97    return true;
98  }
99
100  process(inputs, outputs, parameters) {
101    const output = outputs[0];
102    const outputChannelData = output[0];
103    const outputBuffers = this.outputBuffers;
104    if (this.hasInterrupted) {
105      this.port.postMessage({ event: 'stop' });
106      return false;
107    } else if (outputBuffers.length) {
108      this.hasStarted = true;
109      const { buffer, trackId } = outputBuffers.shift();
110      for (let i = 0; i < outputChannelData.length; i++) {
111        outputChannelData[i] = buffer[i] || 0;
112      }
113      if (trackId) {
114        this.trackSampleOffsets[trackId] =
115          this.trackSampleOffsets[trackId] || 0;
116        this.trackSampleOffsets[trackId] += buffer.length;
117      }
118      return true;
119    } else if (this.hasStarted) {
120      this.port.postMessage({ event: 'stop' });
121      return false;
122    } else {
123      return true;
124    }
125  }
126}
127
128registerProcessor('stream_processor', StreamProcessor);
129`,_y=new Blob([wy],{type:"application/javascript"}),ky=URL.createObjectURL(_y),Sy=ky;class fa{constructor({sampleRate:e=44100}={}){this.scriptSrc=Sy,this.sampleRate=e,this.context=null,this.stream=null,this.analyser=null,this.trackSampleOffsets={},this.interruptedTrackIds={}}async connect(){this.context=new AudioContext({sampleRate:this.sampleRate}),this._speakerID&&this.context.setSinkId(this._speakerID),this.context.state==="suspended"&&await this.context.resume();try{await this.context.audioWorklet.addModule(this.scriptSrc)}catch(t){throw console.error(t),new Error(`Could not add audioWorklet module: ${this.scriptSrc}`)}const e=this.context.createAnalyser();return e.fftSize=8192,e.smoothingTimeConstant=.1,this.analyser=e,!0}getFrequencies(e="frequency",t=-100,r=-30){if(!this.analyser)throw new Error("Not connected, please call .connect() first");return Rn.getFrequencies(this.analyser,this.sampleRate,null,e,t,r)}async updateSpeaker(e){const t=this._speakerID;if(this._speakerID=e,this.context)try{e==="default"?await this.context.setSinkId():await this.context.setSinkId(e)}catch(r){console.error(`Could not set sinkId to ${e}: ${r}`),this._speakerID=t}}_start(){const e=new AudioWorkletNode(this.context,"stream_processor");return e.connect(this.context.destination),e.port.onmessage=t=>{const{event:r}=t.data;if(r==="stop")e.disconnect(),this.stream=null;else if(r==="offset"){const{requestId:i,trackId:s,offset:a}=t.data,o=a/this.sampleRate;this.trackSampleOffsets[i]={trackId:s,offset:a,currentTime:o}}},this.analyser.disconnect(),e.connect(this.analyser),this.stream=e,!0}add16BitPCM(e,t="default"){if(typeof t!="string")throw new Error("trackId must be a string");if(this.interruptedTrackIds[t])return;this.stream||this._start();let r;if(e instanceof Int16Array)r=e;else if(e instanceof ArrayBuffer)r=new Int16Array(e);else throw new Error("argument must be Int16Array or ArrayBuffer");return this.stream.port.postMessage({event:"write",buffer:r,trackId:t}),r}async getTrackSampleOffset(e=!1){if(!this.stream)return null;const t=crypto.randomUUID();this.stream.port.postMessage({event:e?"interrupt":"offset",requestId:t});let r;for(;!r;)r=this.trackSampleOffsets[t],await new Promise(s=>setTimeout(()=>s(),1));const{trackId:i}=r;return e&&i&&(this.interruptedTrackIds[i]=!0),r}async interrupt(){return this.getTrackSampleOffset(!0)}}globalThis.WavStreamPlayer=fa;const xy=`
130class AudioProcessor extends AudioWorkletProcessor {
131
132  constructor() {
133    super();
134    this.port.onmessage = this.receive.bind(this);
135    this.initialize();
136  }
137
138  initialize() {
139    this.foundAudio = false;
140    this.recording = false;
141    this.chunks = [];
142  }
143
144  /**
145   * Concatenates sampled chunks into channels
146   * Format is chunk[Left[], Right[]]
147   */
148  readChannelData(chunks, channel = -1, maxChannels = 9) {
149    let channelLimit;
150    if (channel !== -1) {
151      if (chunks[0] && chunks[0].length - 1 < channel) {
152        throw new Error(
153          \`Channel \${channel} out of range: max \${chunks[0].length}\`
154        );
155      }
156      channelLimit = channel + 1;
157    } else {
158      channel = 0;
159      channelLimit = Math.min(chunks[0] ? chunks[0].length : 1, maxChannels);
160    }
161    const channels = [];
162    for (let n = channel; n < channelLimit; n++) {
163      const length = chunks.reduce((sum, chunk) => {
164        return sum + chunk[n].length;
165      }, 0);
166      const buffers = chunks.map((chunk) => chunk[n]);
167      const result = new Float32Array(length);
168      let offset = 0;
169      for (let i = 0; i < buffers.length; i++) {
170        result.set(buffers[i], offset);
171        offset += buffers[i].length;
172      }
173      channels[n] = result;
174    }
175    return channels;
176  }
177
178  /**
179   * Combines parallel audio data into correct format,
180   * channels[Left[], Right[]] to float32Array[LRLRLRLR...]
181   */
182  formatAudioData(channels) {
183    if (channels.length === 1) {
184      // Simple case is only one channel
185      const float32Array = channels[0].slice();
186      const meanValues = channels[0].slice();
187      return { float32Array, meanValues };
188    } else {
189      const float32Array = new Float32Array(
190        channels[0].length * channels.length
191      );
192      const meanValues = new Float32Array(channels[0].length);
193      for (let i = 0; i < channels[0].length; i++) {
194        const offset = i * channels.length;
195        let meanValue = 0;
196        for (let n = 0; n < channels.length; n++) {
197          float32Array[offset + n] = channels[n][i];
198          meanValue += channels[n][i];
199        }
200        meanValues[i] = meanValue / channels.length;
201      }
202      return { float32Array, meanValues };
203    }
204  }
205
206  /**
207   * Converts 32-bit float data to 16-bit integers
208   */
209  floatTo16BitPCM(float32Array) {
210    const buffer = new ArrayBuffer(float32Array.length * 2);
211    const view = new DataView(buffer);
212    let offset = 0;
213    for (let i = 0; i < float32Array.length; i++, offset += 2) {
214      let s = Math.max(-1, Math.min(1, float32Array[i]));
215      view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);
216    }
217    return buffer;
218  }
219
220  /**
221   * Retrieves the most recent amplitude values from the audio stream
222   * @param {number} channel
223   */
224  getValues(channel = -1) {
225    const channels = this.readChannelData(this.chunks, channel);
226    const { meanValues } = this.formatAudioData(channels);
227    return { meanValues, channels };
228  }
229
230  /**
231   * Exports chunks as an audio/wav file
232   */
233  export() {
234    const channels = this.readChannelData(this.chunks);
235    const { float32Array, meanValues } = this.formatAudioData(channels);
236    const audioData = this.floatTo16BitPCM(float32Array);
237    return {
238      meanValues: meanValues,
239      audio: {
240        bitsPerSample: 16,
241        channels: channels,
242        data: audioData,
243      },
244    };
245  }
246
247  receive(e) {
248    const { event, id } = e.data;
249    let receiptData = {};
250    switch (event) {
251      case 'start':
252        this.recording = true;
253        break;
254      case 'stop':
255        this.recording = false;
256        break;
257      case 'clear':
258        this.initialize();
259        break;
260      case 'export':
261        receiptData = this.export();
262        break;
263      case 'read':
264        receiptData = this.getValues();
265        break;
266      default:
267        break;
268    }
269    // Always send back receipt
270    this.port.postMessage({ event: 'receipt', id, data: receiptData });
271  }
272
273  sendChunk(chunk) {
274    const channels = this.readChannelData([chunk]);
275    const { float32Array, meanValues } = this.formatAudioData(channels);
276    const rawAudioData = this.floatTo16BitPCM(float32Array);
277    const monoAudioData = this.floatTo16BitPCM(meanValues);
278    this.port.postMessage({
279      event: 'chunk',
280      data: {
281        mono: monoAudioData,
282        raw: rawAudioData,
283      },
284    });
285  }
286
287  process(inputList, outputList, parameters) {
288    // Copy input to output (e.g. speakers)
289    // Note that this creates choppy sounds with Mac products
290    const sourceLimit = Math.min(inputList.length, outputList.length);
291    for (let inputNum = 0; inputNum < sourceLimit; inputNum++) {
292      const input = inputList[inputNum];
293      const output = outputList[inputNum];
294      const channelCount = Math.min(input.length, output.length);
295      for (let channelNum = 0; channelNum < channelCount; channelNum++) {
296        input[channelNum].forEach((sample, i) => {
297          output[channelNum][i] = sample;
298        });
299      }
300    }
301    const inputs = inputList[0];
302    // There's latency at the beginning of a stream before recording starts
303    // Make sure we actually receive audio data before we start storing chunks
304    let sliceIndex = 0;
305    if (!this.foundAudio) {
306      for (const channel of inputs) {
307        sliceIndex = 0; // reset for each channel
308        if (this.foundAudio) {
309          break;
310        }
311        if (channel) {
312          for (const value of channel) {
313            if (value !== 0) {
314              // find only one non-zero entry in any channel
315              this.foundAudio = true;
316              break;
317            } else {
318              sliceIndex++;
319            }
320          }
321        }
322      }
323    }
324    if (inputs && inputs[0] && this.foundAudio && this.recording) {
325      // We need to copy the TypedArray, because the \`process\`
326      // internals will reuse the same buffer to hold each input
327      const chunk = inputs.map((input) => input.slice(sliceIndex));
328      this.chunks.push(chunk);
329      this.sendChunk(chunk);
330    }
331    return true;
332  }
333}
334
335registerProcessor('audio_processor', AudioProcessor);
336`,Ey=new Blob([xy],{type:"application/javascript"}),Cy=URL.createObjectURL(Ey),Id=Cy;class Rd{constructor({sampleRate:e=44100,outputToSpeakers:t=!1,debug:r=!1}={}){this.scriptSrc=Id,this.sampleRate=e,this.outputToSpeakers=t,this.debug=!!r,this._deviceChangeCallback=null,this._deviceErrorCallback=null,this._devices=[],this.deviceSelection=null,this.stream=null,this.processor=null,this.source=null,this.node=null,this.recording=!1,this._lastEventId=0,this.eventReceipts={},this.eventTimeout=5e3,this._chunkProcessor=()=>{},this._chunkProcessorSize=void 0,this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)}}static async decode(e,t=44100,r=-1){const i=new AudioContext({sampleRate:t});let s,a;if(e instanceof Blob){if(r!==-1)throw new Error('Can not specify "fromSampleRate" when reading from Blob');a=e,s=await a.arrayBuffer()}else if(e instanceof ArrayBuffer){if(r!==-1)throw new Error('Can not specify "fromSampleRate" when reading from ArrayBuffer');s=e,a=new Blob([s],{type:"audio/wav"})}else{let f,g;if(e instanceof Int16Array){g=e,f=new Float32Array(e.length);for(let v=0;v<e.length;v++)f[v]=e[v]/32768}else if(e instanceof Float32Array)f=e;else if(e instanceof Array)f=new Float32Array(e);else throw new Error('"audioData" must be one of: Blob, Float32Arrray, Int16Array, ArrayBuffer, Array<number>');if(r===-1)throw new Error('Must specify "fromSampleRate" when reading from Float32Array, In16Array or Array');if(r<3e3)throw new Error('Minimum "fromSampleRate" is 3000 (3kHz)');g||(g=ft.floatTo16BitPCM(f));const _={bitsPerSample:16,channels:[f],data:g};a=new ft().pack(r,_).blob,s=await a.arrayBuffer()}const o=await i.decodeAudioData(s),l=o.getChannelData(0),u=URL.createObjectURL(a);return{blob:a,url:u,values:l,audioBuffer:o}}log(){return this.debug&&this.log(...arguments),!0}getSampleRate(){return this.sampleRate}getStatus(){return this.processor?this.recording?"recording":"paused":"ended"}
336async _event(e,t={},r=null){if(r=r||this.processor,!r)throw new Error("Can not send events without recording first");const i={event:e,id:this._lastEventId++,data:t};r.port.postMessage(i);const s=new Date().valueOf();for(;!this.eventReceipts[i.id];){if(new Date().valueOf()-s>this.eventTimeout)throw new Error(`Timeout waiting for "${e}" event`);await new Promise(o=>setTimeout(()=>o(!0),1))}const a=this.eventReceipts[i.id];return delete this.eventReceipts[i.id],a}listenForDeviceChange(e){if(e===null&&this._deviceChangeCallback)navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeCallback),this._deviceChangeCallback=null;else if(e!==null){let t=0,r=[];const i=a=>a.map(o=>o.deviceId).sort().join(","),s=async()=>{let a=++t;const o=await this.listDevices();a===t&&i(r)!==i(o)&&(r=o,e(o.slice()))};navigator.mediaDevices.addEventListener("devicechange",s),s(),this._deviceChangeCallback=s}return!0}listenForDeviceErrors(e){this._deviceErrorCallback=e}async requestPermission(){const e=await navigator.permissions.query({name:"microphone"});if(e.state==="denied")this._deviceErrorCallback&&this._deviceErrorCallback({devices:["mic"],type:"unknown",error:new Error("Microphone access denied")});else if(e.state==="prompt")try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(i=>i.stop())}catch(t){console.error("Error accessing microphone."),this._deviceErrorCallback&&this._deviceErrorCallback({devices:["mic"],type:"unknown",error:t})}return!0}async listDevices(){if(!navigator.mediaDevices||!("enumerateDevices"in navigator.mediaDevices))throw new Error("Could not request user devices");return await this.requestPermission(),(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="audioinput")}async begin(e){if(this.processor)throw new Error("Already connected: please call .end() to start a new session");if(!navigator.mediaDevices||!("getUserMedia"in navigator.mediaDevices))throw this._deviceErrorCallback&&this._deviceErrorCallback({devices:["mic","cam"],type:"undefined-mediadevices"}),new Error("Could not request user media");e=e??this.deviceSelection?.deviceId;try{const o={audio:!0};e&&(o.audio={deviceId:{exact:e}}),this.stream=await navigator.mediaDevices.getUserMedia(o)}catch(o){throw this._deviceErrorCallback&&this._deviceErrorCallback({devices:["mic"],type:"unknown",error:o}),new Error("Could not start media stream")}this.listDevices().then(o=>{e=this.stream.getAudioTracks()[0].getSettings().deviceId,console.log("find current device",o,e,this.stream.getAudioTracks()[0].getSettings()),this.deviceSelection=o.find(l=>l.deviceId===e),console.log("current device",this.deviceSelection)});const t=new AudioContext({sampleRate:this.sampleRate}),r=t.createMediaStreamSource(this.stream);try{await t.audioWorklet.addModule(this.scriptSrc)}catch(o){throw console.error(o),new Error(`Could not add audioWorklet module: ${this.scriptSrc}`)}const i=new AudioWorkletNode(t,"audio_processor");i.port.onmessage=o=>{const{event:l,id:u,data:f}=o.data;if(l==="receipt")this.eventReceipts[u]=f;else if(l==="chunk")if(this._chunkProcessorSize){const g=this._chunkProcessorBuffer;this._chunkProcessorBuffer={raw:ft.mergeBuffers(g.raw,f.raw),mono:ft.mergeBuffers(g.mono,f.mono)},this._chunkProcessorBuffer.mono.byteLength>=this._chunkProcessorSize&&(this._chunkProcessor(this._chunkProcessorBuffer),this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)})}else this._chunkProcessor(f)};const s=r.connect(i),a=t.createAnalyser();return a.fftSize=8192,a.smoothingTimeConstant=.1,s.connect(a),this.outputToSpeakers&&(console.warn(`Warning: Output to speakers may affect sound quality,
337especially due to system audio feedback preventative measures.
338use only for debugging`),a.connect(t.destination)),this.source=r,this.node=s,this.analyser=a,this.processor=i,console.log("begin completed"),!0}getFrequencies(e="frequency",t=-100,r=-30){if(!this.processor)throw new Error("Session ended: please call .begin() first");return Rn.getFrequencies(this.analyser,this.sampleRate,null,e,t,r)}async pause(){if(this.processor){if(!this.recording)throw new Error("Already paused: please call .record() first")}else throw new Error("Session ended: please call .begin() first");return this._chunkProcessorBuffer.raw.byteLength&&this._chunkProcessor(this._chunkProcessorBuffer),this.log("Pausing ..."),await this._event("stop"),this.recording=!1,!0}async record(e=()=>{},t=8192){if(this.processor){if(this.recording)throw new Error("Already recording: please call .pause() first");
338if(typeof e!="function")throw new Error("chunkProcessor must be a function")}else throw new Error("Session ended: please call .begin() first");return this._chunkProcessor=e,this._chunkProcessorSize=t,this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)},this.log("Recording ..."),await this._event("start"),this.recording=!0,!0}async clear(){if(!this.processor)throw new Error("Session ended: please call .begin() first");return await this._event("clear"),!0}async read(){if(!this.processor)throw new Error("Session ended: please call .begin() first");return this.log("Reading ..."),await this._event("read")}async save(e=!1){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(!e&&this.recording)throw new Error("Currently recording: please call .pause() first, or call .save(true) to force");this.log("Exporting ...");const t=await this._event("export");return new ft().pack(this.sampleRate,t.audio)}async end(){if(!this.processor)throw new Error("Session ended: please call .begin() first");const e=this.processor;this.log("Stopping ..."),await this._event("stop"),this.recording=!1,this.stream.getTracks().forEach(a=>a.stop()),this.log("Exporting ...");const r=await this._event("export",{},e);return this.processor.disconnect(),this.source.disconnect(),this.node.disconnect(),this.analyser.disconnect(),this.stream=null,this.processor=null,this.source=null,this.node=null,new ft().pack(this.sampleRate,r.audio)}async quit(){return this.listenForDeviceChange(null),this.deviceSelection=null,this.processor&&await this.end(),!0}}globalThis.WavRecorder=Rd;function ol(n,e,t){if(e===t)return n;const r=new Int16Array(n),i=e/t,s=Math.round(r.length/i),a=new ArrayBuffer(s*2),o=new Int16Array(a);for(let l=0;l<s;l++){const u=l*i,f=Math.floor(u),g=Math.min(f+1,r.length-1),_=u-f;o[l]=Math.round(r[f]*(1-_)+r[g]*_)}return a}class My{constructor({sampleRate:e=44100,outputToSpeakers:t=!1,debug:r=!1}={}){this.scriptSrc=Id,this.sampleRate=e,this.outputToSpeakers=t,this.debug=!!r,this.stream=null,this.processor=null,this.source=null,this.node=null,this.recording=!1,this._lastEventId=0,this.eventReceipts={},this.eventTimeout=5e3,this._chunkProcessor=()=>{},this._chunkProcessorSize=void 0,this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)}}log(){return this.debug&&this.log(...arguments),!0}getSampleRate(){return this.sampleRate}getStatus(){return this.processor?this.recording?"recording":"paused":"ended"}async _event(e,t={},r=null){if(r=r||this.processor,!r)throw new Error("Can not send events without recording first");const i={event:e,id:this._lastEventId++,data:t};r.port.postMessage(i);const s=new Date().valueOf();for(;!this.eventReceipts[i.id];){if(new Date().valueOf()-s>this.eventTimeout)throw new Error(`Timeout waiting for "${e}" event`);await new Promise(o=>setTimeout(()=>o(!0),1))}const a=this.eventReceipts[i.id];return delete this.eventReceipts[i.id],a}async begin(e){if(this.processor)throw new Error("Already connected: please call .end() to start a new session");if(!e||e.kind!=="audio")throw new Error("No audio track provided");this.stream=new MediaStream([e]);const t=navigator.userAgent.toLowerCase().includes("firefox");let r;t?r=new AudioContext:r=new AudioContext({sampleRate:this.sampleRate});const i=r.sampleRate,s=r.createMediaStreamSource(this.stream);try{await r.audioWorklet.addModule(this.scriptSrc)}catch(u){throw console.error(u),new Error(`Could not add audioWorklet module: ${this.scriptSrc}`)}const a=new AudioWorkletNode(r,"audio_processor");a.port.onmessage=u=>{const{event:f,id:g,data:_}=u.data;if(f==="receipt")this.eventReceipts[g]=_;else if(f==="chunk"){const k={raw:ol(_.raw,i,this.sampleRate),mono:ol(_.mono,i,this.sampleRate)};if(this._chunkProcessorSize){const b=this._chunkProcessorBuffer;this._chunkProcessorBuffer={raw:ft.mergeBuffers(b.raw,k.raw),mono:ft.mergeBuffers(b.mono,k.mono)},this._chunkProcessorBuffer.mono.byteLength>=this._chunkProcessorSize&&(this._chunkProcessor(this._chunkProcessorBuffer),this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)})}else this._chunkProcessor(k)}};const o=s.connect(a),l=r.createAnalyser();return l.fftSize=8192,l.smoothingTimeConstant=.1,o.connect(l),this.outputToSpeakers&&(console.warn(`Warning: Output to speakers may affect sound quality,
339especially due to system audio feedback preventative measures.
340use only for debugging`),l.connect(r.destination)),this.source=s,this.node=o,this.analyser=l,this.processor=a,!0}
340getFrequencies(e="frequency",t=-100,r=-30){if(!this.processor)throw new Error("Session ended: please call .begin() first");return Rn.getFrequencies(this.analyser,this.sampleRate,null,e,t,r)}async pause(){if(this.processor){if(!this.recording)throw new Error("Already paused: please call .record() first")}else throw new Error("Session ended: please call .begin() first");return this._chunkProcessorBuffer.raw.byteLength&&this._chunkProcessor(this._chunkProcessorBuffer),this.log("Pausing ..."),await this._event("stop"),this.recording=!1,!0}async record(e=()=>{},t=8192){if(this.processor){if(this.recording)throw new Error("Already recording: HELLO please call .pause() first");if(typeof e!="function")throw new Error("chunkProcessor must be a function")}else throw new Error("Session ended: please call .begin() first");return this._chunkProcessor=e,this._chunkProcessorSize=t,this._chunkProcessorBuffer={raw:new ArrayBuffer(0),mono:new ArrayBuffer(0)},this.log("Recording ..."),await this._event("start"),this.recording=!0,!0}async clear(){if(!this.processor)throw new Error("Session ended: please call .begin() first");return await this._event("clear"),!0}async read(){if(!this.processor)throw new Error("Session ended: please call .begin() first");return this.log("Reading ..."),await this._event("read")}async save(e=!1){if(!this.processor)throw new Error("Session ended: please call .begin() first");if(!e&&this.recording)throw new Error("Currently recording: please call .pause() first, or call .save(true) to force");this.log("Exporting ...");const t=await this._event("export");return new ft().pack(this.sampleRate,t.audio)}async end(){if(!this.processor)throw new Error("Session ended: please call .begin() first");const e=this.processor;this.log("Stopping ..."),await this._event("stop"),this.recording=!1,this.log("Exporting ...");const t=await this._event("export",{},e);return this.processor.disconnect(),this.source.disconnect(),this.node.disconnect(),this.analyser.disconnect(),this.stream=null,this.processor=null,this.source=null,this.node=null,new ft().pack(this.sampleRate,t.audio)}async quit(){return this.listenForDeviceChange(null),this.processor&&await this.end(),!0}}globalThis.WavRecorder=WavRecorder;
340var Ay=(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(r[s]=i[s])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})(),Qt=function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(f){try{u(r.next(f))}catch(g){a(g)}}function l(f){try{u(r.throw(f))}catch(g){a(g)}}function u(f){f.done?s(f.value):i(f.value).then(o,l)}u((r=r.apply(n,e||[])).next())})},Zt=function(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(u){return function(f){return l([u,f])}}function l(u){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(t=0)),t;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,i=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){t.label=u[1];break}if(u[0]===6&&t.label<s[1]){t.label=s[1],s=u;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(u);break}s[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(n,t)}catch(f){u=[6,f],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}},Ld=(function(){function n(){this._callbacks={},this._micEnabled=!0,this._camEnabled=!1,this._supportsScreenShare=!1}return n.prototype.setUserAudioCallback=function(e){this._userAudioCallback=e},n.prototype.setClientOptions=function(e,t){var r,i,s;t===void 0&&(t=!1),!(this._options&&!t)&&(this._options=e,this._callbacks=(r=e.callbacks)!==null&&r!==void 0?r:{},this._micEnabled=(i=e.enableMic)!==null&&i!==void 0?i:!0,this._camEnabled=(s=e.enableCam)!==null&&s!==void 0?s:!1)},Object.defineProperty(n.prototype,"supportsScreenShare",{get:function(){return this._supportsScreenShare},enumerable:!1,configurable:!0}),n})(),Ty=(function(n){Ay(e,n);function e(t,r){t===void 0&&(t=void 0),r===void 0&&(r=24e3);var i=n.call(this)||this;return i._initialized=!1,i._recorderChunkSize=void 0,i._recorderChunkSize=t,i._wavRecorder=new Rd({sampleRate:r}),i._wavStreamPlayer=new fa({sampleRate:24e3}),i}return e.prototype.initialize=function(){return Qt(this,void 0,Promise,function(){return Zt(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this._wavRecorder.begin()];case 1:return t.sent(),[3,3];case 2:return t.sent(),[3,3];case 3:return this._wavRecorder.listenForDeviceChange(null),this._wavRecorder.listenForDeviceChange(this._handleAvailableDevicesUpdated.bind(this)),this._wavRecorder.listenForDeviceErrors(null),this._wavRecorder.listenForDeviceErrors(this._handleDeviceError.bind(this)),[4,this._wavStreamPlayer.connect()];case 4:return t.sent(),this._initialized=!0,[2]}})})},e.prototype.connect=function(){return Qt(this,void 0,Promise,function(){var t;return Zt(this,function(r){switch(r.label){case 0:return this._initialized?[3,2]:[4,this.initialize()];case 1:r.sent(),r.label=2;case 2:return t=this._wavRecorder.getStatus()=="recording",this._micEnabled&&!t?[4,this._startRecording()]:[3,4];case 3:r.sent(),r.label=4;case 4:return this._camEnabled&&console.warn("WavMediaManager does not support video input."),[2]}})})},e.prototype.disconnect=function(){return Qt(this,void 0,Promise,function(){return Zt(this,function(t){switch(t.label){case 0:return this._initialized?[4,this._wavRecorder.end()]:[2];case 1:return t.sent(),[4,this._wavStreamPlayer.interrupt()];case 2:return t.sent(),this._initialized=!1,[2]}})})},e.prototype.userStartedSpeaking=function(){return Qt(this,void 0,Promise,function(){return Zt(this,function(t){return[2,this._wavStreamPlayer.interrupt()]})})},e.prototype.bufferBotAudio=function(t,r){return this._wavStreamPlayer.add16BitPCM(t,r)},e.prototype.getAllMics=function(){return this._wavRecorder.listDevices()},e.prototype.getAllCams=function(){return Promise.resolve([])},e.prototype.getAllSpeakers=function(){return Promise.resolve([])},e.prototype.updateMic=function(t){return Qt(this,void 0,Promise,function(){var r,i,s,a;return Zt(this,function(o){switch(o.label){case 0:return r=this._wavRecorder.deviceSelection,this._wavRecorder.getStatus()==="ended"?[3,2]:[4,this._wavRecorder.end()];case 1:o.sent(),o.label=2;case 2:return o.trys.push([2,6,,7]),[4,this._wavRecorder.begin(t)];case 3:return o.sent(),this._micEnabled?[4,this._startRecording()]:[3,5];case 4:o.sent(),o.label=5;case 5:return i=this._wavRecorder.deviceSelection,i&&r&&r.label!==i.label&&((a=(s=this._callbacks).onMicUpdated)===null||a===void 0||a.call(s,i)),[3,7];case 6:return o.sent(),[3,7];case 7:return[2]}})})},e.prototype.updateCam=function(t){},e.prototype.updateSpeaker=function(t){},Object.defineProperty(e.prototype,"selectedMic",{get:function(){var t;return(t=this._wavRecorder.deviceSelection)!==null&&t!==void 0?t:{}}
340,enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"selectedCam",{get:function(){return{}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"selectedSpeaker",{get:function(){return{}},enumerable:!1,configurable:!0}),e.prototype.enableMic=function(t){return Qt(this,void 0,Promise,function(){var r=this;return Zt(this,function(i){switch(i.label){case 0:return this._micEnabled=t,this._wavRecorder.stream?(this._wavRecorder.stream.getAudioTracks().forEach(function(s){var a,o;s.enabled=t,t||(o=(a=r._callbacks).onTrackStopped)===null||o===void 0||o.call(a,s,cl())}),t?[4,this._startRecording()]:[3,2]):[2];case 1:return i.sent(),[3,4];case 2:return[4,this._wavRecorder.pause()];case 3:i.sent(),i.label=4;case 4:return[2]}})})},e.prototype.enableCam=function(t){console.warn("WavMediaManager does not support video input.")},e.prototype.enableScreenShare=function(t){console.warn("WavMediaManager does not support screen sharing.")},Object.defineProperty(e.prototype,"isCamEnabled",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isMicEnabled",{get:function(){return this._micEnabled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isSharingScreen",{get:function(){return!1},enumerable:!1,configurable:!0}),e.prototype.tracks=function(){var t,r=(t=this._wavRecorder.stream)===null||t===void 0?void 0:t.getTracks()[0];return{local:r?{audio:r}:{}}},e.prototype._startRecording=function(){return Qt(this,void 0,void 0,function(){var t,r=this,i,s,a;return Zt(this,function(o){switch(o.label){case 0:return[4,this._wavRecorder.record(function(l){var u;(u=r._userAudioCallback)===null||u===void 0||u.call(r,l.mono)},this._recorderChunkSize)];case 1:return o.sent(),t=(i=this._wavRecorder.stream)===null||i===void 0?void 0:i.getAudioTracks()[0],t&&((a=(s=this._callbacks).onTrackStarted)===null||a===void 0||a.call(s,t,cl())),[2]}})})},e.prototype._handleAvailableDevicesUpdated=function(t){var r,i,s,a;(i=(r=this._callbacks).onAvailableCamsUpdated)===null||i===void 0||i.call(r,t.filter(function(u){return u.kind==="videoinput"})),(a=(s=this._callbacks).onAvailableMicsUpdated)===null||a===void 0||a.call(s,t.filter(function(u){return u.kind==="audioinput"}));var o=t.find(function(u){return u.deviceId==="default"}),l=this._wavRecorder.deviceSelection;l&&(!t.some(function(u){return u.deviceId===l.deviceId})||l.deviceId==="default"&&l.label!==o?.label)&&this.updateMic("")},e.prototype._handleDeviceError=function(t){var r,i,s=t.devices,a=t.type,o=t.error,l=new Et(s,a,o?.message,o?{sourceError:o}:void 0);(i=(r=this._callbacks).onDeviceError)===null||i===void 0||i.call(r,l)},e})(Ld),cl=function(){return{id:"local",name:"",local:!0}}
340,Ny=(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(r[s]=i[s])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})(),ut=function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(f){try{u(r.next(f))}catch(g){a(g)}}function l(f){try{u(r.throw(f))}catch(g){a(g)}}function u(f){f.done?s(f.value):i(f.value).then(o,l)}u((r=r.apply(n,e||[])).next())})},dt=function(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(u){return function(f){return l([u,f])}}function l(u){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(t=0)),t;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,i=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){t.label=u[1];break}if(u[0]===6&&t.label<s[1]){t.label=s[1],s=u;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(u);break}s[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(n,t)}catch(f){u=[6,f],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}},Oy=(function(n){Ny(e,n);function e(t,r,i,s,a,o,l){t===void 0&&(t=!0),r===void 0&&(r=!0),a===void 0&&(a=void 0),o===void 0&&(o=24e3),l===void 0&&(l=24e3);var u,f=n.call(this)||this;return f._selectedCam={},f._selectedMic={},f._selectedSpeaker={},f._remoteAudioLevelInterval=null,f._recorderChunkSize=void 0,f._initialized=!1,f._connected=!1,f._currentAudioTrack=null,f._connectResolve=null,f.onTrackStartedCallback=i,f.onTrackStoppedCallback=s,f._recorderChunkSize=a,f._supportsScreenShare=!0,f._daily=(u=Wc.getCallInstance())!==null&&u!==void 0?u:Wc.createCallObject(),r&&(f._mediaStreamRecorder=new My({sampleRate:o})),t&&(f._wavStreamPlayer=new fa({sampleRate:l})),f._daily.on("track-started",f.handleTrackStarted.bind(f)),f._daily.on("track-stopped",f.handleTrackStopped.bind(f)),f._daily.on("available-devices-updated",f._handleAvailableDevicesUpdated.bind(f)),f._daily.on("selected-devices-updated",f._handleSelectedDevicesUpdated.bind(f)),f._daily.on("camera-error",f.handleDeviceError.bind(f)),f._daily.on("local-audio-level",f._handleLocalAudioLevel.bind(f)),f}return e.prototype.initialize=function(){return ut(this,void 0,Promise,function(){var t,r,i,s,a,o=this,l,u,f,g,_,k,b,v,E,C,O,j;return dt(this,function(S){switch(S.label){case 0:return this._initialized?(console.warn("DailyMediaManager already initialized"),[2]):[4,this._daily.startCamera({startVideoOff:!this._camEnabled,startAudioOff:!this._micEnabled,dailyConfig:{useDevicePreferenceCookies:!0}})];case 1:return t=S.sent(),[4,this._daily.enumerateDevices()];case 2:return r=S.sent().devices,i=r.filter(function(x){return x.kind==="videoinput"}),s=r.filter(function(x){return x.kind==="audioinput"}),a=r.filter(function(x){return x.kind==="audiooutput"}),(u=(l=this._callbacks).onAvailableCamsUpdated)===null||u===void 0||u.call(l,i),(g=(f=this._callbacks).onAvailableMicsUpdated)===null||g===void 0||g.call(f,s),(k=(_=this._callbacks).onAvailableSpeakersUpdated)===null||k===void 0||k.call(_,a),this._selectedCam=t.camera,(v=(b=this._callbacks).onCamUpdated)===null||v===void 0||v.call(b,t.camera),this._selectedMic=t.mic,(C=(E=this._callbacks).onMicUpdated)===null||C===void 0||C.call(E,t.mic),this._selectedSpeaker=t.speaker,(j=(O=this._callbacks).onSpeakerUpdated)===null||j===void 0||j.call(O,t.speaker),this._daily.isLocalAudioLevelObserverRunning()?[3,4]:[4,this._daily.startLocalAudioLevelObserver(100)];case 3:S.sent(),S.label=4;case 4:return this._wavStreamPlayer?[4,this._wavStreamPlayer.connect()]:[3,6];case 5:S.sent(),this._remoteAudioLevelInterval||(this._remoteAudioLevelInterval=setInterval(function(){var x,T=o._wavStreamPlayer.getFrequencies(),I=0;!((x=T.values)===null||x===void 0)&&x.length&&(I=T.values.reduce(function(F,$){return F+$},0)/T.values.length),o._handleRemoteAudioLevel(I)},100)),S.label=6;case 6:return this._initialized=!0,[2]}})})},e.prototype.connect=function(){return ut(this,void 0,Promise,function(){var t=this;return dt(this,function(r){return this._connected?(console.warn("DailyMediaManager already connected"),[2]):(this._connected=!0,this._initialized?(this._micEnabled&&this._startRecording(),[2]):[2,new Promise(function(i){(function(){return ut(t,void 0,void 0,function(){return dt(this,function(s){switch(s.label){case 0:return this._connectResolve=i,[4,this.initialize()];case 1:return s.sent(),[2]}})})})()})])})})},e.prototype.disconnect=function(){return ut(this,void 0,Promise,function(){var t,r;return dt(this,function(i){switch(i.label){case 0:return this._remoteAudioLevelInterval&&clearInterval(this._remoteAudioLevelInterval),this._remoteAudioLevelInterval=null,this._daily.leave(),this._currentAudioTrack=null,[4,(t=this._mediaStreamRecorder)===null||t===void 0?void 0:t.end()];case 1:return i.sent(),(r=this._wavStreamPlayer)===null||r===void 0||r.interrupt(),this._initialized=!1,this._connected=!1,[2]}})})},e.prototype.userStartedSpeaking=function(){return ut(this,void 0,Promise,function(){var t;return dt(this,function(r){return[2,(t=this._wavStreamPlayer)===null||t===void 0?void 0:t.interrupt()]})})},e.prototype.bufferBotAudio=function(t,r){var i;return(i=this._wavStreamPlayer)===null||i===void 0?void 0:i.add16BitPCM(t,r)},e.prototype.getAllMics=function(){return ut(this,void 0,Promise,function(){var t;return dt(this,function(r){switch(r.label){case 0:return[4,this._daily.enumerateDevices()];case 1:return t=r.sent().devices,[2,t.filter(function(i){return i.kind==="audioinput"})]}})})},e.prototype.getAllCams=function(){return ut(this,void 0,Promise,function(){var t;return dt(this,function(r){switch(r.label){case 0:return[4,this._daily.enumerateDevices()];case 1:return t=r.sent().devices,[2,t.filter(function(i){return i.kind==="videoinput"})]}})})},e.prototype.getAllSpeakers=function(){return ut(this,void 0,Promise,function(){var t;return dt(this,function(r){switch(r.label){case 0:return[4,this._daily.enumerateDevices()];case 1:return t=r.sent().devices,[2,t.filter(function(i){return i.kind==="audiooutput"})]}})})},e.prototype.updateMic=function(t){var r=this;this._daily.setInputDevicesAsync({audioDeviceId:t}).then(function(i){r._selectedMic=i.mic})},e.prototype.updateCam=function(t){var r=this;this._daily.setInputDevicesAsync({videoDeviceId:t}).then(function(i){r._selectedCam=i.camera})},e.prototype.updateSpeaker=function(t){return ut(this,void 0,Promise,function(){var r,i,s,a,o,l,u=this,f,g,_,k;return dt(this,function(b){switch(b.label){case 0:if(this._wavStreamPlayer)return[3,5];b.label=1;case 1:return b.trys.push([1,3,,4]),[4,this._daily.setOutputDeviceAsync({outputDeviceId:t})];case 2:return r=b.sent(),this._selectedSpeaker=r.speaker,(g=(f=this._callbacks).onSpeakerUpdated)===null||g===void 0||g.call(f,this._selectedSpeaker),[3,4];case 3:return i=b.sent(),console.error("Error setting output device",i),[3,4];case 4:return[2];case 5:return t!=="default"&&this._selectedSpeaker.deviceId===t?[2]:(s=t,s!=="default"?[3,7]:[4,this.getAllSpeakers()]);case 6:if(a=b.sent(),o=a.find(function(v){return v.deviceId==="default"}),!o)return console.warn("No default speaker found"),[2];a.splice(a.indexOf(o),1),l=a.find(function(v){return o.label.includes(v.label)}),s=(_=l?.deviceId)!==null&&_!==void 0?_:t,b.label=7;case 7:return(k=this._wavStreamPlayer)===null||k===void 0||k.updateSpeaker(s).then(function(){var v,E;u._selectedSpeaker={deviceId:t},(E=(v=u._callbacks).onSpeakerUpdated)===null||E===void 0||E.call(v,u._selectedSpeaker)}),[2]}})})},Object.defineProperty(e.prototype,"selectedMic",{get:function(){return this._selectedMic}
340,enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"selectedCam",{get:function(){return this._selectedCam},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"selectedSpeaker",{get:function(){return this._selectedSpeaker},enumerable:!1,configurable:!0}),e.prototype.enableMic=function(t){return ut(this,void 0,Promise,function(){var r;return dt(this,function(i){return this._micEnabled=t,!((r=this._daily.participants())===null||r===void 0)&&r.local?(this._daily.setLocalAudio(t),this._mediaStreamRecorder&&(t?this._mediaStreamRecorder.getStatus()==="paused"&&this._startRecording():this._mediaStreamRecorder.getStatus()==="recording"&&this._mediaStreamRecorder.pause()),[2]):[2]})})},e.prototype.enableCam=function(t){this._camEnabled=t,this._daily.setLocalVideo(t)},e.prototype.enableScreenShare=function(t){t?this._daily.startScreenShare():this._daily.stopScreenShare()},Object.defineProperty(e.prototype,"isCamEnabled",{get:function(){return this._daily.localVideo()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isMicEnabled",{get:function(){return this._daily.localAudio()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isSharingScreen",{get:function(){return this._daily.localScreenAudio()||this._daily.localScreenVideo()},enumerable:!1,configurable:!0}),e.prototype.tracks=function(){var t,r,i,s,a,o,l,u,f,g,_,k,b=this._daily.participants();return{local:{audio:(i=(r=(t=b?.local)===null||t===void 0?void 0:t.tracks)===null||r===void 0?void 0:r.audio)===null||i===void 0?void 0:i.persistentTrack,screenAudio:(o=(a=(s=b?.local)===null||s===void 0?void 0:s.tracks)===null||a===void 0?void 0:a.screenAudio)===null||o===void 0?void 0:o.persistentTrack,screenVideo:(f=(u=(l=b?.local)===null||l===void 0?void 0:l.tracks)===null||u===void 0?void 0:u.screenVideo)===null||f===void 0?void 0:f.persistentTrack,video:(k=(_=(g=b?.local)===null||g===void 0?void 0:g.tracks)===null||_===void 0?void 0:_.video)===null||k===void 0?void 0:k.persistentTrack}}},e.prototype._startRecording=function(){var t=this;if(!(!this._connected||!this._mediaStreamRecorder))try{this._mediaStreamRecorder.record(function(i){t._userAudioCallback(i.mono)},this._recorderChunkSize)}catch(i){var r=i;r.message.includes("Already recording")||console.error("Error starting recording",i)}},e.prototype._handleAvailableDevicesUpdated=function(t){var r,i,s,a,o,l;(i=(r=this._callbacks).onAvailableCamsUpdated)===null||i===void 0||i.call(r,t.availableDevices.filter(function(u){return u.kind==="videoinput"})),(a=(s=this._callbacks).onAvailableMicsUpdated)===null||a===void 0||a.call(s,t.availableDevices.filter(function(u){return u.kind==="audioinput"})),(l=(o=this._callbacks).onAvailableSpeakersUpdated)===null||l===void 0||l.call(o,t.availableDevices.filter(function(u){return u.kind==="audiooutput"})),this._selectedSpeaker.deviceId==="default"&&this.updateSpeaker("default")},e.prototype._handleSelectedDevicesUpdated=function(t){var r,i,s,a,o,l;((r=this._selectedCam)===null||r===void 0?void 0:r.deviceId)!==t.devices.camera&&(this._selectedCam=t.devices.camera,(s=(i=this._callbacks).onCamUpdated)===null||s===void 0||s.call(i,t.devices.camera)),((a=this._selectedMic)===null||a===void 0?void 0:a.deviceId)!==t.devices.mic&&(this._selectedMic=t.devices.mic,(l=(o=this._callbacks).onMicUpdated)===null||l===void 0||l.call(o,t.devices.mic))},e.prototype.handleDeviceError=function(t){var r,i,s=function(a){var o=[];switch(a.type){case"permissions":return a.blockedMedia.forEach(function(l){o.push(l==="video"?"cam":"mic")}),new Et(o,a.type,a.msg,{blockedBy:a.blockedBy});case"not-found":return a.missingMedia.forEach(function(l){o.push(l==="video"?"cam":"mic")}),new Et(o,a.type,a.msg);case"constraints":return a.failedMedia.forEach(function(l){o.push(l==="video"?"cam":"mic")}),new Et(o,a.type,a.msg,{reason:a.reason});case"cam-in-use":return o.push("cam"),new Et(o,"in-use",a.msg);case"mic-in-use":return o.push("mic"),new Et(o,"in-use",a.msg);case"cam-mic-in-use":return o.push("cam"),o.push("mic"),new Et(o,"in-use",a.msg);default:return o.push("cam"),o.push("mic"),new Et(o,a.type,a.msg)}};(i=(r=this._callbacks).onDeviceError)===null||i===void 0||i.call(r,s(t.error))},e.prototype._handleLocalAudioLevel=function(t){var r,i;(i=(r=this._callbacks).onLocalAudioLevel)===null||i===void 0||i.call(r,t.audioLevel)},e.prototype._handleRemoteAudioLevel=function(t){var r,i;(i=(r=this._callbacks).onRemoteAudioLevel)===null||i===void 0||i.call(r,t,Py())},e.prototype.handleTrackStarted=function(t){return ut(this,void 0,void 0,function(){var r,i,s,a,o,l;return dt(this,function(u){switch(u.label){case 0:if(!(!((s=t.participant)===null||s===void 0)&&s.local))return[2];if(t.track.kind!=="audio")return[3,15];if(!this._mediaStreamRecorder)return[3,14];switch(r=this._mediaStreamRecorder.getStatus(),i=r,i){case"ended":return[3,1];case"paused":return[3,5];
340case"recording":return[3,6]}return[3,6];case 1:return u.trys.push([1,3,,4]),[4,this._mediaStreamRecorder.begin(t.track)];case 2:return u.sent(),this._connected&&(this._startRecording(),this._connectResolve&&(this._connectResolve(),this._connectResolve=null)),[3,4];case 3:return u.sent(),[3,4];case 4:return[3,14];case 5:return this._startRecording(),[3,14];case 6:return this._currentAudioTrack===t.track?[3,12]:[4,this._mediaStreamRecorder.end()];case 7:u.sent(),u.label=8;case 8:return u.trys.push([8,10,,11]),[4,this._mediaStreamRecorder.begin(t.track)];case 9:return u.sent(),this._startRecording(),[3,11];case 10:return u.sent(),[3,11];case 11:return[3,13];case 12:console.warn("track-started event received for current track and already recording"),u.label=13;case 13:return[3,14];case 14:this._currentAudioTrack=t.track,u.label=15;case 15:return(o=(a=this._callbacks).onTrackStarted)===null||o===void 0||o.call(a,t.track,t.participant?ll(t.participant):void 0),(l=this.onTrackStartedCallback)===null||l===void 0||l.call(this,t),[2]}})})},e.prototype.handleTrackStopped=function(t){var r,i,s,a;!((r=t.participant)===null||r===void 0)&&r.local&&(t.track.kind==="audio"&&this._mediaStreamRecorder&&this._mediaStreamRecorder.getStatus()==="recording"&&this._mediaStreamRecorder.pause(),(s=(i=this._callbacks).onTrackStopped)===null||s===void 0||s.call(i,t.track,t.participant?ll(t.participant):void 0),(a=this.onTrackStoppedCallback)===null||a===void 0||a.call(this,t))},e})(Ld),ll=function(n){return{id:n.user_id,local:n.local,name:n.user_name}},Py=function(){return{id:"bot",local:!1,name:"Bot"}}
340,jy=(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(r[s]=i[s])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})(),Dt=function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(f){try{u(r.next(f))}catch(g){a(g)}}function l(f){try{u(r.throw(f))}catch(g){a(g)}}function u(f){f.done?s(f.value):i(f.value).then(o,l)}u((r=r.apply(n,e||[])).next())})},Ft=function(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(u){return function(f){return l([u,f])}}function l(u){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(t=0)),t;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,i=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){t.label=u[1];break}if(u[0]===6&&t.label<s[1]){t.label=s[1],s=u;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(u);break}s[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(n,t)}catch(f){u=[6,f],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}},kr=function(n,e,t){if(t||arguments.length===2)for(var r=0,i=e.length,s;r<i;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return n.concat(s||Array.prototype.slice.call(e))},Dd=["CONNECTING","OPEN","CLOSING","CLOSED"],Iy=5e3,Ry=15e3,Ly=15e4,ul=2,Dy=10,Fy=1e3,By=3e4,$y=1.5,Uy=4100,Vy="SIG_CONNECTION_CANCELED",zy="WEBSOCKET_ERROR",qe;(function(n){n[n.DEBUG=0]="DEBUG",n[n.ERROR=1]="ERROR",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN"})(qe||(qe={}));var Wy=(function(){function n(e,t){this._closedManually=!1,this._errored=!1,this._rejected=!1,this._timed_out=!1,this._initialConnectionOk=!1,this._ws=new WebSocket(e,t)}return n.prototype.addEventListener=function(e,t){this._ws.addEventListener(e,t)},n.prototype.close=function(e,t){this._ws.close(e,t)},n.prototype.send=function(e){this._ws.send(e)},Object.defineProperty(n.prototype,"url",{get:function(){return this._ws.url},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"readyState",{get:function(){return this._ws.readyState},enumerable:!1,configurable:!0}),n})(),oi=(function(n){jy(e,n);function e(t,r,i){i===void 0&&(i={});var s,a=n.call(this)||this;if(!t)throw new Error("Need a valid WebSocket URL");return a._ws=null,a._url=t,a._protocols=r,a._parseBlobToJson=(s=i?.parseBlobToJson)!==null&&s!==void 0?s:!0,a.init(),a}return e.prototype.init=function(){this._keepAliveTimeout=Ry,this._keepAliveInterval=Iy,this._disconnected=!1,this._keepIntervalID=null,this._shouldRetryFn=null,this._connectionTimeout=Ly,this._reconnectAttempts=0,this._allowedReconnectAttempts=ul,this._reconnectInterval=Fy,this._maxReconnectInterval=By,this._reconnectDecay=$y},e.prototype.connect=function(){return Dt(this,void 0,void 0,function(){var t=this;return Ft(this,function(r){return[2,new Promise(function(i,s){t._disconnected=!1,t.clearReconnectTimeout();var a=new Wy(t._url,t._protocols);t.setConnectionTimeout(),a.addEventListener("close",function(o){var l=o,u=a._timed_out?Uy:l.code,f=a._timed_out?"websocket connection timed out":l.reason;if(a._timed_out=!1,!a._closedManually&&a._initialConnectionOk?(console.warn("signaling socket closed unexpectedly: ".concat(u).concat(f?" "+f:"")),t._closeSocket(),t.emit("close",u,f)):t.log("signaling socket closed"),!a._closedManually&&(a._errored||a._timed_out)&&(console.warn("signaling socket closed on error: ".concat(u).
340concat(f?" "+f:"")),!a._rejected)){a._rejected=!0;var g=new Error("WebSocket connection error (".concat(u,"): ").concat(f));g.name=zy,s(g)}}),a.addEventListener("open",function(o){if(t.log("wss connection opened to",qe.DEBUG,t._url),t.clearConnectionTimeout(),!(a._rejected||a._timed_out)){if(a._closedManually||t._ws&&t._ws!==a){a._rejected=!0,a.close();var l=Error("wss connection interrupted by disconnect or newer connection");l.name=Vy,s(l);return}a._initialConnectionOk=t._url,t._lastMsgRecvTime=Date.now(),t._keepAliveInterval&&(t._keepIntervalID=setInterval(function(){return t.checkSocketHealthAndSendKeepAlive()},t._keepAliveInterval)),t._ws=a,t.emit("open"),i(a)}}),a.addEventListener("error",function(o){if(!a._closedManually){var l=o.currentTarget;t.log("websocket error event: ".concat(l?.url))}a._errored=!0}),a.addEventListener("message",function(o){t._handleMessage(o)})})]})})},e.prototype.setConnectionTimeout=function(){var t=this;this._connectionTimeoutID=setTimeout(function(){return Dt(t,void 0,void 0,function(){return Ft(this,function(r){switch(r.label){case 0:return this.log("Connection reconnect attempt timed out."),this.emit("connection-timeout"),this.clearConnectionTimeout(),[4,this._closeSocket()];case 1:return r.sent(),[2]}})})},this._connectionTimeout)},e.prototype.clearConnectionTimeout=function(){clearTimeout(this._connectionTimeoutID),this._connectionTimeoutID=void 0},e.prototype.clearReconnectTimeout=function(){clearTimeout(this._reconnectTimeoutID),this._reconnectTimeoutID=void 0},e.prototype.clearKeepAliveInterval=function(){this._keepIntervalID&&(clearInterval(this._keepIntervalID),this._keepIntervalID=null)},e.prototype.checkSocketHealthAndSendKeepAlive=function(){return Dt(this,void 0,void 0,function(){return Ft(this,function(t){switch(t.label){case 0:return this._ws&&this._ws.readyState===WebSocket.OPEN?!this._keepAliveTimeout||!this._keepAliveInterval?[2]:Date.now()-this._lastMsgRecvTime>this._keepAliveTimeout?(this.log("Connection is stale, need to reconnect",qe.WARN),[4,this._closeSocket()]):[3,2]:[2];case 1:return t.sent(),[2];case 2:return Date.now()-this._lastMsgSendTime<this._keepAliveInterval?[2]:(this.log("Emitting keep-alive",qe.DEBUG),this.emit("keep-alive"),[2])}})})},e.prototype._closeSocket=function(){return Dt(this,void 0,void 0,function(){var t,r,i;return Ft(this,function(s){switch(s.label){case 0:this.log("Closing"),s.label=1;case 1:return s.trys.push([1,4,,5]),this.clearKeepAliveInterval(),this._lastMsgRecvTime=0,this._ws&&(this._ws._closedManually=!0,this._ws.close()),t=((i=this._ws)===null||i===void 0?void 0:i._initialConnectionOk)&&this._shouldRetryFn&&this._shouldRetryFn(),this._ws=null,t?(this.log("Emitting reconnect",qe.DEBUG),this.emit("reconnecting"),[4,this.retryFailedConnection()]):[3,3];case 2:s.sent(),s.label=3;case 3:return[3,5];case 4:return r=s.sent(),this.log("Error while closing and retrying: ".concat(r),qe.ERROR),[3,5];case 5:return[2]}})})},e.prototype.retryFailedConnection=function(){return Dt(this,void 0,void 0,function(){var t,r=this;return Ft(this,function(i){if(this._reconnectAttempts<this._allowedReconnectAttempts){if(this._reconnectTimeoutID)return this.log("Retry already scheduled"),[2];this.log("Retrying failed connection"),t=this._reconnectInterval*Math.pow(this._reconnectDecay,this._reconnectAttempts),t=t>this._maxReconnectInterval?this._maxReconnectInterval:t,this.log("Reconnecting in ".concat(t/1e3," seconds")),this._reconnectAttempts+=1,this._reconnectTimeoutID=setTimeout(function(){return r.connect()},t)}else this.log("Maximum connection retry attempts exceeded",qe.ERROR),this.emit("reconnect-failed");return[2]})})},e.prototype.log=function(t,r){r===void 0&&(r=qe.DEBUG);for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];switch(r){case qe.DEBUG:console.debug.apply(console,kr(["websocket: ".concat(t)],i,!1));break;case qe.ERROR:console.error.apply(console,kr(["websocket: ".concat(t)],i,!1));break;case qe.WARN:console.warn.apply(console,kr(["websocket: ".concat(t)],i,!1));break;case qe.INFO:default:console.log.apply(console,kr(["websocket: ".concat(t)],i,!1));break}},e.prototype.send=function(t){return Dt(this,void 0,void 0,function(){return Ft(this,function(r){try{this._ws&&this._ws.readyState===WebSocket.OPEN?(this._lastMsgSendTime=Date.now(),this._ws.send(t)):this.log("Failed to send data, web socket not open.",qe.ERROR)}catch(i){this.log("Failed to send data. ".concat(i),qe.ERROR)}return[2]})})},e.prototype.close=function(){return Dt(this,void 0,void 0,function(){return Ft(this,function(t){try{this.log("Closing websocket"),this._disconnected=!0,this.clearReconnectTimeout(),this._closeSocket()}catch(r){this.log("Failed to close websocket. ".concat(r))}return[2]})})},Object.defineProperty(e.prototype,"readyState",{get:function(){var t,r;return(r=(t=this._ws)===null||t===void 0?void 0:t.readyState)!==null&&r!==void 0?r:WebSocket.CLOSED}
340,enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"url",{get:function(){return this._url},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"keepAliveTimeout",{get:function(){return this._keepAliveTimeout},set:function(t){typeof t=="number"&&(this.log("Setting ACK freshness timeout to ".concat(t)),this._keepAliveTimeout=t)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"keepAliveInterval",{get:function(){return this._keepAliveInterval},set:function(t){typeof t=="number"&&(this.log("Setting keep-alive interval to ".concat(t)),this._keepAliveInterval=t)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"shouldRetryFn",{set:function(t){typeof t=="function"&&(this._shouldRetryFn=t)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connectionTimeout",{get:function(){return this._connectionTimeout},set:function(t){typeof t=="number"&&(this._connectionTimeout=t)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxReconnectAttempts",{get:function(){return this._allowedReconnectAttempts},set:function(t){t>0&&t<Dy?(this.log("Setting maximum connection retry attempts to ".concat(t)),this._allowedReconnectAttempts=t):this._allowedReconnectAttempts=ul},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"reconnectInterval",{get:function(){return this._reconnectInterval},set:function(t){typeof t=="number"&&(this._reconnectInterval=t<this._maxReconnectInterval?t:this._maxReconnectInterval)},enumerable:!1,configurable:!0}),e.prototype._handleMessage=function(t){return Dt(this,void 0,void 0,function(){var r,i,s,a=this;return Ft(this,function(o){switch(o.label){case 0:return this._lastMsgRecvTime=Date.now(),r=t.data,i=new Promise(function(l,u){if(typeof r=="string")l(r);else if(r instanceof ArrayBuffer){var f=r;l(new Uint8Array(f))}else if(r instanceof Blob){if(!a._parseBlobToJson){l(r);return}var g=r,_=new FileReader;_.onload=function(){var k=_.result;try{var b=JSON.parse(k);l(b)}catch(v){console.error("Failed to parse JSON from Blob:",v)}},_.readAsText(g)}}),[4,i];case 1:return s=o.sent(),this.emit("message",s),[2]}})})},e})(nu.EventEmitter);["binaryType","bufferedAmount","extensions","protocol","readyState","url","keepAliveTimeout","keepAliveInterval","shouldRetryFn","connectionTimeout","maxReconnectAttempts","reconnectInterval"].forEach(function(n){Object.defineProperty(oi.prototype,n,{enumerable:!0})});["CONNECTING","OPEN","CLOSING","CLOSED"].forEach(function(n){Object.defineProperty(oi.prototype,n,{enumerable:!0,value:Dd.indexOf(n)})});["CONNECTING","OPEN","CLOSING","CLOSED"].forEach(function(n){Object.defineProperty(oi,n,{enumerable:!0,value:Dd.indexOf(n)})});class qy extends er{constructor(){super("pipecat.TextFrame",[{no:1,name:"id",kind:"scalar",T:4,L:0},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"text",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.id=0n,t.name="",t.text="",e!==void 0&&zt(this,t,e),t}internalBinaryRead(e,t,r,i){let s=i??this.create(),a=e.pos+t;for(;e.pos<a;){let[o,l]=e.tag();switch(o){case 1:s.id=e.uint64().toBigInt();break;case 2:s.name=e.string();break;case 3:s.text=e.string();break;default:let u=r.readUnknownField;if(u==="throw")throw new globalThis.Error(`Unknown field ${o} (wire type ${l}) for ${this.typeName}`);let f=e.skip(l);u!==!1&&(u===!0?Xe.onRead:u)(this.typeName,s,o,l,f)}}return s}internalBinaryWrite(e,t,r){e.id!==0n&&t.tag(1,ne.Varint).uint64(e.id),e.name!==""&&t.tag(2,ne.LengthDelimited).string(e.name),e.text!==""&&t.tag(3,ne.LengthDelimited).string(e.text);let i=r.writeUnknownFields;return i!==!1&&(i==!0?Xe.onWrite:i)(this.typeName,e,t),t}}const Gi=new qy;class Jy extends er{constructor(){super("pipecat.AudioRawFrame",[{no:1,name:"id",kind:"scalar",T:4,L:0},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"audio",kind:"scalar",T:12},{no:4,name:"sample_rate",kind:"scalar",T:13},{no:5,name:"num_channels",kind:"scalar",T:13},{no:6,name:"pts",kind:"scalar",opt:!0,T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.id=0n,t.name="",t.audio=new Uint8Array(0),t.sampleRate=0,t.numChannels=0,e!==void 0&&zt(this,t,e),t}internalBinaryRead(e,t,r,i){let s=i??this.create(),a=e.pos+t;for(;e.pos<a;){let[o,l]=e.tag();switch(o){case 1:s.id=e.uint64().toBigInt();break;case 2:s.name=e.string();break;case 3:s.audio=e.bytes();break;case 4:s.sampleRate=e.uint32();break;case 5:s.numChannels=e.uint32();break;case 6:s.pts=e.uint64().toBigInt();break;default:let u=r.readUnknownField;if(u==="throw")throw new globalThis.Error(`Unknown field ${o} (wire type ${l}) for ${this.typeName}`);let f=e.skip(l);u!==!1&&(u===!0?Xe.onRead:u)(this.typeName,s,o,l,f)}}return s}internalBinaryWrite(e,t,r){e.id!==0n&&t.tag(1,ne.Varint).uint64(e.id),e.name!==""&&t.tag(2,ne.LengthDelimited).string(e.name),e.audio.length&&t.tag(3,ne.LengthDelimited).bytes(e.audio),e.sampleRate!==0&&t.tag(4,ne.Varint).uint32(e.sampleRate),e.numChannels!==0&&t.tag(5,ne.Varint).uint32(e.numChannels),e.pts!==void 0&&t.tag(6,ne.Varint).uint64(e.pts);let i=r.writeUnknownFields;return i!==!1&&(i==!0?Xe.onWrite:i)(this.typeName,e,t),t}}const Hi=new Jy;class Gy extends er{constructor(){super("pipecat.TranscriptionFrame",[{no:1,name:"id",kind:"scalar",T:4,L:0},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"text",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",T:9},{no:5,name:"timestamp",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.id=0n,t.name="",t.text="",t.userId="",t.timestamp="",e!==void 0&&zt(this,t,e),t}internalBinaryRead(e,t,r,i){let s=i??this.create(),a=e.pos+t;for(;e.pos<a;){let[o,l]=e.tag();switch(o){case 1:s.id=e.uint64().toBigInt();break;case 2:s.name=e.string();break;case 3:s.text=e.string();break;case 4:s.userId=e.string();break;case 5:s.timestamp=e.string();break;default:let u=r.readUnknownField;if(u==="throw")throw new globalThis.Error(`Unknown field ${o} (wire type ${l}) for ${this.typeName}`);let f=e.skip(l);u!==!1&&(u===!0?Xe.onRead:u)(this.typeName,s,o,l,f)}}return s}internalBinaryWrite(e,t,r){e.id!==0n&&t.tag(1,ne.Varint).uint64(e.id),e.name!==""&&t.tag(2,ne.LengthDelimited).string(e.name),e.text!==""&&t.tag(3,ne.LengthDelimited).string(e.text),e.userId!==""&&t.tag(4,ne.LengthDelimited).string(e.userId),e.timestamp!==""&&t.tag(5,ne.LengthDelimited).string(e.timestamp);let i=r.writeUnknownFields;return i!==!1&&(i==!0?Xe.onWrite:i)(this.typeName,e,t),t}}const Ki=new Gy;class Hy extends er{constructor(){super("pipecat.MessageFrame",[{no:1,name:"data",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.data="",e!==void 0&&zt(this,t,e),t}internalBinaryRead(e,t,r,i){let s=i??this.create(),a=e.pos+t;for(;e.pos<a;){let[o,l]=e.tag();switch(o){case 1:s.data=e.string();break;default:let u=r.readUnknownField;if(u==="throw")throw new globalThis.Error(`Unknown field ${o} (wire type ${l}) for ${this.typeName}`);let f=e.skip(l);u!==!1&&(u===!0?Xe.onRead:u)(this.typeName,s,o,l,f)}}return s}internalBinaryWrite(e,t,r){e.data!==""&&t.tag(1,ne.LengthDelimited).string(e.data);let i=r.writeUnknownFields;return i!==!1&&(i==!0?Xe.onWrite:i)(this.typeName,e,t),t}}const Yi=new Hy;class Ky extends er{constructor(){super("pipecat.Frame",[{no:1,name:"text",kind:"message",oneof:"frame",T:()=>Gi},{no:2,name:"audio",kind:"message",oneof:"frame",T:()=>Hi},{no:3,name:"transcription",kind:"message",oneof:"frame",T:()=>Ki},{no:4,name:"message",kind:"message",oneof:"frame",T:()=>Yi}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.frame={oneofKind:void 0},e!==void 0&&zt(this,t,e),t}internalBinaryRead(e,t,r,i){let s=i??this.create(),a=e.pos+t;for(;e.pos<a;){let[o,l]=e.tag();switch(o){case 1:s.frame={oneofKind:"text",text:Gi.internalBinaryRead(e,e.uint32(),r,s.frame.text)};break;case 2:s.frame={oneofKind:"audio",audio:Hi.internalBinaryRead(e,e.uint32(),r,s.frame.audio)};break;case 3:s.frame={oneofKind:"transcription",transcription:Ki.internalBinaryRead(e,e.uint32(),r,s.frame.transcription)};break;case 4:s.frame={oneofKind:"message",message:Yi.internalBinaryRead(e,e.uint32(),r,s.frame.message)};break;default:let u=r.readUnknownField;if(u==="throw")throw new globalThis.Error(`Unknown field ${o} (wire type ${l}) for ${this.typeName}`);let f=e.skip(l);u!==!1&&(u===!0?Xe.onRead:u)(this.typeName,s,o,l,f)}}return s}internalBinaryWrite(e,t,r){e.frame.oneofKind==="text"&&Gi.internalBinaryWrite(e.frame.text,t.tag(1,ne.LengthDelimited).fork(),r).join(),e.frame.oneofKind==="audio"&&Hi.internalBinaryWrite(e.frame.audio,t.tag(2,ne.LengthDelimited).fork(),r).join(),e.frame.oneofKind==="transcription"&&Ki.internalBinaryWrite(e.frame.transcription,t.tag(3,ne.LengthDelimited).fork(),r).join(),e.frame.oneofKind==="message"&&Yi.internalBinaryWrite(e.frame.message,t.tag(4,ne.LengthDelimited).fork(),r).join();let i=r.writeUnknownFields;return i!==!1&&(i==!0?Xe.onWrite:i)(this.typeName,e,t),t}}const $n=new Ky;class Fd{serialize(e){}serializeAudio(e,t,r){const i=new Uint8Array(e),s=$n.create({frame:{oneofKind:"audio",audio:{id:0n,name:"audio",audio:i,sampleRate:t,numChannels:r}}});return new Uint8Array($n.toBinary(s))}serializeMessage(e){const t=$n.create({frame:{oneofKind:"message",message:{data:JSON.stringify(e)}}});return new Uint8Array($n.toBinary(t))}async deserialize(e){if(!(e instanceof Blob))throw new Error("Unknown data type");const t=await e.arrayBuffer(),r=$n.fromBinary(new Uint8Array(t)).frame;if(r.oneofKind==="audio"){const i=Array.from(r.audio.audio),s=new Uint8Array(i);return{type:"audio",audio:new Int16Array(s.buffer)}}else{if(r.oneofKind==="message")return{type:"message",message:JSON.parse(r.message.data)};throw new Error("Unknown frame kind")}}}
340class jn extends Eu{constructor(e={}){super(),this._wsUrl=null,this.audioQueue=[],this._wsUrl=e.wsUrl??e.ws_url??null,this._recorderSampleRate=e.recorderSampleRate??jn.RECORDER_SAMPLE_RATE,this._mediaManager=e.mediaManager||new Oy(!0,!0,void 0,void 0,512,this._recorderSampleRate,e.playerSampleRate??jn.PLAYER_SAMPLE_RATE),this._mediaManager.setUserAudioCallback(this.handleUserAudioStream.bind(this)),this._ws=null,this._serializer=e.serializer||new Fd,this._maxMessageSize=1048576}initialize(e,t){this._options=e,this._callbacks=e.callbacks??{},this._onMessage=t,this._mediaManager.setClientOptions(e),this.state="disconnected"}async initDevices(){this.state="initializing",await this._mediaManager.initialize(),this.state="initialized"}_validateConnectionParams(e){if(e==null)return;if(typeof e!="object")throw new He("Invalid connection parameters");const t=i=>i.replace(/_([a-z,A-Z])/g,(s,a)=>a.toUpperCase()),r={};for(const[i,s]of Object.entries(e)){const a=t(i);if(a==="wsUrl"){if(typeof s!="string")throw new He(`Invalid type for wsUrl: expected string, got ${typeof s}`)}else if(a==="token"){if(typeof s!="string")throw new He(`Invalid type for token: expected string, got ${typeof s}`)}else throw new He(`Unrecognized connection parameter: ${i}.`);r[a]=s}return r}async _connect(e){if(!this._abortController?.signal.aborted){if(this.state="connecting",this._wsUrl=e?.wsUrl??e?.ws_url??this._wsUrl,e?.token){const t=this._wsUrl.includes("?")?"&":"?";this._wsUrl=`${this._wsUrl}${t}token=${encodeURIComponent(e.token)}`}if(!this._wsUrl)throw ee.error("No url provided for connection"),this.state="error",new ts;try{if(this._ws=this.initializeWebsocket(),await this._ws.connect(),await this._mediaManager.connect(),this._abortController?.signal.aborted)return;this.state="connected",this._callbacks.onConnected?.()}catch(t){const r=`Failed to connect to websocket: ${t}`;throw ee.error(r),this.state="error",new ts(r)}}}async _disconnect(){this.state="disconnecting",await this._mediaManager.disconnect(),await this._ws?.close(),this.state="disconnected",this._callbacks.onDisconnected?.()}getAllMics(){return this._mediaManager.getAllMics()}getAllCams(){return this._mediaManager.getAllCams()}getAllSpeakers(){return this._mediaManager.getAllSpeakers()}async updateMic(e){return this._mediaManager.updateMic(e)}updateCam(e){return this._mediaManager.updateCam(e)}updateSpeaker(e){return this._mediaManager.updateSpeaker(e)}get selectedMic(){return this._mediaManager.selectedMic}get selectedSpeaker(){return this._mediaManager.selectedSpeaker}enableMic(e){this._mediaManager.enableMic(e)}get isMicEnabled(){return this._mediaManager.isMicEnabled}get state(){return this._state}set state(e){this._state!==e&&(this._state=e,this._callbacks.onTransportStateChanged?.(e))}tracks(){return this._mediaManager.tracks()}initializeWebsocket(){const e=new oi(this._wsUrl,void 0,{parseBlobToJson:!1});return e.keepAliveInterval=0,e.on("open",()=>{ee.debug("Websocket connection opened")}),e.on("message",async t=>{try{const r=await this._serializer.deserialize(t);r.type==="audio"?this._mediaManager.bufferBotAudio(r.audio):r.type==="message"&&r.message.label==="rtvi-ai"&&this._onMessage(r.message)}catch(r){ee.error("Failed to deserialize incoming message",r)}}),e.on("error",t=>{this.connectionError(`websocket error: ${t}`)}),e.on("connection-timeout",()=>{this.connectionError("websocket connection timed out")}),e.on("close",t=>{this.connectionError(`websocket connection closed. Code: ${t}`)}),e.on("reconnect-failed",()=>{this.connectionError("websocket reconnect failed")}),e}sendReadyMessage(){this.state="ready",this.sendMessage(Ce.clientReady())}handleUserAudioStream(e){if(this.state==="ready")try{this.flushAudioQueue(),this._sendAudioInput(e)}catch(t){ee.error("Error sending audio stream to websocket:",t),this.state="error"}else this.audioQueue.push(e)}flushAudioQueue(){if(!(this.audioQueue.length<=0))for(ee.info("Will flush audio queue",this.audioQueue.length);this.audioQueue.length>0;){const e=this.audioQueue.shift();e&&this._sendAudioInput(e)}}sendRawMessage(e){const t=this._serializer.serialize(e);this._sendMsg(t)}sendMessage(e){const t=this._serializer.serializeMessage(e);this._sendMsg(t)}async _sendAudioInput(e){try{const t=this._serializer.serializeAudio(e,this._recorderSampleRate,1);await this._sendMsg(t)}catch(t){ee.error("Error sending audio frame",t)}}async _sendMsg(e){if(!this._ws){ee.error("sendMsg called but WS is null");return}if(this._ws.readyState!==WebSocket.OPEN){ee.error("attempt to send to closed socket");return}if(e)try{await this._ws.send(e)}catch(t){ee.error("sendMsg error",t)}}connectionError(e){this._callbacks.onError?.(Ce.error(e,!0))}enableScreenShare(e){throw ee.warn("enableScreenShare not implemented for WebSocketTransport"),new rn("enableScreenShare","webSocketTransport","This feature has not been implemented")}get isSharingScreen(){return ee.warn("isSharingScreen not implemented for WebSocketTransport"),!1}enableCam(e){throw ee.warn("enableCam not implemented for WebSocketTransport"),new rn("enableCam","webSocketTransport","This feature has not been implemented")}get isCamEnabled(){return ee.warn("isCamEnabled not implemented for WebSocketTransport"),!1}get selectedCam(){throw ee.warn("selectedCam not implemented for WebSocketTransport"),new rn("selectedCam","webSocketTransport","This feature has not been implemented")}}jn.RECORDER_SAMPLE_RATE=16e3;jn.PLAYER_SAMPLE_RATE=24e3;const Xi=24e3,Bd=/websocket connection closed\.\s*Code:\s*(\d+)/i;function Yy(n){const e=Bd.exec(n);if(!e)return null;const t=Number.parseInt(e[1],10);return Number.isFinite(t)?t:null}function $d(n){switch(n){case"quota_exhausted":return"Your shared credits can't fund another voice exchange.";case"billing_unavailable":return"Connection to billing lost — session ended. Your credits weren’t over-charged. Try again.";case"service_unavailable":return"Voice service is temporarily unavailable.";case"auth_failed":return"Your session expired. Sign in again to use voice chat.";case"bad_params":return"Voice chat couldn’t start — please try again.";case"concurrent_session":return"You already have an active voice session.";default:return"Connection lost — try again."}}function dl(n){let e;switch(n){case 4429:e="quota_exhausted";break;case 4500:e="billing_unavailable";break;case 4503:e="service_unavailable";break;case 4401:e="auth_failed";break;case 4400:e="bad_params";break;case 1008:e="concurrent_session";break;default:e="network_drop";break}return{kind:e,message:$d(e)}}function Xy(n){const{chatSessionId:e,getAccessToken:t,provider:r,ttsSpeed:i}=n,[s,a]=w.useState("idle"),[o,l]=w.useState(null),[u,f]=w.useState(null),[g,_]=w.useState(null),[k,b]=w.useState([]),[v]=w.useState("NEUTRAL"),[E,C]=w.useState(!1),[O,j]=w.useState(0),[S,x]=w.useState(null),[T,I]=w.useState("normal"),[F,$]=w.useState("idle_neutral"),z=w.useRef(null),fe=w.useRef(null),me=w.useRef(!1),je=w.useRef(!1),_e=w.useRef(null),Te=w.useRef(0),Ie=w.useRef(!1),Re=w.useRef("idle"),ke=w.useRef(null),ie=w.useRef(!1),Se=w.useRef(null),Ne=w.useRef(0);w.useEffect(()=>{Re.current=s},[s]);const Be=w.useCallback(()=>{Se.current!==null&&(cancelAnimationFrame(Se.current),Se.current=null),Ne.current=0},[]),c=w.useCallback(()=>
340{if(Se.current!==null)return;const N=-58,P=-25,R=()=>{const V=fe.current?._wavStreamPlayer;if(V?.analyser)try{const{values:U}=V.getFrequencies("voice",N,P);let ye=0;for(let xe=0;xe<U.length;xe++)U[xe]>ye&&(ye=U[xe]);const ge=Math.pow(ye,1.2),$e=Math.min(ge*1.5,1);Ne.current=Ne.current*.15+$e*.85}catch{}Se.current=requestAnimationFrame(R)};Se.current=requestAnimationFrame(R)},[]),p=w.useCallback(async()=>{Be();try{await z.current?.disconnect()}catch{}if(z.current=null,fe.current=null,ke.current){try{URL.revokeObjectURL(ke.current)}catch{}ke.current=null}x(null),I("normal"),$("idle_neutral")},[Be]),h=w.useCallback(async()=>{if(Ie.current||Re.current==="connecting"||Re.current==="live")return;Ie.current=!0;const N=++Te.current,P=()=>N!==Te.current||me.current;l(null),f(null),_(null),b([]),je.current=!1,_e.current=null,a("connecting"),me.current=!1;try{const R=await t();if(P())return;if(!R)throw new Error("Not signed in");const B={};e&&(B.chatSessionId=e),r&&(B.provider=r),typeof i=="number"&&Number.isFinite(i)&&(B.tts_speed=i);const V=await fetch(`${Sr}/api/chat/realtime/precheck`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${R}`},body:JSON.stringify(B)});if(P())return;if(!V.ok){const Z=await V.json().catch(()=>({}));throw V.status===403&&Z?.error==="QUOTA_EXCEEDED"?(_e.current="quota_exhausted",f("quota_exhausted")):V.status===401?(_e.current="auth_failed",f("auth_failed")):V.status===503&&(_e.current="service_unavailable",f("service_unavailable")),new Error(Z?.message||Z?.error||`precheck failed (${V.status})`)}const{wsUrl:U}=await V.json();if(P())return;if(!U)throw new Error("precheck returned no wsUrl");const ye=new Ty(void 0,Xi);fe.current=ye;try{const Z=ye._wavStreamPlayer;if(Z){const se=`
341// [shizen-patched-worklet v2]
342// Patches the stock @pipecat-ai/websocket-transport StreamProcessor to:
343//   1. Pre-fill 48 buffers (~128ms @ 24kHz) before starting
344//      output. Absorbs OpenAI Realtime's start-of-turn jitter without
345//      adding noticeable latency.
346//   2. Stay alive on mid-stream underrun (outputs silence + re-arms
347//      pre-fill) instead of terminating. Eliminates the worklet-recycle
348//      cycle that the stock worklet's 'stop on empty' behavior causes.
349//
350// Marker in worklet thread console: '[shizen-worklet] processor created'.
351class StreamProcessor extends AudioWorkletProcessor {
352  constructor() {
353    super();
354    this.hasInterrupted = false;
355    this.outputBuffers = [];
356    this.bufferLength = 128;
357    this.write = { buffer: new Float32Array(this.bufferLength), trackId: null };
358    this.writeOffset = 0;
359    this.trackSampleOffsets = {};
360    // Pre-fill state. 'priming' = collecting buffers, output silence.
361    // 'playing' = draining buffers, output real audio. On mid-stream
362    // underrun we flip back to 'priming' to rebuild the cushion before
363    // resuming (otherwise we'd play a stutter then re-underrun).
364    this.mode = 'priming';
365    this.prefillTarget = 48;
366    // eslint-disable-next-line no-console
367    console.log('[shizen-worklet] processor created (prefill=' + this.prefillTarget + ' buffers)');
368    this.port.onmessage = (event) => {
369      if (event.data) {
370        const payload = event.data;
371        if (payload.event === 'write') {
372          const int16Array = payload.buffer;
373          const float32Array = new Float32Array(int16Array.length);
374          for (let i = 0; i < int16Array.length; i++) {
375            float32Array[i] = int16Array[i] / 0x8000;
376          }
377          this.writeData(float32Array, payload.trackId);
378        } else if (payload.event === 'offset' || payload.event === 'interrupt') {
379          const requestId = payload.requestId;
380          const trackId = this.write.trackId;
381          const offset = this.trackSampleOffsets[trackId] || 0;
382          this.port.postMessage({ event: 'offset', requestId, trackId, offset });
383          if (payload.event === 'interrupt') {
384            this.hasInterrupted = true;
385          }
386        } else {
387          throw new Error('Unhandled event "' + payload.event + '"');
388        }
389      }
390    };
391  }
392
393  writeData(float32Array, trackId = null) {
394    let { buffer } = this.write;
395    let offset = this.writeOffset;
396    for (let i = 0; i < float32Array.length; i++) {
397      buffer[offset++] = float32Array[i];
398      if (offset >= buffer.length) {
399        this.outputBuffers.push(this.write);
400        this.write = { buffer: new Float32Array(this.bufferLength), trackId };
401        buffer = this.write.buffer;
402        offset = 0;
403      }
404    }
405    this.writeOffset = offset;
406    return true;
407  }
408
409  process(inputs, outputs, parameters) {
410    const output = outputs[0];
411    const outputChannelData = output[0];
412
413    if (this.hasInterrupted) {
414      // User barge-in. Tear down the worklet as the stock impl does.
415      this.port.postMessage({ event: 'stop' });
416      return false;
417    }
418
419    // Priming: hold output silent until buffer depth reaches target.
420    if (this.mode === 'priming') {
421      if (this.outputBuffers.length >= this.prefillTarget) {
422        this.mode = 'playing';
423      } else {
424        // outputChannelData is already zero-filled by Web Audio.
425        return true;
426      }
427    }
428
429    // Playing: drain one buffer per process() tick.
430    if (this.outputBuffers.length) {
431      const { buffer, trackId } = this.outputBuffers.shift();
432      for (let i = 0; i < outputChannelData.length; i++) {
433        outputChannelData[i] = buffer[i] || 0;
434      }
435      if (trackId) {
436        this.trackSampleOffsets[trackId] = this.trackSampleOffsets[trackId] || 0;
437        this.trackSampleOffsets[trackId] += buffer.length;
438      }
439      return true;
440    }
441
442    // Mid-stream underrun. Drop back to priming so we can rebuild the
443    // cushion before resuming. Output silence this tick and stay alive.
444    this.mode = 'priming';
445    return true;
446  }
447}
448
449registerProcessor('stream_processor', StreamProcessor);
450`,Ae=new Blob([se],{type:"application/javascript"}),nt=URL.createObjectURL(Ae);ke.current=nt,Z.scriptSrc=nt,console.log("[shizen-worklet] scriptSrc swapped on WavStreamPlayer")}else console.warn("[shizen-worklet] WavStreamPlayer not found — patch SKIPPED")}catch(Z){console.warn("[shizen-worklet] could not patch WavStreamPlayer worklet:",Z)}const ge=new jn({mediaManager:ye,serializer:new Fd,recorderSampleRate:Xi,playerSampleRate:Xi}),$e=new ct({transport:ge,enableMic:!0,enableCam:!1,callbacks:{onConnected:()=>{a("live")},onDisconnected:()=>{C(!1),Be(),!me.current&&_e.current===null&&l(Z=>Z??"Voice chat disconnected."),a("idle")},onError:Z=>{const te=Z?.data,se=te?.message||te?.error||Z?.type||"Realtime error",Ae=Yy(se),nt=Bd.test(se);if(Ae!==null||nt){const St=dl(Ae);_e.current=St.kind,f(St.kind),l(St.message)}else je.current?(_e.current="billing_unavailable",f("billing_unavailable"),l(St=>St??dl(null).message)):(_e.current=null,f(null),l(se))},onBotStartedSpeaking:()=>{C(!0),c(),j(Z=>Z+1),ie.current=!0},onBotStoppedSpeaking:()=>{C(!1),Be()},onBotLlmText:Z=>{if(!Z.text)return;const te=ie.current;te&&(ie.current=!1),b(se=>{const Ae=se[se.length-1];return!te&&Ae&&Ae.role==="assistant"?[...se.slice(0,-1),{...Ae,text:Ae.text+Z.text}]:[...se,{role:"assistant",text:Z.text,ts:new Date().toISOString()}]})},onServerMessage:Z=>{if(!Z||typeof Z!="object")return;const te=Z;if(te.type==="avatar_face"&&typeof te.expression=="string")I(te.expression);else if(te.type==="avatar_motion"&&typeof te.motion=="string")$(te.motion);else if(te.type==="credit_warning"||te.type==="quota_warning"){const se=Number(te.credits_remaining);_({kind:"credit_warning",creditsRemaining:Number.isFinite(se)?se:null})}else if(te.type==="session_ending"){const se=typeof te.reason=="string"?te.reason:"";(se==="quota_exhausted"||se==="billing_unavailable"||se==="upstream_failed")&&(je.current=!0)}}}});z.current=$e;const xe=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices),pe={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,echoCancellationType:"system"},Ee=async Z=>{const te=Z?.audio,se=te===!0||te===void 0?pe:{...te,...pe},Ae={...Z,audio:se};return xe(Ae)};navigator.mediaDevices.getUserMedia=Ee;try{await $e.connect({wsUrl:U})}finally{navigator.mediaDevices.getUserMedia=xe}if(ke.current){try{URL.revokeObjectURL(ke.current)}catch{}ke.current=null}if(P()){await p();return}try{const te=ye.tracks()?.local?.audio;te&&x(new MediaStream([te]))}catch{}}catch(R){if(P()){await p();return}const B=_e.current;l(B?$d(B):R instanceof Error?R.message:String(R)),a("error"),await p()}finally{N===Te.current&&(Ie.current=!1)}},[t,e,r,i,c,Be,p]),m=w.useCallback(()=>{_(null)},[]),y=w.useCallback(async()=>{me.current=!0,Te.current++,Ie.current=!1,a("closing"),await p(),a("idle")},[p]);return w.useEffect(()=>()=>{me.current=!0,Te.current++,Ie.current=!1,p()},[p]),w.useMemo(()=>({status:s,error:o,errorKind:u,notice:g,dismissNotice:m,transcript:k,emotion:v,isBotSpeaking:E,mouthOpenYRef:Ne,bigNodSignal:O,micStream:S,agentFace:T,agentMotion:F,start:h,stop:y}),[s,o,u,g,m,k,v,E,O,S,T,F,h,y])}const Qy=45e3,Zy=1e4,ew=.015,tw=250,nw=1e3;function rw(n){const{active:e,micStream:t,isBotSpeaking:r,idleMs:i=Qy,warnMs:s=Zy,speechRmsThreshold:a=ew,onWarn:o,onPause:l,onActivityResume:u}=n,f=w.useRef(Date.now()),g=w.useRef(!1),_=w.useRef(!1),k=w.useRef(r),b=w.useRef(o),v=w.useRef(l),E=w.useRef(u);w.useEffect(()=>{k.current=r},[r]),w.useEffect(()=>{b.current=o},[o]),w.useEffect(()=>{v.current=l},[l]),w.useEffect(()=>{E.current=u},[u]);const C=w.useCallback(()=>{f.current=Date.now(),g.current&&(g.current=!1,E.current?.())},[]),O=w.useCallback(()=>{_.current=!1,C()},[C]);return w.useEffect(()=>{e&&r&&C()},[e,r,C]),w.useEffect(()=>{if(!e)return;f.current=Date.now(),g.current=!1,_.current=!1;const j=setInterval(()=>{if(k.current){f.current=Date.now();return}if(_.current)return;const S=Date.now()-f.current;S>=i?(_.current=!0,v.current()):S>=i-s&&!g.current&&(g.current=!0,b.current())},nw);return()=>clearInterval(j)},[e,i,s]),w.useEffect(()=>{if(!e||!t)return;const j=window.AudioContext??window.webkitAudioContext;if(!j)return;let S=!1,x=null,T=null,I=null;try{x=new j,T=x.createMediaStreamSource(t);const F=x.createAnalyser();F.fftSize=512,T.connect(F);const $=new Float32Array(F.fftSize);I=setInterval(()=>{if(S)return;F.getFloatTimeDomainData($);let z=0;for(let me=0;me<$.length;me++)z+=$[me]*$[me];Math.sqrt(z/$.length)>=a&&C()},tw)}catch{}return()=>{S=!0,I&&clearInterval(I);try{T?.disconnect()}catch{}try{x?.close()}catch{}}},[e,t,a,C]),{keepAlive:O}}function iw(n){return[{id:"welcome",type:"card",content:d.jsxs("div",{className:"ch-tour-welcome",children:[d.jsx("img",{className:"wc-tour-welcome-art",src:"/watercolor/system-v2/modules/journey-conversation.webp",width:"96",height:"96",alt:""}),d.jsx("h2",{className:"ch-tour-welcome-title",children:"Meet Your Conversation Partner"}),d.jsx("p",{className:"ch-tour-welcome-lede",children:"Your personal conversation partner — she knows your approximate Japanese level and adapts her speech accordingly. Simpler words for beginners, more natural Japanese as you improve."}),d.jsx(Or.div,{initial:{opacity:0,y:8}
450,animate:{opacity:1,y:0},transition:{delay:.3,duration:.4},className:"ch-tour-welcome-bubbles",children:["初めまして","こんにちは","お元気ですか"].map((e,t)=>d.jsx(Or.span,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{delay:.4+t*.1,duration:.35},className:"ch-tour-welcome-bubble jp",children:e},e))}),d.jsx("p",{className:"ch-tour-welcome-hint",children:"Conversation practice · Adapts to your level"})]})},{id:"overview-hub",type:"navigate",targetId:"chat-sidebar-overview",title:"Three Ways to Practice",position:"right",spotlightPadding:6,onEnter:()=>n.navigateToTab("overview"),content:d.jsxs("p",{children:["The ",d.jsx("strong",{children:"Overview"})," hub is your starting point. Pick a lesson to review, jump into a roleplay scene, or just start a free chat — three different ways to practice from a single screen."]})},{id:"lesson-review",type:"navigate",targetId:"chat-sidebar-lesson-review",title:"Lesson Review",position:"right",spotlightPadding:6,onEnter:()=>n.navigateToTab("overview"),content:d.jsxs("p",{children:[d.jsx("strong",{children:"Lesson Review"})," mode loads a grammar lesson into the tutor’s memory, then she walks you through it again and quizzes you in conversation. Best after you finish a fresh lesson."]})},{id:"roleplay",type:"navigate",targetId:"chat-sidebar-roleplay",title:"Roleplay Scenarios",position:"right",spotlightPadding:6,onEnter:()=>n.navigateToTab("overview"),content:d.jsxs("p",{children:[d.jsx("strong",{children:"Roleplay"})," drops you into a real-world scene — a restaurant, a konbini, asking for directions. The tutor stays in character; you respond in Japanese as the scene unfolds."]})},{id:"free-chat",type:"navigate",targetId:"chat-sidebar-free-chat",title:"Open conversation",position:"right",spotlightPadding:6,onEnter:()=>n.navigateToTab("overview"),content:d.jsxs("p",{children:[d.jsx("strong",{children:"Open conversation"})," is open-ended — no script, no goal. Talk about the weather, your day, your favorite show. Useful when you want to just stretch your speaking muscles."]})},{id:"avatar",type:"navigate",targetId:"chat-avatar",title:"Animated Tutor",position:"bottom",spotlightPadding:6,onEnter:()=>n.navigateToTab("free-chat"),onExit:()=>n.navigateToTab("overview"),content:d.jsxs("p",{children:["Your tutor has ",d.jsx("strong",{children:"facial animations"})," that express emotion based on the conversation, giving a more natural interaction."]})}]}function sw({onComplete:n,onSkip:e,tourActions:t}){const r=w.useRef(n);r.current=n;const i=w.useRef(e);i.current=e;const s=w.useMemo(()=>({id:"chat-tour",steps:iw(t),storageKey:"chat.onboarding.completed",onComplete:()=>{Fe("chat_tour_completed"),r.current()},onSkip:()=>{Fe("chat_tour_skipped"),t.ensureTextMode(),t.navigateToTab("overview"),i.current()}}),[t]),{markCompleted:a}=xl("chat");return d.jsx(ff,{config:s,autoStart:!0,finishLabel:"Start",accent:"lake",onPersistCompletion:()=>{a()}})}function hl(n,e){return n instanceof Error&&n.message?n.message:typeof n=="string"&&n.length>0?n:e}function aw(n){if(n instanceof Error&&"code"in n){const e=n.code;if(typeof e=="string")return e}}function ow({user:n,getAccessToken:e,openAuthModal:t}){const[r,i]=w.useState(null),[s,a]=w.useState([]),o=w.useCallback(k=>{i(k),k?sessionStorage.setItem("chat.sessionId",k):sessionStorage.removeItem("chat.sessionId")},[]),l=w.useCallback(async()=>{if(!n)return a([]),[];try{const k=await e();if(!k)return a([]),[];Ye.setAccessToken(k);const v=(await Ye.getChatSessions()).sessions||[];return a(v),v}catch(k){return console.error("Failed to load chat sessions:",k),[]}},[n,e]),u=w.useCallback(async k=>{try{const b=await e();if(!b)return t("signup"),{sessionId:null};Ye.setAccessToken(b);const v=s.length===0,E=await Ye.createChatSession(k),C=E.sessionId;if(!C)throw Object.assign(new Error("Chat session response did not include an id"),{code:"INVALID_RESPONSE"});return o(C),Fe("chat_session_started",{is_first_session:v,mode:E.mode}),await l(),{sessionId:C,mode:E.mode,scenarioId:E.scenarioId,lessonNumber:E.lessonContext?.lessonNumber??null,lessonTitle:E.lessonContext?.lessonTitle??null}}catch(b){return console.error("Failed to create chat session:",b),o(null),{sessionId:null,error:{code:aw(b),message:hl(b,"Failed to start chat session")}}}},[l,e,t,s.length,o]),f=w.useCallback((k,b)=>!k||k===r?!1:(o(k),Fe("chat_session_resumed",{...typeof b=="number"&&Number.isFinite(b)?{message_count:Math.max(0,Math.trunc(b))}:{}}),!0),[r,o]),g=w.useCallback(async(k,b)=>{const v=r===k,E=s,C=s.filter(j=>j.id!==k),O=v&&C.length>0?C[0].id:null;a(C),v&&o(O);try{const j=await e();return j?(Ye.setAccessToken(j),await Ye.deleteChatSession(k),Fe("chat_session_deleted",{...typeof b=="number"&&Number.isFinite(b)?{message_count:Math.max(0,Math.trunc(b))}:{}}),{fallbackSessionId:O,wasActive:v}):(a(E),t("signup"),{fallbackSessionId:null,wasActive:!1})}catch(j){return console.error("Failed to delete chat session:",j),a(E),{fallbackSessionId:null,wasActive:!1,error:{message:hl(j,"Failed to delete conversation")}}}},[e,t,r,s,o]),_=w.useCallback(k=>{if(!k)return"Just now";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(k))}catch{return k}},[]);return w.useEffect(()=>{if(!n){a([]);return}l()},[n,l]),{sessionId:r,setSessionId:o,sessions:s,fetchSessions:l,createSession:u,selectSession:f,deleteSession:g,formatSessionTimestamp:_}}function cw({getAccessToken:n}){const[e,t]=w.useState([]),r=w.useCallback(async i=>{try{const s=await n();if(!s)return;Ye.setAccessToken(s);
450const o=(await Ye.getChatMessages(i)).messages.map(l=>({id:l.id,role:l.role,content:l.content_text,createdAt:l.created_at}));t(o)}catch(s){console.error("Failed to load messages:",s)}},[n]);return{messages:e,setMessages:t,loadMessages:r}}const lw="/assets/classroombackground-DDKQsyOZ.webp",uw="/assets/classroomforeground-DbK7Gdio.webp",dw="#6494ce";function hw(n){return n==="lesson_review"||n==="roleplay"?n:"free_chat"}function fw(n){return n.previousStatus==="live"||n.nextStatus!=="live"?null:{mode:n.mode,provider:n.provider,is_resumed:n.messageCount>0,message_count:Math.max(0,Math.trunc(n.messageCount)),...typeof n.connectionLatencyMs=="number"?{connection_latency_ms:Math.max(0,Math.trunc(n.connectionLatencyMs))}:{}}}function pw({assistantText:n,mode:e,provider:t,turnIndex:r,responseDurationMs:i}){const s=n.trim().length;if(s===0)return[];const a={input_mode:"voice_realtime",mode:e,provider:t,turn_index:Math.max(1,Math.trunc(r))};return[{event:"chat_user_turn_finalized",properties:a},{event:"chat_assistant_turn_completed",properties:{...a,response_char_count:s,response_duration_ms:Math.max(0,Math.trunc(i))}}]}function n_(){const{user:n,getAccessToken:e}=Hr(),{openAuthModal:t}=Sh(),{isPro:r,refresh:i}=xh(),{openUpgradeModal:s}=Eh(),a=fl(),{tab:o}=Xd(),{loading:l,completed:u}=xl("chat"),[f,g]=w.useState(!1),_=!l&&!u&&!f,k=["overview","lesson-review","roleplay","free-chat","settings"],b=o&&k.includes(o)?o:"overview";Nh(b);const v=w.useMemo(()=>[{id:"overview",label:"Overview",iconSrc:pl,description:"Pick a mode and start a chat",isHub:!0},{id:"lesson-review",label:"Lesson Review",iconSrc:Os,description:"Reinforce what you studied"},{id:"roleplay",label:"Roleplay",iconSrc:js,description:"Practice a real-world scene"},{id:"free-chat",label:"Open conversation",iconSrc:Ps,description:"No script, just talk"},{id:"settings",label:"Settings",iconSrc:ml,description:"Conversation practice preferences"}],[]);Ch(v,b,D=>{k.includes(D)&&a(`/chat/${D}`)},dw);const E=w.useCallback(D=>{const ae={"lesson-review":"lesson_review",roleplay:"roleplay","free-chat":"free_chat"}[D];ae&&Fe("chat_mode_selected",{mode:ae,source:"sidebar"}),w.startTransition(()=>a(`/chat/${D}`))},[a]),{sessionId:C,setSessionId:O,sessions:j,createSession:S,deleteSession:x}=ow({user:n,getAccessToken:e,openAuthModal:t}),{messages:T,setMessages:I,loadMessages:F}=cw({getAccessToken:e}),$=j.find(D=>D.id===C)??null,z=$?.mode??"free_chat",fe=$?.scenarioId??null,[me,je]=w.useState(!1),[_e]=w.useState(null),[Te,Ie]=w.useState("NEUTRAL"),[Re]=w.useState(0),[ke,ie]=w.useState(null),[Se,Ne]=w.useState(null);w.useEffect(()=>{if(!n){Ne(null);return}let D=!1;return(async()=>{try{const re=await e();if(!re||D)return;Ye.setAccessToken(re);const ae=await Ye.getChatRecentSessions();D||Ne(ae.sessions[0]??null)}catch{D||Ne(null)}})(),()=>{D=!0}},[n,e]);const Be=w.useCallback(D=>{const re=D.mode==="free_chat"?"free-chat":D.mode==="lesson_review"?"lesson-review":"roleplay",ae=D.sessionId?`?resume=${encodeURIComponent(D.sessionId)}`:"";a(`/chat/${re}${ae}`)},[a]),{realtimeProvider:c,ttsSpeed:p,setTtsSpeed:h}=jl(),m=Xy({chatSessionId:C??void 0,getAccessToken:e,provider:c,ttsSpeed:p}),y=w.useRef(null),N=w.useRef("free_chat"),P=w.useRef(0),R=w.useRef(m.status),B=w.useRef(m.isBotSpeaking),V=w.useRef(null),U=w.useRef(!1),ye=w.useRef(null),ge=w.useCallback(D=>{N.current=D??hw($?.mode),y.current=Date.now(),m.start()},[$?.mode,m]);w.useEffect(()=>{const D=R.current,re=m.status;R.current=re;const ae=y.current,Dn=fw({previousStatus:D,nextStatus:re,mode:N.current,provider:c,messageCount:T.length,...ae===null?{}:{connectionLatencyMs:Date.now()-ae}});Dn&&(Fe("chat_voice_session_started",Dn),P.current=0,ye.current=null,y.current=null)},[T.length,m.status,c]),w.useEffect(()=>{const D=B.current,re=m.isBotSpeaking;if(B.current=re,!D&&re){V.current=Date.now(),U.current=!1;return}if(D&&!re&&(U.current=!0),re||!U.current)return;const ae=[...m.transcript].reverse().find(nr=>nr.role==="assistant"&&nr.text.trim().length>0);if(!ae||ae.ts===ye.current)return;const Dn=P.current+1,xa=V.current,Ea=pw({assistantText:ae.text,mode:N.current,provider:c,turnIndex:Dn,responseDurationMs:xa===null?0:Date.now()-xa});for(const{event:nr,properties:Hd}of Ea)Fe(nr,Hd);Ea.length>0&&(P.current=Dn,ye.current=ae.ts,U.current=!1)},[m.isBotSpeaking,m.transcript,c]);const $e=c==="inworld"?{ttsSpeed:p,onTtsSpeedChange:h}:{};w.useEffect(()=>{m.error&&ie(m.error)},[m.error]);const xe=w.useRef(null);
450w.useEffect(()=>{const D=m.errorKind;if(!D){xe.current=null;return}xe.current!==D&&(xe.current=D,D==="quota_exhausted"&&(i(),Mh()&&s("voice_chat","voice_quota_exhausted")))},[m.errorKind,i,s]);const pe=w.useRef(m.status);w.useEffect(()=>{const D=pe.current,re=m.status;pe.current=re,D==="live"&&(re==="idle"||re==="error")&&i()},[m.status,i]);const[Ee,Z]=w.useState(0);w.useEffect(()=>{if(m.status!=="live"){(m.status==="idle"||m.status==="error")&&Z(0);return}const D=Date.now();Z(0);const re=setInterval(()=>{Z(Math.floor((Date.now()-D)/1e3))},1e3);return()=>clearInterval(re)},[m.status]);const[te,se]=w.useState("none"),Ae=w.useCallback(()=>se("warning"),[]),nt=w.useCallback(()=>{m.stop(),se("paused")},[m]),St=w.useCallback(()=>se(D=>D==="warning"?"none":D),[]),ci=rw({active:m.status==="live",micStream:m.micStream,isBotSpeaking:m.isBotSpeaking,onWarn:Ae,onPause:nt,onActivityResume:St});w.useEffect(()=>{(m.status==="connecting"||m.status==="live")&&se("none")},[m.status]);const li=te==="warning"?{realtimeNotice:"Still there? I’ll pause this conversation soon.",noticeActionLabel:"Keep going",onDismissNotice:()=>{ci.keepAlive(),se("none")}}:te==="paused"?{realtimeNotice:"Paused because you seemed away — tap Resume to continue.",onDismissNotice:()=>se("none")}:m.notice?.kind==="credit_warning"?{realtimeNotice:m.notice.creditsRemaining===null?"Your shared credit balance is running low.":`${m.notice.creditsRemaining.toLocaleString()} shared credits remaining.`,onDismissNotice:m.dismissNotice}:{},pa="var(--brand-reading)",Ud=w.useMemo(()=>({ensureVoiceMode:()=>{},ensureTextMode:()=>{},navigateToTab:D=>a(`/chat/${D}`)}),[a]);w.useEffect(()=>{if(!_)return;const D=document.documentElement,re=D.style.getPropertyValue("--module-accent");return D.style.setProperty("--module-accent","var(--brand-reading)"),()=>D.style.setProperty("--module-accent",re)},[_]);const[ui,ma]=w.useState(null),[Vd,di]=w.useState(!1),ga=w.useCallback(async()=>{const D=await S();return D.sessionId?(I([]),D.sessionId):(D.error&&(D.error.code==="SESSION_LIMIT"?ie("You have too many conversations. Delete old ones to start a new chat."):ie(D.error.message)),null)},[S,I]),va=w.useCallback(async(D,re)=>{if(!n){t("signup");return}Fe("chat_lesson_review_selected",{lesson_number:D,source:"picker"});const ae=await S({mode:"lesson_review",lessonNumber:D});if(ae.error){ie(ae.error.message);return}ae.sessionId&&(Fe("chat_lesson_review_started",{lesson_number:D,source:"picker"}),I([]),F(ae.sessionId))},[S,F,t,I,n]),ba=w.useCallback(async(D,re)=>{if(!n){t("signup");return}Fe("chat_roleplay_selected",{scenario_id:D,source:"picker"});const ae=await S({mode:"roleplay",scenarioId:D});if(ae.error){ie(ae.error.message);return}ae.sessionId&&(Fe("chat_roleplay_started",{scenario_id:D,source:"picker"}),I([]),F(ae.sessionId))},[S,F,t,I,n]),zd=w.useCallback(async D=>{if(!D||D===$?.scenarioId)return;const re=m.status==="live"||m.status==="connecting";re&&await m.stop();const ae=await S({mode:"roleplay",scenarioId:D});if(ae.error){ie(ae.error.message);return}ae.sessionId&&(Fe("chat_roleplay_scene_switched",{scenario_id:D}),I([]),F(ae.sessionId),ie(null),re&&m.start())},[$?.scenarioId,S,F,m,I]),ya=w.useCallback(()=>{O(null),I([])},[O,I]),wa=w.useCallback(async D=>{(m.status==="live"||m.status==="connecting")&&await m.stop();const re=await S({mode:"lesson_review",lessonNumber:D});if(re.error){ie(re.error.message);return}re.sessionId&&(Fe("chat_lesson_review_started",{lesson_number:D,source:"restart"}),I([]),F(re.sessionId),ie(null),ge("lesson_review"))},[ge,S,F,m,I]),_a=w.useCallback(async D=>{(m.status==="live"||m.status==="connecting")&&await m.stop();const re=await S({mode:"roleplay",scenarioId:D});if(re.error){ie(re.error.message);return}re.sessionId&&(Fe("chat_roleplay_started",{scenario_id:D,source:"restart"}),I([]),F(re.sessionId),ie(null),ge("roleplay"))},[ge,S,F,m,I]),ka=w.useCallback(async()=>{(m.status==="live"||m.status==="connecting")&&await m.stop();const D=await S({mode:"free_chat"});if(D.error){ie(D.error.message);return}D.sessionId&&(I([]),F(D.sessionId),ie(null),ge("free_chat"))},[ge,S,F,m,I]),Wd=w.useCallback(()=>{$?.mode==="lesson_review"&&$.lessonNumber!=null?wa($.lessonNumber):$?.mode==="roleplay"&&$.scenarioId?_a($.scenarioId):$?.mode==="free_chat"&&ka()},[$,wa,_a,ka]),qd=w.useCallback(async D=>{const re=D===C?T.length:void 0,ae=await x(D,re);if(ae.error){ie(ae.error.message);return}ae.wasActive&&(ae.fallbackSessionId?F(ae.fallbackSessionId):I([]))},[x,F,T.length,C,I]),Jd=T.filter(D=>D.role==="assistant").slice(-1)[0]?.content||"",hi=pf({messageContent:Jd,isSpeaking:m.isBotSpeaking});w.useEffect(()=>{Ie(m.emotion)},[m.emotion]),w.useEffect(()=>{!me&&(_e||T.some(D=>D.role==="assistant"))&&je(!0)},[_e,me,T]),w.useEffect(()=>{n||O(null)},[n,O]);const Ln=w.useRef(!1),[fi,tr]=w.useState(!1);w.useEffect(()=>{(m.status==="live"||m.status==="idle"||m.status==="error")&&(Ln.
450current=!1,tr(!1))},[m.status]);const pi=w.useCallback(async()=>{if(!n){t("signup");return}if(!Ln.current){Ln.current=!0,tr(!0);try{if(!C&&!await ga()){Ln.current=!1,tr(!1);return}ie(null),ge()}catch{Ln.current=!1,tr(!1)}}},[ge,n,t,C,ga]),mi=w.useCallback(()=>{m.stop()},[m]),gi=w.useCallback(()=>di(!0),[]),Gd=$?.mode==="lesson_review"?"Lesson Review":$?.mode==="roleplay"?"Roleplay":"Open conversation";Ah({onBackground:w.useCallback(()=>{m.stop()},[m])});const Sa=w.useRef(m.stop);return w.useEffect(()=>{Sa.current=m.stop},[m.stop]),w.useEffect(()=>()=>{Sa.current()},[]),d.jsxs("div",{className:`wc-root ch-logged${n&&b==="overview"?" wc-overview-refresh":""}${!n&&b==="overview"?" wc-module-public module-landing":""}`,"data-module":"chat",children:[d.jsx(kp,{mode:z,scenarioId:fe}),d.jsx("div",{className:"ch-logged-content",children:d.jsxs("div",{className:`ch-shell${!n&&b==="overview"?" ml-shell":""}${!n&&b!=="overview"?" ch-guest-app":""}`,children:[d.jsx(xf,{activeSection:b,onSectionChange:E,publicOverview:!n&&b==="overview"}),d.jsxs("div",{className:`ch-body${!n&&b==="overview"?" ml-body":""}`,"data-active-tab":b,children:[b==="overview"&&!n&&d.jsx(Pp,{}),b==="overview"&&n&&d.jsxs("header",{className:"ch-page-header",children:[d.jsx("h1",{className:"ch-page-title",children:d.jsx(Wn,{paint:"blue",children:"Conversation"})}),n?d.jsx("p",{className:"ch-page-lede",children:"Practise a lesson, try an everyday scene, or talk about your day with an AI practice partner."}):d.jsxs(d.Fragment,{children:[d.jsxs("p",{className:"hero-lede wc-herolede-full",children:[d.jsx("span",{className:"break",children:"You’ve read the grammar and studied the words — but the moment someone speaks to you, your mind goes blank."}),"Your tutor is a ",d.jsx("em",{children:"patient conversation partner"}),": it waits while you find the words, corrects you as you speak,",d.jsx("span",{className:"break",children:"and pitches every reply to your level."}),"No audience, no time pressure, no embarrassment."]}),d.jsxs("p",{className:"hero-lede wc-herolede-mobile",children:["A ",d.jsx("em",{children:"patient conversation partner"})," that waits while you find the words, corrects you as you speak, and pitches every reply to your level."]})]}),!n&&d.jsxs(d.Fragment,{children:[d.jsx(Cl,{}),d.jsxs("div",{className:"hero-ctas ch-hero-ctas",children:[d.jsx(Th,{as:"button",onClick:()=>t("signup"),variant:"lake",children:"Sign up for free"}),d.jsxs("button",{type:"button",onClick:()=>a("/chat/free-chat"),className:"wc-hero-link",children:["Try a conversation ",d.jsx("span",{className:"arrow","aria-hidden":"true",children:"→"})]})]})]})]}),b==="settings"&&d.jsxs("header",{className:"ch-page-header",children:[d.jsx("h1",{className:"ch-page-title",children:d.jsx(Wn,{paint:"blue",children:"Settings"})}),d.jsx("p",{className:"ch-page-lede",children:"Conversation practice preferences and billing."})]}),b==="overview"&&n&&Se&&d.jsx("div",{className:"ch-resume-slot",children:d.jsx(ap,{candidate:Se,onResume:Be})}),n&&d.jsx(Nf,{}),d.jsxs("div",{className:`ch-main${!n&&b==="overview"?" ml-main":""}`,children:[d.jsx(Yr,{children:ke&&d.jsx(El,{message:ke,variant:"error",onDismiss:()=>ie(null)})}),b==="overview"&&(n?d.jsx(rp,{}):d.jsx(jp,{})),b==="lesson-review"&&($?.mode==="lesson_review"?d.jsx(Ra,{onPick:va,activeSession:{lessonTitle:$.lessonTitle??void 0,lessonNumber:$.lessonNumber??void 0},onBack:ya,chatConversation:d.jsx(yi,{messages:T,liveTranscript:m.transcript,isBotSpeaking:m.isBotSpeaking,mouthOpenYRef:m.mouthOpenYRef,bigNodSignal:m.bigNodSignal,agentFace:m.agentFace,agentMotion:m.agentMotion,expression:hi,currentEmotion:Te,live2dKey:Re,realtimeStatus:m.status,realtimeError:m.error,onStartVoice:()=>{pi()},onStopVoice:mi,startPending:fi,sessionElapsedSeconds:Ee,onStartFreshConversation:gi,isPro:r,greetingMessage:_e,...$e,...li,backgroundSrc:lw,foregroundSrc:uw,avatarPlacement:{scale:.82,top:-.02,anchorY:0}})}):d.jsx(Ra,{onPick:va})),b==="roleplay"&&($?.mode==="roleplay"?d.jsx(Da,{onPick:ba,activeSession:{scenarioId:$.scenarioId??null},onBack:ya,chatConversation:d.jsx(yi,{messages:T,liveTranscript:m.transcript,isBotSpeaking:m.isBotSpeaking,mouthOpenYRef:m.mouthOpenYRef,bigNodSignal:m.bigNodSignal,agentFace:m.agentFace,agentMotion:m.agentMotion,expression:hi,currentEmotion:Te,live2dKey:Re,realtimeStatus:m.status,realtimeError:m.error,onStartVoice:()=>{pi()},onStopVoice:mi,startPending:fi,sessionElapsedSeconds:Ee,onStartFreshConversation:gi,isPro:r,greetingMessage:_e,...$e,...li,backgroundSrc:$.scenarioId?nn[$.scenarioId]?.backgroundAsset:void 0,foregroundSrc:$.scenarioId?nn[$.scenarioId]?.foregroundAsset:void 0,avatarPlacement:$.scenarioId?nn[$.scenarioId]?.avatarPlacement:void 0,sceneSelector:d.jsx(Sp,{scenarioId:$.scenarioId??null,onSelect:D=>{zd(D)}})})}):d.jsx(Da,{onPick:ba})),b==="free-chat"&&d.jsxs("div",{className:"ch-overview",children:[d.jsxs("header",{className:"ch-page-header",children:[d.jsx("h1",{className:"ch-page-title",children:d.jsx(Wn,{paint:"blue",children:"Open conversation"})}),d.jsx("p",{className:"ch-page-lede",children:"Talk to the tutor about anything. No scenario, no lesson — just open conversation at your own pace."})]}),d.jsx(yi,{messages:T,liveTranscript:m.transcript,isBotSpeaking:m.isBotSpeaking,mouthOpenYRef:m.mouthOpenYRef,bigNodSignal:m.bigNodSignal,agentFace:m.agentFace,agentMotion:m.agentMotion,expression:hi,currentEmotion:Te,live2dKey:Re,realtimeStatus:m.status,realtimeError:m.error,onStartVoice:()=>{pi()},onStopVoice:mi,startPending:fi,sessionElapsedSeconds:Ee,onStartFreshConversation:$?.mode==="free_chat"?gi:void 0,isPro:r,greetingMessage:_e,...$e,...li,backgroundSrc:uf,foregroundSrc:lf,avatarPlacement:{scale:.92,top:-.105,anchorY:0}})]}),b==="settings"&&n&&d.jsx(Tf,{isPro:r}),b==="settings"&&!n&&d.jsx(Qf,{reason:"settings",onSignup:()=>t("signup"),onDismiss:()=>a("/chat/overview")})]})]},b)]})}),d.jsx(Ba,{open:!!ui,onOpenChange:D=>{D||ma(null)},children:d.jsxs($a,{className:"border-0 p-0 overflow-hidden",style:{"--module-accent":pa},children:[d.jsxs(Ua,{className:"px-6 pt-6 pb-2",children:[d.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[d.jsx("div",{className:"w-9 h-9 rounded-[var(--wc-radius-leaf)] bg-destructive/15 flex items-center justify-center flex-shrink-0",children:d.jsx(Oa,{size:16,className:"text-destructive"})}),d.jsx(za,{className:"text-lg font-bold",children:"Delete conversation?"})]}),d.jsx(Wa,{className:"pl-12",children:"This will permanently remove this conversation and all its messages. This action cannot be undone."})]}),d.jsxs(Va,{className:"px-6 pb-5 pt-3",children:[d.jsx(Ja,{className:"rounded-[var(--wc-radius-leaf)]",children:"Cancel"}),d.jsx(qa,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90 rounded-[var(--wc-radius-leaf)]",onClick:()=>{ui&&qd(ui),ma(null)},children:"Delete"})]})]})}),d.jsx(Ba,{open:Vd,onOpenChange:di,children:d.jsxs($a,{className:"border-0 p-0 overflow-hidden",style:{"--module-accent":pa},children:[d.jsxs(Ua,{className:"px-6 pt-6 pb-2",children:[d.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[d.jsx("div",{className:"w-9 h-9 rounded-[var(--wc-radius-leaf)] bg-destructive/15 flex items-center justify-center flex-shrink-0",children:d.jsx(Oa,{size:16,className:"text-destructive"})}),d.jsx(za,{className:"text-lg font-bold",children:"Delete this conversation and start over?"})]}),d.jsxs(Wa,{className:"pl-12",children:["This erases your current ",Gd," conversation and its messages. Your other conversations aren’t affected. This can’t be undone."]})]}),d.jsxs(Va,{className:"px-6 pb-5 pt-3",children:[d.jsx(Ja,{className:"rounded-[var(--wc-radius-leaf)]",children:"Cancel"}),d.jsx(qa,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90 rounded-[var(--wc-radius-leaf)]",onClick:()=>{di(!1),Wd()},children:"Delete & start fresh"})]})]})}),_&&d.jsx(sw,{tourActions:Ud,onComplete:()=>{g(!0);const D=Na();D&&a(D,{replace:!0})},onSkip:()=>{g(!0);const D=Na();D&&a(D,{replace:!0})}})]})}export{n_ as ChatInterface,pw as getCompletedVoiceTurnAnalytics,fw as getVoiceSessionStartedProperties,hw as normalizeChatAnalyticsMode};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.