@brainbase-labs/chat-widget 0.1.18 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,17 +1,278 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("react"),g=require("react/jsx-runtime"),Fn="bb-chat-";function Ut(e){try{const n=sessionStorage.getItem(`${Fn}${e}`);return n?JSON.parse(n):null}catch{return null}}function vn(e,n){try{sessionStorage.setItem(`${Fn}${e}`,JSON.stringify(n))}catch{}}function Tn(e){try{sessionStorage.removeItem(`${Fn}${e}`)}catch{}}function qt(e){const{config:n,apiClient:t,mockMode:r,onSessionStart:i,onSessionEnd:l,onMessage:o,onError:a}=e,[c,s]=O.useState([]),[u,p]=O.useState([]),[m,h]=O.useState(!1),[S,I]=O.useState(null),[E,b]=O.useState(null),P=O.useRef(0),v=O.useRef(!1),R=O.useRef({});O.useEffect(()=>{if(v.current)return;v.current=!0;const C=Ut(n.embedId);C&&C.status==="active"&&(b(C.sessionId),s(C.messages),p(C.toolCalls),P.current=C.startTime)},[n.embedId]),O.useEffect(()=>{E&&c.length>0&&vn(n.embedId,{sessionId:E,deploymentId:n.deploymentId,workerId:n.workerId,flowId:n.flowId,startTime:P.current,messages:c,toolCalls:u,status:"active"})},[E,c,u,n]);const V=O.useCallback(async()=>(P.current=Date.now(),b(null),s([]),p([]),Tn(n.embedId),""),[n.embedId]),k=O.useCallback((C,j)=>{s(T=>{let x=!1;const A=T.map(L=>L.id===C?(x=!0,{...L,content:j,status:"streaming"}):L);return x||A.push({id:C,role:"assistant",content:j,timestamp:Date.now(),status:"streaming"}),A})},[]),D=O.useCallback((C,j,T)=>{switch(C.type){case"session":{const x=C.data;x.session_id&&(T(x.session_id),x.is_new&&(P.current=Date.now(),i==null||i(x.session_id)));break}case"message":{const x=C.data;x.content&&(R.current[j]=x.content,k(j,x.content));break}case"chunk":{const x=C.data;if(x.content){const L=(R.current[j]??"")+x.content;R.current[j]=L,k(j,L)}break}case"tool_call":{const x=C.data;if(p(A=>{const L=A.findIndex(q=>q.name===x.function&&q.status==="pending");return L!==-1&&x.result!==void 0?A.map((q,Q)=>Q===L?{...q,result:x.result,status:"completed"}:q):L===-1?[...A,{id:`tc-${Date.now()}-${Math.random().toString(36).slice(2)}`,name:x.function,arguments:x.args??{},status:"pending",timestamp:Date.now()}]:A}),x.content){const A=x.content;R.current[j]=A,k(j,A)}break}case"waiting":break;case"done":{s(x=>x.map(A=>A.id===j?{...A,status:"sent"}:A)),delete R.current[j];break}case"completed":{s(x=>{const A=x.map(L=>L.id===j?{...L,status:"sent"}:L);return E&&vn(n.embedId,{sessionId:E,deploymentId:n.deploymentId,workerId:n.workerId,flowId:n.flowId,startTime:P.current,messages:A,toolCalls:[],status:"completed"}),A}),delete R.current[j];break}case"error":{const x=C.data;s(A=>A.map(L=>L.id===j?{...L,status:"error",content:x.error??"An error occurred"}:L));break}}},[n,E,i,k]),U=O.useCallback(async(C,j,T)=>{const x=C.getReader(),A=new TextDecoder;let L="";try{for(;;){const{done:q,value:Q}=await x.read();if(q)break;L+=A.decode(Q,{stream:!0});let f;for(;(f=L.indexOf(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("react"),p=require("react/jsx-runtime"),Ls="bb-chat-";function mc(t){try{const e=sessionStorage.getItem(`${Ls}${t}`);return e?JSON.parse(e):null}catch{return null}}function Xr(t,e){try{sessionStorage.setItem(`${Ls}${t}`,JSON.stringify(e))}catch{}}function Zr(t){try{sessionStorage.removeItem(`${Ls}${t}`)}catch{}}function gc(t){const{config:e,apiClient:n,mockMode:i,streamMessages:r=!1,artificialDelay:s,onSessionStart:a,onSessionEnd:o,onMessage:c,onError:l}=t,[u,d]=q.useState([]),[h,f]=q.useState([]),[m,g]=q.useState(!1),[w,b]=q.useState(!1),[P,_]=q.useState(null),[S,T]=q.useState(null),C=q.useRef(0),O=q.useRef(!1),L=q.useRef({}),I=q.useRef(null),A=q.useRef(null),R=q.useCallback(()=>{if(!s)return 0;const[K,Z]=s;return(K+Math.random()*(Z-K))*1e3},[s]);q.useEffect(()=>{if(O.current)return;O.current=!0;const K=mc(e.embedId);K&&K.status==="active"&&(T(K.sessionId),d(K.messages),f(K.toolCalls),C.current=K.startTime)},[e.embedId]),q.useEffect(()=>{S&&u.length>0&&Xr(e.embedId,{sessionId:S,deploymentId:e.deploymentId,workerId:e.workerId,flowId:e.flowId,startTime:C.current,messages:u,toolCalls:h,status:"active"})},[S,u,h,e]);const N=q.useCallback(async()=>(C.current=Date.now(),T(null),d([]),f([]),Zr(e.embedId),""),[e.embedId]),Y=q.useCallback((K,Z,y)=>{d(J=>{let X=!1;const W=J.map(se=>se.id===K?(X=!0,{...se,content:Z,status:y}):se);return X||W.push({id:K,role:"assistant",content:Z,timestamp:Date.now(),status:y}),W})},[]),G=q.useCallback((K,Z,y=!1)=>{if(!(!r&&!y))if(y&&s){const J=R();A.current&&clearTimeout(A.current),A.current=setTimeout(()=>{Y(K,Z,"sent")},J)}else Y(K,Z,y?"sent":"streaming")},[r,s,R,Y]),j=q.useCallback((K,Z,y)=>{switch(K.type){case"session":{const J=K.data;J.session_id&&(y(J.session_id),J.is_new&&(C.current=Date.now(),a==null||a(J.session_id)));break}case"message":{const J=K.data;J.content&&(L.current[Z]=J.content,G(Z,J.content));break}case"chunk":{const J=K.data;if(J.content){const W=(L.current[Z]??"")+J.content;L.current[Z]=W,G(Z,W)}break}case"tool_call":{const J=K.data;if(f(X=>{const W=X.findIndex(se=>se.name===J.function&&se.status==="pending");return W!==-1&&J.result!==void 0?X.map((se,De)=>De===W?{...se,result:J.result,status:"completed"}:se):W===-1?[...X,{id:`tc-${Date.now()}-${Math.random().toString(36).slice(2)}`,name:J.function,arguments:J.args??{},status:"pending",timestamp:Date.now()}]:X}),J.content){const X=J.content;L.current[Z]=X,G(Z,X)}break}case"waiting":break;case"done":{if(r)d(J=>J.map(X=>X.id===Z?{...X,status:"sent"}:X));else{const J=L.current[Z]??"";J&&G(Z,J,!0)}delete L.current[Z];break}case"completed":{if(!r){const J=L.current[Z]??"";J&&G(Z,J,!0)}d(J=>{const X=J.map(W=>W.id===Z?{...W,status:"sent"}:W);return S&&Xr(e.embedId,{sessionId:S,deploymentId:e.deploymentId,workerId:e.workerId,flowId:e.flowId,startTime:C.current,messages:X,toolCalls:[],status:"completed"}),X}),delete L.current[Z];break}case"error":{const J=K.data;d(X=>X.map(W=>W.id===Z?{...W,status:"error",content:J.error??"An error occurred"}:W));break}}},[e,S,r,a,G]),$=q.useCallback(async(K,Z,y)=>{const J=K.getReader(),X=new TextDecoder;let W="";try{for(;;){const{done:se,value:De}=await J.read();if(se)break;W+=X.decode(De,{stream:!0});let we;for(;(we=W.indexOf(`
2
2
 
3
- `))!==-1;){const J=L.slice(0,f);L=L.slice(f+2);for(const ue of J.split(`
4
- `))if(ue.startsWith("data: "))try{const d=JSON.parse(ue.slice(6));D(d,j,T)}catch{}}}}finally{x.releaseLock()}},[D]),F=O.useCallback(async C=>{if(!C.trim())return;const j={id:`user-${Date.now()}`,role:"user",content:C,timestamp:Date.now(),status:"sent"};s(L=>[...L,j]),o==null||o(j);const T=`assistant-${Date.now()}`,x={id:T,role:"assistant",content:"",timestamp:Date.now(),status:"streaming"};s(L=>[...L,x]),h(!0),I(null);const A=L=>{b(L)};try{if(r){const L=t.sendMessage(C);for await(const q of L)D(q,T,A)}else{const L=await t.sendMessage({embedId:n.embedId,message:C,sessionId:E??void 0});await U(L,T,A)}s(L=>L.map(q=>q.id===T&&q.status==="streaming"?{...q,status:"sent"}:q))}catch(L){const q=L instanceof Error?L:new Error("Failed to send message");I(q),a==null||a(q),s(Q=>Q.map(f=>f.id===T?{...f,status:"error",content:"Failed to get response"}:f))}finally{h(!1)}},[E,t,r,n.embedId,D,U,o,a]),$=O.useCallback(async()=>{if(!E)return;const C={sessionId:E,deploymentId:n.deploymentId,workerId:n.workerId,flowId:n.flowId,startTime:P.current,messages:c,toolCalls:u,status:"completed"};l==null||l(C),Tn(n.embedId),b(null),s([]),p([])},[E,n,c,u,l]),N=O.useCallback(()=>{s([]),p([])},[]);return{messages:c,toolCalls:u,isLoading:m,error:S,sessionId:E,sendMessage:F,endSession:$,clearMessages:N,startNewSession:V}}const Wt="https://chat-embed-deployment.onrender.com";function Yt(e=Wt){return{async getDeploymentConfig(n){const t=await fetch(`${e}/chat/config/${n}`);if(!t.ok)throw new Error(`Failed to fetch deployment config: ${t.status}`);const r=await t.json();return{embedId:r.embedId,deploymentId:"",workerId:"",flowId:"",welcomeMessage:r.welcomeMessage,agentName:r.agentName,agentLogoUrl:r.agentLogoUrl,primaryColor:r.primaryColor,styling:r.styling}},async sendMessage(n){const t=await fetch(`${e}/chat/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embed_id:n.embedId,message:n.message,session_id:n.sessionId||void 0,metadata:n.metadata})});if(!t.ok){const r=await t.text();throw new Error(`Failed to send message: ${t.status} - ${r}`)}if(!t.body)throw new Error("No response stream available");return t.body}}}const Yr={embedId:"mock-embed-id",deploymentId:"mock-deployment-id",workerId:"mock-worker-id",flowId:"mock-flow-id",agentName:"AI Assistant",agentLogoUrl:void 0,primaryColor:"#1a1a2e",styling:{}},Xr=[{trigger:/hello|hi|hey/i,response:"Hello! I'm a demo AI assistant. How can I help you today?",delay:500},{trigger:/weather/i,response:"I'd check the weather for you, but I'm in mock mode! In production, I could use a weather API.",delay:800,toolCalls:[{name:"get_weather",arguments:{location:"San Francisco"},result:{temperature:72,condition:"sunny"}}]},{trigger:/help|support/i,response:"I'm here to help! You can ask me questions, and I'll do my best to assist you. In production, I'd be connected to your agent with full capabilities.",delay:600},{trigger:/pricing|cost|price/i,response:"For pricing information, I'd typically check our database or connect you with the sales team. This is a mock response demonstrating how I'd handle pricing questions.",delay:700,toolCalls:[{name:"lookup_pricing",arguments:{plan:"all"},result:{plans:[{name:"Starter",price:"$29/mo"},{name:"Pro",price:"$99/mo"}]}}]},{trigger:/.*/,response:"I'm running in mock mode. This is a simulated response to demonstrate the chat UI. In production, I'd be connected to your agent!",delay:1e3}];function $e(e){return new Promise(n=>setTimeout(n,e))}function Xt(e,n){const t={...Yr,...e},r=n??Xr,i=`mock-session-${Date.now()}`;return{async getDeploymentConfig(l){return await $e(300),t},async*sendMessage(l){yield{type:"session",data:{session_id:i,is_new:!0},timestamp:Date.now()};const o=r.find(s=>typeof s.trigger=="string"?l.toLowerCase().includes(s.trigger.toLowerCase()):s.trigger.test(l))??r[r.length-1];if(await $e(o.delay??500),o.toolCalls)for(const s of o.toolCalls)yield{type:"tool_call",data:{function:s.name,args:s.arguments},timestamp:Date.now()},await $e(300),yield{type:"tool_call",data:{function:s.name,result:s.result},timestamp:Date.now()},await $e(200);const a=o.response.split(" ");let c="";for(const s of a)c+=(c?" ":"")+s,yield{type:"message",data:{content:c,role:"assistant"},timestamp:Date.now()},await $e(30+Math.random()*40);yield{type:"done",data:{session_id:i},timestamp:Date.now()}}}}const Qe=({className:e,color:n="currentColor",cutoutColor:t="var(--bb-primary-color)"})=>g.jsxs("svg",{className:e,viewBox:"0 0 800 800",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[g.jsx("path",{d:"M400 412C400 405.373 405.373 400 412 400H788C794.627 400 800 405.373 800 412V740C800 773.137 773.137 800 740 800H412C405.373 800 400 794.627 400 788V412Z",fill:n}),g.jsx("circle",{cx:"400",cy:"400",r:"400",fill:n}),g.jsx("path",{d:"M0 60C0 26.8629 26.8629 0 60 0H397.614C398.932 0 400 1.06811 400 2.38569V2.38569C400 221.982 221.982 400 2.38569 400V400C1.06811 400 0 398.932 0 397.614V60Z",fill:n}),g.jsx("path",{d:"M400 412C400 405.373 405.373 400 412 400H738C744.627 400 750 405.373 750 412V725C750 738.807 738.807 750 725 750H412C405.373 750 400 744.627 400 738V412Z",fill:n}),g.jsx("circle",{cx:"400",cy:"400",r:"350",fill:n}),g.jsx("path",{d:"M50 75C50 61.1929 61.1929 50 75 50H388C394.627 50 400 55.3726 400 62V388C400 394.627 394.627 400 388 400H62C55.3726 400 50 394.627 50 388V75Z",fill:n}),g.jsx("rect",{x:"399.919",y:"209",width:"270",height:"270",rx:"12",transform:"rotate(45 399.919 209)",fill:t})]}),Kr="_header_1p6z5_1",Qr="_compact_1p6z5_9",Zr="_headerBackground_1p6z5_20",Jr="_headerContent_1p6z5_59",Gr="_topRow_1p6z5_64",ei="_agentInfo_1p6z5_79",ni="_agentLogo_1p6z5_85",ti="_agentLogoPlaceholder_1p6z5_102",ri="_brainbaseLogo_1p6z5_123",ii="_agentName_1p6z5_137",li="_actions_1p6z5_144",oi="_actionButton_1p6z5_149",ai="_welcomeText_1p6z5_183",si="_title_1p6z5_202",ui="_subtitle_1p6z5_210",ee={header:Kr,compact:Qr,headerBackground:Zr,headerContent:Jr,topRow:Gr,agentInfo:ei,agentLogo:ni,agentLogoPlaceholder:ti,brainbaseLogo:ri,agentName:ii,actions:li,actionButton:oi,welcomeText:ai,title:si,subtitle:ui},Kt=({agentName:e="AI Assistant",agentLogoUrl:n,welcomeTitle:t,welcomeSubtitle:r,onClose:i,onNewChatRequest:l,showNewChatButton:o=!1,compact:a=!1})=>{const c=t||"Hello there.",s=r!==void 0?r:t?void 0:"How can we help?";return g.jsxs("div",{className:`${ee.header} ${a?ee.compact:""}`,children:[g.jsx("div",{className:ee.headerBackground}),g.jsxs("div",{className:ee.headerContent,children:[g.jsxs("div",{className:ee.topRow,children:[g.jsxs("div",{className:ee.agentInfo,children:[n?g.jsx("img",{src:n,alt:e,className:ee.agentLogo}):g.jsx("div",{className:ee.agentLogoPlaceholder,children:g.jsx(Qe,{className:ee.brainbaseLogo,color:"white",cutoutColor:"var(--bb-primary-color)"})}),g.jsx("span",{className:ee.agentName,children:e})]}),g.jsxs("div",{className:ee.actions,children:[o&&l&&g.jsx("button",{className:ee.actionButton,onClick:l,"aria-label":"Start new chat",type:"button",children:g.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:g.jsx("path",{d:"M12 5V19M5 12H19",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),i&&g.jsx("button",{className:ee.actionButton,onClick:i,"aria-label":"Close chat",type:"button",children:g.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:g.jsx("path",{d:"M6 18L18 6M6 6L18 18",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]}),!a&&g.jsxs("div",{className:ee.welcomeText,children:[g.jsx("h1",{className:ee.title,children:c}),s&&g.jsx("p",{className:ee.subtitle,children:s})]})]})]})};function ci(e,n){const t={};return(e[e.length-1]===""?[...e,""]:e).join((t.padRight?" ":"")+","+(t.padLeft===!1?"":" ")).trim()}const pi=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,hi=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,fi={};function ot(e,n){return(fi.jsx?hi:pi).test(e)}const di=/[ \t\n\f\r]/g;function mi(e){return typeof e=="object"?e.type==="text"?at(e.value):!1:at(e)}function at(e){return e.replace(di,"")===""}class Je{constructor(n,t,r){this.normal=t,this.property=n,r&&(this.space=r)}}Je.prototype.normal={};Je.prototype.property={};Je.prototype.space=void 0;function Qt(e,n){const t={},r={};for(const i of e)Object.assign(t,i.property),Object.assign(r,i.normal);return new Je(t,r,n)}function Ln(e){return e.toLowerCase()}class le{constructor(n,t){this.attribute=t,this.property=n}}le.prototype.attribute="";le.prototype.booleanish=!1;le.prototype.boolean=!1;le.prototype.commaOrSpaceSeparated=!1;le.prototype.commaSeparated=!1;le.prototype.defined=!1;le.prototype.mustUseProperty=!1;le.prototype.number=!1;le.prototype.overloadedBoolean=!1;le.prototype.property="";le.prototype.spaceSeparated=!1;le.prototype.space=void 0;let gi=0;const B=ve(),Z=ve(),Nn=ve(),w=ve(),X=ve(),ze=ve(),ae=ve();function ve(){return 2**++gi}const Pn=Object.freeze(Object.defineProperty({__proto__:null,boolean:B,booleanish:Z,commaOrSpaceSeparated:ae,commaSeparated:ze,number:w,overloadedBoolean:Nn,spaceSeparated:X},Symbol.toStringTag,{value:"Module"})),dn=Object.keys(Pn);class $n extends le{constructor(n,t,r,i){let l=-1;if(super(n,t),st(this,"space",i),typeof r=="number")for(;++l<dn.length;){const o=dn[l];st(this,dn[l],(r&Pn[o])===Pn[o])}}}$n.prototype.defined=!0;function st(e,n,t){t&&(e[n]=t)}function De(e){const n={},t={};for(const[r,i]of Object.entries(e.properties)){const l=new $n(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(l.mustUseProperty=!0),n[r]=l,t[Ln(r)]=r,t[Ln(l.attribute)]=r}return new Je(n,t,e.space)}const Zt=De({properties:{ariaActiveDescendant:null,ariaAtomic:Z,ariaAutoComplete:null,ariaBusy:Z,ariaChecked:Z,ariaColCount:w,ariaColIndex:w,ariaColSpan:w,ariaControls:X,ariaCurrent:null,ariaDescribedBy:X,ariaDetails:null,ariaDisabled:Z,ariaDropEffect:X,ariaErrorMessage:null,ariaExpanded:Z,ariaFlowTo:X,ariaGrabbed:Z,ariaHasPopup:null,ariaHidden:Z,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:X,ariaLevel:w,ariaLive:null,ariaModal:Z,ariaMultiLine:Z,ariaMultiSelectable:Z,ariaOrientation:null,ariaOwns:X,ariaPlaceholder:null,ariaPosInSet:w,ariaPressed:Z,ariaReadOnly:Z,ariaRelevant:null,ariaRequired:Z,ariaRoleDescription:X,ariaRowCount:w,ariaRowIndex:w,ariaRowSpan:w,ariaSelected:Z,ariaSetSize:w,ariaSort:null,ariaValueMax:w,ariaValueMin:w,ariaValueNow:w,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Jt(e,n){return n in e?e[n]:n}function Gt(e,n){return Jt(e,n.toLowerCase())}const yi=De({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:ze,acceptCharset:X,accessKey:X,action:null,allow:null,allowFullScreen:B,allowPaymentRequest:B,allowUserMedia:B,alt:null,as:null,async:B,autoCapitalize:null,autoComplete:X,autoFocus:B,autoPlay:B,blocking:X,capture:null,charSet:null,checked:B,cite:null,className:X,cols:w,colSpan:null,content:null,contentEditable:Z,controls:B,controlsList:X,coords:w|ze,crossOrigin:null,data:null,dateTime:null,decoding:null,default:B,defer:B,dir:null,dirName:null,disabled:B,download:Nn,draggable:Z,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:B,formTarget:null,headers:X,height:w,hidden:Nn,high:w,href:null,hrefLang:null,htmlFor:X,httpEquiv:X,id:null,imageSizes:null,imageSrcSet:null,inert:B,inputMode:null,integrity:null,is:null,isMap:B,itemId:null,itemProp:X,itemRef:X,itemScope:B,itemType:X,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:B,low:w,manifest:null,max:null,maxLength:w,media:null,method:null,min:null,minLength:w,multiple:B,muted:B,name:null,nonce:null,noModule:B,noValidate:B,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:B,optimum:w,pattern:null,ping:X,placeholder:null,playsInline:B,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:B,referrerPolicy:null,rel:X,required:B,reversed:B,rows:w,rowSpan:w,sandbox:X,scope:null,scoped:B,seamless:B,selected:B,shadowRootClonable:B,shadowRootDelegatesFocus:B,shadowRootMode:null,shape:null,size:w,sizes:null,slot:null,span:w,spellCheck:Z,src:null,srcDoc:null,srcLang:null,srcSet:null,start:w,step:null,style:null,tabIndex:w,target:null,title:null,translate:null,type:null,typeMustMatch:B,useMap:null,value:Z,width:w,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:X,axis:null,background:null,bgColor:null,border:w,borderColor:null,bottomMargin:w,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:B,declare:B,event:null,face:null,frame:null,frameBorder:null,hSpace:w,leftMargin:w,link:null,longDesc:null,lowSrc:null,marginHeight:w,marginWidth:w,noResize:B,noHref:B,noShade:B,noWrap:B,object:null,profile:null,prompt:null,rev:null,rightMargin:w,rules:null,scheme:null,scrolling:Z,standby:null,summary:null,text:null,topMargin:w,valueType:null,version:null,vAlign:null,vLink:null,vSpace:w,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:B,disableRemotePlayback:B,prefix:null,property:null,results:w,security:null,unselectable:null},space:"html",transform:Gt}),xi=De({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:ae,accentHeight:w,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:w,amplitude:w,arabicForm:null,ascent:w,attributeName:null,attributeType:null,azimuth:w,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:w,by:null,calcMode:null,capHeight:w,className:X,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:w,diffuseConstant:w,direction:null,display:null,dur:null,divisor:w,dominantBaseline:null,download:B,dx:null,dy:null,edgeMode:null,editable:null,elevation:w,enableBackground:null,end:null,event:null,exponent:w,externalResourcesRequired:null,fill:null,fillOpacity:w,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:ze,g2:ze,glyphName:ze,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:w,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:w,horizOriginX:w,horizOriginY:w,id:null,ideographic:w,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:w,k:w,k1:w,k2:w,k3:w,k4:w,kernelMatrix:ae,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:w,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:w,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:w,overlineThickness:w,paintOrder:null,panose1:null,path:null,pathLength:w,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:X,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:w,pointsAtY:w,pointsAtZ:w,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:ae,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:ae,rev:ae,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:ae,requiredFeatures:ae,requiredFonts:ae,requiredFormats:ae,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:w,specularExponent:w,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:w,strikethroughThickness:w,string:null,stroke:null,strokeDashArray:ae,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:w,strokeOpacity:w,strokeWidth:null,style:null,surfaceScale:w,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:ae,tabIndex:w,tableValues:null,target:null,targetX:w,targetY:w,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:ae,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:w,underlineThickness:w,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:w,values:null,vAlphabetic:w,vMathematical:w,vectorEffect:null,vHanging:w,vIdeographic:w,version:null,vertAdvY:w,vertOriginX:w,vertOriginY:w,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:w,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Jt}),er=De({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,n){return"xlink:"+n.slice(5).toLowerCase()}}),nr=De({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Gt}),tr=De({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),ki={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},bi=/[A-Z]/g,ut=/-[a-z]/g,wi=/^data[-\w.:]+$/i;function Ci(e,n){const t=Ln(n);let r=n,i=le;if(t in e.normal)return e.property[e.normal[t]];if(t.length>4&&t.slice(0,4)==="data"&&wi.test(n)){if(n.charAt(4)==="-"){const l=n.slice(5).replace(ut,_i);r="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=n.slice(4);if(!ut.test(l)){let o=l.replace(bi,Si);o.charAt(0)!=="-"&&(o="-"+o),n="data"+o}}i=$n}return new i(r,n)}function Si(e){return"-"+e.toLowerCase()}function _i(e){return e.charAt(1).toUpperCase()}const Ii=Qt([Zt,yi,er,nr,tr],"html"),Hn=Qt([Zt,xi,er,nr,tr],"svg");function Ei(e){return e.join(" ").trim()}function rr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Pe={},mn,ct;function vi(){if(ct)return mn;ct=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,t=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,l=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,a=/^\s+|\s+$/g,c=`
5
- `,s="/",u="*",p="",m="comment",h="declaration";function S(E,b){if(typeof E!="string")throw new TypeError("First argument must be a string");if(!E)return[];b=b||{};var P=1,v=1;function R(T){var x=T.match(n);x&&(P+=x.length);var A=T.lastIndexOf(c);v=~A?T.length-A:v+T.length}function V(){var T={line:P,column:v};return function(x){return x.position=new k(T),F(),x}}function k(T){this.start=T,this.end={line:P,column:v},this.source=b.source}k.prototype.content=E;function D(T){var x=new Error(b.source+":"+P+":"+v+": "+T);if(x.reason=T,x.filename=b.source,x.line=P,x.column=v,x.source=E,!b.silent)throw x}function U(T){var x=T.exec(E);if(x){var A=x[0];return R(A),E=E.slice(A.length),x}}function F(){U(t)}function $(T){var x;for(T=T||[];x=N();)x!==!1&&T.push(x);return T}function N(){var T=V();if(!(s!=E.charAt(0)||u!=E.charAt(1))){for(var x=2;p!=E.charAt(x)&&(u!=E.charAt(x)||s!=E.charAt(x+1));)++x;if(x+=2,p===E.charAt(x-1))return D("End of comment missing");var A=E.slice(2,x-2);return v+=2,R(A),E=E.slice(x),v+=2,T({type:m,comment:A})}}function C(){var T=V(),x=U(r);if(x){if(N(),!U(i))return D("property missing ':'");var A=U(l),L=T({type:h,property:I(x[0].replace(e,p)),value:A?I(A[0].replace(e,p)):p});return U(o),L}}function j(){var T=[];$(T);for(var x;x=C();)x!==!1&&(T.push(x),$(T));return T}return F(),j()}function I(E){return E?E.replace(a,p):p}return mn=S,mn}var pt;function Ti(){if(pt)return Pe;pt=1;var e=Pe&&Pe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.default=t;const n=e(vi());function t(r,i){let l=null;if(!r||typeof r!="string")return l;const o=(0,n.default)(r),a=typeof i=="function";return o.forEach(c=>{if(c.type!=="declaration")return;const{property:s,value:u}=c;a?i(s,u,c):u&&(l=l||{},l[s]=u)}),l}return Pe}var He={},ht;function Li(){if(ht)return He;ht=1,Object.defineProperty(He,"__esModule",{value:!0}),He.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,t=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,l=function(s){return!s||t.test(s)||e.test(s)},o=function(s,u){return u.toUpperCase()},a=function(s,u){return"".concat(u,"-")},c=function(s,u){return u===void 0&&(u={}),l(s)?s:(s=s.toLowerCase(),u.reactCompat?s=s.replace(i,a):s=s.replace(r,a),s.replace(n,o))};return He.camelCase=c,He}var Ve,ft;function Ni(){if(ft)return Ve;ft=1;var e=Ve&&Ve.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},n=e(Ti()),t=Li();function r(i,l){var o={};return!i||typeof i!="string"||(0,n.default)(i,function(a,c){a&&c&&(o[(0,t.camelCase)(a,l)]=c)}),o}return r.default=r,Ve=r,Ve}var Pi=Ni();const Ai=rr(Pi),ir=lr("end"),Vn=lr("start");function lr(e){return n;function n(t){const r=t&&t.position&&t.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function ji(e){const n=Vn(e),t=ir(e);if(n&&t)return{start:n,end:t}}function Ye(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?dt(e.position):"start"in e||"end"in e?dt(e):"line"in e||"column"in e?An(e):""}function An(e){return mt(e&&e.line)+":"+mt(e&&e.column)}function dt(e){return An(e&&e.start)+"-"+An(e&&e.end)}function mt(e){return e&&typeof e=="number"?e:1}class te extends Error{constructor(n,t,r){super(),typeof t=="string"&&(r=t,t=void 0);let i="",l={},o=!1;if(t&&("line"in t&&"column"in t?l={place:t}:"start"in t&&"end"in t?l={place:t}:"type"in t?l={ancestors:[t],place:t.position}:l={...t}),typeof n=="string"?i=n:!l.cause&&n&&(o=!0,i=n.message,l.cause=n),!l.ruleId&&!l.source&&typeof r=="string"){const c=r.indexOf(":");c===-1?l.ruleId=r:(l.source=r.slice(0,c),l.ruleId=r.slice(c+1))}if(!l.place&&l.ancestors&&l.ancestors){const c=l.ancestors[l.ancestors.length-1];c&&(l.place=c.position)}const a=l.place&&"start"in l.place?l.place.start:l.place;this.ancestors=l.ancestors||void 0,this.cause=l.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=a?a.line:void 0,this.name=Ye(l.place)||"1:1",this.place=l.place||void 0,this.reason=this.message,this.ruleId=l.ruleId||void 0,this.source=l.source||void 0,this.stack=o&&l.cause&&typeof l.cause.stack=="string"?l.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}te.prototype.file="";te.prototype.name="";te.prototype.reason="";te.prototype.message="";te.prototype.stack="";te.prototype.column=void 0;te.prototype.line=void 0;te.prototype.ancestors=void 0;te.prototype.cause=void 0;te.prototype.fatal=void 0;te.prototype.place=void 0;te.prototype.ruleId=void 0;te.prototype.source=void 0;const Un={}.hasOwnProperty,zi=new Map,Mi=/[A-Z]/g,Di=new Set(["table","tbody","thead","tfoot","tr"]),Bi=new Set(["td","th"]),or="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Oi(e,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const t=n.filePath||void 0;let r;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=Wi(t,n.jsxDEV)}else{if(typeof n.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof n.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=qi(t,n.jsx,n.jsxs)}const i={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:r,elementAttributeNameCase:n.elementAttributeNameCase||"react",evaluater:n.createEvaluater?n.createEvaluater():void 0,filePath:t,ignoreInvalidStyle:n.ignoreInvalidStyle||!1,passKeys:n.passKeys!==!1,passNode:n.passNode||!1,schema:n.space==="svg"?Hn:Ii,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},l=ar(i,e,void 0);return l&&typeof l!="string"?l:i.create(e,i.Fragment,{children:l||void 0},void 0)}function ar(e,n,t){if(n.type==="element")return Ri(e,n,t);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return Fi(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return Hi(e,n,t);if(n.type==="mdxjsEsm")return $i(e,n);if(n.type==="root")return Vi(e,n,t);if(n.type==="text")return Ui(e,n)}function Ri(e,n,t){const r=e.schema;let i=r;n.tagName.toLowerCase()==="svg"&&r.space==="html"&&(i=Hn,e.schema=i),e.ancestors.push(n);const l=ur(e,n.tagName,!1),o=Yi(e,n);let a=Wn(e,n);return Di.has(n.tagName)&&(a=a.filter(function(c){return typeof c=="string"?!mi(c):!0})),sr(e,o,l,n),qn(o,a),e.ancestors.pop(),e.schema=r,e.create(n,l,o,t)}function Fi(e,n){if(n.data&&n.data.estree&&e.evaluater){const r=n.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}Ze(e,n.position)}function $i(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);Ze(e,n.position)}function Hi(e,n,t){const r=e.schema;let i=r;n.name==="svg"&&r.space==="html"&&(i=Hn,e.schema=i),e.ancestors.push(n);const l=n.name===null?e.Fragment:ur(e,n.name,!0),o=Xi(e,n),a=Wn(e,n);return sr(e,o,l,n),qn(o,a),e.ancestors.pop(),e.schema=r,e.create(n,l,o,t)}function Vi(e,n,t){const r={};return qn(r,Wn(e,n)),e.create(n,e.Fragment,r,t)}function Ui(e,n){return n.value}function sr(e,n,t,r){typeof t!="string"&&t!==e.Fragment&&e.passNode&&(n.node=r)}function qn(e,n){if(n.length>0){const t=n.length>1?n:n[0];t&&(e.children=t)}}function qi(e,n,t){return r;function r(i,l,o,a){const s=Array.isArray(o.children)?t:n;return a?s(l,o,a):s(l,o)}}function Wi(e,n){return t;function t(r,i,l,o){const a=Array.isArray(l.children),c=Vn(r);return n(i,l,o,a,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function Yi(e,n){const t={};let r,i;for(i in n.properties)if(i!=="children"&&Un.call(n.properties,i)){const l=Ki(e,i,n.properties[i]);if(l){const[o,a]=l;e.tableCellAlignToStyle&&o==="align"&&typeof a=="string"&&Bi.has(n.tagName)?r=a:t[o]=a}}if(r){const l=t.style||(t.style={});l[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return t}function Xi(e,n){const t={};for(const r of n.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const l=r.data.estree.body[0];l.type;const o=l.expression;o.type;const a=o.properties[0];a.type,Object.assign(t,e.evaluater.evaluateExpression(a.argument))}else Ze(e,n.position);else{const i=r.name;let l;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const a=r.value.data.estree.body[0];a.type,l=e.evaluater.evaluateExpression(a.expression)}else Ze(e,n.position);else l=r.value===null?!0:r.value;t[i]=l}return t}function Wn(e,n){const t=[];let r=-1;const i=e.passKeys?new Map:zi;for(;++r<n.children.length;){const l=n.children[r];let o;if(e.passKeys){const c=l.type==="element"?l.tagName:l.type==="mdxJsxFlowElement"||l.type==="mdxJsxTextElement"?l.name:void 0;if(c){const s=i.get(c)||0;o=c+"-"+s,i.set(c,s+1)}}const a=ar(e,l,o);a!==void 0&&t.push(a)}return t}function Ki(e,n,t){const r=Ci(e.schema,n);if(!(t==null||typeof t=="number"&&Number.isNaN(t))){if(Array.isArray(t)&&(t=r.commaSeparated?ci(t):Ei(t)),r.property==="style"){let i=typeof t=="object"?t:Qi(e,String(t));return e.stylePropertyNameCase==="css"&&(i=Zi(i)),["style",i]}return[e.elementAttributeNameCase==="react"&&r.space?ki[r.property]||r.property:r.attribute,t]}}function Qi(e,n){try{return Ai(n,{reactCompat:!0})}catch(t){if(e.ignoreInvalidStyle)return{};const r=t,i=new te("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw i.file=e.filePath||void 0,i.url=or+"#cannot-parse-style-attribute",i}}function ur(e,n,t){let r;if(!t)r={type:"Literal",value:n};else if(n.includes(".")){const i=n.split(".");let l=-1,o;for(;++l<i.length;){const a=ot(i[l])?{type:"Identifier",name:i[l]}:{type:"Literal",value:i[l]};o=o?{type:"MemberExpression",object:o,property:a,computed:!!(l&&a.type==="Literal"),optional:!1}:a}r=o}else r=ot(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(r.type==="Literal"){const i=r.value;return Un.call(e.components,i)?e.components[i]:i}if(e.evaluater)return e.evaluater.evaluateExpression(r);Ze(e)}function Ze(e,n){const t=new te("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:n,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw t.file=e.filePath||void 0,t.url=or+"#cannot-handle-mdx-estrees-without-createevaluater",t}function Zi(e){const n={};let t;for(t in e)Un.call(e,t)&&(n[Ji(t)]=e[t]);return n}function Ji(e){let n=e.replace(Mi,Gi);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function Gi(e){return"-"+e.toLowerCase()}const gn={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},el={};function nl(e,n){const t=el,r=typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,i=typeof t.includeHtml=="boolean"?t.includeHtml:!0;return cr(e,r,i)}function cr(e,n,t){if(tl(e)){if("value"in e)return e.type==="html"&&!t?"":e.value;if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return gt(e.children,n,t)}return Array.isArray(e)?gt(e,n,t):""}function gt(e,n,t){const r=[];let i=-1;for(;++i<e.length;)r[i]=cr(e[i],n,t);return r.join("")}function tl(e){return!!(e&&typeof e=="object")}const yt=document.createElement("i");function Yn(e){const n="&"+e+";";yt.innerHTML=n;const t=yt.textContent;return t.charCodeAt(t.length-1)===59&&e!=="semi"||t===n?!1:t}function ye(e,n,t,r){const i=e.length;let l=0,o;if(n<0?n=-n>i?0:i+n:n=n>i?i:n,t=t>0?t:0,r.length<1e4)o=Array.from(r),o.unshift(n,t),e.splice(...o);else for(t&&e.splice(n,t);l<r.length;)o=r.slice(l,l+1e4),o.unshift(n,0),e.splice(...o),l+=1e4,n+=1e4}function pe(e,n){return e.length>0?(ye(e,e.length,0,n),e):n}const xt={}.hasOwnProperty;function rl(e){const n={};let t=-1;for(;++t<e.length;)il(n,e[t]);return n}function il(e,n){let t;for(t in n){const i=(xt.call(e,t)?e[t]:void 0)||(e[t]={}),l=n[t];let o;if(l)for(o in l){xt.call(i,o)||(i[o]=[]);const a=l[o];ll(i[o],Array.isArray(a)?a:a?[a]:[])}}}function ll(e,n){let t=-1;const r=[];for(;++t<n.length;)(n[t].add==="after"?e:r).push(n[t]);ye(e,0,0,r)}function pr(e,n){const t=Number.parseInt(e,n);return t<9||t===11||t>13&&t<32||t>126&&t<160||t>55295&&t<57344||t>64975&&t<65008||(t&65535)===65535||(t&65535)===65534||t>1114111?"�":String.fromCodePoint(t)}function Me(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const ge=_e(/[A-Za-z]/),se=_e(/[\dA-Za-z]/),ol=_e(/[#-'*+\--9=?A-Z^-~]/);function jn(e){return e!==null&&(e<32||e===127)}const zn=_e(/\d/),al=_e(/[\dA-Fa-f]/),sl=_e(/[!-/:-@[-`{-~]/);function z(e){return e!==null&&e<-2}function ie(e){return e!==null&&(e<0||e===32)}function W(e){return e===-2||e===-1||e===32}const ul=_e(new RegExp("\\p{P}|\\p{S}","u")),cl=_e(/\s/);function _e(e){return n;function n(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function Be(e){const n=[];let t=-1,r=0,i=0;for(;++t<e.length;){const l=e.charCodeAt(t);let o="";if(l===37&&se(e.charCodeAt(t+1))&&se(e.charCodeAt(t+2)))i=2;else if(l<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(l))||(o=String.fromCharCode(l));else if(l>55295&&l<57344){const a=e.charCodeAt(t+1);l<56320&&a>56319&&a<57344?(o=String.fromCharCode(l,a),i=1):o="�"}else o=String.fromCharCode(l);o&&(n.push(e.slice(r,t),encodeURIComponent(o)),r=t+i+1,o=""),i&&(t+=i,i=0)}return n.join("")+e.slice(r)}function K(e,n,t,r){const i=r?r-1:Number.POSITIVE_INFINITY;let l=0;return o;function o(c){return W(c)?(e.enter(t),a(c)):n(c)}function a(c){return W(c)&&l++<i?(e.consume(c),a):(e.exit(t),n(c))}}const pl={tokenize:hl};function hl(e){const n=e.attempt(this.parser.constructs.contentInitial,r,i);let t;return n;function r(a){if(a===null){e.consume(a);return}return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),K(e,n,"linePrefix")}function i(a){return e.enter("paragraph"),l(a)}function l(a){const c=e.enter("chunkText",{contentType:"text",previous:t});return t&&(t.next=c),t=c,o(a)}function o(a){if(a===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(a);return}return z(a)?(e.consume(a),e.exit("chunkText"),l):(e.consume(a),o)}}const fl={tokenize:dl},kt={tokenize:ml};function dl(e){const n=this,t=[];let r=0,i,l,o;return a;function a(v){if(r<t.length){const R=t[r];return n.containerState=R[1],e.attempt(R[0].continuation,c,s)(v)}return s(v)}function c(v){if(r++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,i&&P();const R=n.events.length;let V=R,k;for(;V--;)if(n.events[V][0]==="exit"&&n.events[V][1].type==="chunkFlow"){k=n.events[V][1].end;break}b(r);let D=R;for(;D<n.events.length;)n.events[D][1].end={...k},D++;return ye(n.events,V+1,0,n.events.slice(R)),n.events.length=D,s(v)}return a(v)}function s(v){if(r===t.length){if(!i)return m(v);if(i.currentConstruct&&i.currentConstruct.concrete)return S(v);n.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(kt,u,p)(v)}function u(v){return i&&P(),b(r),m(v)}function p(v){return n.parser.lazy[n.now().line]=r!==t.length,o=n.now().offset,S(v)}function m(v){return n.containerState={},e.attempt(kt,h,S)(v)}function h(v){return r++,t.push([n.currentConstruct,n.containerState]),m(v)}function S(v){if(v===null){i&&P(),b(0),e.consume(v);return}return i=i||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:l}),I(v)}function I(v){if(v===null){E(e.exit("chunkFlow"),!0),b(0),e.consume(v);return}return z(v)?(e.consume(v),E(e.exit("chunkFlow")),r=0,n.interrupt=void 0,a):(e.consume(v),I)}function E(v,R){const V=n.sliceStream(v);if(R&&V.push(null),v.previous=l,l&&(l.next=v),l=v,i.defineSkip(v.start),i.write(V),n.parser.lazy[v.start.line]){let k=i.events.length;for(;k--;)if(i.events[k][1].start.offset<o&&(!i.events[k][1].end||i.events[k][1].end.offset>o))return;const D=n.events.length;let U=D,F,$;for(;U--;)if(n.events[U][0]==="exit"&&n.events[U][1].type==="chunkFlow"){if(F){$=n.events[U][1].end;break}F=!0}for(b(r),k=D;k<n.events.length;)n.events[k][1].end={...$},k++;ye(n.events,U+1,0,n.events.slice(D)),n.events.length=k}}function b(v){let R=t.length;for(;R-- >v;){const V=t[R];n.containerState=V[1],V[0].exit.call(n,e)}t.length=v}function P(){i.write([null]),l=void 0,i=void 0,n.containerState._closeFlow=void 0}}function ml(e,n,t){return K(e,e.attempt(this.parser.constructs.document,n,t),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function bt(e){if(e===null||ie(e)||cl(e))return 1;if(ul(e))return 2}function Xn(e,n,t){const r=[];let i=-1;for(;++i<e.length;){const l=e[i].resolveAll;l&&!r.includes(l)&&(n=l(n,t),r.push(l))}return n}const Mn={name:"attention",resolveAll:gl,tokenize:yl};function gl(e,n){let t=-1,r,i,l,o,a,c,s,u;for(;++t<e.length;)if(e[t][0]==="enter"&&e[t][1].type==="attentionSequence"&&e[t][1]._close){for(r=t;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&n.sliceSerialize(e[r][1]).charCodeAt(0)===n.sliceSerialize(e[t][1]).charCodeAt(0)){if((e[r][1]._close||e[t][1]._open)&&(e[t][1].end.offset-e[t][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[t][1].end.offset-e[t][1].start.offset)%3))continue;c=e[r][1].end.offset-e[r][1].start.offset>1&&e[t][1].end.offset-e[t][1].start.offset>1?2:1;const p={...e[r][1].end},m={...e[t][1].start};wt(p,-c),wt(m,c),o={type:c>1?"strongSequence":"emphasisSequence",start:p,end:{...e[r][1].end}},a={type:c>1?"strongSequence":"emphasisSequence",start:{...e[t][1].start},end:m},l={type:c>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[t][1].start}},i={type:c>1?"strong":"emphasis",start:{...o.start},end:{...a.end}},e[r][1].end={...o.start},e[t][1].start={...a.end},s=[],e[r][1].end.offset-e[r][1].start.offset&&(s=pe(s,[["enter",e[r][1],n],["exit",e[r][1],n]])),s=pe(s,[["enter",i,n],["enter",o,n],["exit",o,n],["enter",l,n]]),s=pe(s,Xn(n.parser.constructs.insideSpan.null,e.slice(r+1,t),n)),s=pe(s,[["exit",l,n],["enter",a,n],["exit",a,n],["exit",i,n]]),e[t][1].end.offset-e[t][1].start.offset?(u=2,s=pe(s,[["enter",e[t][1],n],["exit",e[t][1],n]])):u=0,ye(e,r-1,t-r+3,s),t=r+s.length-u-2;break}}for(t=-1;++t<e.length;)e[t][1].type==="attentionSequence"&&(e[t][1].type="data");return e}function yl(e,n){const t=this.parser.constructs.attentionMarkers.null,r=this.previous,i=bt(r);let l;return o;function o(c){return l=c,e.enter("attentionSequence"),a(c)}function a(c){if(c===l)return e.consume(c),a;const s=e.exit("attentionSequence"),u=bt(c),p=!u||u===2&&i||t.includes(c),m=!i||i===2&&u||t.includes(r);return s._open=!!(l===42?p:p&&(i||!m)),s._close=!!(l===42?m:m&&(u||!p)),n(c)}}function wt(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const xl={name:"autolink",tokenize:kl};function kl(e,n,t){let r=0;return i;function i(h){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),l}function l(h){return ge(h)?(e.consume(h),o):h===64?t(h):s(h)}function o(h){return h===43||h===45||h===46||se(h)?(r=1,a(h)):s(h)}function a(h){return h===58?(e.consume(h),r=0,c):(h===43||h===45||h===46||se(h))&&r++<32?(e.consume(h),a):(r=0,s(h))}function c(h){return h===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),n):h===null||h===32||h===60||jn(h)?t(h):(e.consume(h),c)}function s(h){return h===64?(e.consume(h),u):ol(h)?(e.consume(h),s):t(h)}function u(h){return se(h)?p(h):t(h)}function p(h){return h===46?(e.consume(h),r=0,u):h===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),n):m(h)}function m(h){if((h===45||se(h))&&r++<63){const S=h===45?m:p;return e.consume(h),S}return t(h)}}const pn={partial:!0,tokenize:bl};function bl(e,n,t){return r;function r(l){return W(l)?K(e,i,"linePrefix")(l):i(l)}function i(l){return l===null||z(l)?n(l):t(l)}}const hr={continuation:{tokenize:Cl},exit:Sl,name:"blockQuote",tokenize:wl};function wl(e,n,t){const r=this;return i;function i(o){if(o===62){const a=r.containerState;return a.open||(e.enter("blockQuote",{_container:!0}),a.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(o),e.exit("blockQuoteMarker"),l}return t(o)}function l(o){return W(o)?(e.enter("blockQuotePrefixWhitespace"),e.consume(o),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(o))}}function Cl(e,n,t){const r=this;return i;function i(o){return W(o)?K(e,l,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):l(o)}function l(o){return e.attempt(hr,n,t)(o)}}function Sl(e){e.exit("blockQuote")}const fr={name:"characterEscape",tokenize:_l};function _l(e,n,t){return r;function r(l){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(l),e.exit("escapeMarker"),i}function i(l){return sl(l)?(e.enter("characterEscapeValue"),e.consume(l),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):t(l)}}const dr={name:"characterReference",tokenize:Il};function Il(e,n,t){const r=this;let i=0,l,o;return a;function a(p){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(p),e.exit("characterReferenceMarker"),c}function c(p){return p===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(p),e.exit("characterReferenceMarkerNumeric"),s):(e.enter("characterReferenceValue"),l=31,o=se,u(p))}function s(p){return p===88||p===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(p),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),l=6,o=al,u):(e.enter("characterReferenceValue"),l=7,o=zn,u(p))}function u(p){if(p===59&&i){const m=e.exit("characterReferenceValue");return o===se&&!Yn(r.sliceSerialize(m))?t(p):(e.enter("characterReferenceMarker"),e.consume(p),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return o(p)&&i++<l?(e.consume(p),u):t(p)}}const Ct={partial:!0,tokenize:vl},St={concrete:!0,name:"codeFenced",tokenize:El};function El(e,n,t){const r=this,i={partial:!0,tokenize:V};let l=0,o=0,a;return c;function c(k){return s(k)}function s(k){const D=r.events[r.events.length-1];return l=D&&D[1].type==="linePrefix"?D[2].sliceSerialize(D[1],!0).length:0,a=k,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),u(k)}function u(k){return k===a?(o++,e.consume(k),u):o<3?t(k):(e.exit("codeFencedFenceSequence"),W(k)?K(e,p,"whitespace")(k):p(k))}function p(k){return k===null||z(k)?(e.exit("codeFencedFence"),r.interrupt?n(k):e.check(Ct,I,R)(k)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),m(k))}function m(k){return k===null||z(k)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),p(k)):W(k)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),K(e,h,"whitespace")(k)):k===96&&k===a?t(k):(e.consume(k),m)}function h(k){return k===null||z(k)?p(k):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),S(k))}function S(k){return k===null||z(k)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),p(k)):k===96&&k===a?t(k):(e.consume(k),S)}function I(k){return e.attempt(i,R,E)(k)}function E(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),b}function b(k){return l>0&&W(k)?K(e,P,"linePrefix",l+1)(k):P(k)}function P(k){return k===null||z(k)?e.check(Ct,I,R)(k):(e.enter("codeFlowValue"),v(k))}function v(k){return k===null||z(k)?(e.exit("codeFlowValue"),P(k)):(e.consume(k),v)}function R(k){return e.exit("codeFenced"),n(k)}function V(k,D,U){let F=0;return $;function $(x){return k.enter("lineEnding"),k.consume(x),k.exit("lineEnding"),N}function N(x){return k.enter("codeFencedFence"),W(x)?K(k,C,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):C(x)}function C(x){return x===a?(k.enter("codeFencedFenceSequence"),j(x)):U(x)}function j(x){return x===a?(F++,k.consume(x),j):F>=o?(k.exit("codeFencedFenceSequence"),W(x)?K(k,T,"whitespace")(x):T(x)):U(x)}function T(x){return x===null||z(x)?(k.exit("codeFencedFence"),D(x)):U(x)}}}function vl(e,n,t){const r=this;return i;function i(o){return o===null?t(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),l)}function l(o){return r.parser.lazy[r.now().line]?t(o):n(o)}}const yn={name:"codeIndented",tokenize:Ll},Tl={partial:!0,tokenize:Nl};function Ll(e,n,t){const r=this;return i;function i(s){return e.enter("codeIndented"),K(e,l,"linePrefix",5)(s)}function l(s){const u=r.events[r.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?o(s):t(s)}function o(s){return s===null?c(s):z(s)?e.attempt(Tl,o,c)(s):(e.enter("codeFlowValue"),a(s))}function a(s){return s===null||z(s)?(e.exit("codeFlowValue"),o(s)):(e.consume(s),a)}function c(s){return e.exit("codeIndented"),n(s)}}function Nl(e,n,t){const r=this;return i;function i(o){return r.parser.lazy[r.now().line]?t(o):z(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i):K(e,l,"linePrefix",5)(o)}function l(o){const a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?n(o):z(o)?i(o):t(o)}}const Pl={name:"codeText",previous:jl,resolve:Al,tokenize:zl};function Al(e){let n=e.length-4,t=3,r,i;if((e[t][1].type==="lineEnding"||e[t][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(r=t;++r<n;)if(e[r][1].type==="codeTextData"){e[t][1].type="codeTextPadding",e[n][1].type="codeTextPadding",t+=2,n-=2;break}}for(r=t-1,n++;++r<=n;)i===void 0?r!==n&&e[r][1].type!=="lineEnding"&&(i=r):(r===n||e[r][1].type==="lineEnding")&&(e[i][1].type="codeTextData",r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),n-=r-i-2,r=i+2),i=void 0);return e}function jl(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function zl(e,n,t){let r=0,i,l;return o;function o(p){return e.enter("codeText"),e.enter("codeTextSequence"),a(p)}function a(p){return p===96?(e.consume(p),r++,a):(e.exit("codeTextSequence"),c(p))}function c(p){return p===null?t(p):p===32?(e.enter("space"),e.consume(p),e.exit("space"),c):p===96?(l=e.enter("codeTextSequence"),i=0,u(p)):z(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),c):(e.enter("codeTextData"),s(p))}function s(p){return p===null||p===32||p===96||z(p)?(e.exit("codeTextData"),c(p)):(e.consume(p),s)}function u(p){return p===96?(e.consume(p),i++,u):i===r?(e.exit("codeTextSequence"),e.exit("codeText"),n(p)):(l.type="codeTextData",s(p))}}class Ml{constructor(n){this.left=n?[...n]:[],this.right=[]}get(n){if(n<0||n>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+n+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return n<this.left.length?this.left[n]:this.right[this.right.length-n+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(n,t){const r=t??Number.POSITIVE_INFINITY;return r<this.left.length?this.left.slice(n,r):n>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(n,t,r){const i=t||0;this.setCursor(Math.trunc(n));const l=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&Ue(this.left,r),l.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(n){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(n)}pushMany(n){this.setCursor(Number.POSITIVE_INFINITY),Ue(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Ue(this.right,n.reverse())}setCursor(n){if(!(n===this.left.length||n>this.left.length&&this.right.length===0||n<0&&this.left.length===0))if(n<this.left.length){const t=this.left.splice(n,Number.POSITIVE_INFINITY);Ue(this.right,t.reverse())}else{const t=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Ue(this.left,t.reverse())}}}function Ue(e,n){let t=0;if(n.length<1e4)e.push(...n);else for(;t<n.length;)e.push(...n.slice(t,t+1e4)),t+=1e4}function mr(e){const n={};let t=-1,r,i,l,o,a,c,s;const u=new Ml(e);for(;++t<u.length;){for(;t in n;)t=n[t];if(r=u.get(t),t&&r[1].type==="chunkFlow"&&u.get(t-1)[1].type==="listItemPrefix"&&(c=r[1]._tokenizer.events,l=0,l<c.length&&c[l][1].type==="lineEndingBlank"&&(l+=2),l<c.length&&c[l][1].type==="content"))for(;++l<c.length&&c[l][1].type!=="content";)c[l][1].type==="chunkText"&&(c[l][1]._isInFirstContentOfListItem=!0,l++);if(r[0]==="enter")r[1].contentType&&(Object.assign(n,Dl(u,t)),t=n[t],s=!0);else if(r[1]._container){for(l=t,i=void 0;l--;)if(o=u.get(l),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(i&&(u.get(i)[1].type="lineEndingBlank"),o[1].type="lineEnding",i=l);else if(!(o[1].type==="linePrefix"||o[1].type==="listItemIndent"))break;i&&(r[1].end={...u.get(i)[1].start},a=u.slice(i,t),a.unshift(r),u.splice(i,t-i+1,a))}}return ye(e,0,Number.POSITIVE_INFINITY,u.slice(0)),!s}function Dl(e,n){const t=e.get(n)[1],r=e.get(n)[2];let i=n-1;const l=[];let o=t._tokenizer;o||(o=r.parser[t.contentType](t.start),t._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const a=o.events,c=[],s={};let u,p,m=-1,h=t,S=0,I=0;const E=[I];for(;h;){for(;e.get(++i)[1]!==h;);l.push(i),h._tokenizer||(u=r.sliceStream(h),h.next||u.push(null),p&&o.defineSkip(h.start),h._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(u),h._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),p=h,h=h.next}for(h=t;++m<a.length;)a[m][0]==="exit"&&a[m-1][0]==="enter"&&a[m][1].type===a[m-1][1].type&&a[m][1].start.line!==a[m][1].end.line&&(I=m+1,E.push(I),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(o.events=[],h?(h._tokenizer=void 0,h.previous=void 0):E.pop(),m=E.length;m--;){const b=a.slice(E[m],E[m+1]),P=l.pop();c.push([P,P+b.length-1]),e.splice(P,2,b)}for(c.reverse(),m=-1;++m<c.length;)s[S+c[m][0]]=S+c[m][1],S+=c[m][1]-c[m][0]-1;return s}const Bl={resolve:Rl,tokenize:Fl},Ol={partial:!0,tokenize:$l};function Rl(e){return mr(e),e}function Fl(e,n){let t;return r;function r(a){return e.enter("content"),t=e.enter("chunkContent",{contentType:"content"}),i(a)}function i(a){return a===null?l(a):z(a)?e.check(Ol,o,l)(a):(e.consume(a),i)}function l(a){return e.exit("chunkContent"),e.exit("content"),n(a)}function o(a){return e.consume(a),e.exit("chunkContent"),t.next=e.enter("chunkContent",{contentType:"content",previous:t}),t=t.next,i}}function $l(e,n,t){const r=this;return i;function i(o){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),K(e,l,"linePrefix")}function l(o){if(o===null||z(o))return t(o);const a=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?n(o):e.interrupt(r.parser.constructs.flow,t,n)(o)}}function gr(e,n,t,r,i,l,o,a,c){const s=c||Number.POSITIVE_INFINITY;let u=0;return p;function p(b){return b===60?(e.enter(r),e.enter(i),e.enter(l),e.consume(b),e.exit(l),m):b===null||b===32||b===41||jn(b)?t(b):(e.enter(r),e.enter(o),e.enter(a),e.enter("chunkString",{contentType:"string"}),I(b))}function m(b){return b===62?(e.enter(l),e.consume(b),e.exit(l),e.exit(i),e.exit(r),n):(e.enter(a),e.enter("chunkString",{contentType:"string"}),h(b))}function h(b){return b===62?(e.exit("chunkString"),e.exit(a),m(b)):b===null||b===60||z(b)?t(b):(e.consume(b),b===92?S:h)}function S(b){return b===60||b===62||b===92?(e.consume(b),h):h(b)}function I(b){return!u&&(b===null||b===41||ie(b))?(e.exit("chunkString"),e.exit(a),e.exit(o),e.exit(r),n(b)):u<s&&b===40?(e.consume(b),u++,I):b===41?(e.consume(b),u--,I):b===null||b===32||b===40||jn(b)?t(b):(e.consume(b),b===92?E:I)}function E(b){return b===40||b===41||b===92?(e.consume(b),I):I(b)}}function yr(e,n,t,r,i,l){const o=this;let a=0,c;return s;function s(h){return e.enter(r),e.enter(i),e.consume(h),e.exit(i),e.enter(l),u}function u(h){return a>999||h===null||h===91||h===93&&!c||h===94&&!a&&"_hiddenFootnoteSupport"in o.parser.constructs?t(h):h===93?(e.exit(l),e.enter(i),e.consume(h),e.exit(i),e.exit(r),n):z(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),u):(e.enter("chunkString",{contentType:"string"}),p(h))}function p(h){return h===null||h===91||h===93||z(h)||a++>999?(e.exit("chunkString"),u(h)):(e.consume(h),c||(c=!W(h)),h===92?m:p)}function m(h){return h===91||h===92||h===93?(e.consume(h),a++,p):p(h)}}function xr(e,n,t,r,i,l){let o;return a;function a(m){return m===34||m===39||m===40?(e.enter(r),e.enter(i),e.consume(m),e.exit(i),o=m===40?41:m,c):t(m)}function c(m){return m===o?(e.enter(i),e.consume(m),e.exit(i),e.exit(r),n):(e.enter(l),s(m))}function s(m){return m===o?(e.exit(l),c(o)):m===null?t(m):z(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),K(e,s,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),u(m))}function u(m){return m===o||m===null||z(m)?(e.exit("chunkString"),s(m)):(e.consume(m),m===92?p:u)}function p(m){return m===o||m===92?(e.consume(m),u):u(m)}}function Xe(e,n){let t;return r;function r(i){return z(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t=!0,r):W(i)?K(e,r,t?"linePrefix":"lineSuffix")(i):n(i)}}const Hl={name:"definition",tokenize:Ul},Vl={partial:!0,tokenize:ql};function Ul(e,n,t){const r=this;let i;return l;function l(h){return e.enter("definition"),o(h)}function o(h){return yr.call(r,e,a,t,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function a(h){return i=Me(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),c):t(h)}function c(h){return ie(h)?Xe(e,s)(h):s(h)}function s(h){return gr(e,u,t,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function u(h){return e.attempt(Vl,p,p)(h)}function p(h){return W(h)?K(e,m,"whitespace")(h):m(h)}function m(h){return h===null||z(h)?(e.exit("definition"),r.parser.defined.push(i),n(h)):t(h)}}function ql(e,n,t){return r;function r(a){return ie(a)?Xe(e,i)(a):t(a)}function i(a){return xr(e,l,t,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function l(a){return W(a)?K(e,o,"whitespace")(a):o(a)}function o(a){return a===null||z(a)?n(a):t(a)}}const Wl={name:"hardBreakEscape",tokenize:Yl};function Yl(e,n,t){return r;function r(l){return e.enter("hardBreakEscape"),e.consume(l),i}function i(l){return z(l)?(e.exit("hardBreakEscape"),n(l)):t(l)}}const Xl={name:"headingAtx",resolve:Kl,tokenize:Ql};function Kl(e,n){let t=e.length-2,r=3,i,l;return e[r][1].type==="whitespace"&&(r+=2),t-2>r&&e[t][1].type==="whitespace"&&(t-=2),e[t][1].type==="atxHeadingSequence"&&(r===t-1||t-4>r&&e[t-2][1].type==="whitespace")&&(t-=r+1===t?2:4),t>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[t][1].end},l={type:"chunkText",start:e[r][1].start,end:e[t][1].end,contentType:"text"},ye(e,r,t-r+1,[["enter",i,n],["enter",l,n],["exit",l,n],["exit",i,n]])),e}function Ql(e,n,t){let r=0;return i;function i(u){return e.enter("atxHeading"),l(u)}function l(u){return e.enter("atxHeadingSequence"),o(u)}function o(u){return u===35&&r++<6?(e.consume(u),o):u===null||ie(u)?(e.exit("atxHeadingSequence"),a(u)):t(u)}function a(u){return u===35?(e.enter("atxHeadingSequence"),c(u)):u===null||z(u)?(e.exit("atxHeading"),n(u)):W(u)?K(e,a,"whitespace")(u):(e.enter("atxHeadingText"),s(u))}function c(u){return u===35?(e.consume(u),c):(e.exit("atxHeadingSequence"),a(u))}function s(u){return u===null||u===35||ie(u)?(e.exit("atxHeadingText"),a(u)):(e.consume(u),s)}}const Zl=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],_t=["pre","script","style","textarea"],Jl={concrete:!0,name:"htmlFlow",resolveTo:no,tokenize:to},Gl={partial:!0,tokenize:io},eo={partial:!0,tokenize:ro};function no(e){let n=e.length;for(;n--&&!(e[n][0]==="enter"&&e[n][1].type==="htmlFlow"););return n>1&&e[n-2][1].type==="linePrefix"&&(e[n][1].start=e[n-2][1].start,e[n+1][1].start=e[n-2][1].start,e.splice(n-2,2)),e}function to(e,n,t){const r=this;let i,l,o,a,c;return s;function s(d){return u(d)}function u(d){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(d),p}function p(d){return d===33?(e.consume(d),m):d===47?(e.consume(d),l=!0,I):d===63?(e.consume(d),i=3,r.interrupt?n:f):ge(d)?(e.consume(d),o=String.fromCharCode(d),E):t(d)}function m(d){return d===45?(e.consume(d),i=2,h):d===91?(e.consume(d),i=5,a=0,S):ge(d)?(e.consume(d),i=4,r.interrupt?n:f):t(d)}function h(d){return d===45?(e.consume(d),r.interrupt?n:f):t(d)}function S(d){const he="CDATA[";return d===he.charCodeAt(a++)?(e.consume(d),a===he.length?r.interrupt?n:C:S):t(d)}function I(d){return ge(d)?(e.consume(d),o=String.fromCharCode(d),E):t(d)}function E(d){if(d===null||d===47||d===62||ie(d)){const he=d===47,Ie=o.toLowerCase();return!he&&!l&&_t.includes(Ie)?(i=1,r.interrupt?n(d):C(d)):Zl.includes(o.toLowerCase())?(i=6,he?(e.consume(d),b):r.interrupt?n(d):C(d)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?t(d):l?P(d):v(d))}return d===45||se(d)?(e.consume(d),o+=String.fromCharCode(d),E):t(d)}function b(d){return d===62?(e.consume(d),r.interrupt?n:C):t(d)}function P(d){return W(d)?(e.consume(d),P):$(d)}function v(d){return d===47?(e.consume(d),$):d===58||d===95||ge(d)?(e.consume(d),R):W(d)?(e.consume(d),v):$(d)}function R(d){return d===45||d===46||d===58||d===95||se(d)?(e.consume(d),R):V(d)}function V(d){return d===61?(e.consume(d),k):W(d)?(e.consume(d),V):v(d)}function k(d){return d===null||d===60||d===61||d===62||d===96?t(d):d===34||d===39?(e.consume(d),c=d,D):W(d)?(e.consume(d),k):U(d)}function D(d){return d===c?(e.consume(d),c=null,F):d===null||z(d)?t(d):(e.consume(d),D)}function U(d){return d===null||d===34||d===39||d===47||d===60||d===61||d===62||d===96||ie(d)?V(d):(e.consume(d),U)}function F(d){return d===47||d===62||W(d)?v(d):t(d)}function $(d){return d===62?(e.consume(d),N):t(d)}function N(d){return d===null||z(d)?C(d):W(d)?(e.consume(d),N):t(d)}function C(d){return d===45&&i===2?(e.consume(d),A):d===60&&i===1?(e.consume(d),L):d===62&&i===4?(e.consume(d),J):d===63&&i===3?(e.consume(d),f):d===93&&i===5?(e.consume(d),Q):z(d)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(Gl,ue,j)(d)):d===null||z(d)?(e.exit("htmlFlowData"),j(d)):(e.consume(d),C)}function j(d){return e.check(eo,T,ue)(d)}function T(d){return e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),x}function x(d){return d===null||z(d)?j(d):(e.enter("htmlFlowData"),C(d))}function A(d){return d===45?(e.consume(d),f):C(d)}function L(d){return d===47?(e.consume(d),o="",q):C(d)}function q(d){if(d===62){const he=o.toLowerCase();return _t.includes(he)?(e.consume(d),J):C(d)}return ge(d)&&o.length<8?(e.consume(d),o+=String.fromCharCode(d),q):C(d)}function Q(d){return d===93?(e.consume(d),f):C(d)}function f(d){return d===62?(e.consume(d),J):d===45&&i===2?(e.consume(d),f):C(d)}function J(d){return d===null||z(d)?(e.exit("htmlFlowData"),ue(d)):(e.consume(d),J)}function ue(d){return e.exit("htmlFlow"),n(d)}}function ro(e,n,t){const r=this;return i;function i(o){return z(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),l):t(o)}function l(o){return r.parser.lazy[r.now().line]?t(o):n(o)}}function io(e,n,t){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(pn,n,t)}}const lo={name:"htmlText",tokenize:oo};function oo(e,n,t){const r=this;let i,l,o;return a;function a(f){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(f),c}function c(f){return f===33?(e.consume(f),s):f===47?(e.consume(f),V):f===63?(e.consume(f),v):ge(f)?(e.consume(f),U):t(f)}function s(f){return f===45?(e.consume(f),u):f===91?(e.consume(f),l=0,S):ge(f)?(e.consume(f),P):t(f)}function u(f){return f===45?(e.consume(f),h):t(f)}function p(f){return f===null?t(f):f===45?(e.consume(f),m):z(f)?(o=p,L(f)):(e.consume(f),p)}function m(f){return f===45?(e.consume(f),h):p(f)}function h(f){return f===62?A(f):f===45?m(f):p(f)}function S(f){const J="CDATA[";return f===J.charCodeAt(l++)?(e.consume(f),l===J.length?I:S):t(f)}function I(f){return f===null?t(f):f===93?(e.consume(f),E):z(f)?(o=I,L(f)):(e.consume(f),I)}function E(f){return f===93?(e.consume(f),b):I(f)}function b(f){return f===62?A(f):f===93?(e.consume(f),b):I(f)}function P(f){return f===null||f===62?A(f):z(f)?(o=P,L(f)):(e.consume(f),P)}function v(f){return f===null?t(f):f===63?(e.consume(f),R):z(f)?(o=v,L(f)):(e.consume(f),v)}function R(f){return f===62?A(f):v(f)}function V(f){return ge(f)?(e.consume(f),k):t(f)}function k(f){return f===45||se(f)?(e.consume(f),k):D(f)}function D(f){return z(f)?(o=D,L(f)):W(f)?(e.consume(f),D):A(f)}function U(f){return f===45||se(f)?(e.consume(f),U):f===47||f===62||ie(f)?F(f):t(f)}function F(f){return f===47?(e.consume(f),A):f===58||f===95||ge(f)?(e.consume(f),$):z(f)?(o=F,L(f)):W(f)?(e.consume(f),F):A(f)}function $(f){return f===45||f===46||f===58||f===95||se(f)?(e.consume(f),$):N(f)}function N(f){return f===61?(e.consume(f),C):z(f)?(o=N,L(f)):W(f)?(e.consume(f),N):F(f)}function C(f){return f===null||f===60||f===61||f===62||f===96?t(f):f===34||f===39?(e.consume(f),i=f,j):z(f)?(o=C,L(f)):W(f)?(e.consume(f),C):(e.consume(f),T)}function j(f){return f===i?(e.consume(f),i=void 0,x):f===null?t(f):z(f)?(o=j,L(f)):(e.consume(f),j)}function T(f){return f===null||f===34||f===39||f===60||f===61||f===96?t(f):f===47||f===62||ie(f)?F(f):(e.consume(f),T)}function x(f){return f===47||f===62||ie(f)?F(f):t(f)}function A(f){return f===62?(e.consume(f),e.exit("htmlTextData"),e.exit("htmlText"),n):t(f)}function L(f){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),q}function q(f){return W(f)?K(e,Q,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(f):Q(f)}function Q(f){return e.enter("htmlTextData"),o(f)}}const Kn={name:"labelEnd",resolveAll:co,resolveTo:po,tokenize:ho},ao={tokenize:fo},so={tokenize:mo},uo={tokenize:go};function co(e){let n=-1;const t=[];for(;++n<e.length;){const r=e[n][1];if(t.push(e[n]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const i=r.type==="labelImage"?4:2;r.type="data",n+=i}}return e.length!==t.length&&ye(e,0,e.length,t),e}function po(e,n){let t=e.length,r=0,i,l,o,a;for(;t--;)if(i=e[t][1],l){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;e[t][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(o){if(e[t][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(l=t,i.type!=="labelLink")){r=2;break}}else i.type==="labelEnd"&&(o=t);const c={type:e[l][1].type==="labelLink"?"link":"image",start:{...e[l][1].start},end:{...e[e.length-1][1].end}},s={type:"label",start:{...e[l][1].start},end:{...e[o][1].end}},u={type:"labelText",start:{...e[l+r+2][1].end},end:{...e[o-2][1].start}};return a=[["enter",c,n],["enter",s,n]],a=pe(a,e.slice(l+1,l+r+3)),a=pe(a,[["enter",u,n]]),a=pe(a,Xn(n.parser.constructs.insideSpan.null,e.slice(l+r+4,o-3),n)),a=pe(a,[["exit",u,n],e[o-2],e[o-1],["exit",s,n]]),a=pe(a,e.slice(o+1)),a=pe(a,[["exit",c,n]]),ye(e,l,e.length,a),e}function ho(e,n,t){const r=this;let i=r.events.length,l,o;for(;i--;)if((r.events[i][1].type==="labelImage"||r.events[i][1].type==="labelLink")&&!r.events[i][1]._balanced){l=r.events[i][1];break}return a;function a(m){return l?l._inactive?p(m):(o=r.parser.defined.includes(Me(r.sliceSerialize({start:l.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(m),e.exit("labelMarker"),e.exit("labelEnd"),c):t(m)}function c(m){return m===40?e.attempt(ao,u,o?u:p)(m):m===91?e.attempt(so,u,o?s:p)(m):o?u(m):p(m)}function s(m){return e.attempt(uo,u,p)(m)}function u(m){return n(m)}function p(m){return l._balanced=!0,t(m)}}function fo(e,n,t){return r;function r(p){return e.enter("resource"),e.enter("resourceMarker"),e.consume(p),e.exit("resourceMarker"),i}function i(p){return ie(p)?Xe(e,l)(p):l(p)}function l(p){return p===41?u(p):gr(e,o,a,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(p)}function o(p){return ie(p)?Xe(e,c)(p):u(p)}function a(p){return t(p)}function c(p){return p===34||p===39||p===40?xr(e,s,t,"resourceTitle","resourceTitleMarker","resourceTitleString")(p):u(p)}function s(p){return ie(p)?Xe(e,u)(p):u(p)}function u(p){return p===41?(e.enter("resourceMarker"),e.consume(p),e.exit("resourceMarker"),e.exit("resource"),n):t(p)}}function mo(e,n,t){const r=this;return i;function i(a){return yr.call(r,e,l,o,"reference","referenceMarker","referenceString")(a)}function l(a){return r.parser.defined.includes(Me(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?n(a):t(a)}function o(a){return t(a)}}function go(e,n,t){return r;function r(l){return e.enter("reference"),e.enter("referenceMarker"),e.consume(l),e.exit("referenceMarker"),i}function i(l){return l===93?(e.enter("referenceMarker"),e.consume(l),e.exit("referenceMarker"),e.exit("reference"),n):t(l)}}const yo={name:"labelStartImage",resolveAll:Kn.resolveAll,tokenize:xo};function xo(e,n,t){const r=this;return i;function i(a){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(a),e.exit("labelImageMarker"),l}function l(a){return a===91?(e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelImage"),o):t(a)}function o(a){return a===94&&"_hiddenFootnoteSupport"in r.parser.constructs?t(a):n(a)}}const ko={name:"labelStartLink",resolveAll:Kn.resolveAll,tokenize:bo};function bo(e,n,t){const r=this;return i;function i(o){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelLink"),l}function l(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?t(o):n(o)}}const xn={name:"lineEnding",tokenize:wo};function wo(e,n){return t;function t(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),K(e,n,"linePrefix")}}const sn={name:"thematicBreak",tokenize:Co};function Co(e,n,t){let r=0,i;return l;function l(s){return e.enter("thematicBreak"),o(s)}function o(s){return i=s,a(s)}function a(s){return s===i?(e.enter("thematicBreakSequence"),c(s)):r>=3&&(s===null||z(s))?(e.exit("thematicBreak"),n(s)):t(s)}function c(s){return s===i?(e.consume(s),r++,c):(e.exit("thematicBreakSequence"),W(s)?K(e,a,"whitespace")(s):a(s))}}const re={continuation:{tokenize:Eo},exit:To,name:"list",tokenize:Io},So={partial:!0,tokenize:Lo},_o={partial:!0,tokenize:vo};function Io(e,n,t){const r=this,i=r.events[r.events.length-1];let l=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,o=0;return a;function a(h){const S=r.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!r.containerState.marker||h===r.containerState.marker:zn(h)){if(r.containerState.type||(r.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(sn,t,s)(h):s(h);if(!r.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(h)}return t(h)}function c(h){return zn(h)&&++o<10?(e.consume(h),c):(!r.interrupt||o<2)&&(r.containerState.marker?h===r.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),s(h)):t(h)}function s(h){return e.enter("listItemMarker"),e.consume(h),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||h,e.check(pn,r.interrupt?t:u,e.attempt(So,m,p))}function u(h){return r.containerState.initialBlankLine=!0,l++,m(h)}function p(h){return W(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),m):t(h)}function m(h){return r.containerState.size=l+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(h)}}function Eo(e,n,t){const r=this;return r.containerState._closeFlow=void 0,e.check(pn,i,l);function i(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,K(e,n,"listItemIndent",r.containerState.size+1)(a)}function l(a){return r.containerState.furtherBlankLines||!W(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(_o,n,o)(a))}function o(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,K(e,e.attempt(re,n,t),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function vo(e,n,t){const r=this;return K(e,i,"listItemIndent",r.containerState.size+1);function i(l){const o=r.events[r.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===r.containerState.size?n(l):t(l)}}function To(e){e.exit(this.containerState.type)}function Lo(e,n,t){const r=this;return K(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(l){const o=r.events[r.events.length-1];return!W(l)&&o&&o[1].type==="listItemPrefixWhitespace"?n(l):t(l)}}const It={name:"setextUnderline",resolveTo:No,tokenize:Po};function No(e,n){let t=e.length,r,i,l;for(;t--;)if(e[t][0]==="enter"){if(e[t][1].type==="content"){r=t;break}e[t][1].type==="paragraph"&&(i=t)}else e[t][1].type==="content"&&e.splice(t,1),!l&&e[t][1].type==="definition"&&(l=t);const o={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type="setextHeadingText",l?(e.splice(i,0,["enter",o,n]),e.splice(l+1,0,["exit",e[r][1],n]),e[r][1].end={...e[l][1].end}):e[r][1]=o,e.push(["exit",o,n]),e}function Po(e,n,t){const r=this;let i;return l;function l(s){let u=r.events.length,p;for(;u--;)if(r.events[u][1].type!=="lineEnding"&&r.events[u][1].type!=="linePrefix"&&r.events[u][1].type!=="content"){p=r.events[u][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||p)?(e.enter("setextHeadingLine"),i=s,o(s)):t(s)}function o(s){return e.enter("setextHeadingLineSequence"),a(s)}function a(s){return s===i?(e.consume(s),a):(e.exit("setextHeadingLineSequence"),W(s)?K(e,c,"lineSuffix")(s):c(s))}function c(s){return s===null||z(s)?(e.exit("setextHeadingLine"),n(s)):t(s)}}const Ao={tokenize:jo};function jo(e){const n=this,t=e.attempt(pn,r,e.attempt(this.parser.constructs.flowInitial,i,K(e,e.attempt(this.parser.constructs.flow,i,e.attempt(Bl,i)),"linePrefix")));return t;function r(l){if(l===null){e.consume(l);return}return e.enter("lineEndingBlank"),e.consume(l),e.exit("lineEndingBlank"),n.currentConstruct=void 0,t}function i(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),n.currentConstruct=void 0,t}}const zo={resolveAll:br()},Mo=kr("string"),Do=kr("text");function kr(e){return{resolveAll:br(e==="text"?Bo:void 0),tokenize:n};function n(t){const r=this,i=this.parser.constructs[e],l=t.attempt(i,o,a);return o;function o(u){return s(u)?l(u):a(u)}function a(u){if(u===null){t.consume(u);return}return t.enter("data"),t.consume(u),c}function c(u){return s(u)?(t.exit("data"),l(u)):(t.consume(u),c)}function s(u){if(u===null)return!0;const p=i[u];let m=-1;if(p)for(;++m<p.length;){const h=p[m];if(!h.previous||h.previous.call(r,r.previous))return!0}return!1}}}function br(e){return n;function n(t,r){let i=-1,l;for(;++i<=t.length;)l===void 0?t[i]&&t[i][1].type==="data"&&(l=i,i++):(!t[i]||t[i][1].type!=="data")&&(i!==l+2&&(t[l][1].end=t[i-1][1].end,t.splice(l+2,i-l-2),i=l+2),l=void 0);return e?e(t,r):t}}function Bo(e,n){let t=0;for(;++t<=e.length;)if((t===e.length||e[t][1].type==="lineEnding")&&e[t-1][1].type==="data"){const r=e[t-1][1],i=n.sliceStream(r);let l=i.length,o=-1,a=0,c;for(;l--;){const s=i[l];if(typeof s=="string"){for(o=s.length;s.charCodeAt(o-1)===32;)a++,o--;if(o)break;o=-1}else if(s===-2)c=!0,a++;else if(s!==-1){l++;break}}if(n._contentTypeTextTrailing&&t===e.length&&(a=0),a){const s={type:t===e.length||c||a<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:l?o:r.start._bufferIndex+o,_index:r.start._index+l,line:r.end.line,column:r.end.column-a,offset:r.end.offset-a},end:{...r.end}};r.end={...s.start},r.start.offset===r.end.offset?Object.assign(r,s):(e.splice(t,0,["enter",s,n],["exit",s,n]),t+=2)}t++}return e}const Oo={42:re,43:re,45:re,48:re,49:re,50:re,51:re,52:re,53:re,54:re,55:re,56:re,57:re,62:hr},Ro={91:Hl},Fo={[-2]:yn,[-1]:yn,32:yn},$o={35:Xl,42:sn,45:[It,sn],60:Jl,61:It,95:sn,96:St,126:St},Ho={38:dr,92:fr},Vo={[-5]:xn,[-4]:xn,[-3]:xn,33:yo,38:dr,42:Mn,60:[xl,lo],91:ko,92:[Wl,fr],93:Kn,95:Mn,96:Pl},Uo={null:[Mn,zo]},qo={null:[42,95]},Wo={null:[]},Yo=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:qo,contentInitial:Ro,disable:Wo,document:Oo,flow:$o,flowInitial:Fo,insideSpan:Uo,string:Ho,text:Vo},Symbol.toStringTag,{value:"Module"}));function Xo(e,n,t){let r={_bufferIndex:-1,_index:0,line:t&&t.line||1,column:t&&t.column||1,offset:t&&t.offset||0};const i={},l=[];let o=[],a=[];const c={attempt:D(V),check:D(k),consume:P,enter:v,exit:R,interrupt:D(k,{interrupt:!0})},s={code:null,containerState:{},defineSkip:I,events:[],now:S,parser:e,previous:null,sliceSerialize:m,sliceStream:h,write:p};let u=n.tokenize.call(s,c);return n.resolveAll&&l.push(n),s;function p(N){return o=pe(o,N),E(),o[o.length-1]!==null?[]:(U(n,0),s.events=Xn(l,s.events,s),s.events)}function m(N,C){return Qo(h(N),C)}function h(N){return Ko(o,N)}function S(){const{_bufferIndex:N,_index:C,line:j,column:T,offset:x}=r;return{_bufferIndex:N,_index:C,line:j,column:T,offset:x}}function I(N){i[N.line]=N.column,$()}function E(){let N;for(;r._index<o.length;){const C=o[r._index];if(typeof C=="string")for(N=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===N&&r._bufferIndex<C.length;)b(C.charCodeAt(r._bufferIndex));else b(C)}}function b(N){u=u(N)}function P(N){z(N)?(r.line++,r.column=1,r.offset+=N===-3?2:1,$()):N!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===o[r._index].length&&(r._bufferIndex=-1,r._index++)),s.previous=N}function v(N,C){const j=C||{};return j.type=N,j.start=S(),s.events.push(["enter",j,s]),a.push(j),j}function R(N){const C=a.pop();return C.end=S(),s.events.push(["exit",C,s]),C}function V(N,C){U(N,C.from)}function k(N,C){C.restore()}function D(N,C){return j;function j(T,x,A){let L,q,Q,f;return Array.isArray(T)?ue(T):"tokenize"in T?ue([T]):J(T);function J(G){return Oe;function Oe(be){const Te=be!==null&&G[be],Le=be!==null&&G.null,en=[...Array.isArray(Te)?Te:Te?[Te]:[],...Array.isArray(Le)?Le:Le?[Le]:[]];return ue(en)(be)}}function ue(G){return L=G,q=0,G.length===0?A:d(G[q])}function d(G){return Oe;function Oe(be){return f=F(),Q=G,G.partial||(s.currentConstruct=G),G.name&&s.parser.constructs.disable.null.includes(G.name)?Ie():G.tokenize.call(C?Object.assign(Object.create(s),C):s,c,he,Ie)(be)}}function he(G){return N(Q,f),x}function Ie(G){return f.restore(),++q<L.length?d(L[q]):A}}}function U(N,C){N.resolveAll&&!l.includes(N)&&l.push(N),N.resolve&&ye(s.events,C,s.events.length-C,N.resolve(s.events.slice(C),s)),N.resolveTo&&(s.events=N.resolveTo(s.events,s))}function F(){const N=S(),C=s.previous,j=s.currentConstruct,T=s.events.length,x=Array.from(a);return{from:T,restore:A};function A(){r=N,s.previous=C,s.currentConstruct=j,s.events.length=T,a=x,$()}}function $(){r.line in i&&r.column<2&&(r.column=i[r.line],r.offset+=i[r.line]-1)}}function Ko(e,n){const t=n.start._index,r=n.start._bufferIndex,i=n.end._index,l=n.end._bufferIndex;let o;if(t===i)o=[e[t].slice(r,l)];else{if(o=e.slice(t,i),r>-1){const a=o[0];typeof a=="string"?o[0]=a.slice(r):o.shift()}l>0&&o.push(e[i].slice(0,l))}return o}function Qo(e,n){let t=-1;const r=[];let i;for(;++t<e.length;){const l=e[t];let o;if(typeof l=="string")o=l;else switch(l){case-5:{o="\r";break}case-4:{o=`
6
- `;break}case-3:{o=`\r
7
- `;break}case-2:{o=n?" ":" ";break}case-1:{if(!n&&i)continue;o=" ";break}default:o=String.fromCharCode(l)}i=l===-2,r.push(o)}return r.join("")}function Zo(e){const r={constructs:rl([Yo,...(e||{}).extensions||[]]),content:i(pl),defined:[],document:i(fl),flow:i(Ao),lazy:{},string:i(Mo),text:i(Do)};return r;function i(l){return o;function o(a){return Xo(r,l,a)}}}function Jo(e){for(;!mr(e););return e}const Et=/[\0\t\n\r]/g;function Go(){let e=1,n="",t=!0,r;return i;function i(l,o,a){const c=[];let s,u,p,m,h;for(l=n+(typeof l=="string"?l.toString():new TextDecoder(o||void 0).decode(l)),p=0,n="",t&&(l.charCodeAt(0)===65279&&p++,t=void 0);p<l.length;){if(Et.lastIndex=p,s=Et.exec(l),m=s&&s.index!==void 0?s.index:l.length,h=l.charCodeAt(m),!s){n=l.slice(p);break}if(h===10&&p===m&&r)c.push(-3),r=void 0;else switch(r&&(c.push(-5),r=void 0),p<m&&(c.push(l.slice(p,m)),e+=m-p),h){case 0:{c.push(65533),e++;break}case 9:{for(u=Math.ceil(e/4)*4,c.push(-2);e++<u;)c.push(-1);break}case 10:{c.push(-4),e=1;break}default:r=!0,e=1}p=m+1}return a&&(r&&c.push(-5),n&&c.push(n),c.push(null)),c}}const ea=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function na(e){return e.replace(ea,ta)}function ta(e,n,t){if(n)return n;if(t.charCodeAt(0)===35){const i=t.charCodeAt(1),l=i===120||i===88;return pr(t.slice(l?2:1),l?16:10)}return Yn(t)||e}const wr={}.hasOwnProperty;function ra(e,n,t){return typeof n!="string"&&(t=n,n=void 0),ia(t)(Jo(Zo(t).document().write(Go()(e,n,!0))))}function ia(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:l(it),autolinkProtocol:F,autolinkEmail:F,atxHeading:l(nt),blockQuote:l(Le),characterEscape:F,characterReference:F,codeFenced:l(en),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:l(en,o),codeText:l(Or,o),codeTextData:F,data:F,codeFlowValue:F,definition:l(Rr),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:l(Fr),hardBreakEscape:l(tt),hardBreakTrailing:l(tt),htmlFlow:l(rt,o),htmlFlowData:F,htmlText:l(rt,o),htmlTextData:F,image:l($r),label:o,link:l(it),listItem:l(Hr),listItemValue:m,listOrdered:l(lt,p),listUnordered:l(lt),paragraph:l(Vr),reference:d,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:l(nt),strong:l(Ur),thematicBreak:l(Wr)},exit:{atxHeading:c(),atxHeadingSequence:V,autolink:c(),autolinkEmail:Te,autolinkProtocol:be,blockQuote:c(),characterEscapeValue:$,characterReferenceMarkerHexadecimal:Ie,characterReferenceMarkerNumeric:Ie,characterReferenceValue:G,characterReference:Oe,codeFenced:c(E),codeFencedFence:I,codeFencedFenceInfo:h,codeFencedFenceMeta:S,codeFlowValue:$,codeIndented:c(b),codeText:c(x),codeTextData:$,data:$,definition:c(),definitionDestinationString:R,definitionLabelString:P,definitionTitleString:v,emphasis:c(),hardBreakEscape:c(C),hardBreakTrailing:c(C),htmlFlow:c(j),htmlFlowData:$,htmlText:c(T),htmlTextData:$,image:c(L),label:Q,labelText:q,lineEnding:N,link:c(A),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:he,resourceDestinationString:f,resourceTitleString:J,resource:ue,setextHeading:c(U),setextHeadingLineSequence:D,setextHeadingText:k,strong:c(),thematicBreak:c()}};Cr(n,(e||{}).mdastExtensions||[]);const t={};return r;function r(y){let _={type:"root",children:[]};const M={stack:[_],tokenStack:[],config:n,enter:a,exit:s,buffer:o,resume:u,data:t},H=[];let Y=-1;for(;++Y<y.length;)if(y[Y][1].type==="listOrdered"||y[Y][1].type==="listUnordered")if(y[Y][0]==="enter")H.push(Y);else{const fe=H.pop();Y=i(y,fe,Y)}for(Y=-1;++Y<y.length;){const fe=n[y[Y][0]];wr.call(fe,y[Y][1].type)&&fe[y[Y][1].type].call(Object.assign({sliceSerialize:y[Y][2].sliceSerialize},M),y[Y][1])}if(M.tokenStack.length>0){const fe=M.tokenStack[M.tokenStack.length-1];(fe[1]||vt).call(M,void 0,fe[0])}for(_.position={start:we(y.length>0?y[0][1].start:{line:1,column:1,offset:0}),end:we(y.length>0?y[y.length-2][1].end:{line:1,column:1,offset:0})},Y=-1;++Y<n.transforms.length;)_=n.transforms[Y](_)||_;return _}function i(y,_,M){let H=_-1,Y=-1,fe=!1,Ee,xe,Re,Fe;for(;++H<=M;){const oe=y[H];switch(oe[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{oe[0]==="enter"?Y++:Y--,Fe=void 0;break}case"lineEndingBlank":{oe[0]==="enter"&&(Ee&&!Fe&&!Y&&!Re&&(Re=H),Fe=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Fe=void 0}if(!Y&&oe[0]==="enter"&&oe[1].type==="listItemPrefix"||Y===-1&&oe[0]==="exit"&&(oe[1].type==="listUnordered"||oe[1].type==="listOrdered")){if(Ee){let Ne=H;for(xe=void 0;Ne--;){const ke=y[Ne];if(ke[1].type==="lineEnding"||ke[1].type==="lineEndingBlank"){if(ke[0]==="exit")continue;xe&&(y[xe][1].type="lineEndingBlank",fe=!0),ke[1].type="lineEnding",xe=Ne}else if(!(ke[1].type==="linePrefix"||ke[1].type==="blockQuotePrefix"||ke[1].type==="blockQuotePrefixWhitespace"||ke[1].type==="blockQuoteMarker"||ke[1].type==="listItemIndent"))break}Re&&(!xe||Re<xe)&&(Ee._spread=!0),Ee.end=Object.assign({},xe?y[xe][1].start:oe[1].end),y.splice(xe||H,0,["exit",Ee,oe[2]]),H++,M++}if(oe[1].type==="listItemPrefix"){const Ne={type:"listItem",_spread:!1,start:Object.assign({},oe[1].start),end:void 0};Ee=Ne,y.splice(H,0,["enter",Ne,oe[2]]),H++,M++,Re=void 0,Fe=!0}}}return y[_][1]._spread=fe,M}function l(y,_){return M;function M(H){a.call(this,y(H),H),_&&_.call(this,H)}}function o(){this.stack.push({type:"fragment",children:[]})}function a(y,_,M){this.stack[this.stack.length-1].children.push(y),this.stack.push(y),this.tokenStack.push([_,M||void 0]),y.position={start:we(_.start),end:void 0}}function c(y){return _;function _(M){y&&y.call(this,M),s.call(this,M)}}function s(y,_){const M=this.stack.pop(),H=this.tokenStack.pop();if(H)H[0].type!==y.type&&(_?_.call(this,y,H[0]):(H[1]||vt).call(this,y,H[0]));else throw new Error("Cannot close `"+y.type+"` ("+Ye({start:y.start,end:y.end})+"): it’s not open");M.position.end=we(y.end)}function u(){return nl(this.stack.pop())}function p(){this.data.expectingFirstListItemValue=!0}function m(y){if(this.data.expectingFirstListItemValue){const _=this.stack[this.stack.length-2];_.start=Number.parseInt(this.sliceSerialize(y),10),this.data.expectingFirstListItemValue=void 0}}function h(){const y=this.resume(),_=this.stack[this.stack.length-1];_.lang=y}function S(){const y=this.resume(),_=this.stack[this.stack.length-1];_.meta=y}function I(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function E(){const y=this.resume(),_=this.stack[this.stack.length-1];_.value=y.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const y=this.resume(),_=this.stack[this.stack.length-1];_.value=y.replace(/(\r?\n|\r)$/g,"")}function P(y){const _=this.resume(),M=this.stack[this.stack.length-1];M.label=_,M.identifier=Me(this.sliceSerialize(y)).toLowerCase()}function v(){const y=this.resume(),_=this.stack[this.stack.length-1];_.title=y}function R(){const y=this.resume(),_=this.stack[this.stack.length-1];_.url=y}function V(y){const _=this.stack[this.stack.length-1];if(!_.depth){const M=this.sliceSerialize(y).length;_.depth=M}}function k(){this.data.setextHeadingSlurpLineEnding=!0}function D(y){const _=this.stack[this.stack.length-1];_.depth=this.sliceSerialize(y).codePointAt(0)===61?1:2}function U(){this.data.setextHeadingSlurpLineEnding=void 0}function F(y){const M=this.stack[this.stack.length-1].children;let H=M[M.length-1];(!H||H.type!=="text")&&(H=qr(),H.position={start:we(y.start),end:void 0},M.push(H)),this.stack.push(H)}function $(y){const _=this.stack.pop();_.value+=this.sliceSerialize(y),_.position.end=we(y.end)}function N(y){const _=this.stack[this.stack.length-1];if(this.data.atHardBreak){const M=_.children[_.children.length-1];M.position.end=we(y.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(_.type)&&(F.call(this,y),$.call(this,y))}function C(){this.data.atHardBreak=!0}function j(){const y=this.resume(),_=this.stack[this.stack.length-1];_.value=y}function T(){const y=this.resume(),_=this.stack[this.stack.length-1];_.value=y}function x(){const y=this.resume(),_=this.stack[this.stack.length-1];_.value=y}function A(){const y=this.stack[this.stack.length-1];if(this.data.inReference){const _=this.data.referenceType||"shortcut";y.type+="Reference",y.referenceType=_,delete y.url,delete y.title}else delete y.identifier,delete y.label;this.data.referenceType=void 0}function L(){const y=this.stack[this.stack.length-1];if(this.data.inReference){const _=this.data.referenceType||"shortcut";y.type+="Reference",y.referenceType=_,delete y.url,delete y.title}else delete y.identifier,delete y.label;this.data.referenceType=void 0}function q(y){const _=this.sliceSerialize(y),M=this.stack[this.stack.length-2];M.label=na(_),M.identifier=Me(_).toLowerCase()}function Q(){const y=this.stack[this.stack.length-1],_=this.resume(),M=this.stack[this.stack.length-1];if(this.data.inReference=!0,M.type==="link"){const H=y.children;M.children=H}else M.alt=_}function f(){const y=this.resume(),_=this.stack[this.stack.length-1];_.url=y}function J(){const y=this.resume(),_=this.stack[this.stack.length-1];_.title=y}function ue(){this.data.inReference=void 0}function d(){this.data.referenceType="collapsed"}function he(y){const _=this.resume(),M=this.stack[this.stack.length-1];M.label=_,M.identifier=Me(this.sliceSerialize(y)).toLowerCase(),this.data.referenceType="full"}function Ie(y){this.data.characterReferenceType=y.type}function G(y){const _=this.sliceSerialize(y),M=this.data.characterReferenceType;let H;M?(H=pr(_,M==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):H=Yn(_);const Y=this.stack[this.stack.length-1];Y.value+=H}function Oe(y){const _=this.stack.pop();_.position.end=we(y.end)}function be(y){$.call(this,y);const _=this.stack[this.stack.length-1];_.url=this.sliceSerialize(y)}function Te(y){$.call(this,y);const _=this.stack[this.stack.length-1];_.url="mailto:"+this.sliceSerialize(y)}function Le(){return{type:"blockquote",children:[]}}function en(){return{type:"code",lang:null,meta:null,value:""}}function Or(){return{type:"inlineCode",value:""}}function Rr(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Fr(){return{type:"emphasis",children:[]}}function nt(){return{type:"heading",depth:0,children:[]}}function tt(){return{type:"break"}}function rt(){return{type:"html",value:""}}function $r(){return{type:"image",title:null,url:"",alt:null}}function it(){return{type:"link",title:null,url:"",children:[]}}function lt(y){return{type:"list",ordered:y.type==="listOrdered",start:null,spread:y._spread,children:[]}}function Hr(y){return{type:"listItem",spread:y._spread,checked:null,children:[]}}function Vr(){return{type:"paragraph",children:[]}}function Ur(){return{type:"strong",children:[]}}function qr(){return{type:"text",value:""}}function Wr(){return{type:"thematicBreak"}}}function we(e){return{line:e.line,column:e.column,offset:e.offset}}function Cr(e,n){let t=-1;for(;++t<n.length;){const r=n[t];Array.isArray(r)?Cr(e,r):la(e,r)}}function la(e,n){let t;for(t in n)if(wr.call(n,t))switch(t){case"canContainEols":{const r=n[t];r&&e[t].push(...r);break}case"transforms":{const r=n[t];r&&e[t].push(...r);break}case"enter":case"exit":{const r=n[t];r&&Object.assign(e[t],r);break}}}function vt(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+Ye({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+Ye({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Ye({start:n.start,end:n.end})+") is still open")}function oa(e){const n=this;n.parser=t;function t(r){return ra(r,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function aa(e,n){const t={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(n),!0)};return e.patch(n,t),e.applyData(n,t)}function sa(e,n){const t={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,t),[e.applyData(n,t),{type:"text",value:`
8
- `}]}function ua(e,n){const t=n.value?n.value+`
9
- `:"",r={},i=n.lang?n.lang.split(/\s+/):[];i.length>0&&(r.className=["language-"+i[0]]);let l={type:"element",tagName:"code",properties:r,children:[{type:"text",value:t}]};return n.meta&&(l.data={meta:n.meta}),e.patch(n,l),l=e.applyData(n,l),l={type:"element",tagName:"pre",properties:{},children:[l]},e.patch(n,l),l}function ca(e,n){const t={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,t),e.applyData(n,t)}function pa(e,n){const t={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,t),e.applyData(n,t)}function ha(e,n){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(n.identifier).toUpperCase(),i=Be(r.toLowerCase()),l=e.footnoteOrder.indexOf(r);let o,a=e.footnoteCounts.get(r);a===void 0?(a=0,e.footnoteOrder.push(r),o=e.footnoteOrder.length):o=l+1,a+=1,e.footnoteCounts.set(r,a);const c={type:"element",tagName:"a",properties:{href:"#"+t+"fn-"+i,id:t+"fnref-"+i+(a>1?"-"+a:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(o)}]};e.patch(n,c);const s={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(n,s),e.applyData(n,s)}function fa(e,n){const t={type:"element",tagName:"h"+n.depth,properties:{},children:e.all(n)};return e.patch(n,t),e.applyData(n,t)}function da(e,n){if(e.options.allowDangerousHtml){const t={type:"raw",value:n.value};return e.patch(n,t),e.applyData(n,t)}}function Sr(e,n){const t=n.referenceType;let r="]";if(t==="collapsed"?r+="[]":t==="full"&&(r+="["+(n.label||n.identifier)+"]"),n.type==="imageReference")return[{type:"text",value:"!["+n.alt+r}];const i=e.all(n),l=i[0];l&&l.type==="text"?l.value="["+l.value:i.unshift({type:"text",value:"["});const o=i[i.length-1];return o&&o.type==="text"?o.value+=r:i.push({type:"text",value:r}),i}function ma(e,n){const t=String(n.identifier).toUpperCase(),r=e.definitionById.get(t);if(!r)return Sr(e,n);const i={src:Be(r.url||""),alt:n.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);const l={type:"element",tagName:"img",properties:i,children:[]};return e.patch(n,l),e.applyData(n,l)}function ga(e,n){const t={src:Be(n.url)};n.alt!==null&&n.alt!==void 0&&(t.alt=n.alt),n.title!==null&&n.title!==void 0&&(t.title=n.title);const r={type:"element",tagName:"img",properties:t,children:[]};return e.patch(n,r),e.applyData(n,r)}function ya(e,n){const t={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};e.patch(n,t);const r={type:"element",tagName:"code",properties:{},children:[t]};return e.patch(n,r),e.applyData(n,r)}function xa(e,n){const t=String(n.identifier).toUpperCase(),r=e.definitionById.get(t);if(!r)return Sr(e,n);const i={href:Be(r.url||"")};r.title!==null&&r.title!==void 0&&(i.title=r.title);const l={type:"element",tagName:"a",properties:i,children:e.all(n)};return e.patch(n,l),e.applyData(n,l)}function ka(e,n){const t={href:Be(n.url)};n.title!==null&&n.title!==void 0&&(t.title=n.title);const r={type:"element",tagName:"a",properties:t,children:e.all(n)};return e.patch(n,r),e.applyData(n,r)}function ba(e,n,t){const r=e.all(n),i=t?wa(t):_r(n),l={},o=[];if(typeof n.checked=="boolean"){const u=r[0];let p;u&&u.type==="element"&&u.tagName==="p"?p=u:(p={type:"element",tagName:"p",properties:{},children:[]},r.unshift(p)),p.children.length>0&&p.children.unshift({type:"text",value:" "}),p.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:n.checked,disabled:!0},children:[]}),l.className=["task-list-item"]}let a=-1;for(;++a<r.length;){const u=r[a];(i||a!==0||u.type!=="element"||u.tagName!=="p")&&o.push({type:"text",value:`
10
- `}),u.type==="element"&&u.tagName==="p"&&!i?o.push(...u.children):o.push(u)}const c=r[r.length-1];c&&(i||c.type!=="element"||c.tagName!=="p")&&o.push({type:"text",value:`
11
- `});const s={type:"element",tagName:"li",properties:l,children:o};return e.patch(n,s),e.applyData(n,s)}function wa(e){let n=!1;if(e.type==="list"){n=e.spread||!1;const t=e.children;let r=-1;for(;!n&&++r<t.length;)n=_r(t[r])}return n}function _r(e){const n=e.spread;return n??e.children.length>1}function Ca(e,n){const t={},r=e.all(n);let i=-1;for(typeof n.start=="number"&&n.start!==1&&(t.start=n.start);++i<r.length;){const o=r[i];if(o.type==="element"&&o.tagName==="li"&&o.properties&&Array.isArray(o.properties.className)&&o.properties.className.includes("task-list-item")){t.className=["contains-task-list"];break}}const l={type:"element",tagName:n.ordered?"ol":"ul",properties:t,children:e.wrap(r,!0)};return e.patch(n,l),e.applyData(n,l)}function Sa(e,n){const t={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,t),e.applyData(n,t)}function _a(e,n){const t={type:"root",children:e.wrap(e.all(n))};return e.patch(n,t),e.applyData(n,t)}function Ia(e,n){const t={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,t),e.applyData(n,t)}function Ea(e,n){const t=e.all(n),r=t.shift(),i=[];if(r){const o={type:"element",tagName:"thead",properties:{},children:e.wrap([r],!0)};e.patch(n.children[0],o),i.push(o)}if(t.length>0){const o={type:"element",tagName:"tbody",properties:{},children:e.wrap(t,!0)},a=Vn(n.children[1]),c=ir(n.children[n.children.length-1]);a&&c&&(o.position={start:a,end:c}),i.push(o)}const l={type:"element",tagName:"table",properties:{},children:e.wrap(i,!0)};return e.patch(n,l),e.applyData(n,l)}function va(e,n,t){const r=t?t.children:void 0,l=(r?r.indexOf(n):1)===0?"th":"td",o=t&&t.type==="table"?t.align:void 0,a=o?o.length:n.children.length;let c=-1;const s=[];for(;++c<a;){const p=n.children[c],m={},h=o?o[c]:void 0;h&&(m.align=h);let S={type:"element",tagName:l,properties:m,children:[]};p&&(S.children=e.all(p),e.patch(p,S),S=e.applyData(p,S)),s.push(S)}const u={type:"element",tagName:"tr",properties:{},children:e.wrap(s,!0)};return e.patch(n,u),e.applyData(n,u)}function Ta(e,n){const t={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,t),e.applyData(n,t)}const Tt=9,Lt=32;function La(e){const n=String(e),t=/\r?\n|\r/g;let r=t.exec(n),i=0;const l=[];for(;r;)l.push(Nt(n.slice(i,r.index),i>0,!0),r[0]),i=r.index+r[0].length,r=t.exec(n);return l.push(Nt(n.slice(i),i>0,!1)),l.join("")}function Nt(e,n,t){let r=0,i=e.length;if(n){let l=e.codePointAt(r);for(;l===Tt||l===Lt;)r++,l=e.codePointAt(r)}if(t){let l=e.codePointAt(i-1);for(;l===Tt||l===Lt;)i--,l=e.codePointAt(i-1)}return i>r?e.slice(r,i):""}function Na(e,n){const t={type:"text",value:La(String(n.value))};return e.patch(n,t),e.applyData(n,t)}function Pa(e,n){const t={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,t),e.applyData(n,t)}const Aa={blockquote:aa,break:sa,code:ua,delete:ca,emphasis:pa,footnoteReference:ha,heading:fa,html:da,imageReference:ma,image:ga,inlineCode:ya,linkReference:xa,link:ka,listItem:ba,list:Ca,paragraph:Sa,root:_a,strong:Ia,table:Ea,tableCell:Ta,tableRow:va,text:Na,thematicBreak:Pa,toml:nn,yaml:nn,definition:nn,footnoteDefinition:nn};function nn(){}const Ir=-1,hn=0,Ke=1,un=2,Qn=3,Zn=4,Jn=5,Gn=6,Er=7,vr=8,Pt=typeof self=="object"?self:globalThis,ja=(e,n)=>{const t=(i,l)=>(e.set(l,i),i),r=i=>{if(e.has(i))return e.get(i);const[l,o]=n[i];switch(l){case hn:case Ir:return t(o,i);case Ke:{const a=t([],i);for(const c of o)a.push(r(c));return a}case un:{const a=t({},i);for(const[c,s]of o)a[r(c)]=r(s);return a}case Qn:return t(new Date(o),i);case Zn:{const{source:a,flags:c}=o;return t(new RegExp(a,c),i)}case Jn:{const a=t(new Map,i);for(const[c,s]of o)a.set(r(c),r(s));return a}case Gn:{const a=t(new Set,i);for(const c of o)a.add(r(c));return a}case Er:{const{name:a,message:c}=o;return t(new Pt[a](c),i)}case vr:return t(BigInt(o),i);case"BigInt":return t(Object(BigInt(o)),i);case"ArrayBuffer":return t(new Uint8Array(o).buffer,o);case"DataView":{const{buffer:a}=new Uint8Array(o);return t(new DataView(a),o)}}return t(new Pt[l](o),i)};return r},At=e=>ja(new Map,e)(0),Ae="",{toString:za}={},{keys:Ma}=Object,qe=e=>{const n=typeof e;if(n!=="object"||!e)return[hn,n];const t=za.call(e).slice(8,-1);switch(t){case"Array":return[Ke,Ae];case"Object":return[un,Ae];case"Date":return[Qn,Ae];case"RegExp":return[Zn,Ae];case"Map":return[Jn,Ae];case"Set":return[Gn,Ae];case"DataView":return[Ke,t]}return t.includes("Array")?[Ke,t]:t.includes("Error")?[Er,t]:[un,t]},tn=([e,n])=>e===hn&&(n==="function"||n==="symbol"),Da=(e,n,t,r)=>{const i=(o,a)=>{const c=r.push(o)-1;return t.set(a,c),c},l=o=>{if(t.has(o))return t.get(o);let[a,c]=qe(o);switch(a){case hn:{let u=o;switch(c){case"bigint":a=vr,u=o.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);u=null;break;case"undefined":return i([Ir],o)}return i([a,u],o)}case Ke:{if(c){let m=o;return c==="DataView"?m=new Uint8Array(o.buffer):c==="ArrayBuffer"&&(m=new Uint8Array(o)),i([c,[...m]],o)}const u=[],p=i([a,u],o);for(const m of o)u.push(l(m));return p}case un:{if(c)switch(c){case"BigInt":return i([c,o.toString()],o);case"Boolean":case"Number":case"String":return i([c,o.valueOf()],o)}if(n&&"toJSON"in o)return l(o.toJSON());const u=[],p=i([a,u],o);for(const m of Ma(o))(e||!tn(qe(o[m])))&&u.push([l(m),l(o[m])]);return p}case Qn:return i([a,o.toISOString()],o);case Zn:{const{source:u,flags:p}=o;return i([a,{source:u,flags:p}],o)}case Jn:{const u=[],p=i([a,u],o);for(const[m,h]of o)(e||!(tn(qe(m))||tn(qe(h))))&&u.push([l(m),l(h)]);return p}case Gn:{const u=[],p=i([a,u],o);for(const m of o)(e||!tn(qe(m)))&&u.push(l(m));return p}}const{message:s}=o;return i([a,{name:c,message:s}],o)};return l},jt=(e,{json:n,lossy:t}={})=>{const r=[];return Da(!(n||t),!!n,new Map,r)(e),r},cn=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?At(jt(e,n)):structuredClone(e):(e,n)=>At(jt(e,n));function Ba(e,n){const t=[{type:"text",value:"↩"}];return n>1&&t.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(n)}]}),t}function Oa(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function Ra(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",t=e.options.footnoteBackContent||Ba,r=e.options.footnoteBackLabel||Oa,i=e.options.footnoteLabel||"Footnotes",l=e.options.footnoteLabelTagName||"h2",o=e.options.footnoteLabelProperties||{className:["sr-only"]},a=[];let c=-1;for(;++c<e.footnoteOrder.length;){const s=e.footnoteById.get(e.footnoteOrder[c]);if(!s)continue;const u=e.all(s),p=String(s.identifier).toUpperCase(),m=Be(p.toLowerCase());let h=0;const S=[],I=e.footnoteCounts.get(p);for(;I!==void 0&&++h<=I;){S.length>0&&S.push({type:"text",value:" "});let P=typeof t=="string"?t:t(c,h);typeof P=="string"&&(P={type:"text",value:P}),S.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+m+(h>1?"-"+h:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,h),className:["data-footnote-backref"]},children:Array.isArray(P)?P:[P]})}const E=u[u.length-1];if(E&&E.type==="element"&&E.tagName==="p"){const P=E.children[E.children.length-1];P&&P.type==="text"?P.value+=" ":E.children.push({type:"text",value:" "}),E.children.push(...S)}else u.push(...S);const b={type:"element",tagName:"li",properties:{id:n+"fn-"+m},children:e.wrap(u,!0)};e.patch(s,b),a.push(b)}if(a.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:l,properties:{...cn(o),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:`
12
- `},{type:"element",tagName:"ol",properties:{},children:e.wrap(a,!0)},{type:"text",value:`
13
- `}]}}const Tr=(function(e){if(e==null)return Va;if(typeof e=="function")return fn(e);if(typeof e=="object")return Array.isArray(e)?Fa(e):$a(e);if(typeof e=="string")return Ha(e);throw new Error("Expected function, string, or object as test")});function Fa(e){const n=[];let t=-1;for(;++t<e.length;)n[t]=Tr(e[t]);return fn(r);function r(...i){let l=-1;for(;++l<n.length;)if(n[l].apply(this,i))return!0;return!1}}function $a(e){const n=e;return fn(t);function t(r){const i=r;let l;for(l in e)if(i[l]!==n[l])return!1;return!0}}function Ha(e){return fn(n);function n(t){return t&&t.type===e}}function fn(e){return n;function n(t,r,i){return!!(Ua(t)&&e.call(this,t,typeof r=="number"?r:void 0,i||void 0))}}function Va(){return!0}function Ua(e){return e!==null&&typeof e=="object"&&"type"in e}const Lr=[],qa=!0,zt=!1,Wa="skip";function Ya(e,n,t,r){let i;typeof n=="function"&&typeof t!="function"?(r=t,t=n):i=n;const l=Tr(i),o=r?-1:1;a(e,void 0,[])();function a(c,s,u){const p=c&&typeof c=="object"?c:{};if(typeof p.type=="string"){const h=typeof p.tagName=="string"?p.tagName:typeof p.name=="string"?p.name:void 0;Object.defineProperty(m,"name",{value:"node ("+(c.type+(h?"<"+h+">":""))+")"})}return m;function m(){let h=Lr,S,I,E;if((!n||l(c,s,u[u.length-1]||void 0))&&(h=Xa(t(c,u)),h[0]===zt))return h;if("children"in c&&c.children){const b=c;if(b.children&&h[0]!==Wa)for(I=(r?b.children.length:-1)+o,E=u.concat(b);I>-1&&I<b.children.length;){const P=b.children[I];if(S=a(P,I,E)(),S[0]===zt)return S;I=typeof S[1]=="number"?S[1]:I+o}}return h}}}function Xa(e){return Array.isArray(e)?e:typeof e=="number"?[qa,e]:e==null?Lr:[e]}function Nr(e,n,t,r){let i,l,o;typeof n=="function"&&typeof t!="function"?(l=void 0,o=n,i=t):(l=n,o=t,i=r),Ya(e,l,a,i);function a(c,s){const u=s[s.length-1],p=u?u.children.indexOf(c):void 0;return o(c,p,u)}}const Dn={}.hasOwnProperty,Ka={};function Qa(e,n){const t=n||Ka,r=new Map,i=new Map,l=new Map,o={...Aa,...t.handlers},a={all:s,applyData:Ja,definitionById:r,footnoteById:i,footnoteCounts:l,footnoteOrder:[],handlers:o,one:c,options:t,patch:Za,wrap:es};return Nr(e,function(u){if(u.type==="definition"||u.type==="footnoteDefinition"){const p=u.type==="definition"?r:i,m=String(u.identifier).toUpperCase();p.has(m)||p.set(m,u)}}),a;function c(u,p){const m=u.type,h=a.handlers[m];if(Dn.call(a.handlers,m)&&h)return h(a,u,p);if(a.options.passThrough&&a.options.passThrough.includes(m)){if("children"in u){const{children:I,...E}=u,b=cn(E);return b.children=a.all(u),b}return cn(u)}return(a.options.unknownHandler||Ga)(a,u,p)}function s(u){const p=[];if("children"in u){const m=u.children;let h=-1;for(;++h<m.length;){const S=a.one(m[h],u);if(S){if(h&&m[h-1].type==="break"&&(!Array.isArray(S)&&S.type==="text"&&(S.value=Mt(S.value)),!Array.isArray(S)&&S.type==="element")){const I=S.children[0];I&&I.type==="text"&&(I.value=Mt(I.value))}Array.isArray(S)?p.push(...S):p.push(S)}}}return p}}function Za(e,n){e.position&&(n.position=ji(e))}function Ja(e,n){let t=n;if(e&&e.data){const r=e.data.hName,i=e.data.hChildren,l=e.data.hProperties;if(typeof r=="string")if(t.type==="element")t.tagName=r;else{const o="children"in t?t.children:[t];t={type:"element",tagName:r,properties:{},children:o}}t.type==="element"&&l&&Object.assign(t.properties,cn(l)),"children"in t&&t.children&&i!==null&&i!==void 0&&(t.children=i)}return t}function Ga(e,n){const t=n.data||{},r="value"in n&&!(Dn.call(t,"hProperties")||Dn.call(t,"hChildren"))?{type:"text",value:n.value}:{type:"element",tagName:"div",properties:{},children:e.all(n)};return e.patch(n,r),e.applyData(n,r)}function es(e,n){const t=[];let r=-1;for(n&&t.push({type:"text",value:`
14
- `});++r<e.length;)r&&t.push({type:"text",value:`
15
- `}),t.push(e[r]);return n&&e.length>0&&t.push({type:"text",value:`
16
- `}),t}function Mt(e){let n=0,t=e.charCodeAt(n);for(;t===9||t===32;)n++,t=e.charCodeAt(n);return e.slice(n)}function Dt(e,n){const t=Qa(e,n),r=t.one(e,void 0),i=Ra(t),l=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return i&&l.children.push({type:"text",value:`
17
- `},i),l}function ns(e,n){return e&&"run"in e?async function(t,r){const i=Dt(t,{file:r,...n});await e.run(i,r)}:function(t,r){return Dt(t,{file:r,...e||n})}}function Bt(e){if(e)throw e}var kn,Ot;function ts(){if(Ot)return kn;Ot=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=function(s){return typeof Array.isArray=="function"?Array.isArray(s):n.call(s)==="[object Array]"},l=function(s){if(!s||n.call(s)!=="[object Object]")return!1;var u=e.call(s,"constructor"),p=s.constructor&&s.constructor.prototype&&e.call(s.constructor.prototype,"isPrototypeOf");if(s.constructor&&!u&&!p)return!1;var m;for(m in s);return typeof m>"u"||e.call(s,m)},o=function(s,u){t&&u.name==="__proto__"?t(s,u.name,{enumerable:!0,configurable:!0,value:u.newValue,writable:!0}):s[u.name]=u.newValue},a=function(s,u){if(u==="__proto__")if(e.call(s,u)){if(r)return r(s,u).value}else return;return s[u]};return kn=function c(){var s,u,p,m,h,S,I=arguments[0],E=1,b=arguments.length,P=!1;for(typeof I=="boolean"&&(P=I,I=arguments[1]||{},E=2),(I==null||typeof I!="object"&&typeof I!="function")&&(I={});E<b;++E)if(s=arguments[E],s!=null)for(u in s)p=a(I,u),m=a(s,u),I!==m&&(P&&m&&(l(m)||(h=i(m)))?(h?(h=!1,S=p&&i(p)?p:[]):S=p&&l(p)?p:{},o(I,{name:u,newValue:c(P,S,m)})):typeof m<"u"&&o(I,{name:u,newValue:m}));return I},kn}var rs=ts();const bn=rr(rs);function Bn(e){if(typeof e!="object"||e===null)return!1;const n=Object.getPrototypeOf(e);return(n===null||n===Object.prototype||Object.getPrototypeOf(n)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function is(){const e=[],n={run:t,use:r};return n;function t(...i){let l=-1;const o=i.pop();if(typeof o!="function")throw new TypeError("Expected function as last argument, not "+o);a(null,...i);function a(c,...s){const u=e[++l];let p=-1;if(c){o(c);return}for(;++p<i.length;)(s[p]===null||s[p]===void 0)&&(s[p]=i[p]);i=s,u?ls(u,a)(...s):o(null,...s)}}function r(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return e.push(i),n}}function ls(e,n){let t;return r;function r(...o){const a=e.length>o.length;let c;a&&o.push(i);try{c=e.apply(this,o)}catch(s){const u=s;if(a&&t)throw u;return i(u)}a||(c&&c.then&&typeof c.then=="function"?c.then(l,i):c instanceof Error?i(c):l(c))}function i(o,...a){t||(t=!0,n(o,...a))}function l(o){i(null,o)}}const me={basename:os,dirname:as,extname:ss,join:us,sep:"/"};function os(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Ge(e);let t=0,r=-1,i=e.length,l;if(n===void 0||n.length===0||n.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(l){t=i+1;break}}else r<0&&(l=!0,r=i+1);return r<0?"":e.slice(t,r)}if(n===e)return"";let o=-1,a=n.length-1;for(;i--;)if(e.codePointAt(i)===47){if(l){t=i+1;break}}else o<0&&(l=!0,o=i+1),a>-1&&(e.codePointAt(i)===n.codePointAt(a--)?a<0&&(r=i):(a=-1,r=o));return t===r?r=o:r<0&&(r=e.length),e.slice(t,r)}function as(e){if(Ge(e),e.length===0)return".";let n=-1,t=e.length,r;for(;--t;)if(e.codePointAt(t)===47){if(r){n=t;break}}else r||(r=!0);return n<0?e.codePointAt(0)===47?"/":".":n===1&&e.codePointAt(0)===47?"//":e.slice(0,n)}function ss(e){Ge(e);let n=e.length,t=-1,r=0,i=-1,l=0,o;for(;n--;){const a=e.codePointAt(n);if(a===47){if(o){r=n+1;break}continue}t<0&&(o=!0,t=n+1),a===46?i<0?i=n:l!==1&&(l=1):i>-1&&(l=-1)}return i<0||t<0||l===0||l===1&&i===t-1&&i===r+1?"":e.slice(i,t)}function us(...e){let n=-1,t;for(;++n<e.length;)Ge(e[n]),e[n]&&(t=t===void 0?e[n]:t+"/"+e[n]);return t===void 0?".":cs(t)}function cs(e){Ge(e);const n=e.codePointAt(0)===47;let t=ps(e,!n);return t.length===0&&!n&&(t="."),t.length>0&&e.codePointAt(e.length-1)===47&&(t+="/"),n?"/"+t:t}function ps(e,n){let t="",r=0,i=-1,l=0,o=-1,a,c;for(;++o<=e.length;){if(o<e.length)a=e.codePointAt(o);else{if(a===47)break;a=47}if(a===47){if(!(i===o-1||l===1))if(i!==o-1&&l===2){if(t.length<2||r!==2||t.codePointAt(t.length-1)!==46||t.codePointAt(t.length-2)!==46){if(t.length>2){if(c=t.lastIndexOf("/"),c!==t.length-1){c<0?(t="",r=0):(t=t.slice(0,c),r=t.length-1-t.lastIndexOf("/")),i=o,l=0;continue}}else if(t.length>0){t="",r=0,i=o,l=0;continue}}n&&(t=t.length>0?t+"/..":"..",r=2)}else t.length>0?t+="/"+e.slice(i+1,o):t=e.slice(i+1,o),r=o-i-1;i=o,l=0}else a===46&&l>-1?l++:l=-1}return t}function Ge(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const hs={cwd:fs};function fs(){return"/"}function On(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function ds(e){if(typeof e=="string")e=new URL(e);else if(!On(e)){const n=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw n.code="ERR_INVALID_ARG_TYPE",n}if(e.protocol!=="file:"){const n=new TypeError("The URL must be of scheme file");throw n.code="ERR_INVALID_URL_SCHEME",n}return ms(e)}function ms(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const n=e.pathname;let t=-1;for(;++t<n.length;)if(n.codePointAt(t)===37&&n.codePointAt(t+1)===50){const r=n.codePointAt(t+2);if(r===70||r===102){const i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(n)}const wn=["history","path","basename","stem","extname","dirname"];class Pr{constructor(n){let t;n?On(n)?t={path:n}:typeof n=="string"||gs(n)?t={value:n}:t=n:t={},this.cwd="cwd"in t?"":hs.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<wn.length;){const l=wn[r];l in t&&t[l]!==void 0&&t[l]!==null&&(this[l]=l==="history"?[...t[l]]:t[l])}let i;for(i in t)wn.includes(i)||(this[i]=t[i])}get basename(){return typeof this.path=="string"?me.basename(this.path):void 0}set basename(n){Sn(n,"basename"),Cn(n,"basename"),this.path=me.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?me.dirname(this.path):void 0}set dirname(n){Rt(this.basename,"dirname"),this.path=me.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?me.extname(this.path):void 0}set extname(n){if(Cn(n,"extname"),Rt(this.dirname,"extname"),n){if(n.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(n.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=me.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){On(n)&&(n=ds(n)),Sn(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?me.basename(this.path,this.extname):void 0}set stem(n){Sn(n,"stem"),Cn(n,"stem"),this.path=me.join(this.dirname||"",n+(this.extname||""))}fail(n,t,r){const i=this.message(n,t,r);throw i.fatal=!0,i}info(n,t,r){const i=this.message(n,t,r);return i.fatal=void 0,i}message(n,t,r){const i=new te(n,t,r);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}toString(n){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(n||void 0).decode(this.value)}}function Cn(e,n){if(e&&e.includes(me.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+me.sep+"`")}function Sn(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Rt(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function gs(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const ys=(function(e){const r=this.constructor.prototype,i=r[e],l=function(){return i.apply(l,arguments)};return Object.setPrototypeOf(l,r),l}),xs={}.hasOwnProperty;class et extends ys{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=is()}copy(){const n=new et;let t=-1;for(;++t<this.attachers.length;){const r=this.attachers[t];n.use(...r)}return n.data(bn(!0,{},this.namespace)),n}data(n,t){return typeof n=="string"?arguments.length===2?(En("data",this.frozen),this.namespace[n]=t,this):xs.call(this.namespace,n)&&this.namespace[n]||void 0:n?(En("data",this.frozen),this.namespace=n,this):this.namespace}freeze(){if(this.frozen)return this;const n=this;for(;++this.freezeIndex<this.attachers.length;){const[t,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const i=t.call(n,...r);typeof i=="function"&&this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(n){this.freeze();const t=rn(n),r=this.parser||this.Parser;return _n("parse",r),r(String(t),t)}process(n,t){const r=this;return this.freeze(),_n("process",this.parser||this.Parser),In("process",this.compiler||this.Compiler),t?i(void 0,t):new Promise(i);function i(l,o){const a=rn(n),c=r.parse(a);r.run(c,a,function(u,p,m){if(u||!p||!m)return s(u);const h=p,S=r.stringify(h,m);ws(S)?m.value=S:m.result=S,s(u,m)});function s(u,p){u||!p?o(u):l?l(p):t(void 0,p)}}}processSync(n){let t=!1,r;return this.freeze(),_n("processSync",this.parser||this.Parser),In("processSync",this.compiler||this.Compiler),this.process(n,i),$t("processSync","process",t),r;function i(l,o){t=!0,Bt(l),r=o}}run(n,t,r){Ft(n),this.freeze();const i=this.transformers;return!r&&typeof t=="function"&&(r=t,t=void 0),r?l(void 0,r):new Promise(l);function l(o,a){const c=rn(t);i.run(n,c,s);function s(u,p,m){const h=p||n;u?a(u):o?o(h):r(void 0,h,m)}}}runSync(n,t){let r=!1,i;return this.run(n,t,l),$t("runSync","run",r),i;function l(o,a){Bt(o),i=a,r=!0}}stringify(n,t){this.freeze();const r=rn(t),i=this.compiler||this.Compiler;return In("stringify",i),Ft(n),i(n,r)}use(n,...t){const r=this.attachers,i=this.namespace;if(En("use",this.frozen),n!=null)if(typeof n=="function")c(n,t);else if(typeof n=="object")Array.isArray(n)?a(n):o(n);else throw new TypeError("Expected usable value, not `"+n+"`");return this;function l(s){if(typeof s=="function")c(s,[]);else if(typeof s=="object")if(Array.isArray(s)){const[u,...p]=s;c(u,p)}else o(s);else throw new TypeError("Expected usable value, not `"+s+"`")}function o(s){if(!("plugins"in s)&&!("settings"in s))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");a(s.plugins),s.settings&&(i.settings=bn(!0,i.settings,s.settings))}function a(s){let u=-1;if(s!=null)if(Array.isArray(s))for(;++u<s.length;){const p=s[u];l(p)}else throw new TypeError("Expected a list of plugins, not `"+s+"`")}function c(s,u){let p=-1,m=-1;for(;++p<r.length;)if(r[p][0]===s){m=p;break}if(m===-1)r.push([s,...u]);else if(u.length>0){let[h,...S]=u;const I=r[m][1];Bn(I)&&Bn(h)&&(h=bn(!0,I,h)),r[m]=[s,h,...S]}}}}const ks=new et().freeze();function _n(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function In(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function En(e,n){if(n)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Ft(e){if(!Bn(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function $t(e,n,t){if(!t)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function rn(e){return bs(e)?e:new Pr(e)}function bs(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function ws(e){return typeof e=="string"||Cs(e)}function Cs(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Ss="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Ht=[],Vt={allowDangerousHtml:!0},_s=/^(https?|ircs?|mailto|xmpp)$/i,Is=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Es(e){const n=vs(e),t=Ts(e);return Ls(n.runSync(n.parse(t),t),e)}function vs(e){const n=e.rehypePlugins||Ht,t=e.remarkPlugins||Ht,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Vt}:Vt;return ks().use(oa).use(t).use(ns,r).use(n)}function Ts(e){const n=e.children||"",t=new Pr;return typeof n=="string"&&(t.value=n),t}function Ls(e,n){const t=n.allowedElements,r=n.allowElement,i=n.components,l=n.disallowedElements,o=n.skipHtml,a=n.unwrapDisallowed,c=n.urlTransform||Ns;for(const u of Is)Object.hasOwn(n,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+Ss+u.id,void 0);return Nr(e,s),Oi(e,{Fragment:g.Fragment,components:i,ignoreInvalidStyle:!0,jsx:g.jsx,jsxs:g.jsxs,passKeys:!0,passNode:!0});function s(u,p,m){if(u.type==="raw"&&m&&typeof p=="number")return o?m.children.splice(p,1):m.children[p]={type:"text",value:u.value},p;if(u.type==="element"){let h;for(h in gn)if(Object.hasOwn(gn,h)&&Object.hasOwn(u.properties,h)){const S=u.properties[h],I=gn[h];(I===null||I.includes(u.tagName))&&(u.properties[h]=c(String(S||""),h,u))}}if(u.type==="element"){let h=t?!t.includes(u.tagName):l?l.includes(u.tagName):!1;if(!h&&r&&typeof p=="number"&&(h=!r(u,p,m)),h&&m&&typeof p=="number")return a&&u.children?m.children.splice(p,1,...u.children):m.children.splice(p,1),p}}}function Ns(e){const n=e.indexOf(":"),t=e.indexOf("?"),r=e.indexOf("#"),i=e.indexOf("/");return n===-1||i!==-1&&n>i||t!==-1&&n>t||r!==-1&&n>r||_s.test(e.slice(0,n))?e:""}const Ps="_messageWrapper_1thak_1",As="_user_1thak_19",js="_assistant_1thak_24",zs="_avatar_1thak_28",Ms="_avatarPlaceholder_1thak_43",Ds="_brainbaseLogo_1thak_53",Bs="_messageBubble_1thak_58",Os="_error_1thak_76",Rs="_content_1thak_81",Fs="_markdown_1thak_92",$s="_cursor_1thak_183",Hs="_errorIndicator_1thak_202",ce={messageWrapper:Ps,user:As,assistant:js,avatar:zs,avatarPlaceholder:Ms,brainbaseLogo:Ds,messageBubble:Bs,error:Os,content:Rs,markdown:Fs,cursor:$s,errorIndicator:Hs},Ar=({message:e,agentName:n,agentLogoUrl:t})=>{const r=e.role==="user",i=e.status==="streaming",l=e.status==="error";return g.jsxs("div",{className:`${ce.messageWrapper} ${r?ce.user:ce.assistant}`,children:[!r&&g.jsx("div",{className:ce.avatar,children:t?g.jsx("img",{src:t,alt:n||"AI"}):g.jsx("div",{className:ce.avatarPlaceholder,children:g.jsx(Qe,{className:ce.brainbaseLogo,color:"white",cutoutColor:"var(--bb-primary-color)"})})}),g.jsxs("div",{className:`${ce.messageBubble} ${l?ce.error:""}`,role:"article","aria-label":`${r?"Your message":`${n||"AI"} says`}`,children:[g.jsxs("div",{className:`${ce.content} ${r?"":ce.markdown}`,children:[r?e.content:g.jsx(Es,{components:{a:({href:o,children:a})=>o?g.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",children:a}):g.jsx(g.Fragment,{children:a})},children:e.content}),i&&g.jsx("span",{className:ce.cursor})]}),l&&g.jsxs("div",{className:ce.errorIndicator,children:[g.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",children:[g.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2"}),g.jsx("path",{d:"M12 8V12M12 16H12.01",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),g.jsx("span",{children:"Failed to send"})]})]})]})},Vs="_toolCall_1wby1_1",Us="_iconWrapper_1wby1_24",qs="_spinner_1wby1_33",Ws="_checkIcon_1wby1_48",Ys="_errorIcon_1wby1_54",Xs="_content_1wby1_60",Ks="_label_1wby1_66",Qs="_name_1wby1_73",Zs="_pending_1wby1_78",Js="_completed_1wby1_82",Gs="_error_1wby1_54",de={toolCall:Vs,iconWrapper:Us,spinner:qs,checkIcon:Ws,errorIcon:Ys,content:Xs,label:Ks,name:Qs,pending:Zs,completed:Js,error:Gs},jr=({toolCall:e})=>{const n=e.status==="pending"||e.status==="executing",t=e.status==="completed",r=e.status==="error",i=l=>l.replace(/_/g," ").replace(/([A-Z])/g," $1").trim().toLowerCase().replace(/^./,o=>o.toUpperCase());return g.jsxs("div",{className:`${de.toolCall} ${n?de.pending:""} ${t?de.completed:""} ${r?de.error:""}`,children:[g.jsx("div",{className:de.iconWrapper,children:n?g.jsx("div",{className:de.spinner}):t?g.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:de.checkIcon,children:g.jsx("path",{d:"M20 6L9 17L4 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):g.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:de.errorIcon,children:g.jsx("path",{d:"M6 18L18 6M6 6L18 18",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),g.jsxs("div",{className:de.content,children:[g.jsx("span",{className:de.label,children:n?"Running":t?"Completed":"Failed"}),g.jsx("span",{className:de.name,children:i(e.name)})]})]})},eu="_wrapper_10rss_2",nu="_avatar_10rss_22",tu="_avatarPlaceholder_10rss_37",ru="_brainbaseLogo_10rss_47",iu="_bubble_10rss_52",lu="_dot_10rss_63",Ce={wrapper:eu,avatar:nu,avatarPlaceholder:tu,brainbaseLogo:ru,bubble:iu,dot:lu},zr=({agentName:e="AI",agentLogoUrl:n})=>g.jsxs("div",{className:Ce.wrapper,role:"status","aria-label":`${e} is typing`,children:[g.jsx("div",{className:Ce.avatar,children:n?g.jsx("img",{src:n,alt:e}):g.jsx("div",{className:Ce.avatarPlaceholder,children:g.jsx(Qe,{className:Ce.brainbaseLogo,color:"white",cutoutColor:"var(--bb-primary-color)"})})}),g.jsxs("div",{className:Ce.bubble,children:[g.jsx("span",{className:Ce.dot}),g.jsx("span",{className:Ce.dot}),g.jsx("span",{className:Ce.dot})]})]}),ou="_messageList_9tkjc_1",au="_emptyState_9tkjc_30",su="_emptyIcon_9tkjc_41",uu="_emptyText_9tkjc_53",ln={messageList:ou,emptyState:au,emptyIcon:su,emptyText:uu},Mr=({messages:e,toolCalls:n=[],isLoading:t,agentName:r,agentLogoUrl:i})=>{var c;const l=O.useRef(null),o=O.useRef(null);O.useEffect(()=>{var s;(s=o.current)==null||s.scrollIntoView({behavior:"smooth"})},[e,n,t]);const a=n.filter(s=>s.status==="pending"||s.status==="executing");return g.jsxs("div",{className:ln.messageList,ref:l,role:"log","aria-live":"polite",children:[e.length===0&&!t&&g.jsxs("div",{className:ln.emptyState,children:[g.jsx("div",{className:ln.emptyIcon,children:g.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:g.jsx("path",{d:"M8 12H8.01M12 12H12.01M16 12H16.01M21 12C21 16.4183 16.9706 20 12 20C10.4607 20 9.01172 19.6565 7.74467 19.0511L3 20L4.39499 16.28C3.51156 15.0423 3 13.5743 3 12C3 7.58172 7.02944 4 12 4C16.9706 4 21 7.58172 21 12Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),g.jsx("p",{className:ln.emptyText,children:"Start a conversation"})]}),e.map(s=>g.jsx(Ar,{message:s,agentName:r,agentLogoUrl:i},s.id)),a.map(s=>g.jsx(jr,{toolCall:s},s.id)),t&&((c=e[e.length-1])==null?void 0:c.role)==="user"&&g.jsx(zr,{agentName:r,agentLogoUrl:i}),g.jsx("div",{ref:o})]})},cu="_inputWrapper_5lgg7_1",pu="_inputContainer_5lgg7_7",hu="_textarea_5lgg7_23",fu="_sendButton_5lgg7_50",du="_hint_5lgg7_89",We={inputWrapper:cu,inputContainer:pu,textarea:hu,sendButton:fu,hint:du},Dr=({onSend:e,disabled:n=!1,placeholder:t="Send a message..."})=>{const[r,i]=O.useState(""),l=O.useRef(null),o=O.useCallback(()=>{const s=l.current;s&&(s.style.height="auto",s.style.height=`${Math.min(s.scrollHeight,150)}px`)},[]);O.useEffect(()=>{o()},[r,o]);const a=O.useCallback(s=>{s==null||s.preventDefault();const u=r.trim();u&&!n&&(e(u),i(""),l.current&&(l.current.style.height="auto"))},[r,n,e]),c=O.useCallback(s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),a())},[a]);return g.jsxs("form",{className:We.inputWrapper,onSubmit:a,children:[g.jsxs("div",{className:We.inputContainer,children:[g.jsx("textarea",{ref:l,className:We.textarea,value:r,onChange:s=>i(s.target.value),onKeyDown:c,placeholder:t,disabled:n,rows:1,"aria-label":"Message input"}),g.jsx("button",{type:"submit",className:We.sendButton,disabled:n||!r.trim(),"aria-label":"Send message",children:g.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:g.jsx("path",{d:"M22 2L11 13M22 2L15 22L11 13M22 2L2 9L11 13",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),g.jsxs("div",{className:We.hint,children:["Press ",g.jsx("kbd",{children:"Enter"})," to send, ",g.jsx("kbd",{children:"Shift + Enter"})," for new line"]})]})},mu="_poweredBy_9jh5q_1",gu="_logo_9jh5q_20",yu="_poweredText_9jh5q_24",xu="_text_9jh5q_36",on={poweredBy:mu,logo:gu,poweredText:yu,text:xu},ku=({className:e})=>g.jsxs("svg",{className:e,viewBox:"0 0 800 800",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[g.jsx("path",{d:"M400 412C400 405.373 405.373 400 412 400H788C794.627 400 800 405.373 800 412V740C800 773.137 773.137 800 740 800H412C405.373 800 400 794.627 400 788V412Z",fill:"currentColor"}),g.jsx("circle",{cx:"400",cy:"400",r:"400",fill:"currentColor"}),g.jsx("path",{d:"M0 60C0 26.8629 26.8629 0 60 0H397.614C398.932 0 400 1.06811 400 2.38569V2.38569C400 221.982 221.982 400 2.38569 400V400C1.06811 400 0 398.932 0 397.614V60Z",fill:"currentColor"}),g.jsx("path",{d:"M400 412C400 405.373 405.373 400 412 400H738C744.627 400 750 405.373 750 412V725C750 738.807 738.807 750 725 750H412C405.373 750 400 744.627 400 738V412Z",fill:"currentColor"}),g.jsx("circle",{cx:"400",cy:"400",r:"350",fill:"currentColor"}),g.jsx("path",{d:"M50 75C50 61.1929 61.1929 50 75 50H388C394.627 50 400 55.3726 400 62V388C400 394.627 394.627 400 388 400H62C55.3726 400 50 394.627 50 388V75Z",fill:"currentColor"}),g.jsx("rect",{x:"399.919",y:"209",width:"270",height:"270",rx:"12",transform:"rotate(45 399.919 209)",fill:"var(--bb-surface-bg, #ffffff)"})]}),bu=({showBranding:e=!0})=>e?g.jsxs("a",{href:"https://brainbaselabs.com/",target:"_blank",rel:"noopener noreferrer",className:on.poweredBy,"aria-label":"Powered by Brainbase Labs",children:[g.jsx("span",{className:on.poweredText,children:"Powered by"}),g.jsx(ku,{className:on.logo}),g.jsx("span",{className:on.text,children:"Brainbase Labs"})]}):null,wu="_container_m2o9l_1",Cu="_body_m2o9l_26",Su="_confirmationOverlay_m2o9l_35",_u="_confirmationDialog_m2o9l_56",Iu="_confirmationText_m2o9l_78",Eu="_confirmationButtons_m2o9l_86",vu="_cancelButton_m2o9l_91",Tu="_confirmButton_m2o9l_92",Se={container:wu,body:Cu,confirmationOverlay:Su,confirmationDialog:_u,confirmationText:Iu,confirmationButtons:Eu,cancelButton:vu,confirmButton:Tu},Br=({config:e,messages:n,toolCalls:t=[],isLoading:r,onSendMessage:i,onClose:l,onNewChat:o})=>{var h;const[a,c]=O.useState(!1),s=n.length>0,u=()=>{c(!0)},p=()=>{c(!1),o==null||o()},m=()=>{c(!1)};return g.jsxs("div",{className:Se.container,role:"dialog","aria-label":"Chat window",children:[g.jsx(Kt,{agentName:e.agentName,agentLogoUrl:e.agentLogoUrl,welcomeTitle:e.welcomeMessage||"Hello there.",welcomeSubtitle:e.welcomeMessage?void 0:"How can we help?",onClose:l,onNewChatRequest:u,showNewChatButton:s,compact:s}),g.jsxs("div",{className:Se.body,children:[g.jsx(Mr,{messages:n,toolCalls:t,isLoading:r,agentName:e.agentName,agentLogoUrl:e.agentLogoUrl}),g.jsx(Dr,{onSend:i,disabled:r,placeholder:"Ask a question..."})]}),g.jsx(bu,{showBranding:((h=e.styling)==null?void 0:h.showBranding)??!0}),a&&g.jsx("div",{className:Se.confirmationOverlay,children:g.jsxs("div",{className:Se.confirmationDialog,children:[g.jsx("p",{className:Se.confirmationText,children:"End current chat and start a new conversation?"}),g.jsxs("div",{className:Se.confirmationButtons,children:[g.jsx("button",{className:Se.cancelButton,onClick:m,type:"button",children:"Cancel"}),g.jsx("button",{className:Se.confirmButton,onClick:p,type:"button",children:"End Chat"})]})]})})]})},Lu="_toggleButton_11dqz_1",Nu="_icon_11dqz_31",Pu="_agentLogo_11dqz_36",Au="_unreadBadge_11dqz_43",an={toggleButton:Lu,icon:Nu,agentLogo:Pu,unreadBadge:Au},Rn=({onClick:e,agentLogoUrl:n,unreadCount:t=0})=>g.jsxs("button",{className:an.toggleButton,onClick:e,"aria-label":"Open chat",type:"button",children:[n?g.jsx("img",{src:n,alt:"",className:an.agentLogo}):g.jsx("svg",{className:an.icon,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:g.jsx("path",{d:"M8 12H8.01M12 12H12.01M16 12H16.01M21 12C21 16.4183 16.9706 20 12 20C10.4607 20 9.01172 19.6565 7.74467 19.0511L3 20L4.39499 16.28C3.51156 15.0423 3 13.5743 3 12C3 7.58172 7.02944 4 12 4C16.9706 4 21 7.58172 21 12Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),t>0&&g.jsx("span",{className:an.unreadBadge,children:t>9?"9+":t})]}),ju="_container_kgfgt_1",zu="_header_kgfgt_25",Mu="_logoWrapper_kgfgt_38",Du="_logo_kgfgt_38",Bu="_closeButton_kgfgt_51",Ou="_content_kgfgt_74",Ru="_iconWrapper_kgfgt_84",Fu="_errorIcon_kgfgt_95",$u="_title_kgfgt_101",Hu="_description_kgfgt_109",Vu="_retryButton_kgfgt_117",Uu="_footer_kgfgt_139",qu="_poweredBy_kgfgt_146",Wu="_footerLogo_kgfgt_160",ne={container:ju,header:zu,logoWrapper:Mu,logo:Du,closeButton:Bu,content:Ou,iconWrapper:Ru,errorIcon:Fu,title:$u,description:Hu,retryButton:Vu,footer:Uu,poweredBy:qu,footerLogo:Wu},Yu=({errorType:e,message:n,onRetry:t,onClose:r})=>{const i=()=>{switch(e){case"not_found":return{title:"Chat Not Found",description:n||"This chat widget is not configured correctly. Please check the embed ID.",icon:g.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:ne.errorIcon,children:[g.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M12 7V13M12 16V16.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})};case"network":return{title:"Connection Error",description:n||"Unable to connect to the chat service. Please check your internet connection.",icon:g.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:ne.errorIcon,children:[g.jsx("path",{d:"M12 21C16.9706 21 21 16.9706 21 12C21 7.02944 16.9706 3 12 3C7.02944 3 3 7.02944 3 12C3 16.9706 7.02944 21 12 21Z",stroke:"currentColor",strokeWidth:"1.5"}),g.jsx("path",{d:"M8 15L16 9M8 9L16 15",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})};default:return{title:"Something Went Wrong",description:n||"An unexpected error occurred. Please try again later.",icon:g.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:ne.errorIcon,children:g.jsx("path",{d:"M12 9V13M12 17H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})}}},{title:l,description:o,icon:a}=i();return g.jsxs("div",{className:ne.container,children:[g.jsxs("div",{className:ne.header,children:[g.jsx("div",{className:ne.logoWrapper,children:g.jsx(Qe,{className:ne.logo,color:"white",cutoutColor:"var(--bb-primary-color)"})}),r&&g.jsx("button",{className:ne.closeButton,onClick:r,"aria-label":"Close",type:"button",children:g.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:g.jsx("path",{d:"M6 18L18 6M6 6L18 18",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),g.jsxs("div",{className:ne.content,children:[g.jsx("div",{className:ne.iconWrapper,children:a}),g.jsx("h2",{className:ne.title,children:l}),g.jsx("p",{className:ne.description,children:o}),t&&g.jsx("button",{className:ne.retryButton,onClick:t,type:"button",children:"Try Again"})]}),g.jsx("div",{className:ne.footer,children:g.jsxs("a",{href:"https://brainbaselabs.com",target:"_blank",rel:"noopener noreferrer",className:ne.poweredBy,children:["Powered by"," ",g.jsx(Qe,{className:ne.footerLogo,color:"var(--bb-text-tertiary)",cutoutColor:"var(--bb-surface-bg)"}),g.jsx("span",{children:"Brainbase Labs"})]})})]})},Xu="_widget_1ehud_1",Ku="_inline_1ehud_25",je={widget:Xu,"bottom-right":"_bottom-right_1ehud_10","bottom-left":"_bottom-left_1ehud_17",inline:Ku},Qu=({embedId:e,apiBaseUrl:n=Wt,mockMode:t=!1,mockResponses:r,position:i="bottom-right",defaultOpen:l=!1,primaryColor:o,agentName:a,agentLogoUrl:c,welcomeMessage:s,showBranding:u,className:p,onSessionStart:m,onSessionEnd:h,onMessage:S,onError:I})=>{const[E,b]=O.useState(l),[P,v]=O.useState(null),[R,V]=O.useState(!0),[k,D]=O.useState(null),[U,F]=O.useState(),$=O.useRef(!1),N=O.useMemo(()=>t?Xt({},r):Yt(n),[t,r,n]),C=O.useCallback(async()=>{if(!($.current&&P)){V(!0),D(null),F(void 0);try{const f=await N.getDeploymentConfig(e);v(f),$.current=!0}catch(f){const J=f instanceof Error?f:new Error("Failed to load config");J.message.includes("404")?(D("not_found"),F("The chat widget with this embed ID was not found.")):J.message.includes("Failed to fetch")||J.message.includes("network")?D("network"):D("unknown"),t&&(v({embedId:e,deploymentId:"mock-deployment",workerId:"mock-worker",flowId:"mock-flow",primaryColor:"#1a1a2e",agentName:"AI Assistant",styling:{}}),D(null),$.current=!0),I==null||I(J)}finally{V(!1)}}},[e,t,N,I,P]);O.useEffect(()=>{$.current=!1,C()},[e,t,N]);const j=O.useMemo(()=>{const f=P??{embedId:e,deploymentId:"",workerId:"",flowId:""};return{...f,primaryColor:o??f.primaryColor??"#1a1a2e",agentName:a??f.agentName,agentLogoUrl:c??f.agentLogoUrl,welcomeMessage:s??f.welcomeMessage,styling:{...f.styling??{},...u!==void 0?{showBranding:u}:{}}}},[P,e,o,a,c,s,u]),T=qt({config:j,apiClient:N,mockMode:t,onSessionStart:m,onSessionEnd:h,onMessage:S,onError:I}),x=O.useMemo(()=>({"--bb-primary-color":j.primaryColor??"#1a1a2e"}),[j.primaryColor]),A=()=>{T.endSession(),T.startNewSession()},L=()=>{b(!1)},q=()=>{C()},Q=i==="inline";return R?null:k&&!t?!Q&&!E?g.jsx("div",{className:`${je.widget} ${je[i]} ${p??""}`,style:x,children:g.jsx(Rn,{onClick:()=>b(!0),agentName:a})}):g.jsx("div",{className:`${je.widget} ${je[i]} ${p??""}`,style:x,children:g.jsx(Yu,{errorType:k,message:U,onRetry:q,onClose:Q?void 0:L})}):g.jsx("div",{className:`${je.widget} ${je[i]} ${p??""}`,style:x,children:E||Q?g.jsx(Br,{config:j,messages:T.messages,isLoading:T.isLoading,onSendMessage:T.sendMessage,onClose:Q?void 0:L,onNewChat:A}):g.jsx(Rn,{onClick:()=>b(!0),agentName:j.agentName,agentLogoUrl:j.agentLogoUrl})})};function Zu(){if(typeof crypto<"u"&&crypto.randomUUID)return`bb-${crypto.randomUUID()}`;const e=Date.now().toString(36),n=Math.random().toString(36).substring(2,15),t=Math.random().toString(36).substring(2,15);return`bb-${e}-${n}${t}`}exports.ChatContainer=Br;exports.ChatHeader=Kt;exports.ChatToggleButton=Rn;exports.ChatWidget=Qu;exports.Message=Ar;exports.MessageInput=Dr;exports.MessageList=Mr;exports.ToolCallDisplay=jr;exports.TypingIndicator=zr;exports.clearSession=Tn;exports.createAPIClient=Yt;exports.createMockAPIClient=Xt;exports.generateSessionId=Zu;exports.getStoredSession=Ut;exports.storeSession=vn;exports.useChat=qt;
3
+ `))!==-1;){const Ne=W.slice(0,we);W=W.slice(we+2);for(const Ke of Ne.split(`
4
+ `))if(Ke.startsWith("data: "))try{const $t=JSON.parse(Ke.slice(6));j($t,Z,y)}catch{}}}}finally{J.releaseLock()}},[j]),Q=q.useCallback(async K=>{if(!K.trim())return;const Z={id:`user-${Date.now()}`,role:"user",content:K,timestamp:Date.now(),status:"sent"};d(W=>[...W,Z]),c==null||c(Z);const y=`assistant-${Date.now()}`;if(r){const W={id:y,role:"assistant",content:"",timestamp:Date.now(),status:"streaming"};d(se=>[...se,W])}g(!0),_(null),I.current&&clearTimeout(I.current);const J=1e3+R();I.current=setTimeout(()=>{b(!0)},J);const X=W=>{T(W)};try{if(i){const W=n.sendMessage(K);for await(const se of W)j(se,y,X)}else{const W=await n.sendMessage({embedId:e.embedId,message:K,sessionId:S??void 0});await $(W,y,X)}r&&d(W=>W.map(se=>se.id===y&&se.status==="streaming"?{...se,status:"sent"}:se))}catch(W){const se=W instanceof Error?W:new Error("Failed to send message");_(se),l==null||l(se),r&&d(De=>De.map(we=>we.id===y?{...we,status:"error",content:"Failed to get response"}:we))}finally{I.current&&(clearTimeout(I.current),I.current=null),b(!1),g(!1)}},[S,n,i,r,R,e.embedId,j,$,c,l]),ee=q.useCallback(async()=>{const K=`assistant-${Date.now()}`;if(r){const J={id:K,role:"assistant",content:"",timestamp:Date.now(),status:"streaming"};d(X=>[...X,J])}g(!0),_(null),I.current&&clearTimeout(I.current);const Z=1e3+R();I.current=setTimeout(()=>{b(!0)},Z);const y=J=>{T(J)};try{if(i){const X=n.sendMessage("");for await(const W of X)j(W,K,y)}else{const X=await n.sendMessage({embedId:e.embedId,message:"",sessionId:S??void 0});await $(X,K,y)}r&&d(X=>X.map(W=>W.id===K&&W.status==="streaming"?{...W,status:"sent"}:W))}catch(J){const X=J instanceof Error?J:new Error("Failed to send message");_(X),l==null||l(X),r&&d(W=>W.map(se=>se.id===K?{...se,status:"error",content:"Failed to get response"}:se))}finally{I.current&&(clearTimeout(I.current),I.current=null),b(!1),g(!1)}},[S,n,i,r,R,e.embedId,j,$,l]),ne=q.useCallback(async()=>{if(!S)return;const K={sessionId:S,deploymentId:e.deploymentId,workerId:e.workerId,flowId:e.flowId,startTime:C.current,messages:u,toolCalls:h,status:"completed"};o==null||o(K),Zr(e.embedId),T(null),d([]),f([])},[S,e,u,h,o]),k=q.useCallback(()=>{d([]),f([])},[]);return{messages:u,toolCalls:h,isLoading:m,showTypingIndicator:w,error:P,sessionId:S,sendMessage:Q,sendTriggerMessage:ee,endSession:ne,clearMessages:k,startNewSession:N}}const vc="https://chat-embed-deployment.onrender.com";function yc(t=vc){return{async getDeploymentConfig(e){const n=await fetch(`${t}/chat/config/${e}`);if(!n.ok)throw new Error(`Failed to fetch deployment config: ${n.status}`);const i=await n.json();return{embedId:i.embedId,deploymentId:"",workerId:"",flowId:"",welcomeMessage:i.welcomeMessage,agentName:i.agentName,agentRole:i.agentRole,agentLogoUrl:i.agentLogoUrl,primaryColor:i.primaryColor,styling:i.styling}},async sendMessage(e){const n=await fetch(`${t}/chat/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embed_id:e.embedId,message:e.message,session_id:e.sessionId||void 0,metadata:e.metadata})});if(!n.ok){const i=await n.text();throw new Error(`Failed to send message: ${n.status} - ${i}`)}if(!n.body)throw new Error("No response stream available");return n.body}}}const Zu={embedId:"mock-embed-id",deploymentId:"mock-deployment-id",workerId:"mock-worker-id",flowId:"mock-flow-id",agentName:"AI Assistant",agentRole:"AI Agent",agentLogoUrl:void 0,primaryColor:"#1a1a2e",styling:{}},ed=[{trigger:/hello|hi|hey/i,response:"Hello! I'm a demo AI assistant. How can I help you today?",delay:500},{trigger:/weather/i,response:"I'd check the weather for you, but I'm in mock mode! In production, I could use a weather API.",delay:800,toolCalls:[{name:"get_weather",arguments:{location:"San Francisco"},result:{temperature:72,condition:"sunny"}}]},{trigger:/help|support/i,response:"I'm here to help! You can ask me questions, and I'll do my best to assist you. In production, I'd be connected to your agent with full capabilities.",delay:600},{trigger:/pricing|cost|price/i,response:"For pricing information, I'd typically check our database or connect you with the sales team. This is a mock response demonstrating how I'd handle pricing questions.",delay:700,toolCalls:[{name:"lookup_pricing",arguments:{plan:"all"},result:{plans:[{name:"Starter",price:"$29/mo"},{name:"Pro",price:"$99/mo"}]}}]},{trigger:/.*/,response:"I'm running in mock mode. This is a simulated response to demonstrate the chat UI. In production, I'd be connected to your agent!",delay:1e3}];function Xn(t){return new Promise(e=>setTimeout(e,t))}function bc(t,e){const n={...Zu,...t},i=e??ed,r=`mock-session-${Date.now()}`;return{async getDeploymentConfig(s){return await Xn(300),n},async*sendMessage(s){yield{type:"session",data:{session_id:r,is_new:!0},timestamp:Date.now()};const a=i.find(l=>typeof l.trigger=="string"?s.toLowerCase().includes(l.trigger.toLowerCase()):l.trigger.test(s))??i[i.length-1];if(await Xn(a.delay??500),a.toolCalls)for(const l of a.toolCalls)yield{type:"tool_call",data:{function:l.name,args:l.arguments},timestamp:Date.now()},await Xn(300),yield{type:"tool_call",data:{function:l.name,result:l.result},timestamp:Date.now()},await Xn(200);const o=a.response.split(" ");let c="";for(const l of o)c+=(c?" ":"")+l,yield{type:"message",data:{content:c,role:"assistant"},timestamp:Date.now()},await Xn(30+Math.random()*40);yield{type:"done",data:{session_id:r},timestamp:Date.now()}}}}const Kn=({className:t,color:e="currentColor",cutoutColor:n="var(--bb-primary-color)"})=>p.jsxs("svg",{className:t,viewBox:"0 0 800 800",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[p.jsx("path",{d:"M400 412C400 405.373 405.373 400 412 400H788C794.627 400 800 405.373 800 412V740C800 773.137 773.137 800 740 800H412C405.373 800 400 794.627 400 788V412Z",fill:e}),p.jsx("circle",{cx:"400",cy:"400",r:"400",fill:e}),p.jsx("path",{d:"M0 60C0 26.8629 26.8629 0 60 0H397.614C398.932 0 400 1.06811 400 2.38569V2.38569C400 221.982 221.982 400 2.38569 400V400C1.06811 400 0 398.932 0 397.614V60Z",fill:e}),p.jsx("path",{d:"M400 412C400 405.373 405.373 400 412 400H738C744.627 400 750 405.373 750 412V725C750 738.807 738.807 750 725 750H412C405.373 750 400 744.627 400 738V412Z",fill:e}),p.jsx("circle",{cx:"400",cy:"400",r:"350",fill:e}),p.jsx("path",{d:"M50 75C50 61.1929 61.1929 50 75 50H388C394.627 50 400 55.3726 400 62V388C400 394.627 394.627 400 388 400H62C55.3726 400 50 394.627 50 388V75Z",fill:e}),p.jsx("rect",{x:"399.919",y:"209",width:"270",height:"270",rx:"12",transform:"rotate(45 399.919 209)",fill:n})]}),td="_header_f8qt7_1",nd="_compact_f8qt7_9",id="_headerBackground_f8qt7_20",rd="_headerContent_f8qt7_58",sd="_topRow_f8qt7_63",od="_agentInfo_f8qt7_78",ad="_agentLogo_f8qt7_84",cd="_agentLogoPlaceholder_f8qt7_100",ld="_brainbaseLogo_f8qt7_120",ud="_backButton_f8qt7_135",dd="_agentTextWrapper_f8qt7_165",hd="_agentName_f8qt7_171",fd="_headerSubtitle_f8qt7_179",pd="_actions_f8qt7_187",md="_actionButton_f8qt7_192",gd="_welcomeText_f8qt7_226",vd="_title_f8qt7_245",yd="_subtitle_f8qt7_253",bd="_menuContainer_f8qt7_261",kd="_dropdown_f8qt7_266",Cd="_dropdownItem_f8qt7_290",Sd="_dropdownIcon_f8qt7_327",ve={header:td,compact:nd,headerBackground:id,headerContent:rd,topRow:sd,agentInfo:od,agentLogo:ad,agentLogoPlaceholder:cd,brainbaseLogo:ld,backButton:ud,agentTextWrapper:dd,agentName:hd,headerSubtitle:fd,actions:pd,actionButton:md,welcomeText:gd,title:vd,subtitle:yd,menuContainer:bd,dropdown:kd,dropdownItem:Cd,dropdownIcon:Sd},kc=({agentName:t="AI Assistant",agentLogoUrl:e,headerSubtitle:n,welcomeTitle:i,welcomeSubtitle:r,onClose:s,onBack:a,onNewChatRequest:o,onExpandWindow:c,onDownloadTranscript:l,showMenuButton:u=!1,isExpanded:d=!1,compact:h=!1})=>{const[f,m]=q.useState(!1),g=q.useRef(null);q.useEffect(()=>{const _=S=>{g.current&&!g.current.contains(S.target)&&m(!1)};return f&&document.addEventListener("mousedown",_),()=>{document.removeEventListener("mousedown",_)}},[f]);const w=i||"Hello there.",b=r!==void 0?r:i?void 0:"How can we help?",P=_=>{_(),m(!1)};return p.jsxs("div",{className:`${ve.header} ${h?ve.compact:""}`,children:[p.jsx("div",{className:ve.headerBackground}),p.jsxs("div",{className:ve.headerContent,children:[p.jsxs("div",{className:ve.topRow,children:[p.jsxs("div",{className:ve.agentInfo,children:[p.jsx("button",{className:ve.backButton,onClick:a,"aria-label":"Back",type:"button",children:p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:p.jsx("path",{d:"M15 18L9 12L15 6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),e?p.jsx("img",{src:e,alt:t,className:ve.agentLogo}):p.jsx("div",{className:ve.agentLogoPlaceholder,children:p.jsx(Kn,{className:ve.brainbaseLogo,color:"white",cutoutColor:"var(--bb-primary-color)"})}),p.jsxs("div",{className:ve.agentTextWrapper,children:[p.jsx("span",{className:ve.agentName,children:t}),n&&p.jsx("span",{className:ve.headerSubtitle,children:n})]})]}),p.jsxs("div",{className:ve.actions,children:[u&&p.jsxs("div",{className:ve.menuContainer,ref:g,children:[p.jsx("button",{className:ve.actionButton,onClick:()=>m(!f),"aria-label":"Open menu","aria-expanded":f,type:"button",children:p.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:[p.jsx("circle",{cx:"5",cy:"12",r:"2"}),p.jsx("circle",{cx:"12",cy:"12",r:"2"}),p.jsx("circle",{cx:"19",cy:"12",r:"2"})]})}),f&&p.jsxs("div",{className:ve.dropdown,children:[c&&p.jsx("button",{className:ve.dropdownItem,onClick:()=>P(c),type:"button",children:d?p.jsxs(p.Fragment,{children:[p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:ve.dropdownIcon,children:p.jsx("path",{d:"M4 14H10V20M10 14L3 21M20 10H14V4M14 10L21 3",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),p.jsx("span",{children:"Minimize"})]}):p.jsxs(p.Fragment,{children:[p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:ve.dropdownIcon,children:p.jsx("path",{d:"M15 3H21V9M21 3L13 11M9 21H3V15M3 21L11 13",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),p.jsx("span",{children:"Expand window"})]})}),l&&p.jsxs("button",{className:ve.dropdownItem,onClick:()=>P(l),type:"button",children:[p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:ve.dropdownIcon,children:p.jsx("path",{d:"M21 15V19C21 20.1046 20.1046 21 19 21H5C3.89543 21 3 20.1046 3 19V15M7 10L12 15M12 15L17 10M12 15V3",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),p.jsx("span",{children:"Download transcript"})]}),o&&p.jsxs("button",{className:ve.dropdownItem,onClick:()=>P(o),type:"button",children:[p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:ve.dropdownIcon,children:p.jsx("path",{d:"M12 5V19M5 12H19",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),p.jsx("span",{children:"New chat"})]})]})]}),s&&p.jsx("button",{className:ve.actionButton,onClick:s,"aria-label":"Close chat",type:"button",children:p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:p.jsx("path",{d:"M6 18L18 6M6 6L18 18",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]}),!h&&p.jsxs("div",{className:ve.welcomeText,children:[p.jsx("h1",{className:ve.title,children:w}),b&&p.jsx("p",{className:ve.subtitle,children:b})]})]})]})};function Td(t,e){const n={};return(t[t.length-1]===""?[...t,""]:t).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const wd=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,xd=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,_d={};function xo(t,e){return(_d.jsx?xd:wd).test(t)}const Ed=/[ \t\n\f\r]/g;function Pd(t){return typeof t=="object"?t.type==="text"?_o(t.value):!1:_o(t)}function _o(t){return t.replace(Ed,"")===""}class xi{constructor(e,n,i){this.normal=n,this.property=e,i&&(this.space=i)}}xi.prototype.normal={};xi.prototype.property={};xi.prototype.space=void 0;function Cc(t,e){const n={},i={};for(const r of t)Object.assign(n,r.property),Object.assign(i,r.normal);return new xi(n,i,e)}function es(t){return t.toLowerCase()}class st{constructor(e,n){this.attribute=n,this.property=e}}st.prototype.attribute="";st.prototype.booleanish=!1;st.prototype.boolean=!1;st.prototype.commaOrSpaceSeparated=!1;st.prototype.commaSeparated=!1;st.prototype.defined=!1;st.prototype.mustUseProperty=!1;st.prototype.number=!1;st.prototype.overloadedBoolean=!1;st.prototype.property="";st.prototype.spaceSeparated=!1;st.prototype.space=void 0;let Rd=0;const ae=_n(),Oe=_n(),ts=_n(),B=_n(),Se=_n(),Ln=_n(),lt=_n();function _n(){return 2**++Rd}const ns=Object.freeze(Object.defineProperty({__proto__:null,boolean:ae,booleanish:Oe,commaOrSpaceSeparated:lt,commaSeparated:Ln,number:B,overloadedBoolean:ts,spaceSeparated:Se},Symbol.toStringTag,{value:"Module"})),kr=Object.keys(ns);class js extends st{constructor(e,n,i,r){let s=-1;if(super(e,n),Eo(this,"space",r),typeof i=="number")for(;++s<kr.length;){const a=kr[s];Eo(this,kr[s],(i&ns[a])===ns[a])}}}js.prototype.defined=!0;function Eo(t,e,n){n&&(t[e]=n)}function Yn(t){const e={},n={};for(const[i,r]of Object.entries(t.properties)){const s=new js(i,t.transform(t.attributes||{},i),r,t.space);t.mustUseProperty&&t.mustUseProperty.includes(i)&&(s.mustUseProperty=!0),e[i]=s,n[es(i)]=i,n[es(s.attribute)]=i}return new xi(e,n,t.space)}const Sc=Yn({properties:{ariaActiveDescendant:null,ariaAtomic:Oe,ariaAutoComplete:null,ariaBusy:Oe,ariaChecked:Oe,ariaColCount:B,ariaColIndex:B,ariaColSpan:B,ariaControls:Se,ariaCurrent:null,ariaDescribedBy:Se,ariaDetails:null,ariaDisabled:Oe,ariaDropEffect:Se,ariaErrorMessage:null,ariaExpanded:Oe,ariaFlowTo:Se,ariaGrabbed:Oe,ariaHasPopup:null,ariaHidden:Oe,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Se,ariaLevel:B,ariaLive:null,ariaModal:Oe,ariaMultiLine:Oe,ariaMultiSelectable:Oe,ariaOrientation:null,ariaOwns:Se,ariaPlaceholder:null,ariaPosInSet:B,ariaPressed:Oe,ariaReadOnly:Oe,ariaRelevant:null,ariaRequired:Oe,ariaRoleDescription:Se,ariaRowCount:B,ariaRowIndex:B,ariaRowSpan:B,ariaSelected:Oe,ariaSetSize:B,ariaSort:null,ariaValueMax:B,ariaValueMin:B,ariaValueNow:B,ariaValueText:null,role:null},transform(t,e){return e==="role"?e:"aria-"+e.slice(4).toLowerCase()}});function Tc(t,e){return e in t?t[e]:e}function wc(t,e){return Tc(t,e.toLowerCase())}const Id=Yn({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Ln,acceptCharset:Se,accessKey:Se,action:null,allow:null,allowFullScreen:ae,allowPaymentRequest:ae,allowUserMedia:ae,alt:null,as:null,async:ae,autoCapitalize:null,autoComplete:Se,autoFocus:ae,autoPlay:ae,blocking:Se,capture:null,charSet:null,checked:ae,cite:null,className:Se,cols:B,colSpan:null,content:null,contentEditable:Oe,controls:ae,controlsList:Se,coords:B|Ln,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ae,defer:ae,dir:null,dirName:null,disabled:ae,download:ts,draggable:Oe,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ae,formTarget:null,headers:Se,height:B,hidden:ts,high:B,href:null,hrefLang:null,htmlFor:Se,httpEquiv:Se,id:null,imageSizes:null,imageSrcSet:null,inert:ae,inputMode:null,integrity:null,is:null,isMap:ae,itemId:null,itemProp:Se,itemRef:Se,itemScope:ae,itemType:Se,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ae,low:B,manifest:null,max:null,maxLength:B,media:null,method:null,min:null,minLength:B,multiple:ae,muted:ae,name:null,nonce:null,noModule:ae,noValidate:ae,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:ae,optimum:B,pattern:null,ping:Se,placeholder:null,playsInline:ae,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ae,referrerPolicy:null,rel:Se,required:ae,reversed:ae,rows:B,rowSpan:B,sandbox:Se,scope:null,scoped:ae,seamless:ae,selected:ae,shadowRootClonable:ae,shadowRootDelegatesFocus:ae,shadowRootMode:null,shape:null,size:B,sizes:null,slot:null,span:B,spellCheck:Oe,src:null,srcDoc:null,srcLang:null,srcSet:null,start:B,step:null,style:null,tabIndex:B,target:null,title:null,translate:null,type:null,typeMustMatch:ae,useMap:null,value:Oe,width:B,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Se,axis:null,background:null,bgColor:null,border:B,borderColor:null,bottomMargin:B,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ae,declare:ae,event:null,face:null,frame:null,frameBorder:null,hSpace:B,leftMargin:B,link:null,longDesc:null,lowSrc:null,marginHeight:B,marginWidth:B,noResize:ae,noHref:ae,noShade:ae,noWrap:ae,object:null,profile:null,prompt:null,rev:null,rightMargin:B,rules:null,scheme:null,scrolling:Oe,standby:null,summary:null,text:null,topMargin:B,valueType:null,version:null,vAlign:null,vLink:null,vSpace:B,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ae,disableRemotePlayback:ae,prefix:null,property:null,results:B,security:null,unselectable:null},space:"html",transform:wc}),Md=Yn({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:lt,accentHeight:B,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:B,amplitude:B,arabicForm:null,ascent:B,attributeName:null,attributeType:null,azimuth:B,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:B,by:null,calcMode:null,capHeight:B,className:Se,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:B,diffuseConstant:B,direction:null,display:null,dur:null,divisor:B,dominantBaseline:null,download:ae,dx:null,dy:null,edgeMode:null,editable:null,elevation:B,enableBackground:null,end:null,event:null,exponent:B,externalResourcesRequired:null,fill:null,fillOpacity:B,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Ln,g2:Ln,glyphName:Ln,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:B,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:B,horizOriginX:B,horizOriginY:B,id:null,ideographic:B,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:B,k:B,k1:B,k2:B,k3:B,k4:B,kernelMatrix:lt,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:B,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:B,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:B,overlineThickness:B,paintOrder:null,panose1:null,path:null,pathLength:B,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Se,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:B,pointsAtY:B,pointsAtZ:B,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:lt,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:lt,rev:lt,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:lt,requiredFeatures:lt,requiredFonts:lt,requiredFormats:lt,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:B,specularExponent:B,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:B,strikethroughThickness:B,string:null,stroke:null,strokeDashArray:lt,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:B,strokeOpacity:B,strokeWidth:null,style:null,surfaceScale:B,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:lt,tabIndex:B,tableValues:null,target:null,targetX:B,targetY:B,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:lt,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:B,underlineThickness:B,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:B,values:null,vAlphabetic:B,vMathematical:B,vectorEffect:null,vHanging:B,vIdeographic:B,version:null,vertAdvY:B,vertOriginX:B,vertOriginY:B,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:B,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Tc}),xc=Yn({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(t,e){return"xlink:"+e.slice(5).toLowerCase()}}),_c=Yn({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:wc}),Ec=Yn({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(t,e){return"xml:"+e.slice(3).toLowerCase()}}),Od={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Ad=/[A-Z]/g,Po=/-[a-z]/g,Dd=/^data[-\w.:]+$/i;function Nd(t,e){const n=es(e);let i=e,r=st;if(n in t.normal)return t.property[t.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&Dd.test(e)){if(e.charAt(4)==="-"){const s=e.slice(5).replace(Po,jd);i="data"+s.charAt(0).toUpperCase()+s.slice(1)}else{const s=e.slice(4);if(!Po.test(s)){let a=s.replace(Ad,Ld);a.charAt(0)!=="-"&&(a="-"+a),e="data"+a}}r=js}return new r(i,e)}function Ld(t){return"-"+t.toLowerCase()}function jd(t){return t.charAt(1).toUpperCase()}const Ud=Cc([Sc,Id,xc,_c,Ec],"html"),Us=Cc([Sc,Md,xc,_c,Ec],"svg");function Fd(t){return t.join(" ").trim()}function Pc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Rn={},Cr,Ro;function Bd(){if(Ro)return Cr;Ro=1;var t=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,e=/\n/g,n=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,o=/^\s+|\s+$/g,c=`
5
+ `,l="/",u="*",d="",h="comment",f="declaration";function m(w,b){if(typeof w!="string")throw new TypeError("First argument must be a string");if(!w)return[];b=b||{};var P=1,_=1;function S(G){var j=G.match(e);j&&(P+=j.length);var $=G.lastIndexOf(c);_=~$?G.length-$:_+G.length}function T(){var G={line:P,column:_};return function(j){return j.position=new C(G),I(),j}}function C(G){this.start=G,this.end={line:P,column:_},this.source=b.source}C.prototype.content=w;function O(G){var j=new Error(b.source+":"+P+":"+_+": "+G);if(j.reason=G,j.filename=b.source,j.line=P,j.column=_,j.source=w,!b.silent)throw j}function L(G){var j=G.exec(w);if(j){var $=j[0];return S($),w=w.slice($.length),j}}function I(){L(n)}function A(G){var j;for(G=G||[];j=R();)j!==!1&&G.push(j);return G}function R(){var G=T();if(!(l!=w.charAt(0)||u!=w.charAt(1))){for(var j=2;d!=w.charAt(j)&&(u!=w.charAt(j)||l!=w.charAt(j+1));)++j;if(j+=2,d===w.charAt(j-1))return O("End of comment missing");var $=w.slice(2,j-2);return _+=2,S($),w=w.slice(j),_+=2,G({type:h,comment:$})}}function N(){var G=T(),j=L(i);if(j){if(R(),!L(r))return O("property missing ':'");var $=L(s),Q=G({type:f,property:g(j[0].replace(t,d)),value:$?g($[0].replace(t,d)):d});return L(a),Q}}function Y(){var G=[];A(G);for(var j;j=N();)j!==!1&&(G.push(j),A(G));return G}return I(),Y()}function g(w){return w?w.replace(o,d):d}return Cr=m,Cr}var Io;function Vd(){if(Io)return Rn;Io=1;var t=Rn&&Rn.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.default=n;const e=t(Bd());function n(i,r){let s=null;if(!i||typeof i!="string")return s;const a=(0,e.default)(i),o=typeof r=="function";return a.forEach(c=>{if(c.type!=="declaration")return;const{property:l,value:u}=c;o?r(l,u,c):u&&(s=s||{},s[l]=u)}),s}return Rn}var Zn={},Mo;function qd(){if(Mo)return Zn;Mo=1,Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,e=/-([a-z])/g,n=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,s=function(l){return!l||n.test(l)||t.test(l)},a=function(l,u){return u.toUpperCase()},o=function(l,u){return"".concat(u,"-")},c=function(l,u){return u===void 0&&(u={}),s(l)?l:(l=l.toLowerCase(),u.reactCompat?l=l.replace(r,o):l=l.replace(i,o),l.replace(e,a))};return Zn.camelCase=c,Zn}var ei,Oo;function zd(){if(Oo)return ei;Oo=1;var t=ei&&ei.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},e=t(Vd()),n=qd();function i(r,s){var a={};return!r||typeof r!="string"||(0,e.default)(r,function(o,c){o&&c&&(a[(0,n.camelCase)(o,s)]=c)}),a}return i.default=i,ei=i,ei}var Wd=zd();const Hd=Pc(Wd),Rc=Ic("end"),Fs=Ic("start");function Ic(t){return e;function e(n){const i=n&&n.position&&n.position[t]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function Kd(t){const e=Fs(t),n=Rc(t);if(e&&n)return{start:e,end:n}}function di(t){return!t||typeof t!="object"?"":"position"in t||"type"in t?Ao(t.position):"start"in t||"end"in t?Ao(t):"line"in t||"column"in t?is(t):""}function is(t){return Do(t&&t.line)+":"+Do(t&&t.column)}function Ao(t){return is(t&&t.start)+"-"+is(t&&t.end)}function Do(t){return t&&typeof t=="number"?t:1}class We extends Error{constructor(e,n,i){super(),typeof n=="string"&&(i=n,n=void 0);let r="",s={},a=!1;if(n&&("line"in n&&"column"in n?s={place:n}:"start"in n&&"end"in n?s={place:n}:"type"in n?s={ancestors:[n],place:n.position}:s={...n}),typeof e=="string"?r=e:!s.cause&&e&&(a=!0,r=e.message,s.cause=e),!s.ruleId&&!s.source&&typeof i=="string"){const c=i.indexOf(":");c===-1?s.ruleId=i:(s.source=i.slice(0,c),s.ruleId=i.slice(c+1))}if(!s.place&&s.ancestors&&s.ancestors){const c=s.ancestors[s.ancestors.length-1];c&&(s.place=c.position)}const o=s.place&&"start"in s.place?s.place.start:s.place;this.ancestors=s.ancestors||void 0,this.cause=s.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=o?o.line:void 0,this.name=di(s.place)||"1:1",this.place=s.place||void 0,this.reason=this.message,this.ruleId=s.ruleId||void 0,this.source=s.source||void 0,this.stack=a&&s.cause&&typeof s.cause.stack=="string"?s.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}We.prototype.file="";We.prototype.name="";We.prototype.reason="";We.prototype.message="";We.prototype.stack="";We.prototype.column=void 0;We.prototype.line=void 0;We.prototype.ancestors=void 0;We.prototype.cause=void 0;We.prototype.fatal=void 0;We.prototype.place=void 0;We.prototype.ruleId=void 0;We.prototype.source=void 0;const Bs={}.hasOwnProperty,Gd=new Map,$d=/[A-Z]/g,Jd=new Set(["table","tbody","thead","tfoot","tr"]),Yd=new Set(["td","th"]),Mc="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Qd(t,e){if(!e||e.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=e.filePath||void 0;let i;if(e.development){if(typeof e.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");i=sh(n,e.jsxDEV)}else{if(typeof e.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof e.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");i=rh(n,e.jsx,e.jsxs)}const r={Fragment:e.Fragment,ancestors:[],components:e.components||{},create:i,elementAttributeNameCase:e.elementAttributeNameCase||"react",evaluater:e.createEvaluater?e.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:e.ignoreInvalidStyle||!1,passKeys:e.passKeys!==!1,passNode:e.passNode||!1,schema:e.space==="svg"?Us:Ud,stylePropertyNameCase:e.stylePropertyNameCase||"dom",tableCellAlignToStyle:e.tableCellAlignToStyle!==!1},s=Oc(r,t,void 0);return s&&typeof s!="string"?s:r.create(t,r.Fragment,{children:s||void 0},void 0)}function Oc(t,e,n){if(e.type==="element")return Xd(t,e,n);if(e.type==="mdxFlowExpression"||e.type==="mdxTextExpression")return Zd(t,e);if(e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement")return th(t,e,n);if(e.type==="mdxjsEsm")return eh(t,e);if(e.type==="root")return nh(t,e,n);if(e.type==="text")return ih(t,e)}function Xd(t,e,n){const i=t.schema;let r=i;e.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=Us,t.schema=r),t.ancestors.push(e);const s=Dc(t,e.tagName,!1),a=oh(t,e);let o=qs(t,e);return Jd.has(e.tagName)&&(o=o.filter(function(c){return typeof c=="string"?!Pd(c):!0})),Ac(t,a,s,e),Vs(a,o),t.ancestors.pop(),t.schema=i,t.create(e,s,a,n)}function Zd(t,e){if(e.data&&e.data.estree&&t.evaluater){const i=e.data.estree.body[0];return i.type,t.evaluater.evaluateExpression(i.expression)}yi(t,e.position)}function eh(t,e){if(e.data&&e.data.estree&&t.evaluater)return t.evaluater.evaluateProgram(e.data.estree);yi(t,e.position)}function th(t,e,n){const i=t.schema;let r=i;e.name==="svg"&&i.space==="html"&&(r=Us,t.schema=r),t.ancestors.push(e);const s=e.name===null?t.Fragment:Dc(t,e.name,!0),a=ah(t,e),o=qs(t,e);return Ac(t,a,s,e),Vs(a,o),t.ancestors.pop(),t.schema=i,t.create(e,s,a,n)}function nh(t,e,n){const i={};return Vs(i,qs(t,e)),t.create(e,t.Fragment,i,n)}function ih(t,e){return e.value}function Ac(t,e,n,i){typeof n!="string"&&n!==t.Fragment&&t.passNode&&(e.node=i)}function Vs(t,e){if(e.length>0){const n=e.length>1?e:e[0];n&&(t.children=n)}}function rh(t,e,n){return i;function i(r,s,a,o){const l=Array.isArray(a.children)?n:e;return o?l(s,a,o):l(s,a)}}function sh(t,e){return n;function n(i,r,s,a){const o=Array.isArray(s.children),c=Fs(i);return e(r,s,a,o,{columnNumber:c?c.column-1:void 0,fileName:t,lineNumber:c?c.line:void 0},void 0)}}function oh(t,e){const n={};let i,r;for(r in e.properties)if(r!=="children"&&Bs.call(e.properties,r)){const s=ch(t,r,e.properties[r]);if(s){const[a,o]=s;t.tableCellAlignToStyle&&a==="align"&&typeof o=="string"&&Yd.has(e.tagName)?i=o:n[a]=o}}if(i){const s=n.style||(n.style={});s[t.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return n}function ah(t,e){const n={};for(const i of e.attributes)if(i.type==="mdxJsxExpressionAttribute")if(i.data&&i.data.estree&&t.evaluater){const s=i.data.estree.body[0];s.type;const a=s.expression;a.type;const o=a.properties[0];o.type,Object.assign(n,t.evaluater.evaluateExpression(o.argument))}else yi(t,e.position);else{const r=i.name;let s;if(i.value&&typeof i.value=="object")if(i.value.data&&i.value.data.estree&&t.evaluater){const o=i.value.data.estree.body[0];o.type,s=t.evaluater.evaluateExpression(o.expression)}else yi(t,e.position);else s=i.value===null?!0:i.value;n[r]=s}return n}function qs(t,e){const n=[];let i=-1;const r=t.passKeys?new Map:Gd;for(;++i<e.children.length;){const s=e.children[i];let a;if(t.passKeys){const c=s.type==="element"?s.tagName:s.type==="mdxJsxFlowElement"||s.type==="mdxJsxTextElement"?s.name:void 0;if(c){const l=r.get(c)||0;a=c+"-"+l,r.set(c,l+1)}}const o=Oc(t,s,a);o!==void 0&&n.push(o)}return n}function ch(t,e,n){const i=Nd(t.schema,e);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=i.commaSeparated?Td(n):Fd(n)),i.property==="style"){let r=typeof n=="object"?n:lh(t,String(n));return t.stylePropertyNameCase==="css"&&(r=uh(r)),["style",r]}return[t.elementAttributeNameCase==="react"&&i.space?Od[i.property]||i.property:i.attribute,n]}}function lh(t,e){try{return Hd(e,{reactCompat:!0})}catch(n){if(t.ignoreInvalidStyle)return{};const i=n,r=new We("Cannot parse `style` attribute",{ancestors:t.ancestors,cause:i,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=t.filePath||void 0,r.url=Mc+"#cannot-parse-style-attribute",r}}function Dc(t,e,n){let i;if(!n)i={type:"Literal",value:e};else if(e.includes(".")){const r=e.split(".");let s=-1,a;for(;++s<r.length;){const o=xo(r[s])?{type:"Identifier",name:r[s]}:{type:"Literal",value:r[s]};a=a?{type:"MemberExpression",object:a,property:o,computed:!!(s&&o.type==="Literal"),optional:!1}:o}i=a}else i=xo(e)&&!/^[a-z]/.test(e)?{type:"Identifier",name:e}:{type:"Literal",value:e};if(i.type==="Literal"){const r=i.value;return Bs.call(t.components,r)?t.components[r]:r}if(t.evaluater)return t.evaluater.evaluateExpression(i);yi(t)}function yi(t,e){const n=new We("Cannot handle MDX estrees without `createEvaluater`",{ancestors:t.ancestors,place:e,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=t.filePath||void 0,n.url=Mc+"#cannot-handle-mdx-estrees-without-createevaluater",n}function uh(t){const e={};let n;for(n in t)Bs.call(t,n)&&(e[dh(n)]=t[n]);return e}function dh(t){let e=t.replace($d,hh);return e.slice(0,3)==="ms-"&&(e="-"+e),e}function hh(t){return"-"+t.toLowerCase()}const Sr={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},fh={};function ph(t,e){const n=fh,i=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,r=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return Nc(t,i,r)}function Nc(t,e,n){if(mh(t)){if("value"in t)return t.type==="html"&&!n?"":t.value;if(e&&"alt"in t&&t.alt)return t.alt;if("children"in t)return No(t.children,e,n)}return Array.isArray(t)?No(t,e,n):""}function No(t,e,n){const i=[];let r=-1;for(;++r<t.length;)i[r]=Nc(t[r],e,n);return i.join("")}function mh(t){return!!(t&&typeof t=="object")}const Lo=document.createElement("i");function zs(t){const e="&"+t+";";Lo.innerHTML=e;const n=Lo.textContent;return n.charCodeAt(n.length-1)===59&&t!=="semi"||n===e?!1:n}function At(t,e,n,i){const r=t.length;let s=0,a;if(e<0?e=-e>r?0:r+e:e=e>r?r:e,n=n>0?n:0,i.length<1e4)a=Array.from(i),a.unshift(e,n),t.splice(...a);else for(n&&t.splice(e,n);s<i.length;)a=i.slice(s,s+1e4),a.unshift(e,0),t.splice(...a),s+=1e4,e+=1e4}function gt(t,e){return t.length>0?(At(t,t.length,0,e),t):e}const jo={}.hasOwnProperty;function gh(t){const e={};let n=-1;for(;++n<t.length;)vh(e,t[n]);return e}function vh(t,e){let n;for(n in e){const r=(jo.call(t,n)?t[n]:void 0)||(t[n]={}),s=e[n];let a;if(s)for(a in s){jo.call(r,a)||(r[a]=[]);const o=s[a];yh(r[a],Array.isArray(o)?o:o?[o]:[])}}}function yh(t,e){let n=-1;const i=[];for(;++n<e.length;)(e[n].add==="after"?t:i).push(e[n]);At(t,0,0,i)}function Lc(t,e){const n=Number.parseInt(t,e);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function jn(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Mt=fn(/[A-Za-z]/),ut=fn(/[\dA-Za-z]/),bh=fn(/[#-'*+\--9=?A-Z^-~]/);function rs(t){return t!==null&&(t<32||t===127)}const ss=fn(/\d/),kh=fn(/[\dA-Fa-f]/),Ch=fn(/[!-/:-@[-`{-~]/);function re(t){return t!==null&&t<-2}function it(t){return t!==null&&(t<0||t===32)}function ge(t){return t===-2||t===-1||t===32}const Sh=fn(new RegExp("\\p{P}|\\p{S}","u")),Th=fn(/\s/);function fn(t){return e;function e(n){return n!==null&&n>-1&&t.test(String.fromCharCode(n))}}function Qn(t){const e=[];let n=-1,i=0,r=0;for(;++n<t.length;){const s=t.charCodeAt(n);let a="";if(s===37&&ut(t.charCodeAt(n+1))&&ut(t.charCodeAt(n+2)))r=2;else if(s<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(s))||(a=String.fromCharCode(s));else if(s>55295&&s<57344){const o=t.charCodeAt(n+1);s<56320&&o>56319&&o<57344?(a=String.fromCharCode(s,o),r=1):a="�"}else a=String.fromCharCode(s);a&&(e.push(t.slice(i,n),encodeURIComponent(a)),i=n+r+1,a=""),r&&(n+=r,r=0)}return e.join("")+t.slice(i)}function Te(t,e,n,i){const r=i?i-1:Number.POSITIVE_INFINITY;let s=0;return a;function a(c){return ge(c)?(t.enter(n),o(c)):e(c)}function o(c){return ge(c)&&s++<r?(t.consume(c),o):(t.exit(n),e(c))}}const wh={tokenize:xh};function xh(t){const e=t.attempt(this.parser.constructs.contentInitial,i,r);let n;return e;function i(o){if(o===null){t.consume(o);return}return t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),Te(t,e,"linePrefix")}function r(o){return t.enter("paragraph"),s(o)}function s(o){const c=t.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=c),n=c,a(o)}function a(o){if(o===null){t.exit("chunkText"),t.exit("paragraph"),t.consume(o);return}return re(o)?(t.consume(o),t.exit("chunkText"),s):(t.consume(o),a)}}const _h={tokenize:Eh},Uo={tokenize:Ph};function Eh(t){const e=this,n=[];let i=0,r,s,a;return o;function o(_){if(i<n.length){const S=n[i];return e.containerState=S[1],t.attempt(S[0].continuation,c,l)(_)}return l(_)}function c(_){if(i++,e.containerState._closeFlow){e.containerState._closeFlow=void 0,r&&P();const S=e.events.length;let T=S,C;for(;T--;)if(e.events[T][0]==="exit"&&e.events[T][1].type==="chunkFlow"){C=e.events[T][1].end;break}b(i);let O=S;for(;O<e.events.length;)e.events[O][1].end={...C},O++;return At(e.events,T+1,0,e.events.slice(S)),e.events.length=O,l(_)}return o(_)}function l(_){if(i===n.length){if(!r)return h(_);if(r.currentConstruct&&r.currentConstruct.concrete)return m(_);e.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return e.containerState={},t.check(Uo,u,d)(_)}function u(_){return r&&P(),b(i),h(_)}function d(_){return e.parser.lazy[e.now().line]=i!==n.length,a=e.now().offset,m(_)}function h(_){return e.containerState={},t.attempt(Uo,f,m)(_)}function f(_){return i++,n.push([e.currentConstruct,e.containerState]),h(_)}function m(_){if(_===null){r&&P(),b(0),t.consume(_);return}return r=r||e.parser.flow(e.now()),t.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:s}),g(_)}function g(_){if(_===null){w(t.exit("chunkFlow"),!0),b(0),t.consume(_);return}return re(_)?(t.consume(_),w(t.exit("chunkFlow")),i=0,e.interrupt=void 0,o):(t.consume(_),g)}function w(_,S){const T=e.sliceStream(_);if(S&&T.push(null),_.previous=s,s&&(s.next=_),s=_,r.defineSkip(_.start),r.write(T),e.parser.lazy[_.start.line]){let C=r.events.length;for(;C--;)if(r.events[C][1].start.offset<a&&(!r.events[C][1].end||r.events[C][1].end.offset>a))return;const O=e.events.length;let L=O,I,A;for(;L--;)if(e.events[L][0]==="exit"&&e.events[L][1].type==="chunkFlow"){if(I){A=e.events[L][1].end;break}I=!0}for(b(i),C=O;C<e.events.length;)e.events[C][1].end={...A},C++;At(e.events,L+1,0,e.events.slice(O)),e.events.length=C}}function b(_){let S=n.length;for(;S-- >_;){const T=n[S];e.containerState=T[1],T[0].exit.call(e,t)}n.length=_}function P(){r.write([null]),s=void 0,r=void 0,e.containerState._closeFlow=void 0}}function Ph(t,e,n){return Te(t,t.attempt(this.parser.constructs.document,e,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Fo(t){if(t===null||it(t)||Th(t))return 1;if(Sh(t))return 2}function Ws(t,e,n){const i=[];let r=-1;for(;++r<t.length;){const s=t[r].resolveAll;s&&!i.includes(s)&&(e=s(e,n),i.push(s))}return e}const os={name:"attention",resolveAll:Rh,tokenize:Ih};function Rh(t,e){let n=-1,i,r,s,a,o,c,l,u;for(;++n<t.length;)if(t[n][0]==="enter"&&t[n][1].type==="attentionSequence"&&t[n][1]._close){for(i=n;i--;)if(t[i][0]==="exit"&&t[i][1].type==="attentionSequence"&&t[i][1]._open&&e.sliceSerialize(t[i][1]).charCodeAt(0)===e.sliceSerialize(t[n][1]).charCodeAt(0)){if((t[i][1]._close||t[n][1]._open)&&(t[n][1].end.offset-t[n][1].start.offset)%3&&!((t[i][1].end.offset-t[i][1].start.offset+t[n][1].end.offset-t[n][1].start.offset)%3))continue;c=t[i][1].end.offset-t[i][1].start.offset>1&&t[n][1].end.offset-t[n][1].start.offset>1?2:1;const d={...t[i][1].end},h={...t[n][1].start};Bo(d,-c),Bo(h,c),a={type:c>1?"strongSequence":"emphasisSequence",start:d,end:{...t[i][1].end}},o={type:c>1?"strongSequence":"emphasisSequence",start:{...t[n][1].start},end:h},s={type:c>1?"strongText":"emphasisText",start:{...t[i][1].end},end:{...t[n][1].start}},r={type:c>1?"strong":"emphasis",start:{...a.start},end:{...o.end}},t[i][1].end={...a.start},t[n][1].start={...o.end},l=[],t[i][1].end.offset-t[i][1].start.offset&&(l=gt(l,[["enter",t[i][1],e],["exit",t[i][1],e]])),l=gt(l,[["enter",r,e],["enter",a,e],["exit",a,e],["enter",s,e]]),l=gt(l,Ws(e.parser.constructs.insideSpan.null,t.slice(i+1,n),e)),l=gt(l,[["exit",s,e],["enter",o,e],["exit",o,e],["exit",r,e]]),t[n][1].end.offset-t[n][1].start.offset?(u=2,l=gt(l,[["enter",t[n][1],e],["exit",t[n][1],e]])):u=0,At(t,i-1,n-i+3,l),n=i+l.length-u-2;break}}for(n=-1;++n<t.length;)t[n][1].type==="attentionSequence"&&(t[n][1].type="data");return t}function Ih(t,e){const n=this.parser.constructs.attentionMarkers.null,i=this.previous,r=Fo(i);let s;return a;function a(c){return s=c,t.enter("attentionSequence"),o(c)}function o(c){if(c===s)return t.consume(c),o;const l=t.exit("attentionSequence"),u=Fo(c),d=!u||u===2&&r||n.includes(c),h=!r||r===2&&u||n.includes(i);return l._open=!!(s===42?d:d&&(r||!h)),l._close=!!(s===42?h:h&&(u||!d)),e(c)}}function Bo(t,e){t.column+=e,t.offset+=e,t._bufferIndex+=e}const Mh={name:"autolink",tokenize:Oh};function Oh(t,e,n){let i=0;return r;function r(f){return t.enter("autolink"),t.enter("autolinkMarker"),t.consume(f),t.exit("autolinkMarker"),t.enter("autolinkProtocol"),s}function s(f){return Mt(f)?(t.consume(f),a):f===64?n(f):l(f)}function a(f){return f===43||f===45||f===46||ut(f)?(i=1,o(f)):l(f)}function o(f){return f===58?(t.consume(f),i=0,c):(f===43||f===45||f===46||ut(f))&&i++<32?(t.consume(f),o):(i=0,l(f))}function c(f){return f===62?(t.exit("autolinkProtocol"),t.enter("autolinkMarker"),t.consume(f),t.exit("autolinkMarker"),t.exit("autolink"),e):f===null||f===32||f===60||rs(f)?n(f):(t.consume(f),c)}function l(f){return f===64?(t.consume(f),u):bh(f)?(t.consume(f),l):n(f)}function u(f){return ut(f)?d(f):n(f)}function d(f){return f===46?(t.consume(f),i=0,u):f===62?(t.exit("autolinkProtocol").type="autolinkEmail",t.enter("autolinkMarker"),t.consume(f),t.exit("autolinkMarker"),t.exit("autolink"),e):h(f)}function h(f){if((f===45||ut(f))&&i++<63){const m=f===45?h:d;return t.consume(f),m}return n(f)}}const cr={partial:!0,tokenize:Ah};function Ah(t,e,n){return i;function i(s){return ge(s)?Te(t,r,"linePrefix")(s):r(s)}function r(s){return s===null||re(s)?e(s):n(s)}}const jc={continuation:{tokenize:Nh},exit:Lh,name:"blockQuote",tokenize:Dh};function Dh(t,e,n){const i=this;return r;function r(a){if(a===62){const o=i.containerState;return o.open||(t.enter("blockQuote",{_container:!0}),o.open=!0),t.enter("blockQuotePrefix"),t.enter("blockQuoteMarker"),t.consume(a),t.exit("blockQuoteMarker"),s}return n(a)}function s(a){return ge(a)?(t.enter("blockQuotePrefixWhitespace"),t.consume(a),t.exit("blockQuotePrefixWhitespace"),t.exit("blockQuotePrefix"),e):(t.exit("blockQuotePrefix"),e(a))}}function Nh(t,e,n){const i=this;return r;function r(a){return ge(a)?Te(t,s,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):s(a)}function s(a){return t.attempt(jc,e,n)(a)}}function Lh(t){t.exit("blockQuote")}const Uc={name:"characterEscape",tokenize:jh};function jh(t,e,n){return i;function i(s){return t.enter("characterEscape"),t.enter("escapeMarker"),t.consume(s),t.exit("escapeMarker"),r}function r(s){return Ch(s)?(t.enter("characterEscapeValue"),t.consume(s),t.exit("characterEscapeValue"),t.exit("characterEscape"),e):n(s)}}const Fc={name:"characterReference",tokenize:Uh};function Uh(t,e,n){const i=this;let r=0,s,a;return o;function o(d){return t.enter("characterReference"),t.enter("characterReferenceMarker"),t.consume(d),t.exit("characterReferenceMarker"),c}function c(d){return d===35?(t.enter("characterReferenceMarkerNumeric"),t.consume(d),t.exit("characterReferenceMarkerNumeric"),l):(t.enter("characterReferenceValue"),s=31,a=ut,u(d))}function l(d){return d===88||d===120?(t.enter("characterReferenceMarkerHexadecimal"),t.consume(d),t.exit("characterReferenceMarkerHexadecimal"),t.enter("characterReferenceValue"),s=6,a=kh,u):(t.enter("characterReferenceValue"),s=7,a=ss,u(d))}function u(d){if(d===59&&r){const h=t.exit("characterReferenceValue");return a===ut&&!zs(i.sliceSerialize(h))?n(d):(t.enter("characterReferenceMarker"),t.consume(d),t.exit("characterReferenceMarker"),t.exit("characterReference"),e)}return a(d)&&r++<s?(t.consume(d),u):n(d)}}const Vo={partial:!0,tokenize:Bh},qo={concrete:!0,name:"codeFenced",tokenize:Fh};function Fh(t,e,n){const i=this,r={partial:!0,tokenize:T};let s=0,a=0,o;return c;function c(C){return l(C)}function l(C){const O=i.events[i.events.length-1];return s=O&&O[1].type==="linePrefix"?O[2].sliceSerialize(O[1],!0).length:0,o=C,t.enter("codeFenced"),t.enter("codeFencedFence"),t.enter("codeFencedFenceSequence"),u(C)}function u(C){return C===o?(a++,t.consume(C),u):a<3?n(C):(t.exit("codeFencedFenceSequence"),ge(C)?Te(t,d,"whitespace")(C):d(C))}function d(C){return C===null||re(C)?(t.exit("codeFencedFence"),i.interrupt?e(C):t.check(Vo,g,S)(C)):(t.enter("codeFencedFenceInfo"),t.enter("chunkString",{contentType:"string"}),h(C))}function h(C){return C===null||re(C)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),d(C)):ge(C)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),Te(t,f,"whitespace")(C)):C===96&&C===o?n(C):(t.consume(C),h)}function f(C){return C===null||re(C)?d(C):(t.enter("codeFencedFenceMeta"),t.enter("chunkString",{contentType:"string"}),m(C))}function m(C){return C===null||re(C)?(t.exit("chunkString"),t.exit("codeFencedFenceMeta"),d(C)):C===96&&C===o?n(C):(t.consume(C),m)}function g(C){return t.attempt(r,S,w)(C)}function w(C){return t.enter("lineEnding"),t.consume(C),t.exit("lineEnding"),b}function b(C){return s>0&&ge(C)?Te(t,P,"linePrefix",s+1)(C):P(C)}function P(C){return C===null||re(C)?t.check(Vo,g,S)(C):(t.enter("codeFlowValue"),_(C))}function _(C){return C===null||re(C)?(t.exit("codeFlowValue"),P(C)):(t.consume(C),_)}function S(C){return t.exit("codeFenced"),e(C)}function T(C,O,L){let I=0;return A;function A(j){return C.enter("lineEnding"),C.consume(j),C.exit("lineEnding"),R}function R(j){return C.enter("codeFencedFence"),ge(j)?Te(C,N,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):N(j)}function N(j){return j===o?(C.enter("codeFencedFenceSequence"),Y(j)):L(j)}function Y(j){return j===o?(I++,C.consume(j),Y):I>=a?(C.exit("codeFencedFenceSequence"),ge(j)?Te(C,G,"whitespace")(j):G(j)):L(j)}function G(j){return j===null||re(j)?(C.exit("codeFencedFence"),O(j)):L(j)}}}function Bh(t,e,n){const i=this;return r;function r(a){return a===null?n(a):(t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),s)}function s(a){return i.parser.lazy[i.now().line]?n(a):e(a)}}const Tr={name:"codeIndented",tokenize:qh},Vh={partial:!0,tokenize:zh};function qh(t,e,n){const i=this;return r;function r(l){return t.enter("codeIndented"),Te(t,s,"linePrefix",5)(l)}function s(l){const u=i.events[i.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?a(l):n(l)}function a(l){return l===null?c(l):re(l)?t.attempt(Vh,a,c)(l):(t.enter("codeFlowValue"),o(l))}function o(l){return l===null||re(l)?(t.exit("codeFlowValue"),a(l)):(t.consume(l),o)}function c(l){return t.exit("codeIndented"),e(l)}}function zh(t,e,n){const i=this;return r;function r(a){return i.parser.lazy[i.now().line]?n(a):re(a)?(t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),r):Te(t,s,"linePrefix",5)(a)}function s(a){const o=i.events[i.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?e(a):re(a)?r(a):n(a)}}const Wh={name:"codeText",previous:Kh,resolve:Hh,tokenize:Gh};function Hh(t){let e=t.length-4,n=3,i,r;if((t[n][1].type==="lineEnding"||t[n][1].type==="space")&&(t[e][1].type==="lineEnding"||t[e][1].type==="space")){for(i=n;++i<e;)if(t[i][1].type==="codeTextData"){t[n][1].type="codeTextPadding",t[e][1].type="codeTextPadding",n+=2,e-=2;break}}for(i=n-1,e++;++i<=e;)r===void 0?i!==e&&t[i][1].type!=="lineEnding"&&(r=i):(i===e||t[i][1].type==="lineEnding")&&(t[r][1].type="codeTextData",i!==r+2&&(t[r][1].end=t[i-1][1].end,t.splice(r+2,i-r-2),e-=i-r-2,i=r+2),r=void 0);return t}function Kh(t){return t!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Gh(t,e,n){let i=0,r,s;return a;function a(d){return t.enter("codeText"),t.enter("codeTextSequence"),o(d)}function o(d){return d===96?(t.consume(d),i++,o):(t.exit("codeTextSequence"),c(d))}function c(d){return d===null?n(d):d===32?(t.enter("space"),t.consume(d),t.exit("space"),c):d===96?(s=t.enter("codeTextSequence"),r=0,u(d)):re(d)?(t.enter("lineEnding"),t.consume(d),t.exit("lineEnding"),c):(t.enter("codeTextData"),l(d))}function l(d){return d===null||d===32||d===96||re(d)?(t.exit("codeTextData"),c(d)):(t.consume(d),l)}function u(d){return d===96?(t.consume(d),r++,u):r===i?(t.exit("codeTextSequence"),t.exit("codeText"),e(d)):(s.type="codeTextData",l(d))}}class $h{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,n){const i=n??Number.POSITIVE_INFINITY;return i<this.left.length?this.left.slice(e,i):e>this.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(e,n,i){const r=n||0;this.setCursor(Math.trunc(e));const s=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return i&&ti(this.left,i),s.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),ti(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),ti(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e<this.left.length){const n=this.left.splice(e,Number.POSITIVE_INFINITY);ti(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);ti(this.left,n.reverse())}}}function ti(t,e){let n=0;if(e.length<1e4)t.push(...e);else for(;n<e.length;)t.push(...e.slice(n,n+1e4)),n+=1e4}function Bc(t){const e={};let n=-1,i,r,s,a,o,c,l;const u=new $h(t);for(;++n<u.length;){for(;n in e;)n=e[n];if(i=u.get(n),n&&i[1].type==="chunkFlow"&&u.get(n-1)[1].type==="listItemPrefix"&&(c=i[1]._tokenizer.events,s=0,s<c.length&&c[s][1].type==="lineEndingBlank"&&(s+=2),s<c.length&&c[s][1].type==="content"))for(;++s<c.length&&c[s][1].type!=="content";)c[s][1].type==="chunkText"&&(c[s][1]._isInFirstContentOfListItem=!0,s++);if(i[0]==="enter")i[1].contentType&&(Object.assign(e,Jh(u,n)),n=e[n],l=!0);else if(i[1]._container){for(s=n,r=void 0;s--;)if(a=u.get(s),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(r&&(u.get(r)[1].type="lineEndingBlank"),a[1].type="lineEnding",r=s);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;r&&(i[1].end={...u.get(r)[1].start},o=u.slice(r,n),o.unshift(i),u.splice(r,n-r+1,o))}}return At(t,0,Number.POSITIVE_INFINITY,u.slice(0)),!l}function Jh(t,e){const n=t.get(e)[1],i=t.get(e)[2];let r=e-1;const s=[];let a=n._tokenizer;a||(a=i.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const o=a.events,c=[],l={};let u,d,h=-1,f=n,m=0,g=0;const w=[g];for(;f;){for(;t.get(++r)[1]!==f;);s.push(r),f._tokenizer||(u=i.sliceStream(f),f.next||u.push(null),d&&a.defineSkip(f.start),f._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(u),f._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),d=f,f=f.next}for(f=n;++h<o.length;)o[h][0]==="exit"&&o[h-1][0]==="enter"&&o[h][1].type===o[h-1][1].type&&o[h][1].start.line!==o[h][1].end.line&&(g=h+1,w.push(g),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(a.events=[],f?(f._tokenizer=void 0,f.previous=void 0):w.pop(),h=w.length;h--;){const b=o.slice(w[h],w[h+1]),P=s.pop();c.push([P,P+b.length-1]),t.splice(P,2,b)}for(c.reverse(),h=-1;++h<c.length;)l[m+c[h][0]]=m+c[h][1],m+=c[h][1]-c[h][0]-1;return l}const Yh={resolve:Xh,tokenize:Zh},Qh={partial:!0,tokenize:ef};function Xh(t){return Bc(t),t}function Zh(t,e){let n;return i;function i(o){return t.enter("content"),n=t.enter("chunkContent",{contentType:"content"}),r(o)}function r(o){return o===null?s(o):re(o)?t.check(Qh,a,s)(o):(t.consume(o),r)}function s(o){return t.exit("chunkContent"),t.exit("content"),e(o)}function a(o){return t.consume(o),t.exit("chunkContent"),n.next=t.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,r}}function ef(t,e,n){const i=this;return r;function r(a){return t.exit("chunkContent"),t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),Te(t,s,"linePrefix")}function s(a){if(a===null||re(a))return n(a);const o=i.events[i.events.length-1];return!i.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?e(a):t.interrupt(i.parser.constructs.flow,n,e)(a)}}function Vc(t,e,n,i,r,s,a,o,c){const l=c||Number.POSITIVE_INFINITY;let u=0;return d;function d(b){return b===60?(t.enter(i),t.enter(r),t.enter(s),t.consume(b),t.exit(s),h):b===null||b===32||b===41||rs(b)?n(b):(t.enter(i),t.enter(a),t.enter(o),t.enter("chunkString",{contentType:"string"}),g(b))}function h(b){return b===62?(t.enter(s),t.consume(b),t.exit(s),t.exit(r),t.exit(i),e):(t.enter(o),t.enter("chunkString",{contentType:"string"}),f(b))}function f(b){return b===62?(t.exit("chunkString"),t.exit(o),h(b)):b===null||b===60||re(b)?n(b):(t.consume(b),b===92?m:f)}function m(b){return b===60||b===62||b===92?(t.consume(b),f):f(b)}function g(b){return!u&&(b===null||b===41||it(b))?(t.exit("chunkString"),t.exit(o),t.exit(a),t.exit(i),e(b)):u<l&&b===40?(t.consume(b),u++,g):b===41?(t.consume(b),u--,g):b===null||b===32||b===40||rs(b)?n(b):(t.consume(b),b===92?w:g)}function w(b){return b===40||b===41||b===92?(t.consume(b),g):g(b)}}function qc(t,e,n,i,r,s){const a=this;let o=0,c;return l;function l(f){return t.enter(i),t.enter(r),t.consume(f),t.exit(r),t.enter(s),u}function u(f){return o>999||f===null||f===91||f===93&&!c||f===94&&!o&&"_hiddenFootnoteSupport"in a.parser.constructs?n(f):f===93?(t.exit(s),t.enter(r),t.consume(f),t.exit(r),t.exit(i),e):re(f)?(t.enter("lineEnding"),t.consume(f),t.exit("lineEnding"),u):(t.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===null||f===91||f===93||re(f)||o++>999?(t.exit("chunkString"),u(f)):(t.consume(f),c||(c=!ge(f)),f===92?h:d)}function h(f){return f===91||f===92||f===93?(t.consume(f),o++,d):d(f)}}function zc(t,e,n,i,r,s){let a;return o;function o(h){return h===34||h===39||h===40?(t.enter(i),t.enter(r),t.consume(h),t.exit(r),a=h===40?41:h,c):n(h)}function c(h){return h===a?(t.enter(r),t.consume(h),t.exit(r),t.exit(i),e):(t.enter(s),l(h))}function l(h){return h===a?(t.exit(s),c(a)):h===null?n(h):re(h)?(t.enter("lineEnding"),t.consume(h),t.exit("lineEnding"),Te(t,l,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),u(h))}function u(h){return h===a||h===null||re(h)?(t.exit("chunkString"),l(h)):(t.consume(h),h===92?d:u)}function d(h){return h===a||h===92?(t.consume(h),u):u(h)}}function hi(t,e){let n;return i;function i(r){return re(r)?(t.enter("lineEnding"),t.consume(r),t.exit("lineEnding"),n=!0,i):ge(r)?Te(t,i,n?"linePrefix":"lineSuffix")(r):e(r)}}const tf={name:"definition",tokenize:rf},nf={partial:!0,tokenize:sf};function rf(t,e,n){const i=this;let r;return s;function s(f){return t.enter("definition"),a(f)}function a(f){return qc.call(i,t,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return r=jn(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),f===58?(t.enter("definitionMarker"),t.consume(f),t.exit("definitionMarker"),c):n(f)}function c(f){return it(f)?hi(t,l)(f):l(f)}function l(f){return Vc(t,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function u(f){return t.attempt(nf,d,d)(f)}function d(f){return ge(f)?Te(t,h,"whitespace")(f):h(f)}function h(f){return f===null||re(f)?(t.exit("definition"),i.parser.defined.push(r),e(f)):n(f)}}function sf(t,e,n){return i;function i(o){return it(o)?hi(t,r)(o):n(o)}function r(o){return zc(t,s,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function s(o){return ge(o)?Te(t,a,"whitespace")(o):a(o)}function a(o){return o===null||re(o)?e(o):n(o)}}const of={name:"hardBreakEscape",tokenize:af};function af(t,e,n){return i;function i(s){return t.enter("hardBreakEscape"),t.consume(s),r}function r(s){return re(s)?(t.exit("hardBreakEscape"),e(s)):n(s)}}const cf={name:"headingAtx",resolve:lf,tokenize:uf};function lf(t,e){let n=t.length-2,i=3,r,s;return t[i][1].type==="whitespace"&&(i+=2),n-2>i&&t[n][1].type==="whitespace"&&(n-=2),t[n][1].type==="atxHeadingSequence"&&(i===n-1||n-4>i&&t[n-2][1].type==="whitespace")&&(n-=i+1===n?2:4),n>i&&(r={type:"atxHeadingText",start:t[i][1].start,end:t[n][1].end},s={type:"chunkText",start:t[i][1].start,end:t[n][1].end,contentType:"text"},At(t,i,n-i+1,[["enter",r,e],["enter",s,e],["exit",s,e],["exit",r,e]])),t}function uf(t,e,n){let i=0;return r;function r(u){return t.enter("atxHeading"),s(u)}function s(u){return t.enter("atxHeadingSequence"),a(u)}function a(u){return u===35&&i++<6?(t.consume(u),a):u===null||it(u)?(t.exit("atxHeadingSequence"),o(u)):n(u)}function o(u){return u===35?(t.enter("atxHeadingSequence"),c(u)):u===null||re(u)?(t.exit("atxHeading"),e(u)):ge(u)?Te(t,o,"whitespace")(u):(t.enter("atxHeadingText"),l(u))}function c(u){return u===35?(t.consume(u),c):(t.exit("atxHeadingSequence"),o(u))}function l(u){return u===null||u===35||it(u)?(t.exit("atxHeadingText"),o(u)):(t.consume(u),l)}}const df=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],zo=["pre","script","style","textarea"],hf={concrete:!0,name:"htmlFlow",resolveTo:mf,tokenize:gf},ff={partial:!0,tokenize:yf},pf={partial:!0,tokenize:vf};function mf(t){let e=t.length;for(;e--&&!(t[e][0]==="enter"&&t[e][1].type==="htmlFlow"););return e>1&&t[e-2][1].type==="linePrefix"&&(t[e][1].start=t[e-2][1].start,t[e+1][1].start=t[e-2][1].start,t.splice(e-2,2)),t}function gf(t,e,n){const i=this;let r,s,a,o,c;return l;function l(y){return u(y)}function u(y){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(y),d}function d(y){return y===33?(t.consume(y),h):y===47?(t.consume(y),s=!0,g):y===63?(t.consume(y),r=3,i.interrupt?e:k):Mt(y)?(t.consume(y),a=String.fromCharCode(y),w):n(y)}function h(y){return y===45?(t.consume(y),r=2,f):y===91?(t.consume(y),r=5,o=0,m):Mt(y)?(t.consume(y),r=4,i.interrupt?e:k):n(y)}function f(y){return y===45?(t.consume(y),i.interrupt?e:k):n(y)}function m(y){const J="CDATA[";return y===J.charCodeAt(o++)?(t.consume(y),o===J.length?i.interrupt?e:N:m):n(y)}function g(y){return Mt(y)?(t.consume(y),a=String.fromCharCode(y),w):n(y)}function w(y){if(y===null||y===47||y===62||it(y)){const J=y===47,X=a.toLowerCase();return!J&&!s&&zo.includes(X)?(r=1,i.interrupt?e(y):N(y)):df.includes(a.toLowerCase())?(r=6,J?(t.consume(y),b):i.interrupt?e(y):N(y)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?n(y):s?P(y):_(y))}return y===45||ut(y)?(t.consume(y),a+=String.fromCharCode(y),w):n(y)}function b(y){return y===62?(t.consume(y),i.interrupt?e:N):n(y)}function P(y){return ge(y)?(t.consume(y),P):A(y)}function _(y){return y===47?(t.consume(y),A):y===58||y===95||Mt(y)?(t.consume(y),S):ge(y)?(t.consume(y),_):A(y)}function S(y){return y===45||y===46||y===58||y===95||ut(y)?(t.consume(y),S):T(y)}function T(y){return y===61?(t.consume(y),C):ge(y)?(t.consume(y),T):_(y)}function C(y){return y===null||y===60||y===61||y===62||y===96?n(y):y===34||y===39?(t.consume(y),c=y,O):ge(y)?(t.consume(y),C):L(y)}function O(y){return y===c?(t.consume(y),c=null,I):y===null||re(y)?n(y):(t.consume(y),O)}function L(y){return y===null||y===34||y===39||y===47||y===60||y===61||y===62||y===96||it(y)?T(y):(t.consume(y),L)}function I(y){return y===47||y===62||ge(y)?_(y):n(y)}function A(y){return y===62?(t.consume(y),R):n(y)}function R(y){return y===null||re(y)?N(y):ge(y)?(t.consume(y),R):n(y)}function N(y){return y===45&&r===2?(t.consume(y),$):y===60&&r===1?(t.consume(y),Q):y===62&&r===4?(t.consume(y),K):y===63&&r===3?(t.consume(y),k):y===93&&r===5?(t.consume(y),ne):re(y)&&(r===6||r===7)?(t.exit("htmlFlowData"),t.check(ff,Z,Y)(y)):y===null||re(y)?(t.exit("htmlFlowData"),Y(y)):(t.consume(y),N)}function Y(y){return t.check(pf,G,Z)(y)}function G(y){return t.enter("lineEnding"),t.consume(y),t.exit("lineEnding"),j}function j(y){return y===null||re(y)?Y(y):(t.enter("htmlFlowData"),N(y))}function $(y){return y===45?(t.consume(y),k):N(y)}function Q(y){return y===47?(t.consume(y),a="",ee):N(y)}function ee(y){if(y===62){const J=a.toLowerCase();return zo.includes(J)?(t.consume(y),K):N(y)}return Mt(y)&&a.length<8?(t.consume(y),a+=String.fromCharCode(y),ee):N(y)}function ne(y){return y===93?(t.consume(y),k):N(y)}function k(y){return y===62?(t.consume(y),K):y===45&&r===2?(t.consume(y),k):N(y)}function K(y){return y===null||re(y)?(t.exit("htmlFlowData"),Z(y)):(t.consume(y),K)}function Z(y){return t.exit("htmlFlow"),e(y)}}function vf(t,e,n){const i=this;return r;function r(a){return re(a)?(t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),s):n(a)}function s(a){return i.parser.lazy[i.now().line]?n(a):e(a)}}function yf(t,e,n){return i;function i(r){return t.enter("lineEnding"),t.consume(r),t.exit("lineEnding"),t.attempt(cr,e,n)}}const bf={name:"htmlText",tokenize:kf};function kf(t,e,n){const i=this;let r,s,a;return o;function o(k){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(k),c}function c(k){return k===33?(t.consume(k),l):k===47?(t.consume(k),T):k===63?(t.consume(k),_):Mt(k)?(t.consume(k),L):n(k)}function l(k){return k===45?(t.consume(k),u):k===91?(t.consume(k),s=0,m):Mt(k)?(t.consume(k),P):n(k)}function u(k){return k===45?(t.consume(k),f):n(k)}function d(k){return k===null?n(k):k===45?(t.consume(k),h):re(k)?(a=d,Q(k)):(t.consume(k),d)}function h(k){return k===45?(t.consume(k),f):d(k)}function f(k){return k===62?$(k):k===45?h(k):d(k)}function m(k){const K="CDATA[";return k===K.charCodeAt(s++)?(t.consume(k),s===K.length?g:m):n(k)}function g(k){return k===null?n(k):k===93?(t.consume(k),w):re(k)?(a=g,Q(k)):(t.consume(k),g)}function w(k){return k===93?(t.consume(k),b):g(k)}function b(k){return k===62?$(k):k===93?(t.consume(k),b):g(k)}function P(k){return k===null||k===62?$(k):re(k)?(a=P,Q(k)):(t.consume(k),P)}function _(k){return k===null?n(k):k===63?(t.consume(k),S):re(k)?(a=_,Q(k)):(t.consume(k),_)}function S(k){return k===62?$(k):_(k)}function T(k){return Mt(k)?(t.consume(k),C):n(k)}function C(k){return k===45||ut(k)?(t.consume(k),C):O(k)}function O(k){return re(k)?(a=O,Q(k)):ge(k)?(t.consume(k),O):$(k)}function L(k){return k===45||ut(k)?(t.consume(k),L):k===47||k===62||it(k)?I(k):n(k)}function I(k){return k===47?(t.consume(k),$):k===58||k===95||Mt(k)?(t.consume(k),A):re(k)?(a=I,Q(k)):ge(k)?(t.consume(k),I):$(k)}function A(k){return k===45||k===46||k===58||k===95||ut(k)?(t.consume(k),A):R(k)}function R(k){return k===61?(t.consume(k),N):re(k)?(a=R,Q(k)):ge(k)?(t.consume(k),R):I(k)}function N(k){return k===null||k===60||k===61||k===62||k===96?n(k):k===34||k===39?(t.consume(k),r=k,Y):re(k)?(a=N,Q(k)):ge(k)?(t.consume(k),N):(t.consume(k),G)}function Y(k){return k===r?(t.consume(k),r=void 0,j):k===null?n(k):re(k)?(a=Y,Q(k)):(t.consume(k),Y)}function G(k){return k===null||k===34||k===39||k===60||k===61||k===96?n(k):k===47||k===62||it(k)?I(k):(t.consume(k),G)}function j(k){return k===47||k===62||it(k)?I(k):n(k)}function $(k){return k===62?(t.consume(k),t.exit("htmlTextData"),t.exit("htmlText"),e):n(k)}function Q(k){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(k),t.exit("lineEnding"),ee}function ee(k){return ge(k)?Te(t,ne,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):ne(k)}function ne(k){return t.enter("htmlTextData"),a(k)}}const Hs={name:"labelEnd",resolveAll:wf,resolveTo:xf,tokenize:_f},Cf={tokenize:Ef},Sf={tokenize:Pf},Tf={tokenize:Rf};function wf(t){let e=-1;const n=[];for(;++e<t.length;){const i=t[e][1];if(n.push(t[e]),i.type==="labelImage"||i.type==="labelLink"||i.type==="labelEnd"){const r=i.type==="labelImage"?4:2;i.type="data",e+=r}}return t.length!==n.length&&At(t,0,t.length,n),t}function xf(t,e){let n=t.length,i=0,r,s,a,o;for(;n--;)if(r=t[n][1],s){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;t[n][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(a){if(t[n][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(s=n,r.type!=="labelLink")){i=2;break}}else r.type==="labelEnd"&&(a=n);const c={type:t[s][1].type==="labelLink"?"link":"image",start:{...t[s][1].start},end:{...t[t.length-1][1].end}},l={type:"label",start:{...t[s][1].start},end:{...t[a][1].end}},u={type:"labelText",start:{...t[s+i+2][1].end},end:{...t[a-2][1].start}};return o=[["enter",c,e],["enter",l,e]],o=gt(o,t.slice(s+1,s+i+3)),o=gt(o,[["enter",u,e]]),o=gt(o,Ws(e.parser.constructs.insideSpan.null,t.slice(s+i+4,a-3),e)),o=gt(o,[["exit",u,e],t[a-2],t[a-1],["exit",l,e]]),o=gt(o,t.slice(a+1)),o=gt(o,[["exit",c,e]]),At(t,s,t.length,o),t}function _f(t,e,n){const i=this;let r=i.events.length,s,a;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){s=i.events[r][1];break}return o;function o(h){return s?s._inactive?d(h):(a=i.parser.defined.includes(jn(i.sliceSerialize({start:s.end,end:i.now()}))),t.enter("labelEnd"),t.enter("labelMarker"),t.consume(h),t.exit("labelMarker"),t.exit("labelEnd"),c):n(h)}function c(h){return h===40?t.attempt(Cf,u,a?u:d)(h):h===91?t.attempt(Sf,u,a?l:d)(h):a?u(h):d(h)}function l(h){return t.attempt(Tf,u,d)(h)}function u(h){return e(h)}function d(h){return s._balanced=!0,n(h)}}function Ef(t,e,n){return i;function i(d){return t.enter("resource"),t.enter("resourceMarker"),t.consume(d),t.exit("resourceMarker"),r}function r(d){return it(d)?hi(t,s)(d):s(d)}function s(d){return d===41?u(d):Vc(t,a,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function a(d){return it(d)?hi(t,c)(d):u(d)}function o(d){return n(d)}function c(d){return d===34||d===39||d===40?zc(t,l,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):u(d)}function l(d){return it(d)?hi(t,u)(d):u(d)}function u(d){return d===41?(t.enter("resourceMarker"),t.consume(d),t.exit("resourceMarker"),t.exit("resource"),e):n(d)}}function Pf(t,e,n){const i=this;return r;function r(o){return qc.call(i,t,s,a,"reference","referenceMarker","referenceString")(o)}function s(o){return i.parser.defined.includes(jn(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?e(o):n(o)}function a(o){return n(o)}}function Rf(t,e,n){return i;function i(s){return t.enter("reference"),t.enter("referenceMarker"),t.consume(s),t.exit("referenceMarker"),r}function r(s){return s===93?(t.enter("referenceMarker"),t.consume(s),t.exit("referenceMarker"),t.exit("reference"),e):n(s)}}const If={name:"labelStartImage",resolveAll:Hs.resolveAll,tokenize:Mf};function Mf(t,e,n){const i=this;return r;function r(o){return t.enter("labelImage"),t.enter("labelImageMarker"),t.consume(o),t.exit("labelImageMarker"),s}function s(o){return o===91?(t.enter("labelMarker"),t.consume(o),t.exit("labelMarker"),t.exit("labelImage"),a):n(o)}function a(o){return o===94&&"_hiddenFootnoteSupport"in i.parser.constructs?n(o):e(o)}}const Of={name:"labelStartLink",resolveAll:Hs.resolveAll,tokenize:Af};function Af(t,e,n){const i=this;return r;function r(a){return t.enter("labelLink"),t.enter("labelMarker"),t.consume(a),t.exit("labelMarker"),t.exit("labelLink"),s}function s(a){return a===94&&"_hiddenFootnoteSupport"in i.parser.constructs?n(a):e(a)}}const wr={name:"lineEnding",tokenize:Df};function Df(t,e){return n;function n(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),Te(t,e,"linePrefix")}}const Ni={name:"thematicBreak",tokenize:Nf};function Nf(t,e,n){let i=0,r;return s;function s(l){return t.enter("thematicBreak"),a(l)}function a(l){return r=l,o(l)}function o(l){return l===r?(t.enter("thematicBreakSequence"),c(l)):i>=3&&(l===null||re(l))?(t.exit("thematicBreak"),e(l)):n(l)}function c(l){return l===r?(t.consume(l),i++,c):(t.exit("thematicBreakSequence"),ge(l)?Te(t,o,"whitespace")(l):o(l))}}const Ze={continuation:{tokenize:Ff},exit:Vf,name:"list",tokenize:Uf},Lf={partial:!0,tokenize:qf},jf={partial:!0,tokenize:Bf};function Uf(t,e,n){const i=this,r=i.events[i.events.length-1];let s=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,a=0;return o;function o(f){const m=i.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!i.containerState.marker||f===i.containerState.marker:ss(f)){if(i.containerState.type||(i.containerState.type=m,t.enter(m,{_container:!0})),m==="listUnordered")return t.enter("listItemPrefix"),f===42||f===45?t.check(Ni,n,l)(f):l(f);if(!i.interrupt||f===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),c(f)}return n(f)}function c(f){return ss(f)&&++a<10?(t.consume(f),c):(!i.interrupt||a<2)&&(i.containerState.marker?f===i.containerState.marker:f===41||f===46)?(t.exit("listItemValue"),l(f)):n(f)}function l(f){return t.enter("listItemMarker"),t.consume(f),t.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||f,t.check(cr,i.interrupt?n:u,t.attempt(Lf,h,d))}function u(f){return i.containerState.initialBlankLine=!0,s++,h(f)}function d(f){return ge(f)?(t.enter("listItemPrefixWhitespace"),t.consume(f),t.exit("listItemPrefixWhitespace"),h):n(f)}function h(f){return i.containerState.size=s+i.sliceSerialize(t.exit("listItemPrefix"),!0).length,e(f)}}function Ff(t,e,n){const i=this;return i.containerState._closeFlow=void 0,t.check(cr,r,s);function r(o){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Te(t,e,"listItemIndent",i.containerState.size+1)(o)}function s(o){return i.containerState.furtherBlankLines||!ge(o)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,a(o)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,t.attempt(jf,e,a)(o))}function a(o){return i.containerState._closeFlow=!0,i.interrupt=void 0,Te(t,t.attempt(Ze,e,n),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function Bf(t,e,n){const i=this;return Te(t,r,"listItemIndent",i.containerState.size+1);function r(s){const a=i.events[i.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===i.containerState.size?e(s):n(s)}}function Vf(t){t.exit(this.containerState.type)}function qf(t,e,n){const i=this;return Te(t,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(s){const a=i.events[i.events.length-1];return!ge(s)&&a&&a[1].type==="listItemPrefixWhitespace"?e(s):n(s)}}const Wo={name:"setextUnderline",resolveTo:zf,tokenize:Wf};function zf(t,e){let n=t.length,i,r,s;for(;n--;)if(t[n][0]==="enter"){if(t[n][1].type==="content"){i=n;break}t[n][1].type==="paragraph"&&(r=n)}else t[n][1].type==="content"&&t.splice(n,1),!s&&t[n][1].type==="definition"&&(s=n);const a={type:"setextHeading",start:{...t[i][1].start},end:{...t[t.length-1][1].end}};return t[r][1].type="setextHeadingText",s?(t.splice(r,0,["enter",a,e]),t.splice(s+1,0,["exit",t[i][1],e]),t[i][1].end={...t[s][1].end}):t[i][1]=a,t.push(["exit",a,e]),t}function Wf(t,e,n){const i=this;let r;return s;function s(l){let u=i.events.length,d;for(;u--;)if(i.events[u][1].type!=="lineEnding"&&i.events[u][1].type!=="linePrefix"&&i.events[u][1].type!=="content"){d=i.events[u][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||d)?(t.enter("setextHeadingLine"),r=l,a(l)):n(l)}function a(l){return t.enter("setextHeadingLineSequence"),o(l)}function o(l){return l===r?(t.consume(l),o):(t.exit("setextHeadingLineSequence"),ge(l)?Te(t,c,"lineSuffix")(l):c(l))}function c(l){return l===null||re(l)?(t.exit("setextHeadingLine"),e(l)):n(l)}}const Hf={tokenize:Kf};function Kf(t){const e=this,n=t.attempt(cr,i,t.attempt(this.parser.constructs.flowInitial,r,Te(t,t.attempt(this.parser.constructs.flow,r,t.attempt(Yh,r)),"linePrefix")));return n;function i(s){if(s===null){t.consume(s);return}return t.enter("lineEndingBlank"),t.consume(s),t.exit("lineEndingBlank"),e.currentConstruct=void 0,n}function r(s){if(s===null){t.consume(s);return}return t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),e.currentConstruct=void 0,n}}const Gf={resolveAll:Hc()},$f=Wc("string"),Jf=Wc("text");function Wc(t){return{resolveAll:Hc(t==="text"?Yf:void 0),tokenize:e};function e(n){const i=this,r=this.parser.constructs[t],s=n.attempt(r,a,o);return a;function a(u){return l(u)?s(u):o(u)}function o(u){if(u===null){n.consume(u);return}return n.enter("data"),n.consume(u),c}function c(u){return l(u)?(n.exit("data"),s(u)):(n.consume(u),c)}function l(u){if(u===null)return!0;const d=r[u];let h=-1;if(d)for(;++h<d.length;){const f=d[h];if(!f.previous||f.previous.call(i,i.previous))return!0}return!1}}}function Hc(t){return e;function e(n,i){let r=-1,s;for(;++r<=n.length;)s===void 0?n[r]&&n[r][1].type==="data"&&(s=r,r++):(!n[r]||n[r][1].type!=="data")&&(r!==s+2&&(n[s][1].end=n[r-1][1].end,n.splice(s+2,r-s-2),r=s+2),s=void 0);return t?t(n,i):n}}function Yf(t,e){let n=0;for(;++n<=t.length;)if((n===t.length||t[n][1].type==="lineEnding")&&t[n-1][1].type==="data"){const i=t[n-1][1],r=e.sliceStream(i);let s=r.length,a=-1,o=0,c;for(;s--;){const l=r[s];if(typeof l=="string"){for(a=l.length;l.charCodeAt(a-1)===32;)o++,a--;if(a)break;a=-1}else if(l===-2)c=!0,o++;else if(l!==-1){s++;break}}if(e._contentTypeTextTrailing&&n===t.length&&(o=0),o){const l={type:n===t.length||c||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:s?a:i.start._bufferIndex+a,_index:i.start._index+s,line:i.end.line,column:i.end.column-o,offset:i.end.offset-o},end:{...i.end}};i.end={...l.start},i.start.offset===i.end.offset?Object.assign(i,l):(t.splice(n,0,["enter",l,e],["exit",l,e]),n+=2)}n++}return t}const Qf={42:Ze,43:Ze,45:Ze,48:Ze,49:Ze,50:Ze,51:Ze,52:Ze,53:Ze,54:Ze,55:Ze,56:Ze,57:Ze,62:jc},Xf={91:tf},Zf={[-2]:Tr,[-1]:Tr,32:Tr},ep={35:cf,42:Ni,45:[Wo,Ni],60:hf,61:Wo,95:Ni,96:qo,126:qo},tp={38:Fc,92:Uc},np={[-5]:wr,[-4]:wr,[-3]:wr,33:If,38:Fc,42:os,60:[Mh,bf],91:Of,92:[of,Uc],93:Hs,95:os,96:Wh},ip={null:[os,Gf]},rp={null:[42,95]},sp={null:[]},op=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:rp,contentInitial:Xf,disable:sp,document:Qf,flow:ep,flowInitial:Zf,insideSpan:ip,string:tp,text:np},Symbol.toStringTag,{value:"Module"}));function ap(t,e,n){let i={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const r={},s=[];let a=[],o=[];const c={attempt:O(T),check:O(C),consume:P,enter:_,exit:S,interrupt:O(C,{interrupt:!0})},l={code:null,containerState:{},defineSkip:g,events:[],now:m,parser:t,previous:null,sliceSerialize:h,sliceStream:f,write:d};let u=e.tokenize.call(l,c);return e.resolveAll&&s.push(e),l;function d(R){return a=gt(a,R),w(),a[a.length-1]!==null?[]:(L(e,0),l.events=Ws(s,l.events,l),l.events)}function h(R,N){return lp(f(R),N)}function f(R){return cp(a,R)}function m(){const{_bufferIndex:R,_index:N,line:Y,column:G,offset:j}=i;return{_bufferIndex:R,_index:N,line:Y,column:G,offset:j}}function g(R){r[R.line]=R.column,A()}function w(){let R;for(;i._index<a.length;){const N=a[i._index];if(typeof N=="string")for(R=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===R&&i._bufferIndex<N.length;)b(N.charCodeAt(i._bufferIndex));else b(N)}}function b(R){u=u(R)}function P(R){re(R)?(i.line++,i.column=1,i.offset+=R===-3?2:1,A()):R!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===a[i._index].length&&(i._bufferIndex=-1,i._index++)),l.previous=R}function _(R,N){const Y=N||{};return Y.type=R,Y.start=m(),l.events.push(["enter",Y,l]),o.push(Y),Y}function S(R){const N=o.pop();return N.end=m(),l.events.push(["exit",N,l]),N}function T(R,N){L(R,N.from)}function C(R,N){N.restore()}function O(R,N){return Y;function Y(G,j,$){let Q,ee,ne,k;return Array.isArray(G)?Z(G):"tokenize"in G?Z([G]):K(G);function K(W){return se;function se(De){const we=De!==null&&W[De],Ne=De!==null&&W.null,Ke=[...Array.isArray(we)?we:we?[we]:[],...Array.isArray(Ne)?Ne:Ne?[Ne]:[]];return Z(Ke)(De)}}function Z(W){return Q=W,ee=0,W.length===0?$:y(W[ee])}function y(W){return se;function se(De){return k=I(),ne=W,W.partial||(l.currentConstruct=W),W.name&&l.parser.constructs.disable.null.includes(W.name)?X():W.tokenize.call(N?Object.assign(Object.create(l),N):l,c,J,X)(De)}}function J(W){return R(ne,k),j}function X(W){return k.restore(),++ee<Q.length?y(Q[ee]):$}}}function L(R,N){R.resolveAll&&!s.includes(R)&&s.push(R),R.resolve&&At(l.events,N,l.events.length-N,R.resolve(l.events.slice(N),l)),R.resolveTo&&(l.events=R.resolveTo(l.events,l))}function I(){const R=m(),N=l.previous,Y=l.currentConstruct,G=l.events.length,j=Array.from(o);return{from:G,restore:$};function $(){i=R,l.previous=N,l.currentConstruct=Y,l.events.length=G,o=j,A()}}function A(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function cp(t,e){const n=e.start._index,i=e.start._bufferIndex,r=e.end._index,s=e.end._bufferIndex;let a;if(n===r)a=[t[n].slice(i,s)];else{if(a=t.slice(n,r),i>-1){const o=a[0];typeof o=="string"?a[0]=o.slice(i):a.shift()}s>0&&a.push(t[r].slice(0,s))}return a}function lp(t,e){let n=-1;const i=[];let r;for(;++n<t.length;){const s=t[n];let a;if(typeof s=="string")a=s;else switch(s){case-5:{a="\r";break}case-4:{a=`
6
+ `;break}case-3:{a=`\r
7
+ `;break}case-2:{a=e?" ":" ";break}case-1:{if(!e&&r)continue;a=" ";break}default:a=String.fromCharCode(s)}r=s===-2,i.push(a)}return i.join("")}function up(t){const i={constructs:gh([op,...(t||{}).extensions||[]]),content:r(wh),defined:[],document:r(_h),flow:r(Hf),lazy:{},string:r($f),text:r(Jf)};return i;function r(s){return a;function a(o){return ap(i,s,o)}}}function dp(t){for(;!Bc(t););return t}const Ho=/[\0\t\n\r]/g;function hp(){let t=1,e="",n=!0,i;return r;function r(s,a,o){const c=[];let l,u,d,h,f;for(s=e+(typeof s=="string"?s.toString():new TextDecoder(a||void 0).decode(s)),d=0,e="",n&&(s.charCodeAt(0)===65279&&d++,n=void 0);d<s.length;){if(Ho.lastIndex=d,l=Ho.exec(s),h=l&&l.index!==void 0?l.index:s.length,f=s.charCodeAt(h),!l){e=s.slice(d);break}if(f===10&&d===h&&i)c.push(-3),i=void 0;else switch(i&&(c.push(-5),i=void 0),d<h&&(c.push(s.slice(d,h)),t+=h-d),f){case 0:{c.push(65533),t++;break}case 9:{for(u=Math.ceil(t/4)*4,c.push(-2);t++<u;)c.push(-1);break}case 10:{c.push(-4),t=1;break}default:i=!0,t=1}d=h+1}return o&&(i&&c.push(-5),e&&c.push(e),c.push(null)),c}}const fp=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function pp(t){return t.replace(fp,mp)}function mp(t,e,n){if(e)return e;if(n.charCodeAt(0)===35){const r=n.charCodeAt(1),s=r===120||r===88;return Lc(n.slice(s?2:1),s?16:10)}return zs(n)||t}const Kc={}.hasOwnProperty;function gp(t,e,n){return typeof e!="string"&&(n=e,e=void 0),vp(n)(dp(up(n).document().write(hp()(t,e,!0))))}function vp(t){const e={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:s(Et),autolinkProtocol:I,autolinkEmail:I,atxHeading:s(ot),blockQuote:s(Ne),characterEscape:I,characterReference:I,codeFenced:s(Ke),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:s(Ke,a),codeText:s($t,a),codeTextData:I,data:I,codeFlowValue:I,definition:s(gn),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:s(yt),hardBreakEscape:s(ht),hardBreakTrailing:s(ht),htmlFlow:s(Ut,a),htmlFlowData:I,htmlText:s(Ut,a),htmlTextData:I,image:s(Jt),label:a,link:s(Et),listItem:s(Bt),listItemValue:h,listOrdered:s(Ft,d),listUnordered:s(Ft),paragraph:s(Pn),reference:y,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:s(ot),strong:s(Xe),thematicBreak:s(vn)},exit:{atxHeading:c(),atxHeadingSequence:T,autolink:c(),autolinkEmail:we,autolinkProtocol:De,blockQuote:c(),characterEscapeValue:A,characterReferenceMarkerHexadecimal:X,characterReferenceMarkerNumeric:X,characterReferenceValue:W,characterReference:se,codeFenced:c(w),codeFencedFence:g,codeFencedFenceInfo:f,codeFencedFenceMeta:m,codeFlowValue:A,codeIndented:c(b),codeText:c(j),codeTextData:A,data:A,definition:c(),definitionDestinationString:S,definitionLabelString:P,definitionTitleString:_,emphasis:c(),hardBreakEscape:c(N),hardBreakTrailing:c(N),htmlFlow:c(Y),htmlFlowData:A,htmlText:c(G),htmlTextData:A,image:c(Q),label:ne,labelText:ee,lineEnding:R,link:c($),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:J,resourceDestinationString:k,resourceTitleString:K,resource:Z,setextHeading:c(L),setextHeadingLineSequence:O,setextHeadingText:C,strong:c(),thematicBreak:c()}};Gc(e,(t||{}).mdastExtensions||[]);const n={};return i;function i(E){let F={type:"root",children:[]};const te={stack:[F],tokenStack:[],config:e,enter:o,exit:l,buffer:a,resume:u,data:n},oe=[];let le=-1;for(;++le<E.length;)if(E[le][1].type==="listOrdered"||E[le][1].type==="listUnordered")if(E[le][0]==="enter")oe.push(le);else{const qe=oe.pop();le=r(E,qe,le)}for(le=-1;++le<E.length;){const qe=e[E[le][0]];Kc.call(qe,E[le][1].type)&&qe[E[le][1].type].call(Object.assign({sliceSerialize:E[le][2].sliceSerialize},te),E[le][1])}if(te.tokenStack.length>0){const qe=te.tokenStack[te.tokenStack.length-1];(qe[1]||Ko).call(te,void 0,qe[0])}for(F.position={start:Qt(E.length>0?E[0][1].start:{line:1,column:1,offset:0}),end:Qt(E.length>0?E[E.length-2][1].end:{line:1,column:1,offset:0})},le=-1;++le<e.transforms.length;)F=e.transforms[le](F)||F;return F}function r(E,F,te){let oe=F-1,le=-1,qe=!1,ct,Ge,yn,bn;for(;++oe<=te;){const Me=E[oe];switch(Me[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Me[0]==="enter"?le++:le--,bn=void 0;break}case"lineEndingBlank":{Me[0]==="enter"&&(ct&&!bn&&!le&&!yn&&(yn=oe),bn=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:bn=void 0}if(!le&&Me[0]==="enter"&&Me[1].type==="listItemPrefix"||le===-1&&Me[0]==="exit"&&(Me[1].type==="listUnordered"||Me[1].type==="listOrdered")){if(ct){let Yt=oe;for(Ge=void 0;Yt--;){const be=E[Yt];if(be[1].type==="lineEnding"||be[1].type==="lineEndingBlank"){if(be[0]==="exit")continue;Ge&&(E[Ge][1].type="lineEndingBlank",qe=!0),be[1].type="lineEnding",Ge=Yt}else if(!(be[1].type==="linePrefix"||be[1].type==="blockQuotePrefix"||be[1].type==="blockQuotePrefixWhitespace"||be[1].type==="blockQuoteMarker"||be[1].type==="listItemIndent"))break}yn&&(!Ge||yn<Ge)&&(ct._spread=!0),ct.end=Object.assign({},Ge?E[Ge][1].start:Me[1].end),E.splice(Ge||oe,0,["exit",ct,Me[2]]),oe++,te++}if(Me[1].type==="listItemPrefix"){const Yt={type:"listItem",_spread:!1,start:Object.assign({},Me[1].start),end:void 0};ct=Yt,E.splice(oe,0,["enter",Yt,Me[2]]),oe++,te++,yn=void 0,bn=!0}}}return E[F][1]._spread=qe,te}function s(E,F){return te;function te(oe){o.call(this,E(oe),oe),F&&F.call(this,oe)}}function a(){this.stack.push({type:"fragment",children:[]})}function o(E,F,te){this.stack[this.stack.length-1].children.push(E),this.stack.push(E),this.tokenStack.push([F,te||void 0]),E.position={start:Qt(F.start),end:void 0}}function c(E){return F;function F(te){E&&E.call(this,te),l.call(this,te)}}function l(E,F){const te=this.stack.pop(),oe=this.tokenStack.pop();if(oe)oe[0].type!==E.type&&(F?F.call(this,E,oe[0]):(oe[1]||Ko).call(this,E,oe[0]));else throw new Error("Cannot close `"+E.type+"` ("+di({start:E.start,end:E.end})+"): it’s not open");te.position.end=Qt(E.end)}function u(){return ph(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function h(E){if(this.data.expectingFirstListItemValue){const F=this.stack[this.stack.length-2];F.start=Number.parseInt(this.sliceSerialize(E),10),this.data.expectingFirstListItemValue=void 0}}function f(){const E=this.resume(),F=this.stack[this.stack.length-1];F.lang=E}function m(){const E=this.resume(),F=this.stack[this.stack.length-1];F.meta=E}function g(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function w(){const E=this.resume(),F=this.stack[this.stack.length-1];F.value=E.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const E=this.resume(),F=this.stack[this.stack.length-1];F.value=E.replace(/(\r?\n|\r)$/g,"")}function P(E){const F=this.resume(),te=this.stack[this.stack.length-1];te.label=F,te.identifier=jn(this.sliceSerialize(E)).toLowerCase()}function _(){const E=this.resume(),F=this.stack[this.stack.length-1];F.title=E}function S(){const E=this.resume(),F=this.stack[this.stack.length-1];F.url=E}function T(E){const F=this.stack[this.stack.length-1];if(!F.depth){const te=this.sliceSerialize(E).length;F.depth=te}}function C(){this.data.setextHeadingSlurpLineEnding=!0}function O(E){const F=this.stack[this.stack.length-1];F.depth=this.sliceSerialize(E).codePointAt(0)===61?1:2}function L(){this.data.setextHeadingSlurpLineEnding=void 0}function I(E){const te=this.stack[this.stack.length-1].children;let oe=te[te.length-1];(!oe||oe.type!=="text")&&(oe=at(),oe.position={start:Qt(E.start),end:void 0},te.push(oe)),this.stack.push(oe)}function A(E){const F=this.stack.pop();F.value+=this.sliceSerialize(E),F.position.end=Qt(E.end)}function R(E){const F=this.stack[this.stack.length-1];if(this.data.atHardBreak){const te=F.children[F.children.length-1];te.position.end=Qt(E.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&e.canContainEols.includes(F.type)&&(I.call(this,E),A.call(this,E))}function N(){this.data.atHardBreak=!0}function Y(){const E=this.resume(),F=this.stack[this.stack.length-1];F.value=E}function G(){const E=this.resume(),F=this.stack[this.stack.length-1];F.value=E}function j(){const E=this.resume(),F=this.stack[this.stack.length-1];F.value=E}function $(){const E=this.stack[this.stack.length-1];if(this.data.inReference){const F=this.data.referenceType||"shortcut";E.type+="Reference",E.referenceType=F,delete E.url,delete E.title}else delete E.identifier,delete E.label;this.data.referenceType=void 0}function Q(){const E=this.stack[this.stack.length-1];if(this.data.inReference){const F=this.data.referenceType||"shortcut";E.type+="Reference",E.referenceType=F,delete E.url,delete E.title}else delete E.identifier,delete E.label;this.data.referenceType=void 0}function ee(E){const F=this.sliceSerialize(E),te=this.stack[this.stack.length-2];te.label=pp(F),te.identifier=jn(F).toLowerCase()}function ne(){const E=this.stack[this.stack.length-1],F=this.resume(),te=this.stack[this.stack.length-1];if(this.data.inReference=!0,te.type==="link"){const oe=E.children;te.children=oe}else te.alt=F}function k(){const E=this.resume(),F=this.stack[this.stack.length-1];F.url=E}function K(){const E=this.resume(),F=this.stack[this.stack.length-1];F.title=E}function Z(){this.data.inReference=void 0}function y(){this.data.referenceType="collapsed"}function J(E){const F=this.resume(),te=this.stack[this.stack.length-1];te.label=F,te.identifier=jn(this.sliceSerialize(E)).toLowerCase(),this.data.referenceType="full"}function X(E){this.data.characterReferenceType=E.type}function W(E){const F=this.sliceSerialize(E),te=this.data.characterReferenceType;let oe;te?(oe=Lc(F,te==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):oe=zs(F);const le=this.stack[this.stack.length-1];le.value+=oe}function se(E){const F=this.stack.pop();F.position.end=Qt(E.end)}function De(E){A.call(this,E);const F=this.stack[this.stack.length-1];F.url=this.sliceSerialize(E)}function we(E){A.call(this,E);const F=this.stack[this.stack.length-1];F.url="mailto:"+this.sliceSerialize(E)}function Ne(){return{type:"blockquote",children:[]}}function Ke(){return{type:"code",lang:null,meta:null,value:""}}function $t(){return{type:"inlineCode",value:""}}function gn(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function yt(){return{type:"emphasis",children:[]}}function ot(){return{type:"heading",depth:0,children:[]}}function ht(){return{type:"break"}}function Ut(){return{type:"html",value:""}}function Jt(){return{type:"image",title:null,url:"",alt:null}}function Et(){return{type:"link",title:null,url:"",children:[]}}function Ft(E){return{type:"list",ordered:E.type==="listOrdered",start:null,spread:E._spread,children:[]}}function Bt(E){return{type:"listItem",spread:E._spread,checked:null,children:[]}}function Pn(){return{type:"paragraph",children:[]}}function Xe(){return{type:"strong",children:[]}}function at(){return{type:"text",value:""}}function vn(){return{type:"thematicBreak"}}}function Qt(t){return{line:t.line,column:t.column,offset:t.offset}}function Gc(t,e){let n=-1;for(;++n<e.length;){const i=e[n];Array.isArray(i)?Gc(t,i):yp(t,i)}}function yp(t,e){let n;for(n in e)if(Kc.call(e,n))switch(n){case"canContainEols":{const i=e[n];i&&t[n].push(...i);break}case"transforms":{const i=e[n];i&&t[n].push(...i);break}case"enter":case"exit":{const i=e[n];i&&Object.assign(t[n],i);break}}}function Ko(t,e){throw t?new Error("Cannot close `"+t.type+"` ("+di({start:t.start,end:t.end})+"): a different token (`"+e.type+"`, "+di({start:e.start,end:e.end})+") is open"):new Error("Cannot close document, a token (`"+e.type+"`, "+di({start:e.start,end:e.end})+") is still open")}function bp(t){const e=this;e.parser=n;function n(i){return gp(i,{...e.data("settings"),...t,extensions:e.data("micromarkExtensions")||[],mdastExtensions:e.data("fromMarkdownExtensions")||[]})}}function kp(t,e){const n={type:"element",tagName:"blockquote",properties:{},children:t.wrap(t.all(e),!0)};return t.patch(e,n),t.applyData(e,n)}function Cp(t,e){const n={type:"element",tagName:"br",properties:{},children:[]};return t.patch(e,n),[t.applyData(e,n),{type:"text",value:`
8
+ `}]}function Sp(t,e){const n=e.value?e.value+`
9
+ `:"",i={},r=e.lang?e.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let s={type:"element",tagName:"code",properties:i,children:[{type:"text",value:n}]};return e.meta&&(s.data={meta:e.meta}),t.patch(e,s),s=t.applyData(e,s),s={type:"element",tagName:"pre",properties:{},children:[s]},t.patch(e,s),s}function Tp(t,e){const n={type:"element",tagName:"del",properties:{},children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function wp(t,e){const n={type:"element",tagName:"em",properties:{},children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function xp(t,e){const n=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",i=String(e.identifier).toUpperCase(),r=Qn(i.toLowerCase()),s=t.footnoteOrder.indexOf(i);let a,o=t.footnoteCounts.get(i);o===void 0?(o=0,t.footnoteOrder.push(i),a=t.footnoteOrder.length):a=s+1,o+=1,t.footnoteCounts.set(i,o);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+r,id:n+"fnref-"+r+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};t.patch(e,c);const l={type:"element",tagName:"sup",properties:{},children:[c]};return t.patch(e,l),t.applyData(e,l)}function _p(t,e){const n={type:"element",tagName:"h"+e.depth,properties:{},children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function Ep(t,e){if(t.options.allowDangerousHtml){const n={type:"raw",value:e.value};return t.patch(e,n),t.applyData(e,n)}}function $c(t,e){const n=e.referenceType;let i="]";if(n==="collapsed"?i+="[]":n==="full"&&(i+="["+(e.label||e.identifier)+"]"),e.type==="imageReference")return[{type:"text",value:"!["+e.alt+i}];const r=t.all(e),s=r[0];s&&s.type==="text"?s.value="["+s.value:r.unshift({type:"text",value:"["});const a=r[r.length-1];return a&&a.type==="text"?a.value+=i:r.push({type:"text",value:i}),r}function Pp(t,e){const n=String(e.identifier).toUpperCase(),i=t.definitionById.get(n);if(!i)return $c(t,e);const r={src:Qn(i.url||""),alt:e.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const s={type:"element",tagName:"img",properties:r,children:[]};return t.patch(e,s),t.applyData(e,s)}function Rp(t,e){const n={src:Qn(e.url)};e.alt!==null&&e.alt!==void 0&&(n.alt=e.alt),e.title!==null&&e.title!==void 0&&(n.title=e.title);const i={type:"element",tagName:"img",properties:n,children:[]};return t.patch(e,i),t.applyData(e,i)}function Ip(t,e){const n={type:"text",value:e.value.replace(/\r?\n|\r/g," ")};t.patch(e,n);const i={type:"element",tagName:"code",properties:{},children:[n]};return t.patch(e,i),t.applyData(e,i)}function Mp(t,e){const n=String(e.identifier).toUpperCase(),i=t.definitionById.get(n);if(!i)return $c(t,e);const r={href:Qn(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const s={type:"element",tagName:"a",properties:r,children:t.all(e)};return t.patch(e,s),t.applyData(e,s)}function Op(t,e){const n={href:Qn(e.url)};e.title!==null&&e.title!==void 0&&(n.title=e.title);const i={type:"element",tagName:"a",properties:n,children:t.all(e)};return t.patch(e,i),t.applyData(e,i)}function Ap(t,e,n){const i=t.all(e),r=n?Dp(n):Jc(e),s={},a=[];if(typeof e.checked=="boolean"){const u=i[0];let d;u&&u.type==="element"&&u.tagName==="p"?d=u:(d={type:"element",tagName:"p",properties:{},children:[]},i.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:e.checked,disabled:!0},children:[]}),s.className=["task-list-item"]}let o=-1;for(;++o<i.length;){const u=i[o];(r||o!==0||u.type!=="element"||u.tagName!=="p")&&a.push({type:"text",value:`
10
+ `}),u.type==="element"&&u.tagName==="p"&&!r?a.push(...u.children):a.push(u)}const c=i[i.length-1];c&&(r||c.type!=="element"||c.tagName!=="p")&&a.push({type:"text",value:`
11
+ `});const l={type:"element",tagName:"li",properties:s,children:a};return t.patch(e,l),t.applyData(e,l)}function Dp(t){let e=!1;if(t.type==="list"){e=t.spread||!1;const n=t.children;let i=-1;for(;!e&&++i<n.length;)e=Jc(n[i])}return e}function Jc(t){const e=t.spread;return e??t.children.length>1}function Np(t,e){const n={},i=t.all(e);let r=-1;for(typeof e.start=="number"&&e.start!==1&&(n.start=e.start);++r<i.length;){const a=i[r];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const s={type:"element",tagName:e.ordered?"ol":"ul",properties:n,children:t.wrap(i,!0)};return t.patch(e,s),t.applyData(e,s)}function Lp(t,e){const n={type:"element",tagName:"p",properties:{},children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function jp(t,e){const n={type:"root",children:t.wrap(t.all(e))};return t.patch(e,n),t.applyData(e,n)}function Up(t,e){const n={type:"element",tagName:"strong",properties:{},children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function Fp(t,e){const n=t.all(e),i=n.shift(),r=[];if(i){const a={type:"element",tagName:"thead",properties:{},children:t.wrap([i],!0)};t.patch(e.children[0],a),r.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:t.wrap(n,!0)},o=Fs(e.children[1]),c=Rc(e.children[e.children.length-1]);o&&c&&(a.position={start:o,end:c}),r.push(a)}const s={type:"element",tagName:"table",properties:{},children:t.wrap(r,!0)};return t.patch(e,s),t.applyData(e,s)}function Bp(t,e,n){const i=n?n.children:void 0,s=(i?i.indexOf(e):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,o=a?a.length:e.children.length;let c=-1;const l=[];for(;++c<o;){const d=e.children[c],h={},f=a?a[c]:void 0;f&&(h.align=f);let m={type:"element",tagName:s,properties:h,children:[]};d&&(m.children=t.all(d),t.patch(d,m),m=t.applyData(d,m)),l.push(m)}const u={type:"element",tagName:"tr",properties:{},children:t.wrap(l,!0)};return t.patch(e,u),t.applyData(e,u)}function Vp(t,e){const n={type:"element",tagName:"td",properties:{},children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}const Go=9,$o=32;function qp(t){const e=String(t),n=/\r?\n|\r/g;let i=n.exec(e),r=0;const s=[];for(;i;)s.push(Jo(e.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=n.exec(e);return s.push(Jo(e.slice(r),r>0,!1)),s.join("")}function Jo(t,e,n){let i=0,r=t.length;if(e){let s=t.codePointAt(i);for(;s===Go||s===$o;)i++,s=t.codePointAt(i)}if(n){let s=t.codePointAt(r-1);for(;s===Go||s===$o;)r--,s=t.codePointAt(r-1)}return r>i?t.slice(i,r):""}function zp(t,e){const n={type:"text",value:qp(String(e.value))};return t.patch(e,n),t.applyData(e,n)}function Wp(t,e){const n={type:"element",tagName:"hr",properties:{},children:[]};return t.patch(e,n),t.applyData(e,n)}const Hp={blockquote:kp,break:Cp,code:Sp,delete:Tp,emphasis:wp,footnoteReference:xp,heading:_p,html:Ep,imageReference:Pp,image:Rp,inlineCode:Ip,linkReference:Mp,link:Op,listItem:Ap,list:Np,paragraph:Lp,root:jp,strong:Up,table:Fp,tableCell:Vp,tableRow:Bp,text:zp,thematicBreak:Wp,toml:Pi,yaml:Pi,definition:Pi,footnoteDefinition:Pi};function Pi(){}const Yc=-1,lr=0,fi=1,Ji=2,Ks=3,Gs=4,$s=5,Js=6,Qc=7,Xc=8,Yo=typeof self=="object"?self:globalThis,Kp=(t,e)=>{const n=(r,s)=>(t.set(s,r),r),i=r=>{if(t.has(r))return t.get(r);const[s,a]=e[r];switch(s){case lr:case Yc:return n(a,r);case fi:{const o=n([],r);for(const c of a)o.push(i(c));return o}case Ji:{const o=n({},r);for(const[c,l]of a)o[i(c)]=i(l);return o}case Ks:return n(new Date(a),r);case Gs:{const{source:o,flags:c}=a;return n(new RegExp(o,c),r)}case $s:{const o=n(new Map,r);for(const[c,l]of a)o.set(i(c),i(l));return o}case Js:{const o=n(new Set,r);for(const c of a)o.add(i(c));return o}case Qc:{const{name:o,message:c}=a;return n(new Yo[o](c),r)}case Xc:return n(BigInt(a),r);case"BigInt":return n(Object(BigInt(a)),r);case"ArrayBuffer":return n(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:o}=new Uint8Array(a);return n(new DataView(o),a)}}return n(new Yo[s](a),r)};return i},Qo=t=>Kp(new Map,t)(0),In="",{toString:Gp}={},{keys:$p}=Object,ni=t=>{const e=typeof t;if(e!=="object"||!t)return[lr,e];const n=Gp.call(t).slice(8,-1);switch(n){case"Array":return[fi,In];case"Object":return[Ji,In];case"Date":return[Ks,In];case"RegExp":return[Gs,In];case"Map":return[$s,In];case"Set":return[Js,In];case"DataView":return[fi,n]}return n.includes("Array")?[fi,n]:n.includes("Error")?[Qc,n]:[Ji,n]},Ri=([t,e])=>t===lr&&(e==="function"||e==="symbol"),Jp=(t,e,n,i)=>{const r=(a,o)=>{const c=i.push(a)-1;return n.set(o,c),c},s=a=>{if(n.has(a))return n.get(a);let[o,c]=ni(a);switch(o){case lr:{let u=a;switch(c){case"bigint":o=Xc,u=a.toString();break;case"function":case"symbol":if(t)throw new TypeError("unable to serialize "+c);u=null;break;case"undefined":return r([Yc],a)}return r([o,u],a)}case fi:{if(c){let h=a;return c==="DataView"?h=new Uint8Array(a.buffer):c==="ArrayBuffer"&&(h=new Uint8Array(a)),r([c,[...h]],a)}const u=[],d=r([o,u],a);for(const h of a)u.push(s(h));return d}case Ji:{if(c)switch(c){case"BigInt":return r([c,a.toString()],a);case"Boolean":case"Number":case"String":return r([c,a.valueOf()],a)}if(e&&"toJSON"in a)return s(a.toJSON());const u=[],d=r([o,u],a);for(const h of $p(a))(t||!Ri(ni(a[h])))&&u.push([s(h),s(a[h])]);return d}case Ks:return r([o,a.toISOString()],a);case Gs:{const{source:u,flags:d}=a;return r([o,{source:u,flags:d}],a)}case $s:{const u=[],d=r([o,u],a);for(const[h,f]of a)(t||!(Ri(ni(h))||Ri(ni(f))))&&u.push([s(h),s(f)]);return d}case Js:{const u=[],d=r([o,u],a);for(const h of a)(t||!Ri(ni(h)))&&u.push(s(h));return d}}const{message:l}=a;return r([o,{name:c,message:l}],a)};return s},Xo=(t,{json:e,lossy:n}={})=>{const i=[];return Jp(!(e||n),!!e,new Map,i)(t),i},Yi=typeof structuredClone=="function"?(t,e)=>e&&("json"in e||"lossy"in e)?Qo(Xo(t,e)):structuredClone(t):(t,e)=>Qo(Xo(t,e));function Yp(t,e){const n=[{type:"text",value:"↩"}];return e>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(e)}]}),n}function Qp(t,e){return"Back to reference "+(t+1)+(e>1?"-"+e:"")}function Xp(t){const e=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",n=t.options.footnoteBackContent||Yp,i=t.options.footnoteBackLabel||Qp,r=t.options.footnoteLabel||"Footnotes",s=t.options.footnoteLabelTagName||"h2",a=t.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let c=-1;for(;++c<t.footnoteOrder.length;){const l=t.footnoteById.get(t.footnoteOrder[c]);if(!l)continue;const u=t.all(l),d=String(l.identifier).toUpperCase(),h=Qn(d.toLowerCase());let f=0;const m=[],g=t.footnoteCounts.get(d);for(;g!==void 0&&++f<=g;){m.length>0&&m.push({type:"text",value:" "});let P=typeof n=="string"?n:n(c,f);typeof P=="string"&&(P={type:"text",value:P}),m.push({type:"element",tagName:"a",properties:{href:"#"+e+"fnref-"+h+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(c,f),className:["data-footnote-backref"]},children:Array.isArray(P)?P:[P]})}const w=u[u.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const P=w.children[w.children.length-1];P&&P.type==="text"?P.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...m)}else u.push(...m);const b={type:"element",tagName:"li",properties:{id:e+"fn-"+h},children:t.wrap(u,!0)};t.patch(l,b),o.push(b)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:s,properties:{...Yi(a),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
12
+ `},{type:"element",tagName:"ol",properties:{},children:t.wrap(o,!0)},{type:"text",value:`
13
+ `}]}}const Zc=(function(t){if(t==null)return nm;if(typeof t=="function")return ur(t);if(typeof t=="object")return Array.isArray(t)?Zp(t):em(t);if(typeof t=="string")return tm(t);throw new Error("Expected function, string, or object as test")});function Zp(t){const e=[];let n=-1;for(;++n<t.length;)e[n]=Zc(t[n]);return ur(i);function i(...r){let s=-1;for(;++s<e.length;)if(e[s].apply(this,r))return!0;return!1}}function em(t){const e=t;return ur(n);function n(i){const r=i;let s;for(s in t)if(r[s]!==e[s])return!1;return!0}}function tm(t){return ur(e);function e(n){return n&&n.type===t}}function ur(t){return e;function e(n,i,r){return!!(im(n)&&t.call(this,n,typeof i=="number"?i:void 0,r||void 0))}}function nm(){return!0}function im(t){return t!==null&&typeof t=="object"&&"type"in t}const el=[],rm=!0,Zo=!1,sm="skip";function om(t,e,n,i){let r;typeof e=="function"&&typeof n!="function"?(i=n,n=e):r=e;const s=Zc(r),a=i?-1:1;o(t,void 0,[])();function o(c,l,u){const d=c&&typeof c=="object"?c:{};if(typeof d.type=="string"){const f=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(h,"name",{value:"node ("+(c.type+(f?"<"+f+">":""))+")"})}return h;function h(){let f=el,m,g,w;if((!e||s(c,l,u[u.length-1]||void 0))&&(f=am(n(c,u)),f[0]===Zo))return f;if("children"in c&&c.children){const b=c;if(b.children&&f[0]!==sm)for(g=(i?b.children.length:-1)+a,w=u.concat(b);g>-1&&g<b.children.length;){const P=b.children[g];if(m=o(P,g,w)(),m[0]===Zo)return m;g=typeof m[1]=="number"?m[1]:g+a}}return f}}}function am(t){return Array.isArray(t)?t:typeof t=="number"?[rm,t]:t==null?el:[t]}function tl(t,e,n,i){let r,s,a;typeof e=="function"&&typeof n!="function"?(s=void 0,a=e,r=n):(s=e,a=n,r=i),om(t,s,o,r);function o(c,l){const u=l[l.length-1],d=u?u.children.indexOf(c):void 0;return a(c,d,u)}}const as={}.hasOwnProperty,cm={};function lm(t,e){const n=e||cm,i=new Map,r=new Map,s=new Map,a={...Hp,...n.handlers},o={all:l,applyData:dm,definitionById:i,footnoteById:r,footnoteCounts:s,footnoteOrder:[],handlers:a,one:c,options:n,patch:um,wrap:fm};return tl(t,function(u){if(u.type==="definition"||u.type==="footnoteDefinition"){const d=u.type==="definition"?i:r,h=String(u.identifier).toUpperCase();d.has(h)||d.set(h,u)}}),o;function c(u,d){const h=u.type,f=o.handlers[h];if(as.call(o.handlers,h)&&f)return f(o,u,d);if(o.options.passThrough&&o.options.passThrough.includes(h)){if("children"in u){const{children:g,...w}=u,b=Yi(w);return b.children=o.all(u),b}return Yi(u)}return(o.options.unknownHandler||hm)(o,u,d)}function l(u){const d=[];if("children"in u){const h=u.children;let f=-1;for(;++f<h.length;){const m=o.one(h[f],u);if(m){if(f&&h[f-1].type==="break"&&(!Array.isArray(m)&&m.type==="text"&&(m.value=ea(m.value)),!Array.isArray(m)&&m.type==="element")){const g=m.children[0];g&&g.type==="text"&&(g.value=ea(g.value))}Array.isArray(m)?d.push(...m):d.push(m)}}}return d}}function um(t,e){t.position&&(e.position=Kd(t))}function dm(t,e){let n=e;if(t&&t.data){const i=t.data.hName,r=t.data.hChildren,s=t.data.hProperties;if(typeof i=="string")if(n.type==="element")n.tagName=i;else{const a="children"in n?n.children:[n];n={type:"element",tagName:i,properties:{},children:a}}n.type==="element"&&s&&Object.assign(n.properties,Yi(s)),"children"in n&&n.children&&r!==null&&r!==void 0&&(n.children=r)}return n}function hm(t,e){const n=e.data||{},i="value"in e&&!(as.call(n,"hProperties")||as.call(n,"hChildren"))?{type:"text",value:e.value}:{type:"element",tagName:"div",properties:{},children:t.all(e)};return t.patch(e,i),t.applyData(e,i)}function fm(t,e){const n=[];let i=-1;for(e&&n.push({type:"text",value:`
14
+ `});++i<t.length;)i&&n.push({type:"text",value:`
15
+ `}),n.push(t[i]);return e&&t.length>0&&n.push({type:"text",value:`
16
+ `}),n}function ea(t){let e=0,n=t.charCodeAt(e);for(;n===9||n===32;)e++,n=t.charCodeAt(e);return t.slice(e)}function ta(t,e){const n=lm(t,e),i=n.one(t,void 0),r=Xp(n),s=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&s.children.push({type:"text",value:`
17
+ `},r),s}function pm(t,e){return t&&"run"in t?async function(n,i){const r=ta(n,{file:i,...e});await t.run(r,i)}:function(n,i){return ta(n,{file:i,...t||e})}}function na(t){if(t)throw t}var xr,ia;function mm(){if(ia)return xr;ia=1;var t=Object.prototype.hasOwnProperty,e=Object.prototype.toString,n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(l){return typeof Array.isArray=="function"?Array.isArray(l):e.call(l)==="[object Array]"},s=function(l){if(!l||e.call(l)!=="[object Object]")return!1;var u=t.call(l,"constructor"),d=l.constructor&&l.constructor.prototype&&t.call(l.constructor.prototype,"isPrototypeOf");if(l.constructor&&!u&&!d)return!1;var h;for(h in l);return typeof h>"u"||t.call(l,h)},a=function(l,u){n&&u.name==="__proto__"?n(l,u.name,{enumerable:!0,configurable:!0,value:u.newValue,writable:!0}):l[u.name]=u.newValue},o=function(l,u){if(u==="__proto__")if(t.call(l,u)){if(i)return i(l,u).value}else return;return l[u]};return xr=function c(){var l,u,d,h,f,m,g=arguments[0],w=1,b=arguments.length,P=!1;for(typeof g=="boolean"&&(P=g,g=arguments[1]||{},w=2),(g==null||typeof g!="object"&&typeof g!="function")&&(g={});w<b;++w)if(l=arguments[w],l!=null)for(u in l)d=o(g,u),h=o(l,u),g!==h&&(P&&h&&(s(h)||(f=r(h)))?(f?(f=!1,m=d&&r(d)?d:[]):m=d&&s(d)?d:{},a(g,{name:u,newValue:c(P,m,h)})):typeof h<"u"&&a(g,{name:u,newValue:h}));return g},xr}var gm=mm();const _r=Pc(gm);function cs(t){if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)}function vm(){const t=[],e={run:n,use:i};return e;function n(...r){let s=-1;const a=r.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);o(null,...r);function o(c,...l){const u=t[++s];let d=-1;if(c){a(c);return}for(;++d<r.length;)(l[d]===null||l[d]===void 0)&&(l[d]=r[d]);r=l,u?ym(u,o)(...l):a(null,...l)}}function i(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return t.push(r),e}}function ym(t,e){let n;return i;function i(...a){const o=t.length>a.length;let c;o&&a.push(r);try{c=t.apply(this,a)}catch(l){const u=l;if(o&&n)throw u;return r(u)}o||(c&&c.then&&typeof c.then=="function"?c.then(s,r):c instanceof Error?r(c):s(c))}function r(a,...o){n||(n=!0,e(a,...o))}function s(a){r(null,a)}}const Rt={basename:bm,dirname:km,extname:Cm,join:Sm,sep:"/"};function bm(t,e){if(e!==void 0&&typeof e!="string")throw new TypeError('"ext" argument must be a string');_i(t);let n=0,i=-1,r=t.length,s;if(e===void 0||e.length===0||e.length>t.length){for(;r--;)if(t.codePointAt(r)===47){if(s){n=r+1;break}}else i<0&&(s=!0,i=r+1);return i<0?"":t.slice(n,i)}if(e===t)return"";let a=-1,o=e.length-1;for(;r--;)if(t.codePointAt(r)===47){if(s){n=r+1;break}}else a<0&&(s=!0,a=r+1),o>-1&&(t.codePointAt(r)===e.codePointAt(o--)?o<0&&(i=r):(o=-1,i=a));return n===i?i=a:i<0&&(i=t.length),t.slice(n,i)}function km(t){if(_i(t),t.length===0)return".";let e=-1,n=t.length,i;for(;--n;)if(t.codePointAt(n)===47){if(i){e=n;break}}else i||(i=!0);return e<0?t.codePointAt(0)===47?"/":".":e===1&&t.codePointAt(0)===47?"//":t.slice(0,e)}function Cm(t){_i(t);let e=t.length,n=-1,i=0,r=-1,s=0,a;for(;e--;){const o=t.codePointAt(e);if(o===47){if(a){i=e+1;break}continue}n<0&&(a=!0,n=e+1),o===46?r<0?r=e:s!==1&&(s=1):r>-1&&(s=-1)}return r<0||n<0||s===0||s===1&&r===n-1&&r===i+1?"":t.slice(r,n)}function Sm(...t){let e=-1,n;for(;++e<t.length;)_i(t[e]),t[e]&&(n=n===void 0?t[e]:n+"/"+t[e]);return n===void 0?".":Tm(n)}function Tm(t){_i(t);const e=t.codePointAt(0)===47;let n=wm(t,!e);return n.length===0&&!e&&(n="."),n.length>0&&t.codePointAt(t.length-1)===47&&(n+="/"),e?"/"+n:n}function wm(t,e){let n="",i=0,r=-1,s=0,a=-1,o,c;for(;++a<=t.length;){if(a<t.length)o=t.codePointAt(a);else{if(o===47)break;o=47}if(o===47){if(!(r===a-1||s===1))if(r!==a-1&&s===2){if(n.length<2||i!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",i=0):(n=n.slice(0,c),i=n.length-1-n.lastIndexOf("/")),r=a,s=0;continue}}else if(n.length>0){n="",i=0,r=a,s=0;continue}}e&&(n=n.length>0?n+"/..":"..",i=2)}else n.length>0?n+="/"+t.slice(r+1,a):n=t.slice(r+1,a),i=a-r-1;r=a,s=0}else o===46&&s>-1?s++:s=-1}return n}function _i(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}const xm={cwd:_m};function _m(){return"/"}function ls(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function Em(t){if(typeof t=="string")t=new URL(t);else if(!ls(t)){const e=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+t+"`");throw e.code="ERR_INVALID_ARG_TYPE",e}if(t.protocol!=="file:"){const e=new TypeError("The URL must be of scheme file");throw e.code="ERR_INVALID_URL_SCHEME",e}return Pm(t)}function Pm(t){if(t.hostname!==""){const i=new TypeError('File URL host must be "localhost" or empty on darwin');throw i.code="ERR_INVALID_FILE_URL_HOST",i}const e=t.pathname;let n=-1;for(;++n<e.length;)if(e.codePointAt(n)===37&&e.codePointAt(n+1)===50){const i=e.codePointAt(n+2);if(i===70||i===102){const r=new TypeError("File URL path must not include encoded / characters");throw r.code="ERR_INVALID_FILE_URL_PATH",r}}return decodeURIComponent(e)}const Er=["history","path","basename","stem","extname","dirname"];class nl{constructor(e){let n;e?ls(e)?n={path:e}:typeof e=="string"||Rm(e)?n={value:e}:n=e:n={},this.cwd="cwd"in n?"":xm.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Er.length;){const s=Er[i];s in n&&n[s]!==void 0&&n[s]!==null&&(this[s]=s==="history"?[...n[s]]:n[s])}let r;for(r in n)Er.includes(r)||(this[r]=n[r])}get basename(){return typeof this.path=="string"?Rt.basename(this.path):void 0}set basename(e){Rr(e,"basename"),Pr(e,"basename"),this.path=Rt.join(this.dirname||"",e)}get dirname(){return typeof this.path=="string"?Rt.dirname(this.path):void 0}set dirname(e){ra(this.basename,"dirname"),this.path=Rt.join(e||"",this.basename)}get extname(){return typeof this.path=="string"?Rt.extname(this.path):void 0}set extname(e){if(Pr(e,"extname"),ra(this.dirname,"extname"),e){if(e.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(e.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Rt.join(this.dirname,this.stem+(e||""))}get path(){return this.history[this.history.length-1]}set path(e){ls(e)&&(e=Em(e)),Rr(e,"path"),this.path!==e&&this.history.push(e)}get stem(){return typeof this.path=="string"?Rt.basename(this.path,this.extname):void 0}set stem(e){Rr(e,"stem"),Pr(e,"stem"),this.path=Rt.join(this.dirname||"",e+(this.extname||""))}fail(e,n,i){const r=this.message(e,n,i);throw r.fatal=!0,r}info(e,n,i){const r=this.message(e,n,i);return r.fatal=void 0,r}message(e,n,i){const r=new We(e,n,i);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(e){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(e||void 0).decode(this.value)}}function Pr(t,e){if(t&&t.includes(Rt.sep))throw new Error("`"+e+"` cannot be a path: did not expect `"+Rt.sep+"`")}function Rr(t,e){if(!t)throw new Error("`"+e+"` cannot be empty")}function ra(t,e){if(!t)throw new Error("Setting `"+e+"` requires `path` to be set too")}function Rm(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const Im=(function(t){const i=this.constructor.prototype,r=i[t],s=function(){return r.apply(s,arguments)};return Object.setPrototypeOf(s,i),s}),Mm={}.hasOwnProperty;class Ys extends Im{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=vm()}copy(){const e=new Ys;let n=-1;for(;++n<this.attachers.length;){const i=this.attachers[n];e.use(...i)}return e.data(_r(!0,{},this.namespace)),e}data(e,n){return typeof e=="string"?arguments.length===2?(Or("data",this.frozen),this.namespace[e]=n,this):Mm.call(this.namespace,e)&&this.namespace[e]||void 0:e?(Or("data",this.frozen),this.namespace=e,this):this.namespace}freeze(){if(this.frozen)return this;const e=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...i]=this.attachers[this.freezeIndex];if(i[0]===!1)continue;i[0]===!0&&(i[0]=void 0);const r=n.call(e,...i);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(e){this.freeze();const n=Ii(e),i=this.parser||this.Parser;return Ir("parse",i),i(String(n),n)}process(e,n){const i=this;return this.freeze(),Ir("process",this.parser||this.Parser),Mr("process",this.compiler||this.Compiler),n?r(void 0,n):new Promise(r);function r(s,a){const o=Ii(e),c=i.parse(o);i.run(c,o,function(u,d,h){if(u||!d||!h)return l(u);const f=d,m=i.stringify(f,h);Dm(m)?h.value=m:h.result=m,l(u,h)});function l(u,d){u||!d?a(u):s?s(d):n(void 0,d)}}}processSync(e){let n=!1,i;return this.freeze(),Ir("processSync",this.parser||this.Parser),Mr("processSync",this.compiler||this.Compiler),this.process(e,r),oa("processSync","process",n),i;function r(s,a){n=!0,na(s),i=a}}run(e,n,i){sa(e),this.freeze();const r=this.transformers;return!i&&typeof n=="function"&&(i=n,n=void 0),i?s(void 0,i):new Promise(s);function s(a,o){const c=Ii(n);r.run(e,c,l);function l(u,d,h){const f=d||e;u?o(u):a?a(f):i(void 0,f,h)}}}runSync(e,n){let i=!1,r;return this.run(e,n,s),oa("runSync","run",i),r;function s(a,o){na(a),r=o,i=!0}}stringify(e,n){this.freeze();const i=Ii(n),r=this.compiler||this.Compiler;return Mr("stringify",r),sa(e),r(e,i)}use(e,...n){const i=this.attachers,r=this.namespace;if(Or("use",this.frozen),e!=null)if(typeof e=="function")c(e,n);else if(typeof e=="object")Array.isArray(e)?o(e):a(e);else throw new TypeError("Expected usable value, not `"+e+"`");return this;function s(l){if(typeof l=="function")c(l,[]);else if(typeof l=="object")if(Array.isArray(l)){const[u,...d]=l;c(u,d)}else a(l);else throw new TypeError("Expected usable value, not `"+l+"`")}function a(l){if(!("plugins"in l)&&!("settings"in l))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");o(l.plugins),l.settings&&(r.settings=_r(!0,r.settings,l.settings))}function o(l){let u=-1;if(l!=null)if(Array.isArray(l))for(;++u<l.length;){const d=l[u];s(d)}else throw new TypeError("Expected a list of plugins, not `"+l+"`")}function c(l,u){let d=-1,h=-1;for(;++d<i.length;)if(i[d][0]===l){h=d;break}if(h===-1)i.push([l,...u]);else if(u.length>0){let[f,...m]=u;const g=i[h][1];cs(g)&&cs(f)&&(f=_r(!0,g,f)),i[h]=[l,f,...m]}}}}const Om=new Ys().freeze();function Ir(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function Mr(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function Or(t,e){if(e)throw new Error("Cannot call `"+t+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function sa(t){if(!cs(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function oa(t,e,n){if(!n)throw new Error("`"+t+"` finished async. Use `"+e+"` instead")}function Ii(t){return Am(t)?t:new nl(t)}function Am(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function Dm(t){return typeof t=="string"||Nm(t)}function Nm(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const Lm="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",aa=[],ca={allowDangerousHtml:!0},jm=/^(https?|ircs?|mailto|xmpp)$/i,Um=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Fm(t){const e=Bm(t),n=Vm(t);return qm(e.runSync(e.parse(n),n),t)}function Bm(t){const e=t.rehypePlugins||aa,n=t.remarkPlugins||aa,i=t.remarkRehypeOptions?{...t.remarkRehypeOptions,...ca}:ca;return Om().use(bp).use(n).use(pm,i).use(e)}function Vm(t){const e=t.children||"",n=new nl;return typeof e=="string"&&(n.value=e),n}function qm(t,e){const n=e.allowedElements,i=e.allowElement,r=e.components,s=e.disallowedElements,a=e.skipHtml,o=e.unwrapDisallowed,c=e.urlTransform||zm;for(const u of Um)Object.hasOwn(e,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+Lm+u.id,void 0);return tl(t,l),Qd(t,{Fragment:p.Fragment,components:r,ignoreInvalidStyle:!0,jsx:p.jsx,jsxs:p.jsxs,passKeys:!0,passNode:!0});function l(u,d,h){if(u.type==="raw"&&h&&typeof d=="number")return a?h.children.splice(d,1):h.children[d]={type:"text",value:u.value},d;if(u.type==="element"){let f;for(f in Sr)if(Object.hasOwn(Sr,f)&&Object.hasOwn(u.properties,f)){const m=u.properties[f],g=Sr[f];(g===null||g.includes(u.tagName))&&(u.properties[f]=c(String(m||""),f,u))}}if(u.type==="element"){let f=n?!n.includes(u.tagName):s?s.includes(u.tagName):!1;if(!f&&i&&typeof d=="number"&&(f=!i(u,d,h)),f&&h&&typeof d=="number")return o&&u.children?h.children.splice(d,1,...u.children):h.children.splice(d,1),d}}}function zm(t){const e=t.indexOf(":"),n=t.indexOf("?"),i=t.indexOf("#"),r=t.indexOf("/");return e===-1||r!==-1&&e>r||n!==-1&&e>n||i!==-1&&e>i||jm.test(t.slice(0,e))?t:""}const Wm="_messageWrapper_1lg4d_1",Hm="_user_1lg4d_19",Km="_assistant_1lg4d_24",Gm="_messageBubble_1lg4d_58",$m="_error_1lg4d_76",Jm="_content_1lg4d_81",Ym="_markdown_1lg4d_92",Qm="_cursor_1lg4d_183",Xm="_errorIndicator_1lg4d_202",Zm="_messageContent_1lg4d_219",eg="_messageInfo_1lg4d_227",tg="_fadeOut_1lg4d_259",ng="_agentName_1lg4d_263",ig="_agentRole_1lg4d_268",rg="_separator_1lg4d_272",sg="_timestamp_1lg4d_277",je={messageWrapper:Wm,user:Hm,assistant:Km,messageBubble:Gm,error:$m,content:Jm,markdown:Ym,cursor:Qm,errorIndicator:Xm,messageContent:Zm,messageInfo:eg,fadeOut:tg,agentName:ng,agentRole:ig,separator:rg,timestamp:sg},og=t=>{const n=Date.now()-t,i=Math.floor(n/6e4),r=Math.floor(n/36e5),s=Math.floor(n/864e5);return i<1?"Just now":i<60?`${i}m`:r<24?`${r}h`:`${s}d`},il=({message:t,agentName:e,agentRole:n,isLastAssistantMessage:i=!1})=>{const[r,s]=q.useState(!1),[a,o]=q.useState(!1),[c,l]=q.useState(!1),u=t.role==="user",d=t.status==="streaming",h=t.status==="error",f=t.role==="assistant",m=f&&(i||r);q.useEffect(()=>{if(m&&!a)l(!1),o(!0);else if(!m&&a){l(!0);const b=setTimeout(()=>{o(!1),l(!1)},200);return()=>clearTimeout(b)}},[m,a]);const g=()=>{f&&!i&&s(!r)},w=[je.messageWrapper,u?je.user:je.assistant,f&&!i?je.clickable:""].filter(Boolean).join(" ");return p.jsx("div",{className:w,onClick:g,children:p.jsxs("div",{className:je.messageContent,children:[p.jsxs("div",{className:`${je.messageBubble} ${h?je.error:""}`,role:"article","aria-label":`${u?"Your message":`${e||"AI"} says`}`,children:[p.jsxs("div",{className:`${je.content} ${u?"":je.markdown}`,children:[u?t.content:p.jsx(Fm,{components:{a:({href:b,children:P})=>b?p.jsx("a",{href:b,target:"_blank",rel:"noopener noreferrer",children:P}):p.jsx(p.Fragment,{children:P})},children:t.content}),d&&p.jsx("span",{className:je.cursor})]}),h&&p.jsxs("div",{className:je.errorIndicator,children:[p.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",children:[p.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2"}),p.jsx("path",{d:"M12 8V12M12 16H12.01",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),p.jsx("span",{children:"Failed to send"})]})]}),a&&p.jsxs("div",{className:`${je.messageInfo} ${c?je.fadeOut:""}`,children:[p.jsx("span",{className:je.agentName,children:e||"AI"}),n&&p.jsxs(p.Fragment,{children:[p.jsx("span",{className:je.separator,children:"•"}),p.jsx("span",{className:je.agentRole,children:n})]}),p.jsx("span",{className:je.separator,children:"•"}),p.jsx("span",{className:je.timestamp,children:og(t.timestamp)})]})]})})},ag="_toolCall_1wby1_1",cg="_iconWrapper_1wby1_24",lg="_spinner_1wby1_33",ug="_checkIcon_1wby1_48",dg="_errorIcon_1wby1_54",hg="_content_1wby1_60",fg="_label_1wby1_66",pg="_name_1wby1_73",mg="_pending_1wby1_78",gg="_completed_1wby1_82",vg="_error_1wby1_54",bt={toolCall:ag,iconWrapper:cg,spinner:lg,checkIcon:ug,errorIcon:dg,content:hg,label:fg,name:pg,pending:mg,completed:gg,error:vg},rl=({toolCall:t})=>{const e=t.status==="pending"||t.status==="executing",n=t.status==="completed",i=t.status==="error",r=s=>s.replace(/_/g," ").replace(/([A-Z])/g," $1").trim().toLowerCase().replace(/^./,a=>a.toUpperCase());return p.jsxs("div",{className:`${bt.toolCall} ${e?bt.pending:""} ${n?bt.completed:""} ${i?bt.error:""}`,children:[p.jsx("div",{className:bt.iconWrapper,children:e?p.jsx("div",{className:bt.spinner}):n?p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:bt.checkIcon,children:p.jsx("path",{d:"M20 6L9 17L4 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:bt.errorIcon,children:p.jsx("path",{d:"M6 18L18 6M6 6L18 18",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),p.jsxs("div",{className:bt.content,children:[p.jsx("span",{className:bt.label,children:e?"Running":n?"Completed":"Failed"}),p.jsx("span",{className:bt.name,children:r(t.name)})]})]})},yg="_wrapper_10rss_2",bg="_avatar_10rss_22",kg="_avatarPlaceholder_10rss_37",Cg="_brainbaseLogo_10rss_47",Sg="_bubble_10rss_52",Tg="_dot_10rss_63",Xt={wrapper:yg,avatar:bg,avatarPlaceholder:kg,brainbaseLogo:Cg,bubble:Sg,dot:Tg},sl=({agentName:t="AI",agentLogoUrl:e})=>p.jsxs("div",{className:Xt.wrapper,role:"status","aria-label":`${t} is typing`,children:[p.jsx("div",{className:Xt.avatar,children:e?p.jsx("img",{src:e,alt:t}):p.jsx("div",{className:Xt.avatarPlaceholder,children:p.jsx(Kn,{className:Xt.brainbaseLogo,color:"white",cutoutColor:"var(--bb-primary-color)"})})}),p.jsxs("div",{className:Xt.bubble,children:[p.jsx("span",{className:Xt.dot}),p.jsx("span",{className:Xt.dot}),p.jsx("span",{className:Xt.dot})]})]}),wg="_messageList_9tkjc_1",xg="_emptyState_9tkjc_30",_g="_emptyIcon_9tkjc_41",Eg="_emptyText_9tkjc_53",Mi={messageList:wg,emptyState:xg,emptyIcon:_g,emptyText:Eg},ol=({messages:t,toolCalls:e=[],isLoading:n,showTypingIndicator:i=!1,agentName:r,agentRole:s,agentLogoUrl:a})=>{const o=t.reduce((f,m,g)=>m.role==="assistant"?g:f,-1),c=q.useRef(null),l=q.useRef(null),u=q.useRef(t.length),d=q.useRef(e.length);q.useEffect(()=>{const f=t.length>u.current,m=e.length>d.current;if(f||m||i){const g=c.current;g&&g.scrollTo({top:g.scrollHeight,behavior:"smooth"})}u.current=t.length,d.current=e.length},[t.length,e.length,i]);const h=e.filter(f=>f.status==="pending"||f.status==="executing");return p.jsxs("div",{className:Mi.messageList,ref:c,role:"log","aria-live":"polite",children:[t.length===0&&!n&&p.jsxs("div",{className:Mi.emptyState,children:[p.jsx("div",{className:Mi.emptyIcon,children:p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:p.jsx("path",{d:"M8 12H8.01M12 12H12.01M16 12H16.01M21 12C21 16.4183 16.9706 20 12 20C10.4607 20 9.01172 19.6565 7.74467 19.0511L3 20L4.39499 16.28C3.51156 15.0423 3 13.5743 3 12C3 7.58172 7.02944 4 12 4C16.9706 4 21 7.58172 21 12Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),p.jsx("p",{className:Mi.emptyText,children:"Start a conversation"})]}),t.map((f,m)=>p.jsx(il,{message:f,agentName:r,agentRole:s,isLastAssistantMessage:m===o},f.id)),h.map(f=>p.jsx(rl,{toolCall:f},f.id)),i&&p.jsx(sl,{agentName:r,agentLogoUrl:a}),p.jsx("div",{ref:l})]})},Pg="_inputWrapper_6o34z_1",Rg="_inputContainer_6o34z_7",Ig="_textarea_6o34z_23",Mg="_inputActions_6o34z_51",Og="_actionIcons_6o34z_57",Ag="_iconButton_6o34z_63",Dg="_sendButton_6o34z_96",Ng="_audioButton_6o34z_126",Lg="_audioIcon_6o34z_141",ft={inputWrapper:Pg,inputContainer:Rg,textarea:Ig,inputActions:Mg,actionIcons:Og,iconButton:Ag,sendButton:Dg,audioButton:Ng,audioIcon:Lg},al=({onSend:t,disabled:e=!1,placeholder:n="Message...",onAttachment:i,onEmoji:r,onGif:s,onVoice:a})=>{const[o,c]=q.useState(""),l=q.useRef(null),u=q.useCallback(()=>{const f=l.current;f&&(f.style.height="auto",f.style.height=`${Math.min(f.scrollHeight,150)}px`)},[]);q.useEffect(()=>{u()},[o,u]);const d=q.useCallback(f=>{f==null||f.preventDefault();const m=o.trim();m&&!e&&(t(m),c(""),l.current&&(l.current.style.height="auto"))},[o,e,t]),h=q.useCallback(f=>{f.key==="Enter"&&!f.shiftKey&&(f.preventDefault(),d())},[d]);return p.jsx("form",{className:ft.inputWrapper,onSubmit:d,children:p.jsxs("div",{className:ft.inputContainer,children:[p.jsx("textarea",{ref:l,className:ft.textarea,value:o,onChange:f=>c(f.target.value),onKeyDown:h,placeholder:n,disabled:e,rows:1,"aria-label":"Message input"}),p.jsxs("div",{className:ft.inputActions,children:[p.jsxs("div",{className:ft.actionIcons,children:[i&&p.jsx("button",{type:"button",className:ft.iconButton,onClick:i,disabled:e,"aria-label":"Attach file",children:p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:p.jsx("path",{d:"M21.44 11.05L12.25 20.24C11.1242 21.3658 9.59723 21.9983 8.005 21.9983C6.41277 21.9983 4.88584 21.3658 3.76 20.24C2.63416 19.1142 2.00166 17.5872 2.00166 15.995C2.00166 14.4028 2.63416 12.8758 3.76 11.75L12.33 3.18C13.0806 2.42975 14.0991 2.00127 15.16 2.00127C16.2209 2.00127 17.2394 2.42975 17.99 3.18C18.7403 3.93063 19.1687 4.94905 19.1687 6.01C19.1687 7.07095 18.7403 8.08937 17.99 8.84L9.41 17.41C9.03472 17.7853 8.52573 17.9961 7.995 17.9961C7.46427 17.9961 6.95528 17.7853 6.58 17.41C6.20472 17.0347 5.99389 16.5257 5.99389 15.995C5.99389 15.4643 6.20472 14.9553 6.58 14.58L15.07 6.1",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),r&&p.jsx("button",{type:"button",className:ft.iconButton,onClick:r,disabled:e,"aria-label":"Add emoji",children:p.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",children:[p.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2"}),p.jsx("path",{d:"M8 14C8 14 9.5 16 12 16C14.5 16 16 14 16 14",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),p.jsx("circle",{cx:"9",cy:"9",r:"1",fill:"currentColor"}),p.jsx("circle",{cx:"15",cy:"9",r:"1",fill:"currentColor"})]})}),s&&p.jsx("button",{type:"button",className:ft.iconButton,onClick:s,disabled:e,"aria-label":"Add GIF",children:p.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",children:[p.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",stroke:"currentColor",strokeWidth:"2"}),p.jsx("path",{d:"M8 10V14M8 12H10M8 10H10",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),p.jsx("path",{d:"M13 10V14",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),p.jsx("path",{d:"M16 10V14M16 10H18M16 12H17.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]})}),a&&p.jsx("button",{type:"button",className:ft.iconButton,onClick:a,disabled:e,"aria-label":"Voice message",children:p.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",children:[p.jsx("rect",{x:"9",y:"2",width:"6",height:"11",rx:"3",stroke:"currentColor",strokeWidth:"2"}),p.jsx("path",{d:"M5 10V11C5 14.866 8.13401 18 12 18C15.866 18 19 14.866 19 11V10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),p.jsx("path",{d:"M12 18V22M12 22H8M12 22H16",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})})]}),p.jsx("button",{type:o.trim()?"submit":"button",className:`${ft.sendButton} ${o.trim()?"":ft.audioButton}`,disabled:e,"aria-label":o.trim()?"Send message":"Voice message",onClick:o.trim()?void 0:a,children:o.trim()?p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:p.jsx("path",{d:"M12 19V5M12 5L5 12M12 5L19 12",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):p.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:ft.audioIcon,children:[p.jsx("path",{d:"M4 10V14",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round"}),p.jsx("path",{d:"M9 6V18",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round"}),p.jsx("path",{d:"M14 8V16",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round"}),p.jsx("path",{d:"M19 10V14",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round"})]})})]})]})})},jg="_poweredBy_9jh5q_1",Ug="_logo_9jh5q_20",Fg="_poweredText_9jh5q_24",Bg="_text_9jh5q_36",Oi={poweredBy:jg,logo:Ug,poweredText:Fg,text:Bg},Vg=({className:t})=>p.jsxs("svg",{className:t,viewBox:"0 0 800 800",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[p.jsx("path",{d:"M400 412C400 405.373 405.373 400 412 400H788C794.627 400 800 405.373 800 412V740C800 773.137 773.137 800 740 800H412C405.373 800 400 794.627 400 788V412Z",fill:"currentColor"}),p.jsx("circle",{cx:"400",cy:"400",r:"400",fill:"currentColor"}),p.jsx("path",{d:"M0 60C0 26.8629 26.8629 0 60 0H397.614C398.932 0 400 1.06811 400 2.38569V2.38569C400 221.982 221.982 400 2.38569 400V400C1.06811 400 0 398.932 0 397.614V60Z",fill:"currentColor"}),p.jsx("path",{d:"M400 412C400 405.373 405.373 400 412 400H738C744.627 400 750 405.373 750 412V725C750 738.807 738.807 750 725 750H412C405.373 750 400 744.627 400 738V412Z",fill:"currentColor"}),p.jsx("circle",{cx:"400",cy:"400",r:"350",fill:"currentColor"}),p.jsx("path",{d:"M50 75C50 61.1929 61.1929 50 75 50H388C394.627 50 400 55.3726 400 62V388C400 394.627 394.627 400 388 400H62C55.3726 400 50 394.627 50 388V75Z",fill:"currentColor"}),p.jsx("rect",{x:"399.919",y:"209",width:"270",height:"270",rx:"12",transform:"rotate(45 399.919 209)",fill:"var(--bb-surface-bg, #ffffff)"})]}),qg=({showBranding:t=!0})=>t?p.jsxs("a",{href:"https://brainbaselabs.com/",target:"_blank",rel:"noopener noreferrer",className:Oi.poweredBy,"aria-label":"Powered by Brainbase Labs",children:[p.jsx("span",{className:Oi.poweredText,children:"Powered by"}),p.jsx(Vg,{className:Oi.logo}),p.jsx("span",{className:Oi.text,children:"Brainbase Labs"})]}):null;function zg(t,e){return e.forEach(function(n){n&&typeof n!="string"&&!Array.isArray(n)&&Object.keys(n).forEach(function(i){if(i!=="default"&&!(i in t)){var r=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return n[i]}})}})}),Object.freeze(t)}var Wg=Object.defineProperty,Hg=(t,e,n)=>e in t?Wg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,la=(t,e,n)=>Hg(t,typeof e!="symbol"?e+"":e,n);class Ye{constructor(){la(this,"_locking"),la(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const n=new Promise(r=>e=()=>{this._locks-=1,r()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>n),i}}function Ee(t,e){if(!t)throw new Error(e)}const Kg=34028234663852886e22,Gg=-34028234663852886e22,$g=4294967295,Jg=2147483647,Yg=-2147483648;function Li(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>Jg||t<Yg)throw new Error("invalid int 32: "+t)}function us(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>$g||t<0)throw new Error("invalid uint 32: "+t)}function cl(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(Number.isFinite(t)&&(t>Kg||t<Gg))throw new Error("invalid float 32: "+t)}const ll=Symbol("@bufbuild/protobuf/enum-type");function Qg(t){const e=t[ll];return Ee(e,"missing enum type on enum object"),e}function ul(t,e,n,i){t[ll]=dl(e,n.map(r=>({no:r.no,name:r.name,localName:t[r.no]})))}function dl(t,e,n){const i=Object.create(null),r=Object.create(null),s=[];for(const a of e){const o=hl(a);s.push(o),i[a.name]=o,r[a.no]=o}return{typeName:t,values:s,findName(a){return i[a]},findNumber(a){return r[a]}}}function Xg(t,e,n){const i={};for(const r of e){const s=hl(r);i[s.localName]=s.no,i[s.no]=s.localName}return ul(i,t,e),i}function hl(t){return"localName"in t?t:Object.assign(Object.assign({},t),{localName:t.name})}class Qs{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,n){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(n);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,n){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(n);return r.readMessage(i,e,s,this),this}fromJsonString(e,n){let i;try{i=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,n)}toBinary(e){const n=this.getType(),i=n.runtime.bin,r=i.makeWriteOptions(e),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(e){const n=this.getType(),i=n.runtime.json,r=i.makeWriteOptions(e);return i.writeMessage(this,r)}toJsonString(e){var n;const i=this.toJson(e);return JSON.stringify(i,null,(n=e==null?void 0:e.prettySpaces)!==null&&n!==void 0?n:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Zg(t,e,n,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),a={[s]:function(o){t.util.initFields(this),t.util.initPartial(o,this)}}[s];return Object.setPrototypeOf(a.prototype,new Qs),Object.assign(a,{runtime:t,typeName:e,fields:t.util.newFieldList(n),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return t.util.equals(a,o,c)}}),a}function ev(){let t=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[t,e]}let n=this.buf[this.pos++];if(t|=(n&15)<<28,e=(n&112)>>4,(n&128)==0)return this.assertBounds(),[t,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function Ar(t,e,n){for(let s=0;s<28;s=s+7){const a=t>>>s,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(n.push(c),!o)return}const i=t>>>28&15|(e&7)<<4,r=e>>3!=0;if(n.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const a=e>>>s,o=!!(a>>>7),c=(o?a|128:a)&255;if(n.push(c),!o)return}n.push(e>>>31&1)}}const ji=4294967296;function ua(t){const e=t[0]==="-";e&&(t=t.slice(1));const n=1e6;let i=0,r=0;function s(a,o){const c=Number(t.slice(a,o));r*=n,i=i*n+c,i>=ji&&(r=r+(i/ji|0),i=i%ji)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?pl(i,r):Xs(i,r)}function tv(t,e){let n=Xs(t,e);const i=n.hi&2147483648;i&&(n=pl(n.lo,n.hi));const r=fl(n.lo,n.hi);return i?"-"+r:r}function fl(t,e){if({lo:t,hi:e}=nv(t,e),e<=2097151)return String(ji*e+t);const n=t&16777215,i=(t>>>24|e<<8)&16777215,r=e>>16&65535;let s=n+i*6777216+r*6710656,a=i+r*8147497,o=r*2;const c=1e7;return s>=c&&(a+=Math.floor(s/c),s%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+da(a)+da(s)}function nv(t,e){return{lo:t>>>0,hi:e>>>0}}function Xs(t,e){return{lo:t|0,hi:e|0}}function pl(t,e){return e=~e,t?t=~t+1:e+=1,Xs(t,e)}const da=t=>{const e=String(t);return"0000000".slice(e.length)+e};function ha(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let n=0;n<9;n++)e.push(t&127|128),t=t>>7;e.push(1)}}function iv(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let n=5;(t&128)!==0&&n<10;n++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function rv(){const t=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>s||l<r)throw new Error("int64 invalid: ".concat(c));return l},uParse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>o||l<a)throw new Error("uint64 invalid: ".concat(c));return l},enc(c){return t.setBigInt64(0,this.parse(c),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(c){return t.setBigInt64(0,this.uParse(c),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec(c,l){return t.setInt32(0,c,!0),t.setInt32(4,l,!0),t.getBigInt64(0,!0)},uDec(c,l){return t.setInt32(0,c,!0),t.setInt32(4,l,!0),t.getBigUint64(0,!0)}}}const n=r=>Ee(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>Ee(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),n(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),n(r),ua(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),ua(r)},dec(r,s){return tv(r,s)},uDec(r,s){return fl(r,s)}}}const xe=rv();var D;(function(t){t[t.DOUBLE=1]="DOUBLE",t[t.FLOAT=2]="FLOAT",t[t.INT64=3]="INT64",t[t.UINT64=4]="UINT64",t[t.INT32=5]="INT32",t[t.FIXED64=6]="FIXED64",t[t.FIXED32=7]="FIXED32",t[t.BOOL=8]="BOOL",t[t.STRING=9]="STRING",t[t.BYTES=12]="BYTES",t[t.UINT32=13]="UINT32",t[t.SFIXED32=15]="SFIXED32",t[t.SFIXED64=16]="SFIXED64",t[t.SINT32=17]="SINT32",t[t.SINT64=18]="SINT64"})(D||(D={}));var dn;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING"})(dn||(dn={}));function Zt(t,e,n){if(e===n)return!0;if(t==D.BYTES){if(!(e instanceof Uint8Array)||!(n instanceof Uint8Array)||e.length!==n.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==n[i])return!1;return!0}switch(t){case D.UINT64:case D.FIXED64:case D.INT64:case D.SFIXED64:case D.SINT64:return e==n}return!1}function Gn(t,e){switch(t){case D.BOOL:return!1;case D.UINT64:case D.FIXED64:case D.INT64:case D.SFIXED64:case D.SINT64:return e==0?xe.zero:"0";case D.DOUBLE:case D.FLOAT:return 0;case D.BYTES:return new Uint8Array(0);case D.STRING:return"";default:return 0}}function ml(t,e){switch(t){case D.BOOL:return e===!1;case D.STRING:return e==="";case D.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var Ie;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(Ie||(Ie={}));class sv{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 r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let n=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)n.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,n){return this.uint32((e<<3|n)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(us(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Li(e),ha(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 n=this.textEncoder.encode(e);return this.uint32(n.byteLength),this.raw(n)}float(e){cl(e);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,e,!0),this.raw(n)}double(e){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),this.raw(n)}fixed32(e){us(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){Li(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return Li(e),e=(e<<1^e>>31)>>>0,ha(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),i=new DataView(n.buffer),r=xe.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),i=new DataView(n.buffer),r=xe.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(n)}int64(e){let n=xe.enc(e);return Ar(n.lo,n.hi,this.buf),this}sint64(e){let n=xe.enc(e),i=n.hi>>31,r=n.lo<<1^i,s=(n.hi<<1|n.lo>>>31)^i;return Ar(r,s,this.buf),this}uint64(e){let n=xe.uEnc(e);return Ar(n.lo,n.hi,this.buf),this}}class ov{constructor(e,n){this.varint64=ev,this.uint32=iv,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=n??new TextDecoder}tag(){let e=this.uint32(),n=e>>>3,i=e&7;if(n<=0||i<0||i>5)throw new Error("illegal tag: field no "+n+" wire type "+i);return[n,i]}skip(e,n){let i=this.pos;switch(e){case Ie.Varint:for(;this.buf[this.pos++]&128;);break;case Ie.Bit64:this.pos+=4;case Ie.Bit32:this.pos+=4;break;case Ie.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Ie.StartGroup:for(;;){const[s,a]=this.tag();if(a===Ie.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(a,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,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 xe.dec(...this.varint64())}uint64(){return xe.uDec(...this.varint64())}sint64(){let[e,n]=this.varint64(),i=-(e&1);return e=(e>>>1|(n&1)<<31)^i,n=n>>>1^i,xe.dec(e,n)}bool(){let[e,n]=this.varint64();return e!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return xe.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return xe.dec(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(),n=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(n,n+e)}string(){return this.textDecoder.decode(this.bytes())}}function av(t,e,n,i){let r;return{typeName:e,extendee:n,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=t.util.newFieldList([s]).list()[0]}return r},runtime:t}}function gl(t){const e=t.field.localName,n=Object.create(null);return n[e]=cv(t),[n,()=>n[e]]}function cv(t){const e=t.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return Gn(e.T,e.L);case"message":const n=e.T,i=new n;return n.fieldWrapper?n.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function lv(t,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let n=t.length-1;n>=0;--n)if(t[n].no==e.no)return[t[n]];return[]}return t.filter(n=>n.no===e.no)}let zt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),dr=[];for(let t=0;t<zt.length;t++)dr[zt[t].charCodeAt(0)]=t;dr[45]=zt.indexOf("+");dr[95]=zt.indexOf("/");const vl={dec(t){let e=t.length*3/4;t[t.length-2]=="="?e-=2:t[t.length-1]=="="&&(e-=1);let n=new Uint8Array(e),i=0,r=0,s,a=0;for(let o=0;o<t.length;o++){if(s=dr[t.charCodeAt(o)],s===void 0)switch(t[o]){case"=":r=0;case`
18
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:a=s,r=1;break;case 1:n[i++]=a<<2|(s&48)>>4,a=s,r=2;break;case 2:n[i++]=(a&15)<<4|(s&60)>>2,a=s,r=3;break;case 3:n[i++]=(a&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return n.subarray(0,i)},enc(t){let e="",n=0,i,r=0;for(let s=0;s<t.length;s++)switch(i=t[s],n){case 0:e+=zt[i>>2],r=(i&3)<<4,n=1;break;case 1:e+=zt[r|i>>4],r=(i&15)<<2,n=2;break;case 2:e+=zt[r|i>>6],e+=zt[i&63],n=0;break}return n&&(e+=zt[r],e+="=",n==1&&(e+="=")),e}};function uv(t,e,n){bl(e,t);const i=e.runtime.bin.makeReadOptions(n),r=lv(t.getType().runtime.bin.listUnknownFields(t),e.field),[s,a]=gl(e);for(const o of r)e.runtime.bin.readField(s,i.readerFactory(o.data),e.field,o.wireType,i);return a()}function dv(t,e,n,i){bl(e,t);const r=e.runtime.bin.makeReadOptions(i),s=e.runtime.bin.makeWriteOptions(i);if(yl(t,e)){const l=t.getType().runtime.bin.listUnknownFields(t).filter(u=>u.no!=e.field.no);t.getType().runtime.bin.discardUnknownFields(t);for(const u of l)t.getType().runtime.bin.onUnknownField(t,u.no,u.wireType,u.data)}const a=s.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,n,a,s);const c=r.readerFactory(a.finish());for(;c.pos<c.len;){const[l,u]=c.tag(),d=c.skip(u,l);t.getType().runtime.bin.onUnknownField(t,l,u,d)}}function yl(t,e){const n=t.getType();return e.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(t).find(i=>i.no==e.field.no)}function bl(t,e){Ee(t.extendee.typeName==e.getType().typeName,"extension ".concat(t.typeName," can only be applied to message ").concat(t.extendee.typeName))}function kl(t,e){const n=t.localName;if(t.repeated)return e[n].length>0;if(t.oneof)return e[t.oneof.localName].case===n;switch(t.kind){case"enum":case"scalar":return t.opt||t.req?e[n]!==void 0:t.kind=="enum"?e[n]!==t.T.values[0].no:!ml(t.T,e[n]);case"message":return e[n]!==void 0;case"map":return Object.keys(e[n]).length>0}}function fa(t,e){const n=t.localName,i=!t.opt&&!t.req;if(t.repeated)e[n]=[];else if(t.oneof)e[t.oneof.localName]={case:void 0};else switch(t.kind){case"map":e[n]={};break;case"enum":e[n]=i?t.T.values[0].no:void 0;break;case"scalar":e[n]=i?Gn(t.T,t.L):void 0;break;case"message":e[n]=void 0;break}}function Wt(t,e){if(t===null||typeof t!="object"||!Object.getOwnPropertyNames(Qs.prototype).every(i=>i in t&&typeof t[i]=="function"))return!1;const n=t.getType();return n===null||typeof n!="function"||!("typeName"in n)||typeof n.typeName!="string"?!1:e===void 0?!0:n.typeName==e.typeName}function Cl(t,e){return Wt(e)||!t.fieldWrapper?e:t.fieldWrapper.wrapField(e)}D.DOUBLE,D.FLOAT,D.INT64,D.UINT64,D.INT32,D.UINT32,D.BOOL,D.STRING,D.BYTES;const pa={ignoreUnknownFields:!1},ma={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function hv(t){return t?Object.assign(Object.assign({},pa),t):pa}function fv(t){return t?Object.assign(Object.assign({},ma),t):ma}const Qi=Symbol(),Ui=Symbol();function pv(){return{makeReadOptions:hv,makeWriteOptions:fv,readMessage(t,e,n,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(t.typeName," from JSON: ").concat(It(e)));i=i??new t;const r=new Map,s=n.typeRegistry;for(const[a,o]of Object.entries(e)){const c=t.fields.findJsonName(a);if(c){if(c.oneof){if(o===null&&c.kind=="scalar")continue;const l=r.get(c.oneof);if(l!==void 0)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(l,'", "').concat(a,'"'));r.set(c.oneof,a)}ga(i,o,c,n,t)}else{let l=!1;if(s!=null&&s.findExtension&&a.startsWith("[")&&a.endsWith("]")){const u=s.findExtension(a.substring(1,a.length-1));if(u&&u.extendee.typeName==t.typeName){l=!0;const[d,h]=gl(u);ga(d,o,u.field,n,u),dv(i,u,h(),n)}}if(!l&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(t.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return i},writeMessage(t,e){const n=t.getType(),i={};let r;try{for(r of n.fields.byNumber()){if(!kl(r,t)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!gv(r))continue}const a=r.oneof?t[r.oneof.localName].value:t[r.localName],o=va(r,a,e);o!==void 0&&(i[e.useProtoFieldName?r.name:r.jsonName]=o)}const s=e.typeRegistry;if(s!=null&&s.findExtensionFor)for(const a of n.runtime.bin.listUnknownFields(t)){const o=s.findExtensionFor(n.typeName,a.no);if(o&&yl(t,o)){const c=uv(t,o,e),l=va(o.field,c,e);l!==void 0&&(i[o.field.jsonName]=l)}}}catch(s){const a=r?"cannot encode field ".concat(n.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),o=s instanceof Error?s.message:String(s);throw new Error(a+(o.length>0?": ".concat(o):""))}return i},readScalar(t,e,n){return pi(t,e,n??dn.BIGINT,!0)},writeScalar(t,e,n){if(e!==void 0&&(n||ml(t,e)))return Fi(t,e)},debug:It}}function It(t){if(t===null)return"null";switch(typeof t){case"object":return Array.isArray(t)?"array":"object";case"string":return t.length>100?"string":'"'.concat(t.split('"').join('\\"'),'"');default:return String(t)}}function ga(t,e,n,i,r){let s=n.localName;if(n.repeated){if(Ee(n.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(It(e)));const a=t[s];for(const o of e){if(o===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(It(o)));switch(n.kind){case"message":a.push(n.T.fromJson(o,i));break;case"enum":const c=Dr(n.T,o,i.ignoreUnknownFields,!0);c!==Ui&&a.push(c);break;case"scalar":try{a.push(pi(n.T,o,n.L,!0))}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(It(o));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}}else if(n.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(It(e)));const a=t[s];for(const[o,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let l;try{l=mv(n.K,o)}catch(u){let d="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(It(e));throw u instanceof Error&&u.message.length>0&&(d+=": ".concat(u.message)),new Error(d)}switch(n.V.kind){case"message":a[l]=n.V.T.fromJson(c,i);break;case"enum":const u=Dr(n.V.T,c,i.ignoreUnknownFields,!0);u!==Ui&&(a[l]=u);break;case"scalar":try{a[l]=pi(n.V.T,c,dn.BIGINT,!0)}catch(d){let h="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(It(e));throw d instanceof Error&&d.message.length>0&&(h+=": ".concat(d.message)),new Error(h)}break}}}else switch(n.oneof&&(t=t[n.oneof.localName]={case:s},s="value"),n.kind){case"message":const a=n.T;if(e===null&&a.typeName!="google.protobuf.Value")return;let o=t[s];Wt(o)?o.fromJson(e,i):(t[s]=o=a.fromJson(e,i),a.fieldWrapper&&!n.oneof&&(t[s]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=Dr(n.T,e,i.ignoreUnknownFields,!1);switch(c){case Qi:fa(n,t);break;case Ui:break;default:t[s]=c;break}break;case"scalar":try{const l=pi(n.T,e,n.L,!1);switch(l){case Qi:fa(n,t);break;default:t[s]=l;break}}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(It(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}function mv(t,e){if(t===D.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return pi(t,e,dn.BIGINT,!0).toString()}function pi(t,e,n,i){if(e===null)return i?Gn(t,n):Qi;switch(t){case D.DOUBLE:case D.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return t==D.FLOAT&&cl(r),r;case D.INT32:case D.FIXED32:case D.SFIXED32:case D.SINT32:case D.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return t==D.UINT32||t==D.FIXED32?us(s):Li(s),s;case D.INT64:case D.SFIXED64:case D.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=xe.parse(e);return n?a.toString():a;case D.FIXED64:case D.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=xe.uParse(e);return n?o.toString():o;case D.BOOL:if(typeof e!="boolean")break;return e;case D.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case D.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return vl.dec(e)}throw new Error}function Dr(t,e,n,i){if(e===null)return t.typeName=="google.protobuf.NullValue"?0:i?t.values[0].no:Qi;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const r=t.findName(e);if(r!==void 0)return r.no;if(n)return Ui;break}throw new Error("cannot decode enum ".concat(t.typeName," from JSON: ").concat(It(e)))}function gv(t){return t.repeated||t.kind=="map"?!0:!(t.oneof||t.kind=="message"||t.opt||t.req)}function va(t,e,n){if(t.kind=="map"){Ee(typeof e=="object"&&e!=null);const i={},r=Object.entries(e);switch(t.V.kind){case"scalar":for(const[a,o]of r)i[a.toString()]=Fi(t.V.T,o);break;case"message":for(const[a,o]of r)i[a.toString()]=o.toJson(n);break;case"enum":const s=t.V.T;for(const[a,o]of r)i[a.toString()]=Nr(s,o,n.enumAsInteger);break}return n.emitDefaultValues||r.length>0?i:void 0}if(t.repeated){Ee(Array.isArray(e));const i=[];switch(t.kind){case"scalar":for(let r=0;r<e.length;r++)i.push(Fi(t.T,e[r]));break;case"enum":for(let r=0;r<e.length;r++)i.push(Nr(t.T,e[r],n.enumAsInteger));break;case"message":for(let r=0;r<e.length;r++)i.push(e[r].toJson(n));break}return n.emitDefaultValues||i.length>0?i:void 0}switch(t.kind){case"scalar":return Fi(t.T,e);case"enum":return Nr(t.T,e,n.enumAsInteger);case"message":return Cl(t.T,e).toJson(n)}}function Nr(t,e,n){var i;if(Ee(typeof e=="number"),t.typeName=="google.protobuf.NullValue")return null;if(n)return e;const r=t.findNumber(e);return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:e}function Fi(t,e){switch(t){case D.INT32:case D.SFIXED32:case D.SINT32:case D.FIXED32:case D.UINT32:return Ee(typeof e=="number"),e;case D.FLOAT:case D.DOUBLE:return Ee(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case D.STRING:return Ee(typeof e=="string"),e;case D.BOOL:return Ee(typeof e=="boolean"),e;case D.UINT64:case D.FIXED64:case D.INT64:case D.SFIXED64:case D.SINT64:return Ee(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case D.BYTES:return Ee(e instanceof Uint8Array),vl.enc(e)}}const Mn=Symbol("@bufbuild/protobuf/unknown-fields"),ya={readUnknownFields:!0,readerFactory:t=>new ov(t)},ba={writeUnknownFields:!0,writerFactory:()=>new sv};function vv(t){return t?Object.assign(Object.assign({},ya),t):ya}function yv(t){return t?Object.assign(Object.assign({},ba),t):ba}function bv(){return{makeReadOptions:vv,makeWriteOptions:yv,listUnknownFields(t){var e;return(e=t[Mn])!==null&&e!==void 0?e:[]},discardUnknownFields(t){delete t[Mn]},writeUnknownFields(t,e){const i=t[Mn];if(i)for(const r of i)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(t,e,n,i){const r=t;Array.isArray(r[Mn])||(r[Mn]=[]),r[Mn].push({no:e,wireType:n,data:i})},readMessage(t,e,n,i,r){const s=t.getType(),a=r?e.len:e.pos+n;let o,c;for(;e.pos<a&&([o,c]=e.tag(),!(r===!0&&c==Ie.EndGroup));){const l=s.fields.find(o);if(!l){const u=e.skip(c,o);i.readUnknownFields&&this.onUnknownField(t,o,c,u);continue}ka(t,e,l,c,i)}if(r&&(c!=Ie.EndGroup||o!==n))throw new Error("invalid end group tag")},readField:ka,writeMessage(t,e,n){const i=t.getType();for(const r of i.fields.byNumber()){if(!kl(r,t)){if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));continue}const s=r.oneof?t[r.oneof.localName].value:t[r.localName];Ca(r,s,e,n)}return n.writeUnknownFields&&this.writeUnknownFields(t,e),e},writeField(t,e,n,i){e!==void 0&&Ca(t,e,n,i)}}}function ka(t,e,n,i,r){let{repeated:s,localName:a}=n;switch(n.oneof&&(t=t[n.oneof.localName],t.case!=a&&delete t.value,t.case=a,a="value"),n.kind){case"scalar":case"enum":const o=n.kind=="enum"?D.INT32:n.T;let c=Xi;if(n.kind=="scalar"&&n.L>0&&(c=Cv),s){let h=t[a];if(i==Ie.LengthDelimited&&o!=D.STRING&&o!=D.BYTES){let m=e.uint32()+e.pos;for(;e.pos<m;)h.push(c(e,o))}else h.push(c(e,o))}else t[a]=c(e,o);break;case"message":const l=n.T;s?t[a].push(Bi(e,new l,r,n)):Wt(t[a])?Bi(e,t[a],r,n):(t[a]=Bi(e,new l,r,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(t[a]=l.fieldWrapper.unwrapField(t[a])));break;case"map":let[u,d]=kv(n,e,r);t[a][u]=d;break}}function Bi(t,e,n,i){const r=e.getType().runtime.bin,s=i==null?void 0:i.delimited;return r.readMessage(e,t,s?i.no:t.uint32(),n,s),e}function kv(t,e,n){const i=e.uint32(),r=e.pos+i;let s,a;for(;e.pos<r;){const[o]=e.tag();switch(o){case 1:s=Xi(e,t.K);break;case 2:switch(t.V.kind){case"scalar":a=Xi(e,t.V.T);break;case"enum":a=e.int32();break;case"message":a=Bi(e,new t.V.T,n,void 0);break}break}}if(s===void 0&&(s=Gn(t.K,dn.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),a===void 0)switch(t.V.kind){case"scalar":a=Gn(t.V.T,dn.BIGINT);break;case"enum":a=t.V.T.values[0].no;break;case"message":a=new t.V.T;break}return[s,a]}function Cv(t,e){const n=Xi(t,e);return typeof n=="bigint"?n.toString():n}function Xi(t,e){switch(e){case D.STRING:return t.string();case D.BOOL:return t.bool();case D.DOUBLE:return t.double();case D.FLOAT:return t.float();case D.INT32:return t.int32();case D.INT64:return t.int64();case D.UINT64:return t.uint64();case D.FIXED64:return t.fixed64();case D.BYTES:return t.bytes();case D.FIXED32:return t.fixed32();case D.SFIXED32:return t.sfixed32();case D.SFIXED64:return t.sfixed64();case D.SINT64:return t.sint64();case D.UINT32:return t.uint32();case D.SINT32:return t.sint32()}}function Ca(t,e,n,i){Ee(e!==void 0);const r=t.repeated;switch(t.kind){case"scalar":case"enum":let s=t.kind=="enum"?D.INT32:t.T;if(r)if(Ee(Array.isArray(e)),t.packed)Tv(n,s,t.no,e);else for(const a of e)mi(n,s,t.no,a);else mi(n,s,t.no,e);break;case"message":if(r){Ee(Array.isArray(e));for(const a of e)Sa(n,i,t,a)}else Sa(n,i,t,e);break;case"map":Ee(typeof e=="object"&&e!=null);for(const[a,o]of Object.entries(e))Sv(n,i,t,a,o);break}}function Sv(t,e,n,i,r){t.tag(n.no,Ie.LengthDelimited),t.fork();let s=i;switch(n.K){case D.INT32:case D.FIXED32:case D.UINT32:case D.SFIXED32:case D.SINT32:s=Number.parseInt(i);break;case D.BOOL:Ee(i=="true"||i=="false"),s=i=="true";break}switch(mi(t,n.K,1,s),n.V.kind){case"scalar":mi(t,n.V.T,2,r);break;case"enum":mi(t,D.INT32,2,r);break;case"message":Ee(r!==void 0),t.tag(2,Ie.LengthDelimited).bytes(r.toBinary(e));break}t.join()}function Sa(t,e,n,i){const r=Cl(n.T,i);n.delimited?t.tag(n.no,Ie.StartGroup).raw(r.toBinary(e)).tag(n.no,Ie.EndGroup):t.tag(n.no,Ie.LengthDelimited).bytes(r.toBinary(e))}function mi(t,e,n,i){Ee(i!==void 0);let[r,s]=Sl(e);t.tag(n,r)[s](i)}function Tv(t,e,n,i){if(!i.length)return;t.tag(n,Ie.LengthDelimited).fork();let[,r]=Sl(e);for(let s=0;s<i.length;s++)t[r](i[s]);t.join()}function Sl(t){let e=Ie.Varint;switch(t){case D.BYTES:case D.STRING:e=Ie.LengthDelimited;break;case D.DOUBLE:case D.FIXED64:case D.SFIXED64:e=Ie.Bit64;break;case D.FIXED32:case D.SFIXED32:case D.FLOAT:e=Ie.Bit32;break}const n=D[t].toLowerCase();return[e,n]}function wv(){return{setEnumType:ul,initPartial(t,e){if(t===void 0)return;const n=e.getType();for(const i of n.fields.byMember()){const r=i.localName,s=e,a=t;if(a[r]!=null)switch(i.kind){case"oneof":const o=a[r].case;if(o===void 0)continue;const c=i.findField(o);let l=a[r].value;c&&c.kind=="message"&&!Wt(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===D.BYTES&&(l=ii(l)),s[r]={case:o,value:l};break;case"scalar":case"enum":let u=a[r];i.T===D.BYTES&&(u=i.repeated?u.map(ii):ii(u)),s[r]=u;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===D.BYTES)for(const[f,m]of Object.entries(a[r]))s[r][f]=ii(m);else Object.assign(s[r],a[r]);break;case"message":const h=i.V.T;for(const f of Object.keys(a[r])){let m=a[r][f];h.fieldWrapper||(m=new h(m)),s[r][f]=m}break}break;case"message":const d=i.T;if(i.repeated)s[r]=a[r].map(h=>Wt(h,d)?h:new d(h));else{const h=a[r];d.fieldWrapper?d.typeName==="google.protobuf.BytesValue"?s[r]=ii(h):s[r]=h:s[r]=Wt(h,d)?h:new d(h)}break}}},equals(t,e,n){return e===n?!0:!e||!n?!1:t.fields.byMember().every(i=>{const r=e[i.localName],s=n[i.localName];if(i.repeated){if(r.length!==s.length)return!1;switch(i.kind){case"message":return r.every((a,o)=>i.T.equals(a,s[o]));case"scalar":return r.every((a,o)=>Zt(i.T,a,s[o]));case"enum":return r.every((a,o)=>Zt(D.INT32,a,s[o]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let a=r,o=s;return i.T.fieldWrapper&&(a!==void 0&&!Wt(a)&&(a=i.T.fieldWrapper.wrapField(a)),o!==void 0&&!Wt(o)&&(o=i.T.fieldWrapper.wrapField(o))),i.T.equals(a,o);case"enum":return Zt(D.INT32,r,s);case"scalar":return Zt(i.T,r,s);case"oneof":if(r.case!==s.case)return!1;const c=i.findField(r.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(r.value,s.value);case"enum":return Zt(D.INT32,r.value,s.value);case"scalar":return Zt(c.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const l=Object.keys(r).concat(Object.keys(s));switch(i.V.kind){case"message":const u=i.V.T;return l.every(h=>u.equals(r[h],s[h]));case"enum":return l.every(h=>Zt(D.INT32,r[h],s[h]));case"scalar":const d=i.V.T;return l.every(h=>Zt(d,r[h],s[h]))}break}})},clone(t){const e=t.getType(),n=new e,i=n;for(const r of e.fields.byMember()){const s=t[r.localName];let a;if(r.repeated)a=s.map(Ai);else if(r.kind=="map"){a=i[r.localName];for(const[o,c]of Object.entries(s))a[o]=Ai(c)}else r.kind=="oneof"?a=r.findField(s.case)?{case:s.case,value:Ai(s.value)}:{case:void 0}:a=Ai(s);i[r.localName]=a}for(const r of e.runtime.bin.listUnknownFields(t))e.runtime.bin.onUnknownField(i,r.no,r.wireType,r.data);return n}}}function Ai(t){if(t===void 0)return t;if(Wt(t))return t.clone();if(t instanceof Uint8Array){const e=new Uint8Array(t.byteLength);return e.set(t),e}return t}function ii(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function xv(t,e,n){return{syntax:t,json:pv(),bin:bv(),util:Object.assign(Object.assign({},wv()),{newFieldList:e,initFields:n}),makeMessageType(i,r,s){return Zg(this,i,r,s)},makeEnum:Xg,makeEnumType:dl,getEnumType:Qg,makeExtension(i,r,s){return av(this,i,r,s)}}}class _v{constructor(e,n){this._fields=e,this._normalizer=n}findJsonName(e){if(!this.jsonNames){const n={};for(const i of this.list())n[i.jsonName]=n[i.name]=i;this.jsonNames=n}return this.jsonNames[e]}find(e){if(!this.numbers){const n={};for(const i of this.list())n[i.no]=i;this.numbers=n}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,n)=>e.no-n.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let n;for(const i of this.list())i.oneof?i.oneof!==n&&(n=i.oneof,e.push(n)):e.push(i)}return this.members}}function Tl(t,e){const n=wl(t);return e?n:Ov(Mv(n))}function Ev(t){return Tl(t,!1)}const Pv=wl;function wl(t){let e=!1;const n=[];for(let i=0;i<t.length;i++){let r=t.charAt(i);switch(r){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),e=!1;break;default:e&&(e=!1,r=r.toUpperCase()),n.push(r);break}}return n.join("")}const Rv=new Set(["constructor","toString","toJSON","valueOf"]),Iv=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),xl=t=>"".concat(t,"$"),Mv=t=>Iv.has(t)?xl(t):t,Ov=t=>Rv.has(t)?xl(t):t;class Av{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Ev(e)}addField(e){Ee(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let n=0;n<this.fields.length;n++)this._lookup[this.fields[n].localName]=this.fields[n]}return this._lookup[e]}}function Dv(t,e){var n,i,r,s,a,o;const c=[];let l;for(const u of typeof t=="function"?t():t){const d=u;if(d.localName=Tl(u.name,u.oneof!==void 0),d.jsonName=(n=u.jsonName)!==null&&n!==void 0?n:Pv(u.name),d.repeated=(i=u.repeated)!==null&&i!==void 0?i:!1,u.kind=="scalar"&&(d.L=(r=u.L)!==null&&r!==void 0?r:dn.BIGINT),d.delimited=(s=u.delimited)!==null&&s!==void 0?s:!1,d.req=(a=u.req)!==null&&a!==void 0?a:!1,d.opt=(o=u.opt)!==null&&o!==void 0?o:!1,u.packed===void 0&&(d.packed=u.kind=="enum"||u.kind=="scalar"&&u.T!=D.BYTES&&u.T!=D.STRING),u.oneof!==void 0){const h=typeof u.oneof=="string"?u.oneof:u.oneof.name;(!l||l.name!=h)&&(l=new Av(h)),d.oneof=l,l.addField(d)}c.push(d)}return c}const x=xv("proto3",t=>new _v(t,e=>Dv(e)),t=>{for(const e of t.getType().fields.byMember()){if(e.opt)continue;const n=e.localName,i=t;if(e.repeated){i[n]=[];continue}switch(e.kind){case"oneof":i[n]={case:void 0};break;case"enum":i[n]=0;break;case"map":i[n]={};break;case"scalar":i[n]=Gn(e.T,e.L);break}}});class et extends Qs{constructor(e){super(),this.seconds=xe.zero,this.nanos=0,x.util.initPartial(e,this)}fromJson(e,n){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(x.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const r=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=xe.parse(r/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const n=Number(this.seconds)*1e3;if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?i="."+r.substring(0,3)+"Z":r.substring(6)==="000"?i="."+r.substring(0,6)+"Z":i="."+r+"Z"}return new Date(n).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return et.fromDate(new Date)}static fromDate(e){const n=e.getTime();return new et({seconds:xe.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(e,n){return new et().fromBinary(e,n)}static fromJson(e,n){return new et().fromJson(e,n)}static fromJsonString(e,n){return new et().fromJsonString(e,n)}static equals(e,n){return x.util.equals(et,e,n)}}et.runtime=x;et.typeName="google.protobuf.Timestamp";et.fields=x.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Nv=x.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:et},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Lv,repeated:!0},{no:5,name:"events",kind:"message",T:Uv,repeated:!0}]),Lv=x.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:jv,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),jv=x.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:et},{no:3,name:"value",kind:"scalar",T:2}]),Uv=x.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:et},{no:7,name:"normalized_end_timestamp",kind:"message",T:et,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),_l=x.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),St=x.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Ae=x.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Zs=x.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),li=x.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),bi=x.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),xt=x.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),Cn=x.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),Fv=x.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Ue=x.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),hr=x.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:Zi,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:Fl}]),Zi=x.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Bv=x.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:x.getEnumType(Ae),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),Tn=x.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:x.getEnumType(Un)},{no:4,name:"tracks",kind:"message",T:An,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:Bv},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:x.getEnumType(ki)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:x.getEnumType(xt)},{no:18,name:"kind_details",kind:"enum",T:x.getEnumType(Vv),repeated:!0}]),Un=x.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ki=x.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"}]),Vv=x.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Le=x.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),qv=x.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:cn,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:x.getEnumType(El)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),An=x.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:x.getEnumType(St)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:x.getEnumType(Ae)},{no:10,name:"layers",kind:"message",T:cn,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:qv,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:x.getEnumType(Le)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Fl},{no:19,name:"audio_features",kind:"enum",T:x.getEnumType(Ue),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:x.getEnumType(_l)}]),cn=x.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:x.getEnumType(Zs)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),El=x.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),Je=x.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:x.getEnumType(ue)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:eo,oneof:"value"},{no:3,name:"speaker",kind:"message",T:zv,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Ml,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Wv,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Nv,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:er,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:to,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:no,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:io,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:tr,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:nr,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:ir,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Pl,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),ue=x.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Pl=x.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:x.getEnumType(Le)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),Rl=x.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:eo,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:er,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:to,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:no,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:io,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:tr,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:nr,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:ir,oneof:"value"}]),zv=x.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Il,repeated:!0}]),Il=x.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),eo=x.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),Ml=x.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Wv=x.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:Hv,repeated:!0}]),Hv=x.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),er=x.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),to=x.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),no=x.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),io=x.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Ol,oneof:"value"}]),Ol=x.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),Al=x.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Dl=x.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:x.getEnumType(Nl)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),Nl=x.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Ll=x.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:x.getEnumType(jl)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),jl=x.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),Ul=x.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Ta},{no:2,name:"screen",kind:"message",T:Ta},{no:3,name:"resume_connection",kind:"enum",T:x.getEnumType(bi)},{no:4,name:"disabled_codecs",kind:"message",T:Kv},{no:5,name:"force_relay",kind:"enum",T:x.getEnumType(bi)}]),Ta=x.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:x.getEnumType(bi)}]),Kv=x.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Zi,repeated:!0},{no:2,name:"publish",kind:"message",T:Zi,repeated:!0}]),Fl=x.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),ds=x.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Bl=x.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:x.getEnumType(ds)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),Vl=x.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),tr=x.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:x.getEnumType(Le)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Bl,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Vl,oneof:"content_header"}],{localName:"DataStream_Header"}),nr=x.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),ir=x.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),Gv=x.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),Tt=x.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),hs=x.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),$v=x.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Jv=x.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:hn,oneof:"message"},{no:2,name:"answer",kind:"message",T:hn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:fr,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Ci,oneof:"message"},{no:5,name:"mute",kind:"message",T:pr,oneof:"message"},{no:6,name:"subscription",kind:"message",T:mr,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ql,oneof:"message"},{no:8,name:"leave",kind:"message",T:gr,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Wl,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Gl,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:co,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Pt,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:oo,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Yl,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:so,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:zl,oneof:"message"}]),wa=x.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Yv,oneof:"message"},{no:2,name:"answer",kind:"message",T:hn,oneof:"message"},{no:3,name:"offer",kind:"message",T:hn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:fr,oneof:"message"},{no:5,name:"update",kind:"message",T:Zv,oneof:"message"},{no:6,name:"track_published",kind:"message",T:ro,oneof:"message"},{no:8,name:"leave",kind:"message",T:gr,oneof:"message"},{no:9,name:"mute",kind:"message",T:pr,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:e0,oneof:"message"},{no:11,name:"room_update",kind:"message",T:t0,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:i0,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:s0,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:a0,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:l0,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Xv,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Qv,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:d0,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:p0,oneof:"message"},{no:22,name:"request_response",kind:"message",T:m0,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:g0,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:u0,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:k0,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:c0,oneof:"message"}]),fs=x.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:cn,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:x.getEnumType(El)}]),Ci=x.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:x.getEnumType(St)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:x.getEnumType(Ae)},{no:9,name:"layers",kind:"message",T:cn,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:fs,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:x.getEnumType(Le)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:x.getEnumType(_l)},{no:17,name:"audio_features",kind:"enum",T:x.getEnumType(Ue),repeated:!0}]),fr=x.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:x.getEnumType(Tt)},{no:3,name:"final",kind:"scalar",T:8}]),pr=x.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Yv=x.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:hr},{no:2,name:"participant",kind:"message",T:Tn},{no:3,name:"other_participants",kind:"message",T:Tn,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Hl,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:Ul},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:Dl},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Zi,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Qv=x.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Hl,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Ul},{no:3,name:"server_info",kind:"message",T:Dl},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),ro=x.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:An}]),Xv=x.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),hn=x.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),Zv=x.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Tn,repeated:!0}]),mr=x.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:Al,repeated:!0}]),ql=x.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:x.getEnumType(Zs)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),so=x.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:x.getEnumType(Ue),repeated:!0}]),zl=x.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),gr=x.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:x.getEnumType(xt)},{no:3,name:"action",kind:"enum",T:x.getEnumType(Fn)},{no:4,name:"regions",kind:"message",T:h0}]),Fn=x.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Wl=x.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:cn,repeated:!0}]),oo=x.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),Hl=x.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),e0=x.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Il,repeated:!0}]),t0=x.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:hr}]),n0=x.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:x.getEnumType(li)},{no:3,name:"score",kind:"scalar",T:2}]),i0=x.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:n0,repeated:!0}]),r0=x.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:x.getEnumType(hs)}]),s0=x.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:r0,repeated:!0}]),ao=x.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:x.getEnumType(Zs)},{no:2,name:"enabled",kind:"scalar",T:8}]),o0=x.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ao,repeated:!0}]),a0=x.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ao,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:o0,repeated:!0}]),c0=x.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Gv,repeated:!0}]),Kl=x.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),Gl=x.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Kl,repeated:!0}]),l0=x.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),u0=x.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:hr},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Tn},{no:4,name:"other_participants",kind:"message",T:Tn,repeated:!0}]),co=x.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:hn},{no:2,name:"subscription",kind:"message",T:mr},{no:3,name:"publish_tracks",kind:"message",T:ro,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Jl,repeated:!0},{no:5,name:"offer",kind:"message",T:hn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:$l,repeated:!0}]),$l=x.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Jl=x.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:x.getEnumType(Tt)}]),Pt=x.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:x.getEnumType($v),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),Yl=x.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),d0=x.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),h0=x.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:f0,repeated:!0}]),f0=x.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),p0=x.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:x.getEnumType(Fv)}]),m0=x.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:x.getEnumType(lo)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:fr,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Ci,oneof:"request"},{no:6,name:"mute",kind:"message",T:pr,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:oo,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:so,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:zl,oneof:"request"}]),lo=x.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"}]),g0=x.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Ql=x.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8}]),v0=x.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Ll},{no:2,name:"connection_settings",kind:"message",T:Ql},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:Ci,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:hn},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:x.getEnumType(Cn)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:co}]),y0=x.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:x.getEnumType(b0)},{no:2,name:"join_request",kind:"scalar",T:12}]),b0=x.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),k0=x.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function C0(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Vi={exports:{}},S0=Vi.exports,xa;function T0(){return xa||(xa=1,(function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(S0,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},a=null;function o(g,w){var b=g[w];if(typeof b.bind=="function")return b.bind(g);try{return Function.prototype.bind.call(b,g)}catch{return function(){return Function.prototype.apply.apply(b,[g,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(g){return g==="debug"&&(g="log"),typeof console===n?!1:g==="trace"&&i?c:console[g]!==void 0?o(console,g):console.log!==void 0?o(console,"log"):e}function u(){for(var g=this.getLevel(),w=0;w<r.length;w++){var b=r[w];this[b]=w<g?e:this.methodFactory(b,g,this.name)}if(this.log=this.debug,typeof console===n&&g<this.levels.SILENT)return"No console available for logging"}function d(g){return function(){typeof console!==n&&(u.call(this),this[g].apply(this,arguments))}}function h(g,w,b){return l(g)||d.apply(this,arguments)}function f(g,w){var b=this,P,_,S,T="loglevel";typeof g=="string"?T+=":"+g:typeof g=="symbol"&&(T=void 0);function C(R){var N=(r[R]||"silent").toUpperCase();if(!(typeof window===n||!T)){try{window.localStorage[T]=N;return}catch{}try{window.document.cookie=encodeURIComponent(T)+"="+N+";"}catch{}}}function O(){var R;if(!(typeof window===n||!T)){try{R=window.localStorage[T]}catch{}if(typeof R===n)try{var N=window.document.cookie,Y=encodeURIComponent(T),G=N.indexOf(Y+"=");G!==-1&&(R=/^([^;]+)/.exec(N.slice(G+Y.length+1))[1])}catch{}return b.levels[R]===void 0&&(R=void 0),R}}function L(){if(!(typeof window===n||!T)){try{window.localStorage.removeItem(T)}catch{}try{window.document.cookie=encodeURIComponent(T)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function I(R){var N=R;if(typeof N=="string"&&b.levels[N.toUpperCase()]!==void 0&&(N=b.levels[N.toUpperCase()]),typeof N=="number"&&N>=0&&N<=b.levels.SILENT)return N;throw new TypeError("log.setLevel() called with invalid level: "+R)}b.name=g,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=w||h,b.getLevel=function(){return S??_??P},b.setLevel=function(R,N){return S=I(R),N!==!1&&C(S),u.call(b)},b.setDefaultLevel=function(R){_=I(R),O()||b.setLevel(R,!1)},b.resetLevel=function(){S=null,L(),u.call(b)},b.enableAll=function(R){b.setLevel(b.levels.TRACE,R)},b.disableAll=function(R){b.setLevel(b.levels.SILENT,R)},b.rebuild=function(){if(a!==b&&(P=I(a.getLevel())),u.call(b),a===b)for(var R in s)s[R].rebuild()},P=I(a?a.getLevel():"WARN");var A=O();A!=null&&(S=I(A)),u.call(b)}a=new f,a.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var b=s[w];return b||(b=s[w]=new f(w,a.methodFactory)),b};var m=typeof window!==n?window.log:void 0;return a.noConflict=function(){return typeof window!==n&&window.log===a&&(window.log=m),a},a.getLoggers=function(){return s},a.default=a,a})})(Vi)),Vi.exports}var vr=T0(),ps;(function(t){t[t.trace=0]="trace",t[t.debug=1]="debug",t[t.info=2]="info",t[t.warn=3]="warn",t[t.error=4]="error",t[t.silent=5]="silent"})(ps||(ps={}));var _t;(function(t){t.Default="livekit",t.Room="livekit-room",t.TokenSource="livekit-token-source",t.Participant="livekit-participant",t.Track="livekit-track",t.Publication="livekit-track-publication",t.Engine="livekit-engine",t.Signal="livekit-signal",t.PCManager="livekit-pc-manager",t.PCTransport="livekit-pc-transport",t.E2EE="lk-e2ee"})(_t||(_t={}));let ce=vr.getLogger("livekit");Object.values(_t).map(t=>vr.getLogger(t));ce.setDefaultLevel(ps.info);function Gt(t){const e=vr.getLogger(t);return e.setDefaultLevel(ce.getLevel()),e}const w0=vr.getLogger("lk-e2ee"),ri=7e3,x0=[0,300,4*300,9*300,16*300,ri,ri,ri,ri,ri];class _0{constructor(e){this._retryDelays=e!==void 0?[...e]:x0}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const n=this._retryDelays[e.retryCount];return e.retryCount<=1?n:n+Math.random()*1e3}}function E0(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(n[i[r]]=t[i[r]]);return n}function v(t,e,n,i){function r(s){return s instanceof n?s:new n(function(a){a(s)})}return new(n||(n=Promise))(function(s,a){function o(u){try{l(i.next(u))}catch(d){a(d)}}function c(u){try{l(i.throw(u))}catch(d){a(d)}}function l(u){u.done?s(u.value):r(u.value).then(o,c)}l((i=i.apply(t,e||[])).next())})}function _a(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ht(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof _a=="function"?_a(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(s){n[s]=t[s]&&function(a){return new Promise(function(o,c){a=t[s](a),r(o,c,a.done,a.value)})}}function r(s,a,o,c){Promise.resolve(c).then(function(l){s({value:l,done:o})},a)}}var Di={exports:{}},Ea;function P0(){if(Ea)return Di.exports;Ea=1;var t=typeof Reflect=="object"?Reflect:null,e=t&&typeof t.apply=="function"?t.apply:function(T,C,O){return Function.prototype.apply.call(T,C,O)},n;t&&typeof t.ownKeys=="function"?n=t.ownKeys:Object.getOwnPropertySymbols?n=function(T){return Object.getOwnPropertyNames(T).concat(Object.getOwnPropertySymbols(T))}:n=function(T){return Object.getOwnPropertyNames(T)};function i(S){console&&console.warn&&console.warn(S)}var r=Number.isNaN||function(T){return T!==T};function s(){s.init.call(this)}Di.exports=s,Di.exports.once=b,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||r(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(T){if(typeof T!="number"||T<0||r(T))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+T+".");return this._maxListeners=T,this};function c(S){return S._maxListeners===void 0?s.defaultMaxListeners:S._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(T){for(var C=[],O=1;O<arguments.length;O++)C.push(arguments[O]);var L=T==="error",I=this._events;if(I!==void 0)L=L&&I.error===void 0;else if(!L)return!1;if(L){var A;if(C.length>0&&(A=C[0]),A instanceof Error)throw A;var R=new Error("Unhandled error."+(A?" ("+A.message+")":""));throw R.context=A,R}var N=I[T];if(N===void 0)return!1;if(typeof N=="function")e(N,this,C);else for(var Y=N.length,G=m(N,Y),O=0;O<Y;++O)e(G[O],this,C);return!0};function l(S,T,C,O){var L,I,A;if(o(C),I=S._events,I===void 0?(I=S._events=Object.create(null),S._eventsCount=0):(I.newListener!==void 0&&(S.emit("newListener",T,C.listener?C.listener:C),I=S._events),A=I[T]),A===void 0)A=I[T]=C,++S._eventsCount;else if(typeof A=="function"?A=I[T]=O?[C,A]:[A,C]:O?A.unshift(C):A.push(C),L=c(S),L>0&&A.length>L&&!A.warned){A.warned=!0;var R=new Error("Possible EventEmitter memory leak detected. "+A.length+" "+String(T)+" listeners added. Use emitter.setMaxListeners() to increase limit");R.name="MaxListenersExceededWarning",R.emitter=S,R.type=T,R.count=A.length,i(R)}return S}s.prototype.addListener=function(T,C){return l(this,T,C,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(T,C){return l(this,T,C,!0)};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 d(S,T,C){var O={fired:!1,wrapFn:void 0,target:S,type:T,listener:C},L=u.bind(O);return L.listener=C,O.wrapFn=L,L}s.prototype.once=function(T,C){return o(C),this.on(T,d(this,T,C)),this},s.prototype.prependOnceListener=function(T,C){return o(C),this.prependListener(T,d(this,T,C)),this},s.prototype.removeListener=function(T,C){var O,L,I,A,R;if(o(C),L=this._events,L===void 0)return this;if(O=L[T],O===void 0)return this;if(O===C||O.listener===C)--this._eventsCount===0?this._events=Object.create(null):(delete L[T],L.removeListener&&this.emit("removeListener",T,O.listener||C));else if(typeof O!="function"){for(I=-1,A=O.length-1;A>=0;A--)if(O[A]===C||O[A].listener===C){R=O[A].listener,I=A;break}if(I<0)return this;I===0?O.shift():g(O,I),O.length===1&&(L[T]=O[0]),L.removeListener!==void 0&&this.emit("removeListener",T,R||C)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(T){var C,O,L;if(O=this._events,O===void 0)return this;if(O.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):O[T]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete O[T]),this;if(arguments.length===0){var I=Object.keys(O),A;for(L=0;L<I.length;++L)A=I[L],A!=="removeListener"&&this.removeAllListeners(A);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(C=O[T],typeof C=="function")this.removeListener(T,C);else if(C!==void 0)for(L=C.length-1;L>=0;L--)this.removeListener(T,C[L]);return this};function h(S,T,C){var O=S._events;if(O===void 0)return[];var L=O[T];return L===void 0?[]:typeof L=="function"?C?[L.listener||L]:[L]:C?w(L):m(L,L.length)}s.prototype.listeners=function(T){return h(this,T,!0)},s.prototype.rawListeners=function(T){return h(this,T,!1)},s.listenerCount=function(S,T){return typeof S.listenerCount=="function"?S.listenerCount(T):f.call(S,T)},s.prototype.listenerCount=f;function f(S){var T=this._events;if(T!==void 0){var C=T[S];if(typeof C=="function")return 1;if(C!==void 0)return C.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function m(S,T){for(var C=new Array(T),O=0;O<T;++O)C[O]=S[O];return C}function g(S,T){for(;T+1<S.length;T++)S[T]=S[T+1];S.pop()}function w(S){for(var T=new Array(S.length),C=0;C<T.length;++C)T[C]=S[C].listener||S[C];return T}function b(S,T){return new Promise(function(C,O){function L(A){S.removeListener(T,I),O(A)}function I(){typeof S.removeListener=="function"&&S.removeListener("error",L),C([].slice.call(arguments))}_(S,T,I,{once:!0}),T!=="error"&&P(S,L,{once:!0})})}function P(S,T,C){typeof S.on=="function"&&_(S,"error",T,C)}function _(S,T,C,O){if(typeof S.on=="function")O.once?S.once(T,C):S.on(T,C);else if(typeof S.addEventListener=="function")S.addEventListener(T,function L(I){O.once&&S.removeEventListener(T,L),C(I)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof S)}return Di.exports}var Lt=P0();let Xl=!0,Zl=!0;function ui(t,e,n){const i=t.match(e);return i&&i.length>=n&&parseFloat(i[n],10)}function En(t,e,n){if(!t.RTCPeerConnection)return;const i=t.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return r.apply(this,arguments);const c=l=>{const u=n(l);u&&(o.handleEvent?o.handleEvent(u):o(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),r.apply(this,[a,c])};const s=i.removeEventListener;i.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(o))return s.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[a,c])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function R0(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(Xl=t,t?"adapter.js logging disabled":"adapter.js logging enabled")}function I0(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(Zl=!t,"adapter.js deprecation warnings "+(t?"disabled":"enabled"))}function eu(){if(typeof window=="object"){if(Xl)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function uo(t,e){Zl&&console.warn(t+" is deprecated, please use "+e+" instead.")}function M0(t){const e={browser:null,version:null};if(typeof t>"u"||!t.navigator||!t.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:n}=t;if(n.userAgentData&&n.userAgentData.brands){const i=n.userAgentData.brands.find(r=>r.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(n.mozGetUserMedia)e.browser="firefox",e.version=parseInt(ui(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||t.isSecureContext===!1&&t.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(ui(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(t.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(ui(n.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=t.RTCRtpTransceiver&&"currentDirection"in t.RTCRtpTransceiver.prototype,e._safariVersion=ui(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function Pa(t){return Object.prototype.toString.call(t)==="[object Object]"}function tu(t){return Pa(t)?Object.keys(t).reduce(function(e,n){const i=Pa(t[n]),r=i?tu(t[n]):t[n],s=i&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[n]:r})},{}):t}function ms(t,e,n){!e||n.has(e.id)||(n.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?ms(t,t.get(e[i]),n):i.endsWith("Ids")&&e[i].forEach(r=>{ms(t,t.get(r),n)})}))}function Ra(t,e,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return t.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{t.forEach(o=>{o.type===i&&o.trackId===a.id&&ms(t,o,r)})}),r}const Ia=eu;function nu(t,e){const n=t&&t.navigator;if(!n.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const u=typeof o[l]=="object"?o[l]:{ideal:o[l]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const d=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(u.ideal!==void 0){c.optional=c.optional||[];let h={};typeof u.ideal=="number"?(h[d("min",l)]=u.ideal,c.optional.push(h),h={},h[d("max",l)]=u.ideal,c.optional.push(h)):(h[d("",l)]=u.ideal,c.optional.push(h))}u.exact!==void 0&&typeof u.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[d("",l)]=u.exact):["min","max"].forEach(h=>{u[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[d(h,l)]=u[h])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},r=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const l=function(u,d,h){d in u&&!(h in u)&&(u[h]=u[d],delete u[d])};o=JSON.parse(JSON.stringify(o)),l(o.audio,"autoGainControl","googAutoGainControl"),l(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let l=o.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const u=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete o.video.facingMode;let d;if(l.exact==="environment"||l.ideal==="environment"?d=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(d=["front"]),d)return n.mediaDevices.enumerateDevices().then(h=>{h=h.filter(m=>m.kind==="videoinput");let f=h.find(m=>d.some(g=>m.label.toLowerCase().includes(g)));return!f&&h.length&&d.includes("back")&&(f=h[h.length-1]),f&&(o.video.deviceId=l.exact?{exact:f.deviceId}:{ideal:f.deviceId}),o.video=i(o.video),Ia("chrome: "+JSON.stringify(o)),c(o)})}o.video=i(o.video)}return Ia("chrome: "+JSON.stringify(o)),c(o)},s=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,l){r(o,u=>{n.webkitGetUserMedia(u,c,d=>{l&&l(s(d))})})};if(n.getUserMedia=a.bind(n),n.mediaDevices.getUserMedia){const o=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(c){return r(c,l=>o(l).then(u=>{if(l.audio&&!u.getAudioTracks().length||l.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(d=>{d.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function iu(t){t.MediaStream=t.MediaStream||t.webkitMediaStream}function ru(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("ontrack"in t.RTCPeerConnection.prototype)){Object.defineProperty(t.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(n){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=n)},enumerable:!0,configurable:!0});const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",r=>{let s;t.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===r.track.id):s={track:r.track};const a=new Event("track");a.track=r.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(r=>{let s;t.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===r.id):s={track:r};const a=new Event("track");a.track=r,a.receiver=s,a.transceiver={receiver:s},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else En(t,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function su(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("getSenders"in t.RTCPeerConnection.prototype)&&"createDTMFSender"in t.RTCPeerConnection.prototype){const e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!t.RTCPeerConnection.prototype.getSenders){t.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(o,c){let l=r.apply(this,arguments);return l||(l=e(this,o),this._senders.push(l)),l};const s=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const c=this._senders.indexOf(o);c!==-1&&this._senders.splice(c,1)}}const n=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.apply(this,[s]),s.getTracks().forEach(a=>{const o=this._senders.find(c=>c.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof t=="object"&&t.RTCPeerConnection&&"getSenders"in t.RTCPeerConnection.prototype&&"createDTMFSender"in t.RTCPeerConnection.prototype&&t.RTCRtpSender&&!("dtmf"in t.RTCRtpSender.prototype)){const e=t.RTCPeerConnection.prototype.getSenders;t.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i},Object.defineProperty(t.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ou(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender&&t.RTCRtpReceiver))return;if(!("getStats"in t.RTCRtpSender.prototype)){const n=t.RTCPeerConnection.prototype.getSenders;n&&(t.RTCPeerConnection.prototype.getSenders=function(){const s=n.apply(this,[]);return s.forEach(a=>a._pc=this),s});const i=t.RTCPeerConnection.prototype.addTrack;i&&(t.RTCPeerConnection.prototype.addTrack=function(){const s=i.apply(this,arguments);return s._pc=this,s}),t.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>Ra(a,s.track,!0))}}if(!("getStats"in t.RTCRtpReceiver.prototype)){const n=t.RTCPeerConnection.prototype.getReceivers;n&&(t.RTCPeerConnection.prototype.getReceivers=function(){const r=n.apply(this,[]);return r.forEach(s=>s._pc=this),r}),En(t,"track",i=>(i.receiver._pc=i.srcElement,i)),t.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>Ra(s,r.track,!1))}}if(!("getStats"in t.RTCRtpSender.prototype&&"getStats"in t.RTCRtpReceiver.prototype))return;const e=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof t.MediaStreamTrack){const i=arguments[0];let r,s,a;return this.getSenders().forEach(o=>{o.track===i&&(r?a=!0:r=o)}),this.getReceivers().forEach(o=>(o.track===i&&(s?a=!0:s=o),o.track===i)),a||r&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function au(t){t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const n=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(l=>{if(this.getSenders().find(d=>d.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();n.apply(this,arguments);const c=this.getSenders().filter(l=>o.indexOf(l)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const i=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const r=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),r.apply(this,arguments)}}function cu(t,e){if(!t.RTCPeerConnection)return;if(t.RTCPeerConnection.prototype.addTrack&&e.version>=65)return au(t);const n=t.RTCPeerConnection.prototype.getLocalStreams;t.RTCPeerConnection.prototype.getLocalStreams=function(){const u=n.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(d=>this._reverseStreams[d.id])};const i=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(d=>{if(this.getSenders().find(f=>f.track===d))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const d=new t.MediaStream(u.getTracks());this._streams[u.id]=d,this._reverseStreams[d.id]=u,u=d}i.apply(this,[u])};const r=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},t.RTCPeerConnection.prototype.addTrack=function(u,d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(g=>g===u))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(g=>g.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const m=this._streams[d.id];if(m)m.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new t.MediaStream([u]);this._streams[d.id]=g,this._reverseStreams[g.id]=d,this.addStream(g)}return this.getSenders().find(g=>g.track===u)};function s(l,u){let d=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],m=l._streams[f.id];d=d.replace(new RegExp(m.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:d})}function a(l,u){let d=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],m=l._streams[f.id];d=d.replace(new RegExp(f.id,"g"),m.id)}),new RTCSessionDescription({type:u.type,sdp:d})}["createOffer","createAnswer"].forEach(function(l){const u=t.RTCPeerConnection.prototype[l],d={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[m=>{const g=s(this,m);h[0].apply(null,[g])},m=>{h[1]&&h[1].apply(null,m)},arguments[2]]):u.apply(this,arguments).then(m=>s(this,m))}};t.RTCPeerConnection.prototype[l]=d[l]});const o=t.RTCPeerConnection.prototype.setLocalDescription;t.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(t.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(t.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:s(this,l)}}),t.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(g=>u.track===g)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function gs(t,e){!t.RTCPeerConnection&&t.webkitRTCPeerConnection&&(t.RTCPeerConnection=t.webkitRTCPeerConnection),t.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){const i=t.RTCPeerConnection.prototype[n],r={[n](){return arguments[0]=new(n==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};t.RTCPeerConnection.prototype[n]=r[n]})}function lu(t,e){En(t,"negotiationneeded",n=>{const i=n.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return n})}var Ma=Object.freeze({__proto__:null,fixNegotiationNeeded:lu,shimAddTrackRemoveTrack:cu,shimAddTrackRemoveTrackWithNative:au,shimGetSendersWithDtmf:su,shimGetUserMedia:nu,shimMediaStream:iu,shimOnTrack:ru,shimPeerConnection:gs,shimSenderReceiverGetStats:ou});function uu(t,e){const n=t&&t.navigator,i=t&&t.MediaStreamTrack;if(n.getUserMedia=function(r,s,a){uo("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(r).then(s,a)},!(e.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const r=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},s=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a.audio,"autoGainControl","mozAutoGainControl"),r(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return r(o,"mozAutoGainControl","autoGainControl"),r(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o,"autoGainControl","mozAutoGainControl"),r(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function O0(t,e){t.navigator.mediaDevices&&"getDisplayMedia"in t.navigator.mediaDevices||t.navigator.mediaDevices&&(t.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,t.navigator.mediaDevices.getUserMedia(i)})}function du(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function vs(t,e){if(typeof t!="object"||!(t.RTCPeerConnection||t.mozRTCPeerConnection))return;!t.RTCPeerConnection&&t.mozRTCPeerConnection&&(t.RTCPeerConnection=t.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const s=t.RTCPeerConnection.prototype[r],a={[r](){return arguments[0]=new(r==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};t.RTCPeerConnection.prototype[r]=a[r]});const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){const[s,a,o]=arguments;return i.apply(this,[s||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(l=>{l.type=n[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((u,d)=>{c.set(d,Object.assign({},u,{type:n[u.type]||u.type}))})}return c}).then(a,o)}}function hu(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender)||t.RTCRtpSender&&"getStats"in t.RTCRtpSender.prototype)return;const e=t.RTCPeerConnection.prototype.getSenders;e&&(t.RTCPeerConnection.prototype.getSenders=function(){const r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});const n=t.RTCPeerConnection.prototype.addTrack;n&&(t.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),t.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function fu(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender)||t.RTCRtpSender&&"getStats"in t.RTCRtpReceiver.prototype)return;const e=t.RTCPeerConnection.prototype.getReceivers;e&&(t.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i}),En(t,"track",n=>(n.receiver._pc=n.srcElement,n)),t.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function pu(t){!t.RTCPeerConnection||"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(n){uo("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&n.getTracks().includes(i.track)&&this.removeTrack(i)})})}function mu(t){t.DataChannel&&!t.RTCDataChannel&&(t.RTCDataChannel=t.DataChannel)}function gu(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const e=t.RTCPeerConnection.prototype.addTransceiver;e&&(t.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const r=i.length>0;r&&i.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=e.apply(this,arguments);if(r){const{sender:a}=s,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function vu(t){if(!(typeof t=="object"&&t.RTCRtpSender))return;const e=t.RTCRtpSender.prototype.getParameters;e&&(t.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function yu(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function bu(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;const e=t.RTCPeerConnection.prototype.createAnswer;t.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var Oa=Object.freeze({__proto__:null,shimAddTransceiver:gu,shimCreateAnswer:bu,shimCreateOffer:yu,shimGetDisplayMedia:O0,shimGetParameters:vu,shimGetUserMedia:uu,shimOnTrack:du,shimPeerConnection:vs,shimRTCDataChannel:mu,shimReceiverGetStats:fu,shimRemoveStream:pu,shimSenderGetStats:hu});function ku(t){if(!(typeof t!="object"||!t.RTCPeerConnection)){if("getLocalStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in t.RTCPeerConnection.prototype)){const e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>e.call(this,r,i)),i.getVideoTracks().forEach(r=>e.call(this,r,i))},t.RTCPeerConnection.prototype.addTrack=function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),a=1;a<r;a++)s[a-1]=arguments[a];return s&&s.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(n){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(n);if(i===-1)return;this._localStreams.splice(i,1);const r=n.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function Cu(t){if(!(typeof t!="object"||!t.RTCPeerConnection)&&("getRemoteStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in t.RTCPeerConnection.prototype))){Object.defineProperty(t.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(n){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=n),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function Su(t){if(typeof t!="object"||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype,n=e.createOffer,i=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(l,u){const d=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[d]);return u?(h.then(l,u),Promise.resolve()):h},e.createAnswer=function(l,u){const d=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[d]);return u?(h.then(l,u),Promise.resolve()):h};let o=function(c,l,u){const d=r.apply(this,[c]);return u?(d.then(l,u),Promise.resolve()):d};e.setLocalDescription=o,o=function(c,l,u){const d=s.apply(this,[c]);return u?(d.then(l,u),Promise.resolve()):d},e.setRemoteDescription=o,o=function(c,l,u){const d=a.apply(this,[c]);return u?(d.then(l,u),Promise.resolve()):d},e.addIceCandidate=o}function Tu(t){const e=t&&t.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const n=e.mediaDevices,i=n.getUserMedia.bind(n);e.mediaDevices.getUserMedia=r=>i(wu(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,r,s){e.mediaDevices.getUserMedia(i).then(r,s)}).bind(e))}function wu(t){return t&&t.video!==void 0?Object.assign({},t,{video:tu(t.video)}):t}function xu(t){if(!t.RTCPeerConnection)return;const e=t.RTCPeerConnection;t.RTCPeerConnection=function(i,r){if(i&&i.iceServers){const s=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(uo("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(i.iceServers[a])}i.iceServers=s}return new e(i,r)},t.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(t.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function _u(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Eu(t){const e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const r=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Pu(t){typeof t!="object"||t.AudioContext||(t.AudioContext=t.webkitAudioContext)}var Aa=Object.freeze({__proto__:null,shimAudioContext:Pu,shimCallbacksAPI:Su,shimConstraints:wu,shimCreateOfferLegacy:Eu,shimGetUserMedia:Tu,shimLocalStreamsAPI:ku,shimRTCIceServerUrls:xu,shimRemoteStreamsAPI:Cu,shimTrackEventTransceiver:_u}),Lr={exports:{}},Da;function A0(){return Da||(Da=1,(function(t){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(n){return n.trim().split(`
19
+ `).map(i=>i.trim())},e.splitSections=function(n){return n.split(`
20
+ m=`).map((r,s)=>(s>0?"m="+r:r).trim()+`\r
21
+ `)},e.getDescription=function(n){const i=e.splitSections(n);return i&&i[0]},e.getMediaSections=function(n){const i=e.splitSections(n);return i.shift(),i},e.matchPrefix=function(n,i){return e.splitLines(n).filter(r=>r.indexOf(i)===0)},e.parseCandidate=function(n){let i;n.indexOf("a=candidate:")===0?i=n.substring(12).split(" "):i=n.substring(10).split(" ");const r={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let s=8;s<i.length;s+=2)switch(i[s]){case"raddr":r.relatedAddress=i[s+1];break;case"rport":r.relatedPort=parseInt(i[s+1],10);break;case"tcptype":r.tcpType=i[s+1];break;case"ufrag":r.ufrag=i[s+1],r.usernameFragment=i[s+1];break;default:r[i[s]]===void 0&&(r[i[s]]=i[s+1]);break}return r},e.writeCandidate=function(n){const i=[];i.push(n.foundation);const r=n.component;r==="rtp"?i.push(1):r==="rtcp"?i.push(2):i.push(r),i.push(n.protocol.toUpperCase()),i.push(n.priority),i.push(n.address||n.ip),i.push(n.port);const s=n.type;return i.push("typ"),i.push(s),s!=="host"&&n.relatedAddress&&n.relatedPort&&(i.push("raddr"),i.push(n.relatedAddress),i.push("rport"),i.push(n.relatedPort)),n.tcpType&&n.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(n.tcpType)),(n.usernameFragment||n.ufrag)&&(i.push("ufrag"),i.push(n.usernameFragment||n.ufrag)),"candidate:"+i.join(" ")},e.parseIceOptions=function(n){return n.substring(14).split(" ")},e.parseRtpMap=function(n){let i=n.substring(9).split(" ");const r={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),r.name=i[0],r.clockRate=parseInt(i[1],10),r.channels=i.length===3?parseInt(i[2],10):1,r.numChannels=r.channels,r},e.writeRtpMap=function(n){let i=n.payloadType;n.preferredPayloadType!==void 0&&(i=n.preferredPayloadType);const r=n.channels||n.numChannels||1;return"a=rtpmap:"+i+" "+n.name+"/"+n.clockRate+(r!==1?"/"+r:"")+`\r
22
+ `},e.parseExtmap=function(n){const i=n.substring(9).split(" ");return{id:parseInt(i[0],10),direction:i[0].indexOf("/")>0?i[0].split("/")[1]:"sendrecv",uri:i[1],attributes:i.slice(2).join(" ")}},e.writeExtmap=function(n){return"a=extmap:"+(n.id||n.preferredId)+(n.direction&&n.direction!=="sendrecv"?"/"+n.direction:"")+" "+n.uri+(n.attributes?" "+n.attributes:"")+`\r
23
+ `},e.parseFmtp=function(n){const i={};let r;const s=n.substring(n.indexOf(" ")+1).split(";");for(let a=0;a<s.length;a++)r=s[a].trim().split("="),i[r[0].trim()]=r[1];return i},e.writeFmtp=function(n){let i="",r=n.payloadType;if(n.preferredPayloadType!==void 0&&(r=n.preferredPayloadType),n.parameters&&Object.keys(n.parameters).length){const s=[];Object.keys(n.parameters).forEach(a=>{n.parameters[a]!==void 0?s.push(a+"="+n.parameters[a]):s.push(a)}),i+="a=fmtp:"+r+" "+s.join(";")+`\r
24
+ `}return i},e.parseRtcpFb=function(n){const i=n.substring(n.indexOf(" ")+1).split(" ");return{type:i.shift(),parameter:i.join(" ")}},e.writeRtcpFb=function(n){let i="",r=n.payloadType;return n.preferredPayloadType!==void 0&&(r=n.preferredPayloadType),n.rtcpFeedback&&n.rtcpFeedback.length&&n.rtcpFeedback.forEach(s=>{i+="a=rtcp-fb:"+r+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r
25
+ `}),i},e.parseSsrcMedia=function(n){const i=n.indexOf(" "),r={ssrc:parseInt(n.substring(7,i),10)},s=n.indexOf(":",i);return s>-1?(r.attribute=n.substring(i+1,s),r.value=n.substring(s+1)):r.attribute=n.substring(i+1),r},e.parseSsrcGroup=function(n){const i=n.substring(13).split(" ");return{semantics:i.shift(),ssrcs:i.map(r=>parseInt(r,10))}},e.getMid=function(n){const i=e.matchPrefix(n,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(n){const i=n.substring(14).split(" ");return{algorithm:i[0].toLowerCase(),value:i[1].toUpperCase()}},e.getDtlsParameters=function(n,i){return{role:"auto",fingerprints:e.matchPrefix(n+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(n,i){let r="a=setup:"+i+`\r
26
+ `;return n.fingerprints.forEach(s=>{r+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
27
+ `}),r},e.parseCryptoLine=function(n){const i=n.substring(9).split(" ");return{tag:parseInt(i[0],10),cryptoSuite:i[1],keyParams:i[2],sessionParams:i.slice(3)}},e.writeCryptoLine=function(n){return"a=crypto:"+n.tag+" "+n.cryptoSuite+" "+(typeof n.keyParams=="object"?e.writeCryptoKeyParams(n.keyParams):n.keyParams)+(n.sessionParams?" "+n.sessionParams.join(" "):"")+`\r
28
+ `},e.parseCryptoKeyParams=function(n){if(n.indexOf("inline:")!==0)return null;const i=n.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(n){return n.keyMethod+":"+n.keySalt+(n.lifeTime?"|"+n.lifeTime:"")+(n.mkiValue&&n.mkiLength?"|"+n.mkiValue+":"+n.mkiLength:"")},e.getCryptoParameters=function(n,i){return e.matchPrefix(n+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(n,i){const r=e.matchPrefix(n+i,"a=ice-ufrag:")[0],s=e.matchPrefix(n+i,"a=ice-pwd:")[0];return r&&s?{usernameFragment:r.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(n){let i="a=ice-ufrag:"+n.usernameFragment+`\r
29
+ a=ice-pwd:`+n.password+`\r
30
+ `;return n.iceLite&&(i+=`a=ice-lite\r
31
+ `),i},e.parseRtpParameters=function(n){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=e.splitLines(n)[0].split(" ");i.profile=s[2];for(let o=3;o<s.length;o++){const c=s[o],l=e.matchPrefix(n,"a=rtpmap:"+c+" ")[0];if(l){const u=e.parseRtpMap(l),d=e.matchPrefix(n,"a=fmtp:"+c+" ");switch(u.parameters=d.length?e.parseFmtp(d[0]):{},u.rtcpFeedback=e.matchPrefix(n,"a=rtcp-fb:"+c+" ").map(e.parseRtcpFb),i.codecs.push(u),u.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(u.name.toUpperCase());break}}}e.matchPrefix(n,"a=extmap:").forEach(o=>{i.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(n,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(o=>{a.forEach(c=>{o.rtcpFeedback.find(u=>u.type===c.type&&u.parameter===c.parameter)||o.rtcpFeedback.push(c)})}),i},e.writeRtpDescription=function(n,i){let r="";r+="m="+n+" ",r+=i.codecs.length>0?"9":"0",r+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=i.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
32
+ `,r+=`c=IN IP4 0.0.0.0\r
33
+ `,r+=`a=rtcp:9 IN IP4 0.0.0.0\r
34
+ `,i.codecs.forEach(a=>{r+=e.writeRtpMap(a),r+=e.writeFmtp(a),r+=e.writeRtcpFb(a)});let s=0;return i.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(r+="a=maxptime:"+s+`\r
35
+ `),i.headerExtensions&&i.headerExtensions.forEach(a=>{r+=e.writeExtmap(a)}),r},e.parseRtpEncodingParameters=function(n){const i=[],r=e.parseRtpParameters(n),s=r.fecMechanisms.indexOf("RED")!==-1,a=r.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(n,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),c=o.length>0&&o[0].ssrc;let l;const u=e.matchPrefix(n,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(m=>parseInt(m,10)));u.length>0&&u[0].length>1&&u[0][0]===c&&(l=u[0][1]),r.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let f={ssrc:c,codecPayloadType:parseInt(h.parameters.apt,10)};c&&l&&(f.rtx={ssrc:l}),i.push(f),s&&(f=JSON.parse(JSON.stringify(f)),f.fec={ssrc:c,mechanism:a?"red+ulpfec":"red"},i.push(f))}}),i.length===0&&c&&i.push({ssrc:c});let d=e.matchPrefix(n,"b=");return d.length&&(d[0].indexOf("b=TIAS:")===0?d=parseInt(d[0].substring(7),10):d[0].indexOf("b=AS:")===0?d=parseInt(d[0].substring(5),10)*1e3*.95-2e3*8:d=void 0,i.forEach(h=>{h.maxBitrate=d})),i},e.parseRtcpParameters=function(n){const i={},r=e.matchPrefix(n,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const s=e.matchPrefix(n,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=s.length===0;const a=e.matchPrefix(n,"a=rtcp-mux");return i.mux=a.length>0,i},e.writeRtcpParameters=function(n){let i="";return n.reducedSize&&(i+=`a=rtcp-rsize\r
36
+ `),n.mux&&(i+=`a=rtcp-mux\r
37
+ `),n.ssrc!==void 0&&n.cname&&(i+="a=ssrc:"+n.ssrc+" cname:"+n.cname+`\r
38
+ `),i},e.parseMsid=function(n){let i;const r=e.matchPrefix(n,"a=msid:");if(r.length===1)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=e.matchPrefix(n,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(s.length>0)return i=s[0].value.split(" "),{stream:i[0],track:i[1]}},e.parseSctpDescription=function(n){const i=e.parseMLine(n),r=e.matchPrefix(n,"a=max-message-size:");let s;r.length>0&&(s=parseInt(r[0].substring(19),10)),isNaN(s)&&(s=65536);const a=e.matchPrefix(n,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=e.matchPrefix(n,"a=sctpmap:");if(o.length>0){const c=o[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:s}}},e.writeSctpDescription=function(n,i){let r=[];return n.protocol!=="DTLS/SCTP"?r=["m="+n.kind+" 9 "+n.protocol+" "+i.protocol+`\r
39
+ `,`c=IN IP4 0.0.0.0\r
40
+ `,"a=sctp-port:"+i.port+`\r
41
+ `]:r=["m="+n.kind+" 9 "+n.protocol+" "+i.port+`\r
42
+ `,`c=IN IP4 0.0.0.0\r
43
+ `,"a=sctpmap:"+i.port+" "+i.protocol+` 65535\r
44
+ `],i.maxMessageSize!==void 0&&r.push("a=max-message-size:"+i.maxMessageSize+`\r
45
+ `),r.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(n,i,r){let s;const a=i!==void 0?i:2;return n?s=n:s=e.generateSessionId(),`v=0\r
46
+ o=`+(r||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r
47
+ s=-\r
48
+ t=0 0\r
49
+ `},e.getDirection=function(n,i){const r=e.splitLines(n);for(let s=0;s<r.length;s++)switch(r[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[s].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(n){return e.splitLines(n)[0].split(" ")[0].substring(2)},e.isRejected=function(n){return n.split(" ",2)[1]==="0"},e.parseMLine=function(n){const r=e.splitLines(n)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},e.parseOLine=function(n){const r=e.matchPrefix(n,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},e.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;const i=e.splitLines(n);for(let r=0;r<i.length;r++)if(i[r].length<2||i[r].charAt(1)!=="=")return!1;return!0},t.exports=e})(Lr)),Lr.exports}var Ru=A0(),Bn=C0(Ru),D0=zg({__proto__:null,default:Bn},[Ru]);function qi(t){if(!t.RTCIceCandidate||t.RTCIceCandidate&&"foundation"in t.RTCIceCandidate.prototype)return;const e=t.RTCIceCandidate;t.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const r=new e(i),s=Bn.parseCandidate(i.candidate);for(const a in s)a in r||Object.defineProperty(r,a,{value:s[a]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new e(i)},t.RTCIceCandidate.prototype=e.prototype,En(t,"icecandidate",n=>(n.candidate&&Object.defineProperty(n,"candidate",{value:new t.RTCIceCandidate(n.candidate),writable:"false"}),n))}function ys(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||En(t,"icecandidate",e=>{if(e.candidate){const n=Bn.parseCandidate(e.candidate.candidate);n.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[n.priority>>24])}return e})}function zi(t,e){if(!t.RTCPeerConnection)return;"sctp"in t.RTCPeerConnection.prototype||Object.defineProperty(t.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const n=function(o){if(!o||!o.sdp)return!1;const c=Bn.splitSections(o.sdp);return c.shift(),c.some(l=>{const u=Bn.parseMLine(l);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},i=function(o){const c=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const l=parseInt(c[1],10);return l!==l?-1:l},r=function(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},s=function(o,c){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);const u=Bn.matchPrefix(o.sdp,"a=max-message-size:");return u.length>0?l=parseInt(u[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(l=2147483637),l},a=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(n(arguments[0])){const c=i(arguments[0]),l=r(c),u=s(arguments[0],c);let d;l===0&&u===0?d=Number.POSITIVE_INFINITY:l===0||u===0?d=Math.max(l,u):d=Math.min(l,u);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return d}}),this._sctp=h}return a.apply(this,arguments)}}function Wi(t){if(!(t.RTCPeerConnection&&"createDataChannel"in t.RTCPeerConnection.prototype))return;function e(i,r){const s=i.send;i.send=function(){const o=arguments[0],c=o.length||o.size||o.byteLength;if(i.readyState==="open"&&r.sctp&&c>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return s.apply(i,arguments)}}const n=t.RTCPeerConnection.prototype.createDataChannel;t.RTCPeerConnection.prototype.createDataChannel=function(){const r=n.apply(this,arguments);return e(r,this),r},En(t,"datachannel",i=>(e(i.channel,i.target),i))}function bs(t){if(!t.RTCPeerConnection||"connectionState"in t.RTCPeerConnection.prototype)return;const e=t.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(n){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),n&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=n)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(n=>{const i=e[n];e[n]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const a=new Event("connectionstatechange",r);s.dispatchEvent(a)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function ks(t,e){if(!t.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const n=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(`
50
+ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
51
+ `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
52
+ `);t.RTCSessionDescription&&r instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return n.apply(this,arguments)}}function Hi(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Ki(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const n=t.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return n.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?n.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>n.apply(this,[a]))})}var N0=Object.freeze({__proto__:null,removeExtmapAllowMixed:ks,shimAddIceCandidateNullOrEmpty:Hi,shimConnectionState:bs,shimMaxMessageSize:zi,shimParameterlessSetLocalDescription:Ki,shimRTCIceCandidate:qi,shimRTCIceCandidateRelayProtocol:ys,shimSendThrowTypeError:Wi});function L0(){let{window:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=eu,i=M0(t),r={browserDetails:i,commonShim:N0,extractVersion:ui,disableLog:R0,disableWarnings:I0,sdp:D0};switch(i.browser){case"chrome":if(!Ma||!gs||!e.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(i.version===null)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=Ma,Hi(t,i),Ki(t),nu(t,i),iu(t),gs(t,i),ru(t),cu(t,i),su(t),ou(t),lu(t,i),qi(t),ys(t),bs(t),zi(t,i),Wi(t),ks(t,i);break;case"firefox":if(!Oa||!vs||!e.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=Oa,Hi(t,i),Ki(t),uu(t,i),vs(t,i),du(t),pu(t),hu(t),fu(t),mu(t),gu(t),vu(t),yu(t),bu(t),qi(t),bs(t),zi(t,i),Wi(t);break;case"safari":if(!Aa||!e.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=Aa,Hi(t,i),Ki(t),xu(t),Eu(t),Su(t),ku(t),Cu(t),_u(t),Tu(t),Pu(t),qi(t),ys(t),zi(t,i),Wi(t),ks(t,i);break;default:n("Unsupported browser!");break}return r}L0({window:typeof window>"u"?void 0:window});class tt extends Promise{constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}const j0=/version\/(\d+(\.?_?\d+)+)/i;let jr;function rt(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const n=navigator.userAgent.toLowerCase();if(jr===void 0||e){const i=U0.find(r=>{let{test:s}=r;return s.test(n)});jr=i==null?void 0:i.describe(n)}return jr}const U0=[{test:/firefox|iceweasel|fxios/i,describe(t){return{name:"Firefox",version:Gi(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Ur(t)}}},{test:/chrom|crios|crmo/i,describe(t){return{name:"Chrome",version:Gi(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t),os:t.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Ur(t)}}},{test:/safari|applewebkit/i,describe(t){return{name:"Safari",version:Gi(j0,t),os:t.includes("mobile/")?"iOS":"macOS",osVersion:Ur(t)}}}];function Gi(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(t);return i&&i.length>=n&&i[n]||""}function Ur(t){return t.includes("mac os")?Gi(/\(.+?(\d+_\d+(:?_\d+)?)/,t,1).replace(/_/g,"."):void 0}var F0="2.17.0";const B0=F0,V0=16;class jt extends Error{constructor(e,n){super(n||"an error has occured"),this.name="LiveKitError",this.code=e}}var Ce;(function(t){t[t.NotAllowed=0]="NotAllowed",t[t.ServerUnreachable=1]="ServerUnreachable",t[t.InternalError=2]="InternalError",t[t.Cancelled=3]="Cancelled",t[t.LeaveRequest=4]="LeaveRequest",t[t.Timeout=5]="Timeout",t[t.WebSocket=6]="WebSocket",t[t.ServiceNotFound=7]="ServiceNotFound"})(Ce||(Ce={}));class ie extends jt{constructor(e,n,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=Ce[n]}static notAllowed(e,n,i){return new ie(e,Ce.NotAllowed,n,i)}static timeout(e){return new ie(e,Ce.Timeout)}static leaveRequest(e,n){return new ie(e,Ce.LeaveRequest,void 0,n)}static internal(e,n){return new ie(e,Ce.InternalError,void 0,n)}static cancelled(e){return new ie(e,Ce.Cancelled)}static serverUnreachable(e,n){return new ie(e,Ce.ServerUnreachable,n)}static websocket(e,n,i){return new ie(e,Ce.WebSocket,n,i)}static serviceNotFound(e,n){return new ie(e,Ce.ServiceNotFound,void 0,n)}}class ho extends jt{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Kt extends jt{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class q0 extends jt{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Re extends jt{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Vn extends jt{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Na extends jt{constructor(e,n){super(15,e),this.name="PublishTrackError",this.status=n}}class La extends jt{constructor(e,n){super(15,e),this.name="SignalRequestError",this.reason=n,this.reasonName=typeof n=="string"?n:lo[n]}}var $e;(function(t){t[t.AlreadyOpened=0]="AlreadyOpened",t[t.AbnormalEnd=1]="AbnormalEnd",t[t.DecodeFailed=2]="DecodeFailed",t[t.LengthExceeded=3]="LengthExceeded",t[t.Incomplete=4]="Incomplete",t[t.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",t[t.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})($e||($e={}));class mt extends jt{constructor(e,n){super(16,e),this.name="DataStreamError",this.reason=n,this.reasonName=$e[n]}}class On extends jt{constructor(e){super(18,e),this.name="SignalReconnectError"}}var rr;(function(t){t.PermissionDenied="PermissionDenied",t.NotFound="NotFound",t.DeviceInUse="DeviceInUse",t.Other="Other"})(rr||(rr={}));(function(t){function e(n){if(n&&"name"in n)return n.name==="NotFoundError"||n.name==="DevicesNotFoundError"?t.NotFound:n.name==="NotAllowedError"||n.name==="PermissionDeniedError"?t.PermissionDenied:n.name==="NotReadableError"||n.name==="TrackStartError"?t.DeviceInUse:t.Other}t.getFailure=e})(rr||(rr={}));class Be{}Be.setTimeout=function(){return setTimeout(...arguments)};Be.setInterval=function(){return setInterval(...arguments)};Be.clearTimeout=function(){return clearTimeout(...arguments)};Be.clearInterval=function(){return clearInterval(...arguments)};var U;(function(t){t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting",t.Reconnected="reconnected",t.Disconnected="disconnected",t.ConnectionStateChanged="connectionStateChanged",t.Moved="moved",t.MediaDevicesChanged="mediaDevicesChanged",t.ParticipantConnected="participantConnected",t.ParticipantDisconnected="participantDisconnected",t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalAudioSilenceDetected="localAudioSilenceDetected",t.ActiveSpeakersChanged="activeSpeakersChanged",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.ParticipantAttributesChanged="participantAttributesChanged",t.ParticipantActive="participantActive",t.RoomMetadataChanged="roomMetadataChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.AudioPlaybackStatusChanged="audioPlaybackChanged",t.VideoPlaybackStatusChanged="videoPlaybackChanged",t.MediaDevicesError="mediaDevicesError",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.SignalConnected="signalConnected",t.RecordingStatusChanged="recordingStatusChanged",t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ActiveDeviceChanged="activeDeviceChanged",t.ChatMessage="chatMessage",t.LocalTrackSubscribed="localTrackSubscribed",t.MetricsReceived="metricsReceived"})(U||(U={}));var H;(function(t){t.TrackPublished="trackPublished",t.TrackSubscribed="trackSubscribed",t.TrackSubscriptionFailed="trackSubscriptionFailed",t.TrackUnpublished="trackUnpublished",t.TrackUnsubscribed="trackUnsubscribed",t.TrackMuted="trackMuted",t.TrackUnmuted="trackUnmuted",t.LocalTrackPublished="localTrackPublished",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackCpuConstrained="localTrackCpuConstrained",t.LocalSenderCreated="localSenderCreated",t.ParticipantMetadataChanged="participantMetadataChanged",t.ParticipantNameChanged="participantNameChanged",t.DataReceived="dataReceived",t.SipDTMFReceived="sipDTMFReceived",t.TranscriptionReceived="transcriptionReceived",t.IsSpeakingChanged="isSpeakingChanged",t.ConnectionQualityChanged="connectionQualityChanged",t.TrackStreamStateChanged="trackStreamStateChanged",t.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",t.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",t.TrackCpuConstrained="trackCpuConstrained",t.MediaDevicesError="mediaDevicesError",t.AudioStreamAcquired="audioStreamAcquired",t.ParticipantPermissionsChanged="participantPermissionsChanged",t.PCTrackAdded="pcTrackAdded",t.AttributesChanged="attributesChanged",t.LocalTrackSubscribed="localTrackSubscribed",t.ChatMessage="chatMessage",t.Active="active"})(H||(H={}));var z;(function(t){t.TransportsCreated="transportsCreated",t.Connected="connected",t.Disconnected="disconnected",t.Resuming="resuming",t.Resumed="resumed",t.Restarting="restarting",t.Restarted="restarted",t.SignalResumed="signalResumed",t.SignalRestarted="signalRestarted",t.Closing="closing",t.MediaTrackAdded="mediaTrackAdded",t.ActiveSpeakersUpdate="activeSpeakersUpdate",t.DataPacketReceived="dataPacketReceived",t.RTPVideoMapUpdate="rtpVideoMapUpdate",t.DCBufferStatusChanged="dcBufferStatusChanged",t.ParticipantUpdate="participantUpdate",t.RoomUpdate="roomUpdate",t.SpeakersChanged="speakersChanged",t.StreamStateChanged="streamStateChanged",t.ConnectionQualityUpdate="connectionQualityUpdate",t.SubscriptionError="subscriptionError",t.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",t.RemoteMute="remoteMute",t.SubscribedQualityUpdate="subscribedQualityUpdate",t.LocalTrackUnpublished="localTrackUnpublished",t.LocalTrackSubscribed="localTrackSubscribed",t.Offline="offline",t.SignalRequestResponse="signalRequestResponse",t.SignalConnected="signalConnected",t.RoomMoved="roomMoved"})(z||(z={}));var V;(function(t){t.Message="message",t.Muted="muted",t.Unmuted="unmuted",t.Restarted="restarted",t.Ended="ended",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",t.CpuConstrained="cpuConstrained",t.UpdateSettings="updateSettings",t.UpdateSubscription="updateSubscription",t.AudioPlaybackStarted="audioPlaybackStarted",t.AudioPlaybackFailed="audioPlaybackFailed",t.AudioSilenceDetected="audioSilenceDetected",t.VisibilityChanged="visibilityChanged",t.VideoDimensionsChanged="videoDimensionsChanged",t.VideoPlaybackStarted="videoPlaybackStarted",t.VideoPlaybackFailed="videoPlaybackFailed",t.ElementAttached="elementAttached",t.ElementDetached="elementDetached",t.UpstreamPaused="upstreamPaused",t.UpstreamResumed="upstreamResumed",t.SubscriptionPermissionChanged="subscriptionPermissionChanged",t.SubscriptionStatusChanged="subscriptionStatusChanged",t.SubscriptionFailed="subscriptionFailed",t.TrackProcessorUpdate="trackProcessorUpdate",t.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",t.TranscriptionReceived="transcriptionReceived",t.TimeSyncUpdate="timeSyncUpdate",t.PreConnectBufferFlushed="preConnectBufferFlushed"})(V||(V={}));function z0(t){return typeof t>"u"?t:typeof structuredClone=="function"?typeof t=="object"&&t!==null?structuredClone(Object.assign({},t)):structuredClone(t):JSON.parse(JSON.stringify(t))}class ye{constructor(e,n,i,r,s){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(n!==void 0&&i!==void 0)this.width=e,this.height=n,this.aspectRatio=e/n,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const W0=["vp8","h264"],H0=["vp8","h264","vp9","av1","h265"];function K0(t){return!!W0.find(e=>e===t)}const G0=K0;var ja;(function(t){t[t.PREFER_REGRESSION=0]="PREFER_REGRESSION",t[t.SIMULCAST=1]="SIMULCAST",t[t.REGRESSION=2]="REGRESSION"})(ja||(ja={}));var Cs;(function(t){t.telephone={maxBitrate:12e3},t.speech={maxBitrate:24e3},t.music={maxBitrate:48e3},t.musicStereo={maxBitrate:64e3},t.musicHighQuality={maxBitrate:96e3},t.musicHighQualityStereo={maxBitrate:128e3}})(Cs||(Cs={}));const Si={h90:new ye(160,90,9e4,20),h180:new ye(320,180,16e4,20),h216:new ye(384,216,18e4,20),h360:new ye(640,360,45e4,20),h540:new ye(960,540,8e5,25),h720:new ye(1280,720,17e5,30),h1080:new ye(1920,1080,3e6,30),h1440:new ye(2560,1440,5e6,30),h2160:new ye(3840,2160,8e6,30)},Ss={h120:new ye(160,120,7e4,20),h180:new ye(240,180,125e3,20),h240:new ye(320,240,14e4,20),h360:new ye(480,360,33e4,20),h480:new ye(640,480,5e5,20),h540:new ye(720,540,6e5,25),h720:new ye(960,720,13e5,30),h1080:new ye(1440,1080,23e5,30),h1440:new ye(1920,1440,38e5,30)},fo={h360fps3:new ye(640,360,2e5,3,"medium"),h360fps15:new ye(640,360,4e5,15,"medium"),h720fps5:new ye(1280,720,8e5,5,"medium"),h720fps15:new ye(1280,720,15e5,15,"medium"),h720fps30:new ye(1280,720,2e6,30,"medium"),h1080fps15:new ye(1920,1080,25e5,15,"medium"),h1080fps30:new ye(1920,1080,5e6,30,"medium"),original:new ye(0,0,7e6,30,"medium")};function Iu(t,e,n){var i,r,s,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:l}=Au(t??{}),u=e==null?void 0:e.processor,d=n==null?void 0:n.processor,h=o??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(Ts(h.audio,e),(i=(s=h.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||u)&&(h.audio.processor=c??u)),h.video&&(Ts(h.video,n),(r=(a=h.video).deviceId)!==null&&r!==void 0||(a.deviceId={ideal:"default"}),(l||d)&&(h.video.processor=l??d)),h}function Ts(t,e){return Object.keys(e).forEach(n=>{t[n]===void 0&&(t[n]=e[n])}),t}function po(t){var e,n,i,r;const s={};if(t.video)if(typeof t.video=="object"){const a={},o=a,c=t.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":Ts(o,c.resolution);break;default:o[l]=c[l]}}),s.video=a,(e=(i=s.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else s.video=t.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return t.audio?typeof t.audio=="object"?(s.audio=t.audio,(n=(r=s.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Mu(t){return v(this,arguments,void 0,function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=Ou();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,a=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield Ve(n),r.getByteTimeDomainData(a);const c=a.some(l=>l!==128&&l!==0);return i.close(),!c}return!1})()})}function Ou(){var t;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const n=new e({latencyHint:"interactive"});if(n.state==="suspended"&&typeof window<"u"&&(!((t=window.document)===null||t===void 0)&&t.body)){const i=()=>v(this,void 0,void 0,function*(){var r;try{n.state==="suspended"&&(yield n.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}finally{(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)}});n.addEventListener("statechange",()=>{var r;n.state==="closed"&&((r=window.document.body)===null||r===void 0||r.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return n}}function $0(t){return t==="audioinput"?M.Source.Microphone:t==="videoinput"?M.Source.Camera:M.Source.Unknown}function ws(t){return t===M.Source.Microphone?"audioinput":t===M.Source.Camera?"videoinput":void 0}function J0(t){var e,n;let i=(e=t.video)!==null&&e!==void 0?e:!0;return t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(i=typeof i=="boolean"?{}:i,xn()?i=Object.assign(Object.assign({},i),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:(n=t.audio)!==null&&n!==void 0?n:!1,video:i,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}}function gi(t){return t.split("/")[1].toLowerCase()}function Y0(t){const e=[];return t.forEach(n=>{n.track!==void 0&&e.push(new ro({cid:n.track.mediaStreamID,track:n.trackInfo}))}),e}function de(t){return"mediaStreamTrack"in t?{trackID:t.sid,source:t.source,muted:t.isMuted,enabled:t.mediaStreamTrack.enabled,kind:t.kind,streamID:t.mediaStreamID,streamTrackID:t.mediaStreamTrack.id}:{trackID:t.trackSid,enabled:t.isEnabled,muted:t.isMuted,trackInfo:Object.assign({mimeType:t.mimeType,name:t.trackName,encrypted:t.isEncrypted,kind:t.kind,source:t.source},t.track?de(t.track):{})}}function Q0(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function X0(t,e){var n;t===void 0&&(t={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(t)],r={};for(const s of i)t[s]!==e[s]&&(r[s]=(n=e[s])!==null&&n!==void 0?n:"");return r}function Au(t){const e=Object.assign({},t);let n,i;return typeof e.audio=="object"&&e.audio.processor&&(n=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:z0(e)}}function Z0(t){switch(t){case Ae.CAMERA:return M.Source.Camera;case Ae.MICROPHONE:return M.Source.Microphone;case Ae.SCREEN_SHARE:return M.Source.ScreenShare;case Ae.SCREEN_SHARE_AUDIO:return M.Source.ScreenShareAudio;default:return M.Source.Unknown}}function Ua(t,e){return t.width*t.height<e.width*e.height}function ey(t,e){var n;return(n=t.layers)===null||n===void 0?void 0:n.find(i=>i.quality===e)}const ty=5e3,si=[];var dt;(function(t){t[t.LOW=0]="LOW",t[t.MEDIUM=1]="MEDIUM",t[t.HIGH=2]="HIGH"})(dt||(dt={}));class M extends Lt.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=M.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ce,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),ty):this.handleAppVisibilityChanged()},this.log=Gt((r=i.loggerName)!==null&&r!==void 0?r:_t.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=M.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),de(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let n="audio";this.kind===M.Kind.Video&&(n="video"),this.attachedElements.length===0&&this.kind===M.Kind.Video&&this.addAppVisibilityListener(),e||(n==="audio"&&(si.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&si.splice(si.indexOf(e),1)),e||(e=document.createElement(n))),this.attachedElements.includes(e)||this.attachedElements.push(e),Dn(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?V.AudioPlaybackStarted:V.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?V.AudioPlaybackFailed:V.VideoPlaybackFailed,s):s.name==="AbortError"?ce.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):ce.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&i.some(a=>a.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(V.ElementAttached,e),e}detach(e){try{if(e){qn(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(V.ElementDetached,e)),e}const n=[];return this.attachedElements.forEach(i=>{qn(this.mediaStreamTrack,i),n.push(i),this.recycleElement(i),this.emit(V.ElementDetached,i)}),this.attachedElements=[],n}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Gt(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let n=!0;e.pause(),si.forEach(i=>{i.parentElement||(n=!1)}),n&&si.push(e)}}handleAppVisibilityChanged(){return v(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===M.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){nt()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){nt()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Dn(t,e){let n;e.srcObject instanceof MediaStream?n=e.srcObject:n=new MediaStream;let i;t.kind==="audio"?i=n.getAudioTracks():i=n.getVideoTracks(),i.includes(t)||(i.forEach(r=>{n.removeTrack(r)}),n.addTrack(t)),(!xn()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=n.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==n&&(e.srcObject=n,(xn()||wn())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=n,e.play().catch(()=>{})},0))}function qn(t,e){if(e.srcObject instanceof MediaStream){const n=e.srcObject;n.removeTrack(t),n.getTracks().length>0?e.srcObject=n:e.srcObject=null}}(function(t){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=t.Kind||(t.Kind={}));let n;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(n=t.Source||(t.Source={}));let i;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(i=t.StreamState||(t.StreamState={}));function r(l){switch(l){case e.Audio:return St.AUDIO;case e.Video:return St.VIDEO;default:return St.DATA}}t.kindToProto=r;function s(l){switch(l){case St.AUDIO:return e.Audio;case St.VIDEO:return e.Video;default:return e.Unknown}}t.kindFromProto=s;function a(l){switch(l){case n.Camera:return Ae.CAMERA;case n.Microphone:return Ae.MICROPHONE;case n.ScreenShare:return Ae.SCREEN_SHARE;case n.ScreenShareAudio:return Ae.SCREEN_SHARE_AUDIO;default:return Ae.UNKNOWN}}t.sourceToProto=a;function o(l){switch(l){case Ae.CAMERA:return n.Camera;case Ae.MICROPHONE:return n.Microphone;case Ae.SCREEN_SHARE:return n.ScreenShare;case Ae.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}t.sourceFromProto=o;function c(l){switch(l){case hs.ACTIVE:return i.Active;case hs.PAUSED:return i.Paused;default:return i.Unknown}}t.streamStateFromProto=c})(M||(M={}));const ny="|",Fa="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function iy(t){const e=t.split(ny);return e.length>1?[e[0],t.substr(e[0].length+1)]:[t,""]}function Ve(t){return new tt(e=>Be.setTimeout(e,t))}function xs(){return"addTransceiver"in RTCPeerConnection.prototype}function _s(){return"addTrack"in RTCPeerConnection.prototype}function ry(){if(!("getCapabilities"in RTCRtpSender)||xn()||wn())return!1;const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function sy(){if(!("getCapabilities"in RTCRtpSender)||wn())return!1;if(xn()){const n=rt();if(n!=null&&n.version&&Nt(n.version,"16")<0||(n==null?void 0:n.os)==="iOS"&&(n!=null&&n.osVersion)&&Nt(n.osVersion,"16")<0)return!1}const t=RTCRtpSender.getCapabilities("video");let e=!1;if(t){for(const n of t.codecs)if(n.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function wt(t){return t==="av1"||t==="vp9"}function Es(t){return!document||Ti()?!1:(t||(t=document.createElement("audio")),"setSinkId"in t)}function oy(){return typeof RTCPeerConnection>"u"?!1:xs()||_s()}function wn(){var t;return((t=rt())===null||t===void 0?void 0:t.name)==="Firefox"}function Ba(){const t=rt();return!!t&&t.name==="Chrome"&&t.os!=="iOS"}function xn(){var t;return((t=rt())===null||t===void 0?void 0:t.name)==="Safari"}function Ti(){const t=rt();return(t==null?void 0:t.name)==="Safari"||(t==null?void 0:t.os)==="iOS"}function ay(){const t=rt();return(t==null?void 0:t.name)==="Safari"&&t.version.startsWith("17.")||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&Nt(t.osVersion,"17")>=0}function cy(t){return t||(t=rt()),(t==null?void 0:t.name)==="Safari"&&Nt(t.version,"18.3")>0||(t==null?void 0:t.os)==="iOS"&&!!(t!=null&&t.osVersion)&&Nt(t.osVersion,"18.3")>0}function Du(){var t,e;return nt()?(e=(t=navigator.userAgentData)===null||t===void 0?void 0:t.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function ly(){const t=rt(),e="17.2";if(t)return t.name!=="Safari"&&t.os!=="iOS"||t.os==="iOS"&&t.osVersion&&Nt(t.osVersion,e)>=0?!0:t.name==="Safari"&&Nt(t.version,e)>=0}function nt(){return typeof document<"u"}function Dt(){return navigator.product=="ReactNative"}function $n(t){return t.hostname.endsWith(".livekit.cloud")||t.hostname.endsWith(".livekit.run")}function Fr(t){return $n(t)?t.hostname.split(".")[0]:null}function Nu(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Lu(){if(!Dt())return;let t=Nu();if(t)return t.platform}function Va(){if(nt())return window.devicePixelRatio;if(Dt()){let t=Nu();if(t)return t.devicePixelRatio}return 1}function Nt(t,e){const n=t.split("."),i=e.split("."),r=Math.min(n.length,i.length);for(let s=0;s<r;++s){const a=parseInt(n[s],10),o=parseInt(i[s],10);if(a>o)return 1;if(a<o)return-1;if(s===r-1&&a===o)return 0}return t===""&&e!==""?-1:e===""?1:n.length==i.length?0:n.length<i.length?-1:1}function uy(t){for(const e of t)e.target.handleResize(e)}function dy(t){for(const e of t)e.target.handleVisibilityChanged(e)}let Br=null;const qa=()=>(Br||(Br=new ResizeObserver(uy)),Br);let Vr=null;const za=()=>(Vr||(Vr=new IntersectionObserver(dy,{root:null,rootMargin:"0px"})),Vr);function hy(){var t;const e=new Ll({sdk:jl.JS,protocol:V0,version:B0});return Dt()&&(e.os=(t=Lu())!==null&&t!==void 0?t:""),e}function Wa(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=t,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(t/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const a=r.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=n,o}let oi;function qr(){if(!oi){const t=new AudioContext,e=t.createOscillator(),n=t.createGain();n.gain.setValueAtTime(0,0);const i=t.createMediaStreamDestination();if(e.connect(n),n.connect(i),e.start(),[oi]=i.stream.getAudioTracks(),!oi)throw Error("Could not get empty media stream audio track");oi.enabled=!1}return oi.clone()}class vt{get isResolved(){return this._isResolved}constructor(e,n){this._isResolved=!1,this.onFinally=n,this.promise=new Promise((i,r)=>v(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,e&&(yield e(i,r))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function fy(t){return H0.includes(t)}function ln(t){if(typeof t=="string"||typeof t=="number")return t;if(Array.isArray(t))return t[0];if(t.exact!==void 0)return Array.isArray(t.exact)?t.exact[0]:t.exact;if(t.ideal!==void 0)return Array.isArray(t.ideal)?t.ideal[0]:t.ideal;throw Error("could not unwrap constraint")}function py(t){return t.startsWith("http")?t.replace(/^(http)/,"ws"):t}function wi(t){return t.startsWith("ws")?t.replace(/^(ws)/,"http"):t}function my(t,e){return t.segments.map(n=>{let{id:i,text:r,language:s,startTime:a,endTime:o,final:c}=n;var l;const u=(l=e.get(i))!==null&&l!==void 0?l:Date.now(),d=Date.now();return c?e.delete(i):e.set(i,u),{id:i,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:s,firstReceivedTime:u,lastReceivedTime:d}})}function gy(t){const{id:e,timestamp:n,message:i,editTimestamp:r}=t;return{id:e,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function Ha(t){switch(t.reason){case Ce.LeaveRequest:return t.context;case Ce.Cancelled:return xt.CLIENT_INITIATED;case Ce.NotAllowed:return xt.USER_REJECTED;case Ce.ServerUnreachable:return xt.JOIN_FAILURE;default:return xt.UNKNOWN_REASON}}function $i(t){return t!==void 0?Number(t):void 0}function Sn(t){return t!==void 0?BigInt(t):void 0}function zn(t){return!!t&&!(t instanceof MediaStreamTrack)&&t.isLocal}function Ot(t){return!!t&&t.kind==M.Kind.Audio}function pn(t){return!!t&&t.kind==M.Kind.Video}function en(t){return zn(t)&&pn(t)}function Vt(t){return zn(t)&&Ot(t)}function Ps(t){return!!t&&!t.isLocal}function vy(t){return!!t&&!t.isLocal}function zr(t){return Ps(t)&&pn(t)}function yy(t){return t.isLocal}function by(t,e){const n=[];let i=new TextEncoder().encode(t);for(;i.length>e;){let r=e;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}n.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&n.push(i),n}function ky(t){var e;const n=t.get("Cache-Control");if(n){const i=(e=n.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(i)return parseInt(i,10)}}function Cy(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=Sy(t,e);return n?i:mo(i,"v1")}function Sy(t,e){const n=new URL(py(t));return e.forEach((i,r)=>{n.searchParams.set(r,i)}),mo(n,"rtc")}function Ty(t){const e=new URL(wi(t));return mo(e,"validate")}function ju(t){return t.endsWith("/")?t:"".concat(t,"/")}function mo(t,e){return t.pathname="".concat(ju(t.pathname)).concat(e),t}function Ka(t){if(typeof t=="string")return wa.fromJson(JSON.parse(t),{ignoreUnknownFields:!0});if(t instanceof ArrayBuffer)return wa.fromBinary(new Uint8Array(t));throw new Error("could not decode websocket message: ".concat(typeof t))}function wy(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(t instanceof AbortSignal))return e;const n=t.reason;switch(typeof n){case"string":return n;case"object":return n instanceof Error?n.message:e;default:return"toString"in n?n.toString():e}}const xy=10,ai="lk_e2ee",_y="LKFrameEncryptionKey",Ey={sharedKey:!1,ratchetSalt:_y,ratchetWindowSize:8,failureTolerance:xy,keyringSize:16};var un;(function(t){t.SetKey="setKey",t.RatchetRequest="ratchetRequest",t.KeyRatcheted="keyRatcheted"})(un||(un={}));var Ga;(function(t){t.KeyRatcheted="keyRatcheted"})(Ga||(Ga={}));var an;(function(t){t.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",t.EncryptionError="encryptionError"})(an||(an={}));var $a;(function(t){t.Error="cryptorError"})($a||($a={}));function Py(){return Ry()||Rs()}function Rs(){return typeof window.RTCRtpScriptTransform<"u"}function Ry(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Iy(t){var e,n,i,r,s;if(((e=t.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((n=t.value)===null||n===void 0?void 0:n.case)!=="metrics"&&((i=t.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((r=t.value)===null||r===void 0?void 0:r.case)!=="transcription"&&((s=t.value)===null||s===void 0?void 0:s.case)!=="encryptedPacket")return new Rl({value:t.value})}class vS extends Lt.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(n,i,r)=>{ce.debug("key ratcheted event received",{ratchetResult:n,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Ey),e),this.on(un.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,n,i){const r={key:e,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(n??"shared","-").concat(i??0),r),this.emit(un.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,n){this.emit(un.RatchetRequest,e,n)}}var Ja;(function(t){t[t.InvalidKey=0]="InvalidKey",t[t.MissingKey=1]="MissingKey",t[t.InternalError=2]="InternalError"})(Ja||(Ja={}));class My extends Lt.EventEmitter{constructor(e,n){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var r,s;const{kind:a,data:o}=i.data;switch(a){case"error":if(ce.error(o.error.message),o.uuid){const u=this.decryptDataRequests.get(o.uuid);if(u!=null&&u.reject){u.reject(o.error);break}const d=this.encryptDataRequests.get(o.uuid);if(d!=null&&d.reject){d.reject(o.error);break}}this.emit(an.EncryptionError,o.error,o.participantIdentity);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(u=>{this.postKey(u)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(u=>{this.postKey(u)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity))this.emit(an.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const u=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(o.participantIdentity);if(!u)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(an.ParticipantEncryptionStatusChanged,o.enabled,u)}break;case"ratchetKey":this.keyProvider.emit(un.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(o.uuid);c!=null&&c.resolve&&c.resolve(o);break;case"encryptDataResponse":const l=this.encryptDataRequests.get(o.uuid);l!=null&&l.resolve&&l.resolve(o);break}},this.onWorkerError=i=>{ce.error("e2ee worker encountered an error:",{error:i.error}),this.emit(an.EncryptionError,i.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=n}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Py())throw new ho("tried to setup end-to-end encryption on an unsupported browser");if(ce.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const n={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:w0.getLevel()}};this.worker&&(ce.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(n))}}setParticipantCryptorEnabled(e,n){ce.debug("set e2ee to ".concat(e," for participant ").concat(n)),this.postEnable(e,n)}setSifTrailer(e){!e||e.length===0?ce.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(z.RTPVideoMapUpdate,n=>{this.postRTPMap(n)})}setupEventListeners(e,n){e.on(U.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==Le.NONE,r.identity)),e.on(U.ConnectionStateChanged,i=>{i===me.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==Le.NONE,r.identity)})})}).on(U.TrackUnsubscribed,(i,r,s)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(U.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(U.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");n.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(H.LocalSenderCreated,(i,r)=>v(this,void 0,void 0,function*(){this.setupE2EESender(r,i)})),e.localParticipant.on(H.LocalTrackPublished,i=>{if(!pn(i.track)||!Ti())return;const r={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:gi(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(r)}),n.on(un.SetKey,i=>this.postKey(i)).on(un.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}encryptData(e){return v(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const n=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:n,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new vt;return r.onFinally=()=>{this.encryptDataRequests.delete(n)},this.encryptDataRequests.set(n,r),this.worker.postMessage(i),r.promise})}handleEncryptedData(e,n,i,r){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const s=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:n,participantIdentity:i,keyIndex:r}},o=new vt;return o.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,n){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:n}};this.worker.postMessage(i)}postKey(e){let{key:n,participantIdentity:i,keyIndex:r}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity),key:n,keyIndex:r}};this.worker.postMessage(a)}postEnable(e,n){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:n}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var n;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((n=this.room)===null||n===void 0)&&n.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const n={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(n)}setupE2EEReceiver(e,n,i){if(e.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,n,e.kind==="video"?gi(i.mimeType):void 0)}}setupE2EESender(e,n){if(!zn(e)||!n){n||ce.warn("early return because sender is not ready");return}this.handleSender(n,e.mediaStreamID,void 0)}handleReceiver(e,n,i,r){return v(this,void 0,void 0,function*(){if(this.worker){if(Rs()&&!Ba()){const s={kind:"decode",participantIdentity:i,trackId:n,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(ai in e&&r){const c={kind:"updateCodec",data:{trackId:n,codec:r,participantIdentity:i}};this.worker.postMessage(c);return}let s=e.writableStream,a=e.readableStream;if(!s||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,s=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:s,trackId:n,codec:r,participantIdentity:i,isReuse:ai in e}};this.worker.postMessage(o,[a,s])}e[ai]=!0}})}handleSender(e,n,i){var r;if(!(ai in e||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Rs()&&!Ba()){ce.info("initialize script transform");const s={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:n,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{ce.info("initialize encoded streams");const s=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:s.readable,writableStream:s.writable,codec:i,trackId:n,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(a,[s.readable,s.writable])}e[ai]=!0}}}const Oy=500,Ay=15e3;class Wn{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Wn),this._instance}addFailedConnectionAttempt(e){var n;const i=new URL(e),r=Fr(i);if(!r)return;let s=(n=this.failedConnectionAttempts.get(r))!==null&&n!==void 0?n:0;this.failedConnectionAttempts.set(r,s+1),this.backOffPromises.set(r,Ve(Math.min(Oy*Math.pow(2,s),Ay)))}getBackOffPromise(e){const n=new URL(e),i=n&&Fr(n);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const n=new URL(e),i=n&&Fr(n);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Wn._instance=null;const Wr="default";class Fe{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Fe),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return v(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;if(((s=Fe.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){ce.debug("awaiting getUserMedia promise");try{n?yield Fe.userMediaPromiseMap.get(n):yield Promise.all(Fe.userMediaPromiseMap.values())}catch{ce.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(r&&!(xn()&&i.hasDeviceInUse(n))&&(a.filter(c=>c.kind===n).length===0||a.some(c=>{const l=c.label==="",u=n?c.kind===n:!0;return l&&u}))){const c={video:n!=="audioinput"&&n!=="audiooutput",audio:n!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);a=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(u=>{u.stop()})}return i._previousDevices=a,n&&(a=a.filter(o=>o.kind===n)),a})()})}normalizeDeviceId(e,n,i){return v(this,void 0,void 0,function*(){if(n!==Wr)return n;const r=yield this.getDevices(e),s=r.find(o=>o.deviceId===Wr);if(!s){ce.warn("could not reliably determine default device");return}const a=r.find(o=>o.deviceId!==Wr&&o.groupId===(i??s.groupId));if(!a){ce.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?Fe.userMediaPromiseMap.has(e):Fe.userMediaPromiseMap.size>0}}Fe.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];Fe.userMediaPromiseMap=new Map;var vi;(function(t){t[t.WAITING=0]="WAITING",t[t.RUNNING=1]="RUNNING",t[t.COMPLETED=2]="COMPLETED"})(vi||(vi={}));class Dy{constructor(){this.pendingTasks=new Map,this.taskMutex=new Ye,this.nextTaskIndex=0}run(e){return v(this,void 0,void 0,function*(){const n={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:vi.WAITING};this.pendingTasks.set(n.id,n);const i=yield this.taskMutex.lock();try{return n.executedAt=Date.now(),n.status=vi.RUNNING,yield e()}finally{n.status=vi.COMPLETED,this.pendingTasks.delete(n.id),i()}})}flush(){return v(this,void 0,void 0,function*(){return this.run(()=>v(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class Ny{get readyState(){return this.ws.readyState}constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,r;if(!((i=n.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const s=new WebSocket(e,(r=n.protocols)!==null&&r!==void 0?r:[]);s.binaryType="arraybuffer",this.ws=s;const a=function(){let{closeCode:o,reason:c}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return s.close(o,c)};this.opened=new tt((o,c)=>{const l=()=>{c(ie.websocket("Encountered websocket error during connection establishment"))};s.onopen=()=>{o({readable:new ReadableStream({start(u){s.onmessage=d=>{let{data:h}=d;return u.enqueue(h)},s.onerror=d=>u.error(d)},cancel:a}),writable:new WritableStream({write(u){s.send(u)},abort(){s.close()},close:a}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",l)},s.addEventListener("error",l)}),this.closed=new tt((o,c)=>{const l=()=>v(this,void 0,void 0,function*(){const u=new tt(h=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",f=>{h(f)},{once:!0})}),d=yield tt.race([Ve(250),u]);d?o(d):c(ie.websocket("Encountered unspecified websocket error without a timely close event"))});s.onclose=u=>{let{code:d,reason:h}=u;o({closeCode:d,reason:h}),s.removeEventListener("error",l)},s.addEventListener("error",l)}),n.signal&&(n.signal.onabort=()=>s.close()),this.close=a}}const Ly=["syncState","trickle","offer","answer","simulate","leave"];function jy(t){const e=Ly.indexOf(t.case)>=0;return ce.trace("request allowed to bypass queue:",{canPass:e,req:t}),e}var ke;(function(t){t[t.CONNECTING=0]="CONNECTING",t[t.CONNECTED=1]="CONNECTED",t[t.RECONNECTING=2]="RECONNECTING",t[t.DISCONNECTING=3]="DISCONNECTING",t[t.DISCONNECTED=4]="DISCONNECTED"})(ke||(ke={}));const Uy=250;class go{get currentState(){return this.state}get isDisconnected(){return this.state===ke.DISCONNECTING||this.state===ke.DISCONNECTED}get isEstablishingConnection(){return this.state===ke.CONNECTING||this.state===ke.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=ke.DISCONNECTED,this.log=ce,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=Gt((i=n.loggerName)!==null&&i!==void 0?i:_t.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=e,this.requestQueue=new Dy,this.queuedRequests=[],this.closingLock=new Ye,this.connectionLock=new Ye,this.state=ke.DISCONNECTED}get logContext(){var e,n;return(n=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&n!==void 0?n:{}}join(e,n,i,r){return v(this,arguments,void 0,function(s,a,o,c){var l=this;let u=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){return l.state=ke.CONNECTING,l.options=o,yield l.connect(s,a,o,c,u)})()})}reconnect(e,n,i,r){return v(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=ke.RECONNECTING,this.clearPingInterval(),yield this.connect(e,n,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}),void 0,this.useV0SignalPath)})}connect(e,n,i,r){return v(this,arguments,void 0,function(s,a,o,c){var l=this;let u=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){const d=yield l.connectionLock.lock();l.connectOptions=o,l.useV0SignalPath=u;const h=hy(),f=u?Fy(a,h,o):By(a,h,o),m=Cy(s,f,u).toString(),g=Ty(m).toString();return new Promise((w,b)=>v(l,void 0,void 0,function*(){var P,_;try{let S=!1;const T=A=>v(this,void 0,void 0,function*(){if(S)return;S=!0;const R=A instanceof Event?A.currentTarget:A,N=wy(R,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(N)).catch(Y=>{this.log.error(Y),this.close()}):this.close(),C(),b(ie.cancelled(N))});c==null||c.addEventListener("abort",T);const C=()=>{clearTimeout(O),c==null||c.removeEventListener("abort",T)},O=setTimeout(()=>{T(ie.timeout("room connection has timed out (signal)"))},o.websocketTimeout),L=(A,R)=>{this.handleSignalConnected(A,O,R)},I=new URL(m);I.searchParams.has("access_token")&&I.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(I),Object.assign({reconnect:o.reconnect,reconnectReason:o.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new Ny(m);try{this.ws.closed.then($=>{var Q;this.isEstablishingConnection&&b(ie.internal("Websocket got closed during a (re)connection attempt: ".concat($.reason))),$.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:$.reason,code:$.closeCode,wasClean:$.closeCode===1e3,state:this.state})),this.state===ke.CONNECTED&&this.handleOnClose((Q=$.reason)!==null&&Q!==void 0?Q:"Unexpected WS error"))}).catch($=>{this.isEstablishingConnection&&b(ie.internal("Websocket error during a (re)connection attempt: ".concat($)))});const A=yield this.ws.opened.catch($=>v(this,void 0,void 0,function*(){if(this.state!==ke.CONNECTED){this.state=ke.DISCONNECTED,clearTimeout(O);const Q=yield this.handleConnectionError($,g);b(Q);return}this.handleWSError($),b($)}));if(clearTimeout(O),!A)return;const R=A.readable.getReader();this.streamWriter=A.writable.getWriter();const N=yield R.read();if(R.releaseLock(),!N.value)throw ie.internal("no message received as first message");const Y=Ka(N.value),G=this.validateFirstMessage(Y,(P=o.reconnect)!==null&&P!==void 0?P:!1);if(!G.isValid){b(G.error);return}((_=Y.message)===null||_===void 0?void 0:_.case)==="join"&&(this.pingTimeoutDuration=Y.message.value.pingTimeout,this.pingIntervalDuration=Y.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})));const j=G.shouldProcessFirstMessage?Y:void 0;L(A,j),w(G.response)}catch(A){b(A)}finally{C()}}finally{d()}}))})()})}startReadingLoop(e,n){return v(this,void 0,void 0,function*(){for(n&&this.handleSignalResponse(n);;){this.signalLatency&&(yield Ve(this.signalLatency));const{done:i,value:r}=yield e.read();if(i)break;const s=Ka(r);this.handleSignalResponse(s)}})}close(){return v(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([ke.DISCONNECTING||ke.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const r=yield e.closingLock.lock();try{if(e.clearPingInterval(),n&&(e.state=ke.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const s=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([s,Ve(Uy)])}}catch(s){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:s}))}finally{n&&(e.state=ke.DISCONNECTED),r()}})()})}sendOffer(e,n){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Nn(e,n)})}sendAnswer(e,n){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Nn(e,n)})}sendIceCandidate(e,n){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new fr({candidateInit:JSON.stringify(e),target:n})})}sendMuteTrack(e,n){return this.sendRequest({case:"mute",value:new pr({sid:e,muted:n})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,n){return v(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const o=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new oo({requestId:o,metadata:i,name:r,attributes:a})}),o})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,n){return this.sendRequest({case:"updateLayers",value:new Wl({trackSid:e,layers:n})})}sendUpdateSubscriptionPermissions(e,n){return this.sendRequest({case:"subscriptionPermission",value:new Gl({allParticipants:e,trackPermissions:n})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:xe.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Yl({timestamp:xe.parse(Date.now()),rtt:xe.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,n){return this.sendRequest({case:"updateAudioTrack",value:new so({trackSid:e,features:n})})}sendLeave(){return this.sendRequest({case:"leave",value:new gr({reason:xt.CLIENT_INITIATED,action:Fn.DISCONNECT})})}sendRequest(e){return v(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!r&&!jy(n)&&i.state===ke.RECONNECTING){i.queuedRequests.push(()=>v(i,void 0,void 0,function*(){yield this.sendRequest(n,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield Ve(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(n.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(n==null?void 0:n.case),i.logContext);return}const a=new Jv({message:n});try{i.useJSON?yield i.streamWriter.write(a.toJsonString()):yield i.streamWriter.write(a.toBinary())}catch(o){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:o}))}})()})}handleSignalResponse(e){var n,i;const r=e.message;if(r==null){this.log.debug("received unsupported message",this.logContext);return}let s=!1;if(r.case==="answer"){const a=Ya(r.value);this.onAnswer&&this.onAnswer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="offer"){const a=Ya(r.value);this.onOffer&&this.onOffer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="trickle"){const a=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(a,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((n=r.value.participants)!==null&&n!==void 0?n:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):r.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(r.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:r.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return v(this,void 0,void 0,function*(){if(this.state===ke.DISCONNECTED)return;const n=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),n&&n(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Be.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Be.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Be.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Be.clearInterval(this.pingInterval)}handleSignalConnected(e,n,i){this.state=ke.CONNECTED,clearTimeout(n),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,n){var i,r,s,a,o;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===ke.RECONNECTING&&((r=e.message)===null||r===void 0?void 0:r.case)!=="leave"?((s=e.message)===null||s===void 0?void 0:s.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((a=e.message)===null||a===void 0?void 0:a.case)==="leave"?{isValid:!1,error:ie.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:n?{isValid:!1,error:ie.internal("Unexpected first message")}:{isValid:!1,error:ie.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,n){return v(this,void 0,void 0,function*(){try{const i=yield fetch(n);switch(i.status){case 404:return ie.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const r=yield i.text();return ie.notAllowed(r,i.status);default:break}return e instanceof ie?e:ie.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof ie?i:ie.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function Ya(t){const e={type:"offer",sdp:t.sdp};switch(t.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=t.type;break}return e}function Nn(t,e){return new hn({sdp:t.sdp,type:t.type,id:e})}function Fy(t,e,n){var i;const r=new URLSearchParams;return r.set("access_token",t),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid)),r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",Dt()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),n.adaptiveStream&&r.set("adaptive_stream","1"),n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}function By(t,e,n){const i=new URLSearchParams;i.set("access_token",t);const r=new v0({clientInfo:e,connectionSettings:new Ql({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0});n.reconnectReason&&(r.reconnectReason=n.reconnectReason);const s=new y0({joinRequest:r.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(s.toBinary()))),i}class Qa{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const n=this.buffer[0];if(this._totalSize-n.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Vy{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,n){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const r=i+this.ttl;return this._map.set(e,{value:n,expiresAt:r}),this}get(e){const n=this._map.get(e);if(n){if(n.expiresAt<Date.now()){this._map.delete(e);return}return n.value}}has(e){const n=this._map.get(e);return n?n.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[n,i]of this._map.entries())i.expiresAt<e&&this._map.delete(n);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,n,this.asValueMap())}map(e){this.cleanup();const n=[],i=this.asValueMap();for(const[r,s]of i.entries())n.push(e(s,r,i));return n}asValueMap(){const e=new Map;for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(n,i.value);return e}}var kt={},Hr={},Kr={exports:{}},Xa;function vo(){if(Xa)return Kr.exports;Xa=1;var t=Kr.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var n="candidate:%s %d %s %d %s %d typ %s";return n+=e.raddr!=null?" raddr %s rport %d":"%v%v",n+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(n+=" generation %d"),n+=e["network-id"]!=null?" network-id %d":"%v",n+=e["network-cost"]!=null?" network-cost %d":"%v",n}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var n="ssrc:%d";return e.attribute!=null&&(n+=" %s",e.value!=null&&(n+=":%s")),n}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var n="mediaclk:";return n+=e.id!=null?"id=%s %s":"%v%s",n+=e.mediaClockValue!=null?"=%s":"",n+=e.rateNumerator!=null?" rate=%s":"",n+=e.rateDenominator!=null?"/%s":"",n}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(t).forEach(function(e){var n=t[e];n.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),Kr.exports}var Za;function qy(){return Za||(Za=1,(function(t){var e=function(o){return String(Number(o))===o?Number(o):o},n=function(o,c,l,u){if(u&&!l)c[u]=e(o[1]);else for(var d=0;d<l.length;d+=1)o[d+1]!=null&&(c[l[d]]=e(o[d+1]))},i=function(o,c,l){var u=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:u&&!c[o.name]&&(c[o.name]={});var d=o.push?{}:u?c[o.name]:c;n(l.match(o.reg),d,o.names,o.name),o.push&&c[o.push].push(d)},r=vo(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(o){var c={},l=[],u=c;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(d){var h=d[0],f=d.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var m=0;m<(r[h]||[]).length;m+=1){var g=r[h][m];if(g.reg.test(f))return i(g,u,f)}}),c.media=l,c};var a=function(o,c){var l=c.split(/=(.+)/,2);return l.length===2?o[l[0]]=e(l[1]):l.length===1&&c.length>1&&(o[l[0]]=void 0),o};t.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(o){return o.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(o){for(var c=[],l=o.split(" ").map(e),u=0;u<l.length;u+=3)c.push({component:l[u],ip:l[u+1],port:l[u+2]});return c},t.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},t.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(l){var u,d=!1;return l[0]!=="~"?u=e(l):(u=e(l.substring(1,l.length)),d=!0),{scid:u,paused:d}})})}})(Hr)),Hr}var Gr,ec;function zy(){if(ec)return Gr;ec=1;var t=vo(),e=/%[sdv%]/g,n=function(a){var o=1,c=arguments,l=c.length;return a.replace(e,function(u){if(o>=l)return u;var d=c[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(d);case"%d":return Number(d);case"%v":return""}})},i=function(a,o,c){var l=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,u=[a+"="+l];if(o.names)for(var d=0;d<o.names.length;d+=1){var h=o.names[d];o.name?u.push(c[o.name][h]):u.push(c[o.names[d]])}else u.push(c[o.name]);return n.apply(null,u)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return Gr=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(d){d.payloads==null&&(d.payloads="")});var c=o.outerOrder||r,l=o.innerOrder||s,u=[];return c.forEach(function(d){t[d].forEach(function(h){h.name in a&&a[h.name]!=null?u.push(i(d,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(f){u.push(i(d,h,f))})})}),a.media.forEach(function(d){u.push(i("m",t.m[0],d)),l.forEach(function(h){t[h].forEach(function(f){f.name in d&&d[f.name]!=null?u.push(i(h,f,d)):f.push in d&&d[f.push]!=null&&d[f.push].forEach(function(m){u.push(i(h,f,m))})})})}),u.join(`\r
53
+ `)+`\r
54
+ `},Gr}var tc;function Wy(){if(tc)return kt;tc=1;var t=qy(),e=zy(),n=vo();return kt.grammar=n,kt.write=e,kt.parse=t.parse,kt.parseParams=t.parseParams,kt.parseFmtpConfig=t.parseFmtpConfig,kt.parsePayloads=t.parsePayloads,kt.parseRemoteCandidates=t.parseRemoteCandidates,kt.parseImageAttributes=t.parseImageAttributes,kt.parseSimulcastStreamList=t.parseSimulcastStreamList,kt}var sn=Wy();function yo(t,e,n){var i,r,s;e===void 0&&(e=50),n===void 0&&(n={});var a=(i=n.isImmediate)!=null&&i,o=(r=n.callback)!=null&&r,c=n.maxWait,l=Date.now(),u=[];function d(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),m=this;return new Promise(function(g,w){var b=a&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!a){var _=t.apply(m,f);o&&o(_),u.forEach(function(S){return(0,S.resolve)(_)}),u=[]}},d()),b){var P=t.apply(m,f);return o&&o(P),g(P)}u.push({resolve:g,reject:w})})};return h.cancel=function(f){s!==void 0&&clearTimeout(s),u.forEach(function(m){return(0,m.reject)(f)}),u=[]},h}const Hy=.7,Ky=20,Hn={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class nc extends Lt.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=ce,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=yo(r=>v(this,void 0,void 0,function*(){this.emit(Hn.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),Ky),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Gt((i=n.loggerName)!==null&&i!==void 0?i:_t.PCTransport),this.loggerOptions=n,this.config=e,this._pc=this.createPC(),this.offerLock=new Ye}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=n=>{var i;n.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,n.candidate))},e.onicecandidateerror=n=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,n)},e.oniceconnectionstatechange=()=>{var n;(n=this.onIceConnectionStateChange)===null||n===void 0||n.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var n;(n=this.onSignalingStatechange)===null||n===void 0||n.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var n;(n=this.onConnectionStateChange)===null||n===void 0||n.call(this,e.connectionState)},e.ondatachannel=n=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,n)},e.ontrack=n=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,n)},e}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return v(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,n){return v(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&n>0&&n!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:n,latestOfferId:this.latestOfferId})),!1;let r;if(e.type==="offer"){let{stereoMids:s,nackMids:a}=Gy(e);this.remoteStereoMids=s,this.remoteNackMids=a}else if(e.type==="answer"){const s=sn.parse((i=e.sdp)!==null&&i!==void 0?i:"");s.media.forEach(a=>{const o=bo(a.mid);a.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||o!=c.transceiver.mid)return!1;let l=0;if(a.rtp.some(d=>d.codec.toUpperCase()===c.codec.toUpperCase()?(l=d.payload,!0):!1),l===0)return!0;let u=!1;for(const d of a.fmtp)if(d.payload===l){d.config=d.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),u=!0;break}return u||c.maxbr>0&&a.fmtp.push({payload:l,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),r=sn.write(s)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Hn.NegotiationComplete),e.sdp&&sn.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(Hn.RTPVideoPayloadTypes,a.rtp)})),!0})}createAndSendOffer(e){return v(this,void 0,void 0,function*(){var n;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=this.latestOfferId+1;this.latestOfferId=r;const s=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:s.sdp},this.logContext));const a=sn.parse((n=s.sdp)!==null&&n!==void 0?n:"");if(a.media.forEach(o=>{rc(o),o.type==="audio"?ic(o,["all"],[]):o.type==="video"&&this.trackBitrates.some(c=>{if(!o.msid||!c.cid||!o.msid.includes(c.cid))return!1;let l=0;if(o.rtp.some(d=>d.codec.toUpperCase()===c.codec.toUpperCase()?(l=d.payload,!0):!1),l===0||(wt(c.codec)&&!xn()&&this.ensureVideoDDExtensionForSVC(o,a),!wt(c.codec)))return!0;const u=Math.round(c.maxbr*Hy);for(const d of o.fmtp)if(d.payload===l){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(u));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(s,sn.write(a)),this.onOffer(s,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return v(this,void 0,void 0,function*(){var e;const n=yield this.pc.createAnswer(),i=sn.parse((e=n.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{rc(r),r.type==="audio"&&ic(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,sn.write(i)),n})}createDataChannel(e,n){return this.pc.createDataChannel(e,n)}addTransceiver(e,n){return this.pc.addTransceiver(e,n)}addTransceiverOfKind(e,n){return this.pc.addTransceiver(e,n)}addTrack(e){if(!this._pc)throw new Re("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var n;if(!this._pc)throw new Re("PC closed, cannot configure");return(n=this._pc)===null||n===void 0?void 0:n.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var n;return(n=this._pc)===null||n===void 0?void 0:n.removeTrack(e)}getConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&n!==void 0?n:"closed"}getICEConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&n!==void 0?n:"closed"}getSignallingState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&n!==void 0?n:"closed"}getTransceivers(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&n!==void 0?n:[]}getSenders(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&n!==void 0?n:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return v(this,void 0,void 0,function*(){var e;if(!this._pc)return;let n="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":n=o.selectedCandidatePairId;break;case"candidate-pair":n===""&&o.selected&&(n=o.id),i.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),n==="")return;const a=(e=i.get(n))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,n,i){return v(this,void 0,void 0,function*(){if(n){const r=e.sdp;e.sdp=n;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:n})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const a={error:s,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new Vn(s)}})}ensureVideoDDExtensionForSVC(e,n){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Fa))){if(this.ddExtID===0){let a=0;n.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(l=>{l.value>a&&(a=l.value)}))}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:Fa})}}}function ic(t,e,n){const i=bo(t.mid);let r=0;t.rtp.some(s=>s.codec==="opus"?(r=s.payload,!0):!1),r>0&&(t.rtcpFb||(t.rtcpFb=[]),n.includes(i)&&!t.rtcpFb.some(s=>s.payload===r&&s.type==="nack")&&t.rtcpFb.push({payload:r,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&t.fmtp.some(s=>s.payload===r?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function Gy(t){var e;const n=[],i=[],r=sn.parse((e=t.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(a=>{var o;const c=bo(a.mid);a.type==="audio"&&(a.rtp.some(l=>l.codec==="opus"?(s=l.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(l=>l.payload===s&&l.type==="nack")&&i.push(c),a.fmtp.some(l=>l.payload===s?(l.config.includes("sprop-stereo=1")&&n.push(c),!0):!1))}),{stereoMids:n,nackMids:i}}function rc(t){if(t.connection){const e=t.connection.ip.indexOf(":")>=0;(t.connection.version===4&&e||t.connection.version===6&&!e)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}function bo(t){return typeof t=="number"?t.toFixed(0):t}const Is="vp8",$y={audioPreset:Cs.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:fo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Is,backupCodec:!0,preConnectBuffer:!1},Uu={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Fu={deviceId:{ideal:"default"},resolution:Si.h720.resolution},Jy={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new _0,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},ko={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var _e;(function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"})(_e||(_e={}));class Yy{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,n,i){var r;this.peerConnectionTimeout=ko.peerConnectionTimeout,this.log=ce,this.updateState=()=>{var s,a;const o=this.state,c=this.requiredTransports.map(l=>l.getConnectionState());c.every(l=>l==="connected")?this.state=_e.CONNECTED:c.some(l=>l==="failed")?this.state=_e.FAILED:c.some(l=>l==="connecting")?this.state=_e.CONNECTING:c.every(l=>l==="closed")?this.state=_e.CLOSED:c.some(l=>l==="closed")?this.state=_e.CLOSING:c.every(l=>l==="new")&&(this.state=_e.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(_e[o]," to ").concat(_e[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.log=Gt((r=i.loggerName)!==null&&r!==void 0?r:_t.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=n!=="subscriber-primary",this.isSubscriberConnectionRequired=n==="subscriber-primary",this.publisher=new nc(e,i),this._mode=n,n!=="publisher-only"&&(this.subscriber=new nc(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Tt.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,s)},this.subscriber.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Tt.PUBLISHER)},this.publisher.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)},this.publisher.onOffer=(s,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,s,a)},this.state=_e.NEW,this.connectionLock=new Ye,this.remoteOfferLock=new Ye}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,n){return this.publisher.setRemoteDescription(e,n)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return v(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const n=this.publisher;for(const i of n.getSenders())try{n.canRemoveTrack()&&n.removeTrack(i)}catch(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return v(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,n){return v(this,void 0,void 0,function*(){var i;n===Tt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,n){return v(this,void 0,void 0,function*(){var i,r,s;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const a=yield this.remoteOfferLock.lock();try{return(yield(r=this.subscriber)===null||r===void 0?void 0:r.setRemoteDescription(e,n))?yield(s=this.subscriber)===null||s===void 0?void 0:s.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,n){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),n&&this.triggerIceRestart()}ensurePCTransportConnection(e,n){return v(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,n)))}finally{r()}})}negotiate(e){return v(this,void 0,void 0,function*(){return new tt((n,i)=>v(this,void 0,void 0,function*(){const r=setTimeout(()=>{i(new Vn("negotiation timed out"))},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i(new Vn("negotiation aborted"))};e.signal.addEventListener("abort",s),this.publisher.once(Hn.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Hn.NegotiationComplete,()=>{clearTimeout(r),n()})}),yield this.publisher.negotiate(a=>{clearTimeout(r),a instanceof Error?i(a):i(new Error(String(a)))})}))})}addPublisherTransceiver(e,n){return this.publisher.addTransceiver(e,n)}addPublisherTransceiverOfKind(e,n){return this.publisher.addTransceiverOfKind(e,n)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(r=>r.receiver===e);return i==null?void 0:i.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,n){return this.publisher.createDataChannel(e,n)}getConnectedAddress(e){return e===Tt.PUBLISHER?this.publisher.getConnectedAddress():e===Tt.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,n){return v(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,l)=>v(s,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Be.clearTimeout(d),l(ie.cancelled("room connection has been cancelled"))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=Be.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),l(ie.internal("could not establish pc connection"))},a);for(;this.state!==_e.CONNECTED;)if(yield Ve(50),r!=null&&r.signal.aborted){l(ie.cancelled("room connection has been cancelled"));return}Be.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),c()}))})()})}}const Bu=5e3,Qy=3e4;class pe{static fetchRegionSettings(e,n,i){return v(this,void 0,void 0,function*(){const r=yield pe.fetchLock.lock();try{const s=yield fetch("".concat(Xy(e),"/regions"),{headers:{authorization:"Bearer ".concat(n)},signal:i});if(s.ok){const a=ky(s.headers),o=a?a*1e3:Bu;return{regionSettings:yield s.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw s.status===401?ie.notAllowed("Could not fetch region settings: ".concat(s.statusText),s.status):ie.internal("Could not fetch region settings: ".concat(s.statusText))}catch(s){throw s instanceof ie?s:i!=null&&i.aborted?ie.cancelled("Region fetching was aborted"):ie.serverUnreachable("Could not fetch region settings, ".concat(s instanceof Error?"".concat(s.name,": ").concat(s.message):s))}finally{r()}})}static scheduleRefetch(e,n,i){return v(this,void 0,void 0,function*(){const r=pe.settingsTimeouts.get(e.hostname);clearTimeout(r),pe.settingsTimeouts.set(e.hostname,setTimeout(()=>v(this,void 0,void 0,function*(){try{const s=yield pe.fetchRegionSettings(e,n);pe.updateCachedRegionSettings(e,n,s)}catch(s){if(s instanceof ie&&s.reason===Ce.NotAllowed){ce.debug("token is not valid, cancelling auto region refresh");return}ce.debug("auto refetching of region settings failed",{error:s}),pe.scheduleRefetch(e,n,i)}}),i))})}static updateCachedRegionSettings(e,n,i){pe.cache.set(e.hostname,i),pe.scheduleRefetch(e,n,i.maxAgeInMs)}static stopRefetch(e){const n=pe.settingsTimeouts.get(e);n&&(clearTimeout(n),pe.settingsTimeouts.delete(e))}static scheduleCleanup(e){let n=pe.connectionTrackers.get(e);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{const i=pe.connectionTrackers.get(e);i&&i.connectionCount===0&&(ce.debug("stopping region refetch after disconnect delay",{hostname:e}),pe.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},Qy))}static cancelCleanup(e){const n=pe.connectionTrackers.get(e);n!=null&&n.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let n=pe.connectionTrackers.get(e);n||(n={connectionCount:0},pe.connectionTrackers.set(e,n)),n.connectionCount++,pe.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,n=pe.connectionTrackers.get(e);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&pe.scheduleCleanup(e))}constructor(e,n){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=n}updateToken(e){this.token=e}isCloud(){return $n(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return v(this,void 0,void 0,function*(){return pe.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return v(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let n=pe.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(e),pe.updateCachedRegionSettings(this.serverUrl,this.token,n));const i=n.regionSettings.regions.filter(r=>!this.attemptedRegions.find(s=>s.url===r.url));if(i.length>0){const r=i[0];return this.attemptedRegions.push(r),ce.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){pe.updateCachedRegionSettings(this.serverUrl,this.token,e)}}pe.cache=new Map;pe.settingsTimeouts=new Map;pe.connectionTrackers=new Map;pe.fetchLock=new Ye;function Xy(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class Pe extends Error{constructor(e,n,i){super(n),this.code=e,this.message=sc(n,Pe.MAX_MESSAGE_BYTES),this.data=i?sc(i,Pe.MAX_DATA_BYTES):void 0}static fromProto(e){return new Pe(e.code,e.message,e.data)}toProto(){return new Ol({code:this.code,message:this.message,data:this.data})}static builtIn(e,n){return new Pe(Pe.ErrorCode[e],Pe.ErrorMessage[e],n)}}Pe.MAX_MESSAGE_BYTES=256;Pe.MAX_DATA_BYTES=15360;Pe.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404};Pe.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const Vu=15360;function Co(t){return new TextEncoder().encode(t).length}function sc(t,e){if(Co(t)<=e)return t;let n=0,i=t.length;const r=new TextEncoder;for(;n<i;){const s=Math.floor((n+i+1)/2);r.encode(t.slice(0,s)).length<=e?n=s:i=s-1}return t.slice(0,n)}const So=2e3;function yr(t,e){if(!e)return 0;let n,i;return"bytesReceived"in t?(n=t.bytesReceived,i=e.bytesReceived):"bytesSent"in t&&(n=t.bytesSent,i=e.bytesSent),n===void 0||i===void 0||t.timestamp===void 0||e.timestamp===void 0?0:(n-i)*8*1e3/(t.timestamp-e.timestamp)}const To=typeof MediaRecorder<"u";class Zy{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const eb=To?MediaRecorder:Zy;class tb extends eb{constructor(e,n){if(!To)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),n);let i,r;const s=()=>r===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),r==null||r.close(),r=void 0},o=c=>{r==null||r.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),r=void 0};this.byteStream=new ReadableStream({start:c=>{r=c,i=l=>v(this,void 0,void 0,function*(){let u;if(l.data.arrayBuffer){const d=yield l.data.arrayBuffer();u=new Uint8Array(d)}else if(l.data.byteArray)u=l.data.byteArray;else throw new Error("no data available!");s()||c.enqueue(u)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function nb(){return To}const ib=1e3,rb=1e4;class qu extends M{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,n,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,n,s),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=yo(()=>v(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>v(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(V.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Ye,this.pauseUpstreamLock=new Ye,this.trackChangeLock=new Ye,this.trackChangeLock.lock().then(a=>v(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==M.Kind.Video)return;const{width:e,height:n}=this._mediaStreamTrack.getSettings();if(e&&n)return{width:e,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,n;return(n=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&n!==void 0?n:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,n){return v(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!n)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{qn(this._mediaStreamTrack,s)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Dn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{Dn(r??e,s)}))})}waitForDimensions(){return v(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ib;return(function*(){var i;if(e.kind===M.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=rt())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Ve(10));const r=Date.now();for(;Date.now()-r<n;){const s=e.dimensions;if(s)return s;yield Ve(50)}throw new Kt("unable to get track dimensions after timeout")})()})}setDeviceId(e){return v(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===ln(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),ln(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return v(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===M.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===M.Kind.Audio?"audioinput":"videoinput";return n?Fe.getInstance().normalizeDeviceId(s,i,r):i})()})}mute(){return v(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return v(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,n){return v(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Kt("unable to replace an unpublished track");let r,s;return typeof n=="boolean"?r=n:n!==void 0&&(r=n.userProvidedTrack,s=n.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return v(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,s=E0(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===M.Kind.Video?a.video=i||r?{deviceId:i,facingMode:r}:!0:a.audio=i?Object.assign({deviceId:i},s):!0,this.attachedElements.forEach(l=>{qn(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===M.Kind.Video&&(yield c.applyConstraints(s)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(V.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?V.Muted:V.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return v(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Du()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return v(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(V.UpstreamPaused,this);const i=rt();if((i==null?void 0:i.name)==="Safari"&&Nt(i.version,"12.0")<0)throw new ho("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{n()}})}resumeUpstream(){return v(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(V.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}})}getRTCStatsReport(){return v(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return v(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;const a=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield n.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Dn(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:l})),setTimeout(()=>{o.play().catch(u=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:u}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))}),i.processor=n,i.processorElement=o,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(qn(i._mediaStreamTrack,l),Dn(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(V.TrackProcessorUpdate,i.processor)}finally{a()}})()})}getProcessor(){return this.processor}stopProcessor(){return v(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(n)}finally{i()}})()})}internalStopProcessor(){return v(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,n||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(V.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!nb()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let n="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(n)||(n="video/mp4"),this.localTrackRecorder=new tb(this,{mimeType:n})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},rb)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class sr extends qu{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,M.Kind.Audio,n,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>v(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=yr(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(V.AudioTrackFeatureUpdate,this,Ue.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(V.AudioTrackFeatureUpdate,this,Ue.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return v(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===M.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return v(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==ln(this._constraints.deviceId);return this.source===M.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{n()}})}restartTrack(e){return v(this,void 0,void 0,function*(){let n;if(e){const i=po({audio:e});typeof i.audio!="boolean"&&(n=i.audio)}yield this.restart(n)})}restart(e){const n=Object.create(null,{restart:{get:()=>super.restart}});return v(this,void 0,void 0,function*(){const i=yield n.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){nt()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},So)))}setProcessor(e){return v(this,void 0,void 0,function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!Dt()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(n=this.sender)===null||n===void 0?void 0:n.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(V.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return v(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const n=yield this.sender.getStats();let i;return n.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return v(this,void 0,void 0,function*(){const e=yield Mu(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(V.AudioSilenceDetected)),e})}}function sb(t,e,n){switch(t.kind){case"audio":return new sr(t,e,!1,void 0,n);case"video":return new or(t,e,!1,n);default:throw new Kt("unsupported track type: ".concat(t.kind))}}const ob=Object.values(Si),ab=Object.values(Ss),cb=Object.values(fo),lb=[Si.h180,Si.h360],ub=[Ss.h180,Ss.h360],db=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(n=>{var i,r;return new ye(Math.floor(t.width/n.scaleResolutionDownBy),Math.floor(t.height/n.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(n.scaleResolutionDownBy,2)*(((i=t.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=n.fps)!==null&&r!==void 0?r:30))))),n.fps,t.encoding.priority)}),Ms=["q","h","f"];function Os(t,e,n,i){var r,s;let a=i==null?void 0:i.videoEncoding;t&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!a&&!o&&!c||!e||!n)return[{}];a||(a=fb(t,e,n,l),ce.debug("using video encoding",a));const u=a.maxFramerate,d=new ye(e,n,a.maxBitrate,a.maxFramerate,a.priority);if(c&&wt(l)){const m=new zu(c),g=[];if(m.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const w=rt();if(Ti()||Dt()||(w==null?void 0:w.name)==="Chrome"&&Nt(w==null?void 0:w.version,"113")<0){const b=m.suffix=="h"?2:3,P=cy(w);for(let _=0;_<m.spatial;_+=1)g.push({rid:Ms[2-_],maxBitrate:a.maxBitrate/Math.pow(b,_),maxFramerate:d.encoding.maxFramerate,scaleResolutionDownBy:P?Math.pow(2,_):void 0});g[0].scalabilityMode=c}else g.push({maxBitrate:a.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:c});return d.encoding.priority&&(g[0].priority=d.encoding.priority,g[0].networkPriority=d.encoding.priority),ce.debug("using svc encoding",{encodings:g}),g}if(!o)return[a];let h=[];t?h=(r=ac(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:oc(t,d):h=(s=ac(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:oc(t,d);let f;if(h.length>0){const m=h[0];h.length>1&&([,f]=h);const g=Math.max(e,n);if(g>=960&&f)return $r(e,n,[m,f,d],u);if(g>=480)return $r(e,n,[m,d],u)}return $r(e,n,[d])}function hb(t,e,n){var i,r,s,a;if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;e!==n.backupCodec.codec&&ce.warn("requested a different codec than specified as backup",{serverRequested:e,backup:n.backupCodec.codec}),n.videoCodec=e,n.videoEncoding=n.backupCodec.encoding;const o=t.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(r=t.dimensions)===null||r===void 0?void 0:r.width,l=(s=o.height)!==null&&s!==void 0?s:(a=t.dimensions)===null||a===void 0?void 0:a.height;return t.source===M.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),Os(t.source===M.Source.ScreenShare,c,l,n)}function fb(t,e,n,i){const r=pb(t,e,n);let{encoding:s}=r[0];const a=Math.max(e,n);for(let o=0;o<r.length;o+=1){const c=r[o];if(s=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function pb(t,e,n){if(t)return cb;const i=e>n?e/n:n/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?ob:ab}function oc(t,e){if(t)return db(e);const{width:n,height:i}=e,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?lb:ub}function $r(t,e,n,i){const r=[];if(n.forEach((s,a)=>{if(a>=Ms.length)return;const o=Math.min(t,e),l={rid:Ms[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},u=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;u&&(l.maxFramerate=u);const d=wn()||a===0;s.encoding.priority&&d&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),Dt()&&Lu()==="ios"){let s;r.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let a=!0;r.forEach(o=>{var c;o.maxFramerate!=s&&(a&&(a=!1,ce.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ce.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function ac(t){if(t)return t.sort((e,n)=>{const{encoding:i}=e,{encoding:r}=n;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class zu{constructor(e){const n=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!n)throw new Error("invalid scalability mode");if(this.spatial=parseInt(n[1]),this.temporal=parseInt(n[2]),n.length>3)switch(n[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=n[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function mb(t){return t.source===M.Source.ScreenShare||t.constraints.height&&ln(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const gb=5e3;class or extends qu{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,M.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>v(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const a=new Map(s.map(c=>[c.rid,c])),o=s.some(c=>c.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(V.CpuConstrained)),this.prevStats){let c=0;a.forEach((l,u)=>{var d;const h=(d=this.prevStats)===null||d===void 0?void 0:d.get(u);c+=yr(l,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new Ye}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var n;if(this.signalClient=e,!nt())return;const i=(n=this.sender)===null||n===void 0?void 0:n.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},So))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return v(this,void 0,void 0,function*(){var n,i,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=Ht(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;o=!0)s=l.value,o=!1,yield(a=s.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(u){i={error:u}}finally{try{!o&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return v(this,void 0,void 0,function*(){var n,i,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=Ht(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;o=!0){s=l.value,o=!1;const u=s;yield(a=u.sender)===null||a===void 0?void 0:a.replaceTrack(u.mediaStreamTrack)}}catch(u){i={error:u}}finally{try{!o&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return v(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===M.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return v(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.source===M.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{n()}})}setTrackMuted(e){super.setTrackMuted(e);for(const n of this.simulcastCodecs.values())n.mediaStreamTrack.enabled=!e}getSenderStats(){return v(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const n=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const a={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},o=i.get(r.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),n.push(a)}}),n.sort((r,s)=>{var a,o;return((a=s.frameWidth)!==null&&a!==void 0?a:0)-((o=r.frameWidth)!==null&&o!==void 0?o:0)}),n})}setPublishingQuality(e){const n=[];for(let i=dt.LOW;i<=dt.HIGH;i+=1)n.push(new ao({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(wt(this.codec),n)}restartTrack(e){return v(this,void 0,void 0,function*(){var n,i,r,s,a;let o;if(e){const d=po({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,l=Ht(this.simulcastCodecs.values()),u;u=yield l.next(),n=u.done,!n;c=!0){s=u.value,c=!1;const d=s;d.sender&&((a=d.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){i={error:d}}finally{try{!c&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}setProcessor(e){const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return v(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,c,l,u,d;if(yield n.setProcessor.call(r,i,s),!((u=r.processor)===null||u===void 0)&&u.processedTrack)try{for(var h=!0,f=Ht(r.simulcastCodecs.values()),m;m=yield f.next(),a=m.done,!a;h=!0)l=m.value,h=!1,yield(d=l.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(g){o={error:g}}finally{try{!h&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return v(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const n=this.sender.getParameters();n.degradationPreference=e,this.sender.setParameters(n)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},this.logContext))}})}addSimulcastTrack(e,n){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:n};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,n){const i=this.simulcastCodecs.get(e);i&&(i.sender=n,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},gb))}setPublishingCodecs(e){return v(this,void 0,void 0,function*(){var n,i,r,s,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(wt(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(n=!0,i=Ht(e);r=yield i.next(),s=r.done,!s;n=!0){c=r.value,n=!1;const u=c;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(wt(u.codec),u.qualities);else{const d=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const h of u.qualities)if(h.enabled){l.push(u.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield cc(d.sender,d.encodings,u.qualities,this.senderLock,wt(u.codec),this.log,this.logContext))}}}catch(u){a={error:u}}finally{try{!n&&!s&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return l})}setPublishingLayers(e,n){return v(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:n}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:n})),!(!this.sender||!this.encodings)&&(yield cc(this.sender,this.encodings,n,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return v(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const n=this.sender.getParameters();n.encodings=n.encodings.map((i,r)=>{var s;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&wt(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),this.encodings=n.encodings,yield this.sender.setParameters(n)}catch(n){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:n})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return v(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Du()&&this.isInBackground&&this.source===M.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function cc(t,e,n,i,r,s,a){return v(this,void 0,void 0,function*(){const o=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:t,qualities:n,senderEncodings:e}));try{const c=t.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:l,senderEncodings:e}));return}let u=!1;!1&&l[0].scalabilityMode||(r&&n.some(f=>f.enabled)&&n.forEach(f=>f.enabled=!0),l.forEach((h,f)=>{var m;let g=(m=h.rid)!==null&&m!==void 0?m:"";g===""&&(g="q");const w=Wu(g),b=n.find(P=>P.quality===w);b&&h.active!==b.enabled&&(u=!0,h.active=b.enabled,s.debug("setting layer ".concat(b.quality," to ").concat(h.active?"enabled":"disabled"),a),wn()&&(b.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),u&&(c.encodings=l,s.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:c.encodings})),yield t.setParameters(c))}finally{o()}})}function Wu(t){switch(t){case"f":return dt.HIGH;case"h":return dt.MEDIUM;case"q":return dt.LOW;default:return dt.HIGH}}function lc(t,e,n,i){if(!n)return[new cn({quality:dt.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,s=new zu(r),a=[],o=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)a.push(new cn({quality:Math.min(dt.HIGH,s.spatial-1)-l,width:Math.ceil(t/Math.pow(o,l)),height:Math.ceil(e/Math.pow(o,l)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return a}return n.map(r=>{var s,a,o;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=Wu((a=r.rid)!==null&&a!==void 0?a:"");return new cn({quality:l,width:Math.ceil(t/c),height:Math.ceil(e/c),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const uc="_lossy",dc="_reliable",vb=2*1e3,Jr="leave-reconnect",yb=3e4,bb=8*1024,kb=256*1024;var pt;(function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"})(pt||(pt={}));class Cb extends Lt.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var n;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=ko.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=pt.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=ce,this.reliableDataSequence=1,this.reliableMessageBuffer=new Qa,this.reliableReceivedState=new Vy(yb),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>v(this,[i],void 0,function(r){var s=this;let{channel:a}=r;return(function*(){if(a){if(a.label===dc)s.reliableDCSub=a;else if(a.label===uc)s.lossyDCSub=a;else return;s.log.debug("on data channel ".concat(a.id,", ").concat(a.label),s.logContext),a.onmessage=s.handleDataMessage}})()}),this.handleDataMessage=i=>v(this,void 0,void 0,function*(){var r,s,a,o,c;const l=yield this.dataProcessLock.lock();try{let u;if(i.data instanceof ArrayBuffer)u=i.data;else if(i.data instanceof Blob)u=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const d=Je.fromBinary(new Uint8Array(u));if(d.sequence>0&&d.participantSid!==""){const h=this.reliableReceivedState.get(d.participantSid);if(h&&d.sequence<=h)return;this.reliableReceivedState.set(d.participantSid,d.sequence)}if(((r=d.value)===null||r===void 0?void 0:r.case)==="speaker")this.emit(z.ActiveSpeakersUpdate,d.value.value.speakers);else if(((s=d.value)===null||s===void 0?void 0:s.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(d.value.value.encryptedValue,d.value.value.iv,d.participantIdentity,d.value.value.keyIndex),f=Rl.fromBinary(h.payload),m=new Je({value:f.value,participantIdentity:d.participantIdentity,participantSid:d.participantSid});((o=m.value)===null||o===void 0?void 0:o.case)==="user"&&hc(m,m.value.value),this.emit(z.DataPacketReceived,m,d.value.value.encryptionType)}else((c=d.value)===null||c===void 0?void 0:c.case)==="user"&&hc(d,d.value.value),this.emit(z.DataPacketReceived,d,Le.NONE)}finally{l()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?ue.LOSSY:ue.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(z.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===Jr&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Be.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===pt.Connected&&i();const s=()=>{this.off(z.Disconnected,a),i()},a=()=>{this.off(z.Restarted,s),r()};this.once(z.Restarted,s),this.once(z.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{if(i===ue.RELIABLE){const s=this.dataChannelForKind(i);s&&this.reliableMessageBuffer.alignBufferedAmount(s.bufferedAmount)}const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(z.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>v(this,void 0,void 0,function*(){!this.url||!(yield fetch(wi(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===ke.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===ke.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Cn.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>v(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(wi(this.url),{method:"HEAD"}),Ve(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Gt((n=e.loggerName)!==null&&n!==void 0?n:_t.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new go(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new Ye,this.dataProcessLock=new Ye,this.dcBufferStatus=new Map([[ue.LOSSY,!0],[ue.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(z.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(z.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(z.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(z.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(z.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(z.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(z.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(z.SignalRequestResponse,i)}get logContext(){var e,n,i,r,s,a;return{room:(n=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||n===void 0?void 0:n.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(a=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||a===void 0?void 0:a.identity,pID:this.participantSid}}join(e,n,i,r){return v(this,arguments,void 0,function(s,a,o,c){var l=this;let u=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){l.url=s,l.token=a,l.signalOpts=o,l.maxJoinAttempts=o.maxRetries;try{l.joinAttempts+=1,l.setupSignalClientCallbacks();const d=yield l.client.join(s,a,o,c,u);return l._isClosed=!1,l.latestJoinResponse=d,l.subscriberPrimary=d.subscriberPrimary,l.pcManager||(yield l.configure(d,!u)),(!l.subscriberPrimary||d.fastPublish)&&l.negotiate().catch(h=>{ce.error(h,l.logContext)}),l.registerOnLineListener(),l.clientConfiguration=d.clientConfiguration,l.emit(z.SignalConnected,d),d}catch(d){if(d instanceof ie){if(d.reason===Ce.ServerUnreachable){if(l.log.warn("Couldn't connect to server, attempt ".concat(l.joinAttempts," of ").concat(l.maxJoinAttempts),l.logContext),l.joinAttempts<l.maxJoinAttempts)return l.join(s,a,o,c,u)}else if(d.reason===Ce.ServiceNotFound)return l.log.warn("Initial connection failed: ".concat(d.message," – Retrying")),l.join(s,a,o,c,!0)}throw d}})()})}close(){return v(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(z.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return v(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const n=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};n(this.lossyDC),n(this.lossyDCSub),n(this.reliableDC),n(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Qa,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return v(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Kt("a track with the same ID has already been published");return new Promise((n,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(ie.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),n(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:n}=this.pendingTrackResolvers[e.track.id];n&&n(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(n){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:n}))}return!1}updateMuteStatus(e,n){this.client.sendMuteTrack(e,n)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return v(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,n){return v(this,void 0,void 0,function*(){var i,r;if(this.pcManager&&this.pcManager.currentState!==_e.NEW)return;this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const s=this.makeRTCConfiguration(e);this.pcManager=new Yy(s,n?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(z.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(a,o)=>{this.client.sendIceCandidate(a,o)},this.pcManager.onPublisherOffer=(a,o)=>{this.client.sendOffer(a,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(a,o,c)=>v(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(a),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),a===_e.CONNECTED){const d=this.pcState===pt.New;this.pcState=pt.Connected,d&&this.emit(z.Connected,e)}else a===_e.FAILED&&(this.pcState===pt.Connected||this.pcState===pt.Reconnecting)&&(this.pcState=pt.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?Cn.RR_SUBSCRIBER_FAILED:Cn.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===ke.RECONNECTING,u=[_e.FAILED,_e.CLOSING,_e.CLOSED].includes(a);l&&u&&!this._isClosed&&this.emit(z.Offline)}),this.pcManager.onTrack=a=>{a.streams.length!==0&&this.emit(z.MediaTrackAdded,a.track,a.streams[0],a.receiver)},Sb((r=e.serverInfo)===null||r===void 0?void 0:r.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,n,i)=>v(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,n))}),this.client.onTrickle=(e,n)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:n})),this.pcManager.addIceCandidate(e,n))},this.client.onOffer=(e,n,i)=>v(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=n,!this.pcManager)return;this.midToTrackId=i;const r=yield this.pcManager.createSubscriberAnswerFromOffer(e,n);r&&this.client.sendAnswer(r,n)}),this.client.onLocalTrackPublished=e=>{var n;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(n=e.track)===null||n===void 0?void 0:n.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(z.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(z.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var n;this.token=e,(n=this.regionUrlProvider)===null||n===void 0||n.updateToken(e)},this.client.onRemoteMuteChanged=(e,n)=>{this.emit(z.RemoteMute,e,n)},this.client.onSubscribedQualityUpdate=e=>{this.emit(z.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var n;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(z.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var n,i;const r={direction:"recvonly"};for(let s=0;s<e.numAudios;s++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("audio",r);for(let s=0;s<e.numVideos;s++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",r);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",Cn.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:Bu,regionSettings:e.regions})),e.action){case Fn.DISCONNECT:this.emit(z.Disconnected,e==null?void 0:e.reason),this.close();break;case Fn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Jr);break;case Fn.RESUME:this.handleDisconnect(Jr)}}}makeRTCConfiguration(e){var n;const i=Object.assign({},this.rtcConfig);if(!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(s=>{const a={urls:s.urls};s.username&&(a.username=s.username),s.credential&&(a.credential=s.credential),r.push(a)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===bi.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(uc,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(dc,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(ue.LOSSY);if(e){const n=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(n,bb),kb)}},1e3))}createSender(e,n,i){return v(this,void 0,void 0,function*(){if(xs())return yield this.createTransceiverRTCRtpSender(e,n,i);if(_s())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Re("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,n,i,r){return v(this,void 0,void 0,function*(){if(xs())return this.createSimulcastTransceiverSender(e,n,i,r);if(_s())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Re("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,n,i){return v(this,void 0,void 0,function*(){if(!this.pcManager)throw new Re("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),pn(e)&&(e.codec=n.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,n,i,r){return v(this,void 0,void 0,function*(){if(!this.pcManager)throw new Re("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const a=yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return v(this,void 0,void 0,function*(){if(!this.pcManager)throw new Re("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return v(this,void 0,void 0,function*(){var n,i,r;if(!this._isClosed){if(this.attemptingReconnect){ce.warn("already attempting reconnect, returning early",this.logContext);return}(((n=this.clientConfiguration)===null||n===void 0?void 0:n.resumeConnection)===bi.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:_e.NEW)===_e.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof Re?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),a=!1):s instanceof On||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Cn.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(z.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(n){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:n}))}return null}restartConnection(e){return v(this,void 0,void 0,function*(){var n,i,r;try{if(!this.url||!this.token)throw new Re("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(z.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new On;s=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(a){throw a instanceof ie&&a.reason===Ce.NotAllowed?new Re("could not reconnect, token might be expired"):new On}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(z.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==ke.CONNECTED)throw new On("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(z.Restarted)}catch(s){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return v(this,void 0,void 0,function*(){var n;if(!this.url||!this.token)throw new Re("could not reconnect, url or token not saved");if(!this.pcManager)throw new Re("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(z.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof ie&&r.reason===Ce.NotAllowed?new Re("could not reconnect, token might be expired"):r instanceof ie&&r.reason===Ce.LeaveRequest?r:new On(s)}if(this.emit(z.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==ke.CONNECTED)throw new On("Signal connection got severed during reconnect");this.client.setReconnected(),((n=this.reliableDC)===null||n===void 0?void 0:n.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(z.Resumed)})}waitForPCInitialConnection(e,n){return v(this,void 0,void 0,function*(){if(!this.pcManager)throw new Re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,e)})}waitForPCReconnected(){return v(this,void 0,void 0,function*(){this.pcState=pt.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ve(vb),!this.pcManager)throw new Re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=pt.Connected}catch(e){throw this.pcState=pt.Disconnected,ie.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,n,i,r){return v(this,void 0,void 0,function*(){const s=new Je({destinationIdentities:[e],kind:ue.RELIABLE,value:{case:"rpcResponse",value:new io({requestId:n,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,ue.RELIABLE)})}publishRpcAck(e,n){return v(this,void 0,void 0,function*(){const i=new Je({destinationIdentities:[e],kind:ue.RELIABLE,value:{case:"rpcAck",value:new no({requestId:n})}});yield this.sendDataPacket(i,ue.RELIABLE)})}sendDataPacket(e,n){return v(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(n),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const s=Iy(e);if(s){const a=yield this.e2eeManager.encryptData(s.toBinary());e.value={case:"encryptedPacket",value:new Pl({encryptedValue:a.payload,iv:a.iv,keyIndex:a.keyIndex})}}}n===ue.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),r=this.dataChannelForKind(n);if(r){if(n===ue.RELIABLE)yield this.waitForBufferStatusLow(n),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(n)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;r.send(i)}this.updateAndEmitDCBufferStatus(n)})}resendReliableMessagesForResume(e){return v(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(ue.RELIABLE);const n=this.dataChannelForKind(ue.RELIABLE);n&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{n.send(i.data)})),this.updateAndEmitDCBufferStatus(ue.RELIABLE)})}waitForBufferStatusLow(e){return new tt((n,i)=>v(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))n();else{const r=()=>i(new Re("engine closed"));for(this.once(z.Closing,r);!this.dcBufferStatus.get(e);)yield Ve(10);this.off(z.Closing,r),n()}}))}ensureDataTransportConnected(e){return v(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var s;if(!i.pcManager)throw new Re("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw ie.internal("".concat(o," connection not set"));let c=!1;!r&&!i.dataChannelForKind(n,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate().catch(d=>{ce.error(d,i.logContext)});const l=i.dataChannelForKind(n,r);if((l==null?void 0:l.readyState)==="open")return;const u=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<u;){if(a.isICEConnected&&((s=i.dataChannelForKind(n,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield Ve(50)}throw ie.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return v(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==_e.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return v(this,void 0,void 0,function*(){return new tt((e,n)=>v(this,void 0,void 0,function*(){if(!this.pcManager){n(new Vn("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&n(new Vn("cannot negotiate on closed engine")),this.on(z.Closing,r),this.pcManager.publisher.once(Hn.RTPVideoPayloadTypes,s=>{const a=new Map;s.forEach(o=>{const c=o.codec.toLowerCase();fy(c)&&a.set(o.payload,c)}),this.emit(z.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Vn&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Cn.RR_UNKNOWN),s instanceof Error?n(s):n(new Error(String(s)))}finally{this.off(z.Closing,r)}}))})}dataChannelForKind(e,n){if(n){if(e===ue.LOSSY)return this.lossyDCSub;if(e===ue.RELIABLE)return this.reliableDCSub}else{if(e===ue.LOSSY)return this.lossyDC;if(e===ue.RELIABLE)return this.reliableDC}}sendSyncState(e,n){var i,r,s,a;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),u=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getLocalDescription(),d=(a=(s=this.signalOpts)===null||s===void 0?void 0:s.autoSubscribe)!==null&&a!==void 0?a:!0,h=new Array,f=new Array;e.forEach(m=>{m.isDesired!==d&&h.push(m.trackSid),m.isEnabled||f.push(m.trackSid)}),this.client.sendSyncState(new co({answer:this.pcManager.mode==="publisher-only"?c?Nn({sdp:c.sdp,type:c.type}):void 0:u?Nn({sdp:u.sdp,type:u.type}):void 0,offer:this.pcManager.mode==="publisher-only"?o?Nn({sdp:o.sdp,type:o.type}):void 0:l?Nn({sdp:l.sdp,type:l.type}):void 0,subscription:new mr({trackSids:h,subscribe:!d,participantTracks:[]}),publishTracks:Y0(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((m,g)=>new $l({publisherSid:g,lastSeq:m}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new Jl({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(ue.LOSSY),Tt.PUBLISHER),n(this.dataChannelForKind(ue.RELIABLE),Tt.PUBLISHER),n(this.dataChannelForKind(ue.LOSSY,!0),Tt.SUBSCRIBER),n(this.dataChannelForKind(ue.RELIABLE,!0),Tt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Be.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){nt()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){nt()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var n;const i=(n=this.pcManager)===null||n===void 0?void 0:n.getMidForReceiver(e);if(i){const r=Object.entries(this.midToTrackId).find(s=>{let[a]=s;return a===i});if(r)return r[1]}}}function Sb(t){return t!==void 0&&t>13}function hc(t,e){const n=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=n,e.participantIdentity=n;const i=t.destinationIdentities.length!==0?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=i,e.destinationIdentities=i}class Hu{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new mt("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),$e.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new mt("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),$e.LengthExceeded)}}constructor(e,n,i,r){this.reader=n,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=r}}class Tb extends Hu{handleChunkReceived(e){var n;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let n=new vt,i=null,r=null;if(this.signal){const a=this.signal;r=()=>{var o;(o=n.reject)===null||o===void 0||o.call(n,a.reason)},a.addEventListener("abort",r),i=a}const s=()=>{e.releaseLock(),i&&r&&i.removeEventListener("abort",r),this.signal=void 0};return{next:()=>v(this,void 0,void 0,function*(){var a,o;try{const{done:c,value:l}=yield Promise.race([e.read(),n.promise,(o=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&o!==void 0?o:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(l),{done:!1,value:l.content})}catch(c){throw s(),c}}),return(){return v(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return v(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,a;let o=new Set;const c=n.signal?e.withAbortSignal(n.signal):e;try{for(var l=!0,u=Ht(c),d;d=yield u.next(),i=d.done,!i;l=!0){a=d.value,l=!1;const h=a;o.add(h)}}catch(h){r={error:h}}finally{try{!l&&!i&&(s=u.return)&&(yield s.call(u))}finally{if(r)throw r.error}}return Array.from(o)})()})}}class wb extends Hu{constructor(e,n,i,r){super(e,n,i,r),this.receivedChunks=new Map}handleChunkReceived(e){var n;const i=$i(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),n=new TextDecoder("utf-8",{fatal:!0});let i=new vt,r=null,s=null;if(this.signal){const o=this.signal;s=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,o.reason)},o.addEventListener("abort",s),r=o}const a=()=>{e.releaseLock(),r&&s&&r.removeEventListener("abort",s),this.signal=void 0};return{next:()=>v(this,void 0,void 0,function*(){var o,c;try{const{done:l,value:u}=yield Promise.race([e.read(),i.promise,(c=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(l)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(u);let d;try{d=n.decode(u.content)}catch(h){throw new mt("Cannot decode datastream chunk ".concat(u.chunkIndex," as text: ").concat(h),$e.DecodeFailed)}return{done:!1,value:d}}}catch(l){throw a(),l}}),return(){return v(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return v(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,a;let o="";const c=n.signal?e.withAbortSignal(n.signal):e;try{for(var l=!0,u=Ht(c),d;d=yield u.next(),i=d.done,!i;l=!0)a=d.value,l=!1,o+=a}catch(h){r={error:h}}finally{try{!l&&!i&&(s=u.return)&&(yield s.call(u))}finally{if(r)throw r.error}}return o})()})}}class xb{constructor(){this.log=ce,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,n){if(this.textStreamHandlers.has(e))throw new mt('A text stream handler for topic "'.concat(e,'" has already been set.'),$e.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,n){if(this.byteStreamHandlers.has(e))throw new mt('A byte stream handler for topic "'.concat(e,'" has already been set.'),$e.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var n,i,r,s;const a=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(a.length>0||o.length>0){const c=new mt("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),$e.AbnormalEnd);for(const[l,u]of o)(i=(n=u.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(n,c),this.byteStreamControllers.delete(l);for(const[l,u]of a)(s=(r=u.outOfBandFailureRejectingFuture).reject)===null||s===void 0||s.call(r,c),this.textStreamControllers.delete(l)}}handleDataStreamPacket(e,n){return v(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,n);case"streamChunk":return this.handleStreamChunk(e.value.value,n);case"streamTrailer":return this.handleStreamTrailer(e.value.value,n);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,n,i){return v(this,void 0,void 0,function*(){var r;if(e.contentHeader.case==="byteHeader"){const s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o=new vt;o.promise.catch(u=>{this.log.error(u)});const c={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:$i(e.timestamp),attributes:e.attributes,encryptionType:i},l=new ReadableStream({start:u=>{if(a=u,this.textStreamControllers.has(e.streamId))throw new mt("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),$e.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:o})}});s(new Tb(c,l,$i(e.totalLength),o),{identity:n})}else if(e.contentHeader.case==="textHeader"){const s=this.textStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o=new vt;o.promise.catch(u=>{this.log.error(u)});const c={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i},l=new ReadableStream({start:u=>{if(a=u,this.textStreamControllers.has(e.streamId))throw new mt("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),$e.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:o})}});s(new wb(c,l,$i(e.totalLength),o),{identity:n})}})}handleStreamChunk(e,n){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new mt("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),$e.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==n?(r.controller.error(new mt("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),$e.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&r.controller.enqueue(e))}handleStreamTrailer(e,n){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==n?i.controller.error(new mt("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),$e.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==n?r.controller.error(new mt("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),$e.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Ku{constructor(e,n,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=n}write(e){return this.defaultWriter.write(e)}close(){return v(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class _b extends Ku{}class Eb extends Ku{}const fc=15e3;class Pb{constructor(e,n){this.engine=e,this.log=n}setupEngine(e){this.engine=e}sendText(e,n){return v(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=n==null?void 0:n.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),l=(d,h)=>{var f;c[h]=d;const m=c.reduce((g,w)=>g+w,0);(f=n==null?void 0:n.onProgress)===null||f===void 0||f.call(n,m)},u=yield this.streamText({streamId:r,totalSize:a,destinationIdentities:n==null?void 0:n.destinationIdentities,topic:n==null?void 0:n.topic,attachedStreamIds:o,attributes:n==null?void 0:n.attributes});return yield u.write(e),l(1,0),yield u.close(),n!=null&&n.attachments&&o&&(yield Promise.all(n.attachments.map((d,h)=>v(this,void 0,void 0,function*(){return this._sendFile(o[h],d,{topic:n.topic,mimeType:d.type,onProgress:f=>{l(f,h+1)}})})))),u.info})}streamText(e){return v(this,void 0,void 0,function*(){var n,i,r;const s=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),a={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?Le.GCM:Le.NONE},o=new tr({streamId:s,mimeType:a.mimeType,topic:a.topic,timestamp:Sn(a.timestamp),totalLength:Sn(e==null?void 0:e.totalSize),attributes:a.attributes,contentHeader:{case:"textHeader",value:new Bl({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?ds.UPDATE:ds.CREATE})}}),c=e==null?void 0:e.destinationIdentities,l=new Je({destinationIdentities:c,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(l,ue.RELIABLE);let u=0;const d=this.engine,h=new WritableStream({write(g){return v(this,void 0,void 0,function*(){for(const w of by(g,fc)){const b=new nr({content:w,streamId:s,chunkIndex:Sn(u)}),P=new Je({destinationIdentities:c,value:{case:"streamChunk",value:b}});yield d.sendDataPacket(P,ue.RELIABLE),u+=1}})},close(){return v(this,void 0,void 0,function*(){const g=new ir({streamId:s}),w=new Je({destinationIdentities:c,value:{case:"streamTrailer",value:g}});yield d.sendDataPacket(w,ue.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let f=()=>v(this,void 0,void 0,function*(){yield m.close()});d.once(z.Closing,f);const m=new _b(h,a,()=>this.engine.off(z.Closing,f));return m})}sendFile(e,n){return v(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,n),{id:i}})}_sendFile(e,n,i){return v(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:n.size,name:n.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:n.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),a=n.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return v(this,void 0,void 0,function*(){var n,i,r,s,a,o;const c=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),l=e==null?void 0:e.destinationIdentities,u={id:c,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?Le.GCM:Le.NONE},d=new tr({totalLength:Sn((o=u.size)!==null&&o!==void 0?o:0),mimeType:u.mimeType,streamId:c,topic:u.topic,timestamp:Sn(Date.now()),attributes:u.attributes,contentHeader:{case:"byteHeader",value:new Vl({name:u.name})}}),h=new Je({destinationIdentities:l,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(h,ue.RELIABLE);let f=0;const m=new Ye,g=this.engine,w=this.log,b=new WritableStream({write(_){return v(this,void 0,void 0,function*(){const S=yield m.lock();let T=0;try{for(;T<_.byteLength;){const C=_.slice(T,T+fc),O=new Je({destinationIdentities:l,value:{case:"streamChunk",value:new nr({content:C,streamId:c,chunkIndex:Sn(f)})}});yield g.sendDataPacket(O,ue.RELIABLE),f+=1,T+=C.byteLength}}finally{S()}})},close(){return v(this,void 0,void 0,function*(){const _=new ir({streamId:c}),S=new Je({destinationIdentities:l,value:{case:"streamTrailer",value:_}});yield g.sendDataPacket(S,ue.RELIABLE)})},abort(_){w.error("Sink error:",_)}});return new Eb(b,u)})}}class Gu extends M{constructor(e,n,i,r,s){super(e,i,s),this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?V.Muted:V.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const n=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(V.Ended,this))};e.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return v(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),So)),Q0()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var n;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(n=this.receiver)===null||n===void 0?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(V.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class Rb extends Gu{constructor(e,n,i,r,s,a){super(e,n,M.Kind.Audio,i,a),this.monitorReceiver=()=>v(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=yr(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var n;for(const i of this.attachedElements)this.audioContext?(n=this.gainNode)===null||n===void 0||n.gain.setTargetAtTime(e,0,.1):i.volume=e;Dt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Dt())return 1;let e=0;return this.attachedElements.forEach(n=>{n.volume>e&&(e=n.volume)}),e}setSinkId(e){return v(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(n=>{if(Es(n))return n.setSinkId(e)}))})}attach(e){const n=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Es(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&n&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let n;return e?(n=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(n=super.detach(),this.disconnectWebAudio()),n}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,n){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(V.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(V.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,n;(e=this.gainNode)===null||e===void 0||e.disconnect(),(n=this.sourceNode)===null||n===void 0||n.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return v(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n;return e.forEach(i=>{i.type==="inbound-rtp"&&(n={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),n})}}const Yr=100;class Ib extends Gu{constructor(e,n,i,r,s){super(e,n,M.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>v(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=yr(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=yo(()=>{this.updateDimensions()},Yr),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===M.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(n=>{e?qn(this._mediaStreamTrack,n):Dn(this._mediaStreamTrack,n)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(n=>n.element===e)===void 0){const n=new Mb(e);this.observeElementInfo(n)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(n=>n===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const n=this.elementInfos.filter(i=>i===e);for(const i of n)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let n=[];if(e)return this.stopObservingElement(e),super.detach(e);n=super.detach();for(const i of n)this.stopObservingElement(i);return n}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return v(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,n={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),n&&i!==""&&r.get(i)&&(n.mimeType=r.get(i).mimeType),n})}stopObservingElement(e){const n=this.elementInfos.filter(i=>i.element===e);for(const i of n)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return v(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var n,i;const r=this.elementInfos.reduce((c,l)=>Math.max(c,l.visibilityChangedAt||0),0),s=!((i=(n=this.adaptiveStreamSettings)===null||n===void 0?void 0:n.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,a=this.elementInfos.some(c=>c.pictureInPicture),o=this.elementInfos.some(c=>c.visible)&&!s||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-r<Yr){Be.setTimeout(()=>{this.updateVisibility()},Yr);return}this.lastVisible=o,this.emit(V.VisibilityChanged,o,this)}}updateDimensions(){var e,n;let i=0,r=0;const s=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*s,c=a.height()*s;o+c>i+r&&(i=o,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((n=this.lastDimensions)===null||n===void 0?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(V.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return n==="screen"?Va():n||(Va()>2?2:1)}}class Mb{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,n){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:a}=i;s===this.element&&(this.isIntersecting=a,this.isPiP=ci(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ci(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=ci(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=n??As(e),this.isPiP=nt()&&ci(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,n,i;this.isIntersecting=As(this.element),this.isPiP=ci(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,za().observe(this.element),qa().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,n,i,r,s;(e=za())===null||e===void 0||e.unobserve(this.element),(n=qa())===null||n===void 0||n.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function ci(t){var e,n;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?As(t,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function As(t,e){const n=e||window;let i=t.offsetTop,r=t.offsetLeft;const s=t.offsetWidth,a=t.offsetHeight,{hidden:o}=t,{display:c}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,i+=t.offsetTop,r+=t.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+a>n.pageYOffset&&r+s>n.pageXOffset&&!o&&c!=="none"}class qt extends Lt.EventEmitter{constructor(e,n,i,r){var s;super(),this.metadataMuted=!1,this.encryption=Le.NONE,this.log=ce,this.handleMuted=()=>{this.emit(V.Muted)},this.handleUnmuted=()=>{this.emit(V.Unmuted)},this.log=Gt((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:_t.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=n,this.trackName=i,this.source=M.Source.Unknown}setTrack(e){this.track&&(this.track.off(V.Muted,this.handleMuted),this.track.off(V.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(V.Muted,this.handleMuted),e.on(V.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),de(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Le.NONE}get audioTrack(){if(Ot(this.track))return this.track}get videoTrack(){if(pn(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=M.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===M.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(t){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(t.SubscriptionStatus||(t.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(t.PermissionStatus||(t.PermissionStatus={}))})(qt||(qt={}));class Ds extends qt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(V.Ended)},this.handleCpuConstrained=()=>{this.track&&pn(this.track)&&this.emit(V.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(V.Ended,this.handleTrackEnded),this.track.off(V.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(V.Ended,this.handleTrackEnded),e.on(V.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return v(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return v(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return v(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return v(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Ot(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(Ue.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(Ue.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(Ue.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(Ue.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(Ue.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Ue.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function br(t,e){return v(this,void 0,void 0,function*(){t??(t={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=Au(t);let a=s.audio,o=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),t.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const d=s.audio.deviceId;s.audio.deviceId={exact:d},n=!0,a=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:d}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const d=s.video.deviceId;s.video.deviceId={exact:d},n=!0,o=Object.assign(Object.assign({},s.video),{deviceId:{ideal:d}})}s.audio===!0?s.audio={deviceId:"default"}:typeof s.audio=="object"&&s.audio!==null&&(s.audio=Object.assign(Object.assign({},s.audio),{deviceId:s.audio.deviceId||"default"})),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const c=Iu(s,Uu,Fu),l=po(c),u=navigator.mediaDevices.getUserMedia(l);s.audio&&(Fe.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Fe.userMediaPromiseMap.delete("audioinput"))),s.video&&(Fe.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Fe.userMediaPromiseMap.delete("videoinput")));try{const d=yield u;return yield Promise.all(d.getTracks().map(h=>v(this,void 0,void 0,function*(){const f=h.kind==="audio";let m=f?c.audio:c.video;(typeof m=="boolean"||!m)&&(m={});let g;const w=f?l.audio:l.video;typeof w!="boolean"&&(g=w);const b=h.getSettings().deviceId;g!=null&&g.deviceId&&ln(g.deviceId)!==b?g.deviceId=b:g||(g={deviceId:b});const P=sb(h,g,e);return P.kind===M.Kind.Video?P.source=M.Source.Camera:P.kind===M.Kind.Audio&&(P.source=M.Source.Microphone),P.mediaStream=d,Ot(P)&&i?yield P.setProcessor(i):pn(P)&&r&&(yield P.setProcessor(r)),P})))}catch(d){if(!n)throw d;return br(Object.assign(Object.assign({},t),{audio:a,video:o}),e)}})}function Ob(t){return v(this,void 0,void 0,function*(){return(yield br({audio:!1,video:!0}))[0]})}function Ab(t){return v(this,void 0,void 0,function*(){return(yield br({audio:!0,video:!1}))[0]})}var on;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(on||(on={}));function Db(t){switch(t){case li.EXCELLENT:return on.Excellent;case li.GOOD:return on.Good;case li.POOR:return on.Poor;case li.LOST:return on.Lost;default:return on.Unknown}}class $u extends Lt.EventEmitter{get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===ki.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Un.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,n,i,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:ki.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=on.Unknown,this.log=ce,this.log=Gt((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:_t.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,n]of this.trackPublications)if(n.source===e)return n}getTrackPublicationByName(e){for(const[,n]of this.trackPublications)if(n.trackName===e)return n}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new vt,this.once(H.Active,()=>{var e,n;(n=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||n===void 0||n.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const n=this.getTrackPublication(M.Source.Camera);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const n=this.getTrackPublication(M.Source.Microphone);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(M.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var n;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Un.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==Un.ACTIVE&&this.emit(H.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const n=this.metadata!==e,i=this.metadata;this.metadata=e,n&&this.emit(H.ParticipantMetadataChanged,i)}_setName(e){const n=this.name!==e;this.name=e,n&&this.emit(H.ParticipantNameChanged,e)}_setAttributes(e){const n=X0(this.attributes,e);this._attributes=e,Object.keys(n).length>0&&this.emit(H.AttributesChanged,n)}setPermissions(e){var n,i,r,s,a,o;const c=this.permissions,l=e.canPublish!==((n=this.permissions)===null||n===void 0?void 0:n.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,d)=>{var h;return u!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[d])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,l&&this.emit(H.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(H.IsSpeakingChanged,e))}setConnectionQuality(e){const n=this._connectionQuality;this._connectionQuality=Db(e),n!==this._connectionQuality&&this.emit(H.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,n;this.activeFuture&&((n=(e=this.activeFuture).reject)===null||n===void 0||n.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(n=>Ot(n.track)&&n.track.setAudioContext(e))}addTrackPublication(e){e.on(V.Muted,()=>{this.emit(H.TrackMuted,e)}),e.on(V.Unmuted,()=>{this.emit(H.TrackUnmuted,e)});const n=e;switch(n.track&&(n.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case M.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case M.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Nb(t){var e,n,i;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Kl({participantIdentity:(e=t.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(n=t.participantSid)!==null&&n!==void 0?n:"",allTracks:(i=t.allowAll)!==null&&i!==void 0?i:!1,trackSids:t.allowedTrackSids||[]})}class Lb extends $u{constructor(e,n,i,r,s,a){super(e,n,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Le.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new vt)},this.handleReconnected=()=>{var o,c;(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||c===void 0||c.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var o,c,l,u,d,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||c===void 0||c.call(o,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((u=(l=this.signalConnectedFuture).reject)===null||u===void 0||u.call(l,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(d=this.activeAgentFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var c,l;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new vt),(l=(c=this.signalConnectedFuture).resolve)===null||l===void 0||l.call(c)},this.handleSignalRequestResponse=o=>{const{requestId:c,reason:l,message:u}=o,d=this.pendingSignalRequests.get(c);d&&(l!==lo.OK&&d.reject(new La(u,l)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let c=o.value.value,l=null,u=null;c.value.case==="payload"?l=c.value.value:c.value.case==="error"&&(u=Pe.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,l,u);break;case"rpcAck":let d=o.value.value;this.handleIncomingRpcAck(d.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(o=>Nb(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,c)=>{if(c===void 0&&(c=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),de(o)));return}this.engine.updateMuteStatus(o.sid,c)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),de(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),de(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const c=this.audioTrackPublications.get(o.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(o,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),de(c))),this.emit(H.LocalTrackCpuConstrained,o,c)},this.handleSubscribedQualityUpdate=o=>v(this,void 0,void 0,function*(){var c,l,u,d,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(o.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!f.videoTrack)return;const m=yield f.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var g=!0,w=Ht(m),b;b=yield w.next(),c=b.done,!c;g=!0){d=b.value,g=!1;const P=d;G0(P)&&(this.log.debug("publish ".concat(P," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),de(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,P,f.options))}}catch(P){l={error:P}}finally{try{!g&&!c&&(u=w.return)&&(yield u.call(w))}finally{if(l)throw l.error}}}),this.handleLocalTrackUnpublished=o=>{const c=this.trackPublications.get(o.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=o=>v(this,void 0,void 0,function*(){if(o.source===M.Source.ScreenShare||o.source===M.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),de(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(Vt(o)||en(o))try{if(nt())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:o.source===M.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),de(o))),c.onchange=()=>{c.state!=="denied"&&(o.isMuted||o.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),de(o))),Vt(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),de(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s,this.roomOutgoingDataStreamManager=a}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Le.NONE}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setupEngine(e){var n;this.engine=e,this.engine.on(z.RemoteMute,(i,r)=>{const s=this.trackPublications.get(i);!s||!s.track||(r?s.mute():s.unmute())}),!((n=this.signalConnectedFuture)===null||n===void 0)&&n.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(z.Connected,this.handleReconnected).on(z.SignalConnected,this.handleSignalConnected).on(z.SignalRestarted,this.handleReconnected).on(z.SignalResumed,this.handleReconnected).on(z.Restarting,this.handleReconnecting).on(z.Resuming,this.handleReconnecting).on(z.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(z.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(z.Closing,this.handleClosing).on(z.SignalRequestResponse,this.handleSignalRequestResponse).on(z.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return v(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return v(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return v(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return v(this,arguments,void 0,function(n){var i=this;let{metadata:r,name:s,attributes:a}=n;return(function*(){return new tt((o,c)=>v(i,void 0,void 0,function*(){var l,u;try{let d=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(u=s??this.name)!==null&&u!==void 0?u:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:m=>{c(m),d=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-f<5e3&&!d;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(m=>{let[g,w]=m;return this.attributes[g]===w||w===""&&!this.attributes[g]}))){this.pendingSignalRequests.delete(h),o();return}yield Ve(50)}c(new La("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error?c(d):c(new Error(String(d)))}}))})()})}setCameraEnabled(e,n,i){return this.setTrackEnabled(M.Source.Camera,e,n,i)}setMicrophoneEnabled(e,n,i){return this.setTrackEnabled(M.Source.Microphone,e,n,i)}setScreenShareEnabled(e,n,i){return this.setTrackEnabled(M.Source.ScreenShare,e,n,i)}setE2EEEnabled(e){return v(this,void 0,void 0,function*(){this.encryptionType=e?Le.GCM:Le.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,n,i,r){return v(this,void 0,void 0,function*(){var s,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:n})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(n)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case M.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case M.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case M.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Kt(e)}}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l instanceof Error&&this.emit(H.MediaDevicesError,l,ws(e)),this.pendingPublishing.delete(e),l}for(const l of c){const u=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===M.Source.Microphone&&Ot(l)&&u.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer())}try{const l=[];for(const d of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),de(d))),l.push(this.publishTrack(d,r));[o]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===M.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(M.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return v(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(M.Source.Camera)||this.pendingPublishing.has(M.Source.Microphone))){this.pendingPublishing.add(M.Source.Camera),this.pendingPublishing.add(M.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(n=>this.publishTrack(n)))}finally{this.pendingPublishing.delete(M.Source.Camera),this.pendingPublishing.delete(M.Source.Microphone)}}})}createTracks(e){return v(this,void 0,void 0,function*(){var n,i;e??(e={});const r=Iu(e,(n=this.roomOptions)===null||n===void 0?void 0:n.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield br(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Ot(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=M.Source.Microphone,this.emit(H.AudioStreamAcquired)),pn(o)&&(this.cameraError=void 0,o.source=M.Source.Camera),o))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return v(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new ho("getDisplayMedia not supported");e.resolution===void 0&&!ay()&&(e.resolution=fo.h1080fps30.resolution);const n=J0(e),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new Kt("no video track found");const s=new or(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=M.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(i.getAudioTracks().length>0){this.emit(H.AudioStreamAcquired);const o=new sr(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=M.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,n){return v(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,n)})}publishOrRepublishTrack(e,n){return v(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var o,c,l,u;Vt(i)&&i.setAudioContext(s.audioContext),yield(o=s.reconnectFuture)===null||o===void 0?void 0:o.promise,s.republishPromise&&!a&&(yield s.republishPromise),zn(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let d;if(i instanceof MediaStreamTrack)d=i.getConstraints();else{d=i.constraints;let b;switch(i.source){case M.Source.Microphone:b="audioinput";break;case M.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(d=Object.assign(Object.assign({},d),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new sr(i,d,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new or(i,d,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Kt("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(h=b)}),h)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),de(h))),h;const f=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r),m="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,g=(c=f.forceStereo)!==null&&c!==void 0?c:m;g&&(f.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),de(i))),f.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=f.dtx)!==null&&l!==void 0||(f.dtx=!1),(u=f.red)!==null&&u!==void 0||(f.red=!1)),!ly()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},s.logContext)),f.simulcast=!1),f.source&&(i.source=f.source);const w=new Promise((b,P)=>v(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ke.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:de(i)}));let _=!1;const S=setTimeout(()=>{_=!0,i.stop(),P(new Na("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(S),_)return;const T=yield this.publish(i,f,g);b(T)}else try{const _=yield this.publish(i,f,g);b(_)}catch(_){P(_)}}catch(_){P(_)}}));s.pendingPublishPromises.set(i,w);try{return yield w}catch(b){throw b}finally{s.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new vt),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),de(e))),!1;const{canPublish:n,canPublishSources:i}=this.permissions;return n&&(i.length===0||i.map(r=>Z0(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),de(e))),!1)}publish(e,n,i){return v(this,void 0,void 0,function*(){var r,s,a,o,c,l,u,d,h,f;if(!this.hasPermissionsToPublish(e))throw new Na("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(I=>zn(e)&&I.source===e.source)&&e.source!==M.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),de(e))),n.stopMicTrackOnMute&&Ot(e)&&(e.stopOnMute=!0),e.source===M.Source.ScreenShare&&wn()&&(n.simulcast=!1),n.videoCodec==="av1"&&!ry()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!sy()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=Is),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(I=>n.videoCodec===gi(I.mime))||(n.videoCodec=gi(this.enabledPublishVideoCodecs[0].mime)));const g=n.videoCodec;e.on(V.Muted,this.onTrackMuted),e.on(V.Unmuted,this.onTrackUnmuted),e.on(V.Ended,this.handleTrackEnded),e.on(V.UpstreamPaused,this.onTrackUpstreamPaused),e.on(V.UpstreamResumed,this.onTrackUpstreamResumed),e.on(V.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const w=[],b=!(!((r=n.dtx)!==null&&r!==void 0)||r),P=e.getSourceTrackSettings();P.autoGainControl&&w.push(Ue.TF_AUTO_GAIN_CONTROL),P.echoCancellation&&w.push(Ue.TF_ECHO_CANCELLATION),P.noiseSuppression&&w.push(Ue.TF_NOISE_SUPPRESSION),P.channelCount&&P.channelCount>1&&w.push(Ue.TF_STEREO),b&&w.push(Ue.TF_NO_DTX),Vt(e)&&e.hasPreConnectBuffer&&w.push(Ue.TF_PRECONNECT_BUFFER);const _=new Ci({cid:e.mediaStreamTrack.id,name:n.name,type:M.kindToProto(e.kind),muted:e.isMuted,source:M.sourceToProto(e.source),disableDtx:b,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=n.red)!==null&&s!==void 0)||s),stream:n==null?void 0:n.stream,backupCodecPolicy:n==null?void 0:n.backupCodecPolicy,audioFeatures:w});let S;if(e.kind===M.Kind.Video){let I={width:0,height:0};try{I=yield e.waitForDimensions()}catch{const R=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:Si.h720.resolution;I={width:R.width,height:R.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),de(e)),{dims:I}))}_.width=I.width,_.height=I.height,en(e)&&(wt(g)&&(e.source===M.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),de(e))))),n.scalabilityMode=(c=n.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),_.simulcastCodecs=[new fs({codec:g,cid:e.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:Is}),n.backupCodec&&g!==n.backupCodec.codec&&_.encryption===Le.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),_.simulcastCodecs.push(new fs({codec:n.backupCodec.codec,cid:""})))),S=Os(e.source===M.Source.ScreenShare,_.width,_.height,n),_.layers=lc(_.width,_.height,S,wt(n.videoCodec))}else e.kind===M.Kind.Audio&&(S=[{maxBitrate:(l=n.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(d=(u=n.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&d!==void 0?d:"high",networkPriority:(f=(h=n.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Re("cannot publish track when not connected");const T=()=>v(this,void 0,void 0,function*(){var I,A,R;if(!this.engine.pcManager)throw new Re("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,n,S),this.emit(H.LocalSenderCreated,e.sender,e),en(e)&&((I=n.degradationPreference)!==null&&I!==void 0||(n.degradationPreference=mb(e)),e.setDegradationPreference(n.degradationPreference)),S)if(wn()&&e.kind===M.Kind.Audio){let N;for(const Y of this.engine.pcManager.publisher.getTransceivers())if(Y.sender===e.sender){N=Y;break}N&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:N,codec:"opus",maxbr:!((A=S[0])===null||A===void 0)&&A.maxBitrate?S[0].maxBitrate/1e3:0})}else e.codec&&wt(e.codec)&&(!((R=S[0])===null||R===void 0)&&R.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:_.cid,codec:e.codec,maxbr:S[0].maxBitrate/1e3});yield this.engine.negotiate()});let C;const O=new Promise((I,A)=>v(this,void 0,void 0,function*(){var R;try{C=yield this.engine.addTrack(_),I(C)}catch(N){e.sender&&(!((R=this.engine.pcManager)===null||R===void 0)&&R.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(Y=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),de(e)),{error:Y}))})),A(N)}}));if(this.enabledPublishVideoCodecs.length>0)C=(yield Promise.all([O,T()]))[0];else{C=yield O;let I;if(C.codecs.forEach(A=>{I===void 0&&(I=A.mimeType)}),I&&e.kind===M.Kind.Video){const A=gi(I);A!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),de(e)),{codec:A})),n.videoCodec=A,S=Os(e.source===M.Source.ScreenShare,_.width,_.height,n))}yield T()}const L=new Ds(e.kind,C,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(L.on(V.CpuConstrained,I=>this.onTrackCpuConstrained(I,L)),L.options=n,e.sid=C.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:S,trackInfo:C})),en(e)?e.startMonitor(this.engine.client):Vt(e)&&e.startMonitor(),this.addTrackPublication(L),this.emit(H.LocalTrackPublished,L),Vt(e)&&C.audioFeatures.includes(Ue.TF_PRECONNECT_BUFFER)){const I=e.getPreConnectBuffer(),A=e.getPreConnectBufferMimeType();this.on(H.LocalTrackSubscribed,R=>{if(R.trackSid===C.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),de(e))),e.stopPreConnectBuffer()}}),I&&new Promise((N,Y)=>v(this,void 0,void 0,function*(){var G,j,$,Q,ee,ne;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),de(e)));const y=setTimeout(()=>{Y(new Error("agent not active within 10 seconds"))},1e4),J=yield this.waitUntilActiveAgentPresent();clearTimeout(y),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),de(e)));const X=yield this.streamBytes({name:"preconnect-buffer",mimeType:A,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[J.identity],attributes:{trackId:L.trackSid,sampleRate:String((ee=P.sampleRate)!==null&&ee!==void 0?ee:"48000"),channels:String((ne=P.channelCount)!==null&&ne!==void 0?ne:"1")}});try{for(var k=!0,K=Ht(I),Z;Z=yield K.next(),G=Z.done,!G;k=!0){Q=Z.value,k=!1;const W=Q;yield X.write(W)}}catch(W){j={error:W}}finally{try{!k&&!G&&($=K.return)&&(yield $.call(K))}finally{if(j)throw j.error}}yield X.close(),N()}catch(y){Y(y)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),de(e)))}).catch(N=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),de(e)),{error:N}))})}return L})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,n,i){return v(this,void 0,void 0,function*(){var r;if(this.encryptionType!==Le.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new Kt("track is not published");if(!en(e))throw new Kt("track is not a video track");const a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),o=hb(e,n,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),de(e)));return}const c=e.addSimulcastTrack(n,o);if(!c)return;const l=new Ci({cid:c.mediaStreamTrack.id,type:M.kindToProto(e.kind),muted:e.isMuted,source:M.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=lc(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new Re("cannot publish track when not connected");const u=()=>v(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),u()]))[0];this.log.debug("published ".concat(n," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:h}))})}unpublishTrack(e,n){return v(this,void 0,void 0,function*(){var i,r;if(zn(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),de(e))),yield l)}const s=this.getPublicationForTrack(e),a=s?de(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=s.track,e.off(V.Muted,this.onTrackMuted),e.off(V.Unmuted,this.onTrackUnmuted),e.off(V.Ended,this.handleTrackEnded),e.off(V.UpstreamPaused,this.onTrackUpstreamPaused),e.off(V.UpstreamResumed,this.onTrackUpstreamResumed),e.off(V.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),n===void 0&&(n=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),n?e.stop():e.stopMonitor();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<_e.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),en(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(o=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case M.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case M.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(H.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return v(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return v(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new tt((s,a)=>v(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(n&&(c.options=Object.assign(Object.assign({},c.options),n)),o.push(c))}),yield Promise.all(o.map(c=>v(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==M.Source.ScreenShare&&l.source!==M.Source.ScreenShareAudio&&(Vt(l)||en(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return v(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const s=r.reliable?ue.RELIABLE:ue.LOSSY,a=r.destinationIdentities,o=r.topic;let c=new eo({participantIdentity:i.identity,payload:n,destinationIdentities:a,topic:o});const l=new Je({kind:s,value:{case:"user",value:c}});yield i.engine.sendDataPacket(l,s)})()})}publishDtmf(e,n){return v(this,void 0,void 0,function*(){const i=new Je({kind:ue.RELIABLE,value:{case:"sipDtmf",value:new Ml({code:e,digit:n})}});yield this.engine.sendDataPacket(i,ue.RELIABLE)})}sendChatMessage(e,n){return v(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:n==null?void 0:n.attachments},r=new Je({value:{case:"chatMessage",value:new er(Object.assign(Object.assign({},i),{timestamp:xe.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,ue.RELIABLE),this.emit(H.ChatMessage,i),i})}editChatMessage(e,n){return v(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},n),{message:e,editTimestamp:Date.now()}),r=new Je({value:{case:"chatMessage",value:new er(Object.assign(Object.assign({},i),{timestamp:xe.parse(i.timestamp),editTimestamp:xe.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,ue.RELIABLE),this.emit(H.ChatMessage,i),i})}sendText(e,n){return v(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,n)})}streamText(e){return v(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,n){return v(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,n)})}streamBytes(e){return v(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:n,method:i,payload:r,responseTimeout:s=15e3}=e;const a=7e3,o=a+1e3;return new tt((c,l)=>v(this,void 0,void 0,function*(){var u,d,h,f;if(Co(r)>Vu){l(Pe.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((d=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||d===void 0)&&d.version&&Nt((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){l(Pe.builtIn("UNSUPPORTED_SERVER"));return}const m=Math.max(s,o),g=crypto.randomUUID();yield this.publishRpcRequest(n,g,i,r,m);const w=setTimeout(()=>{this.pendingAcks.delete(g),l(Pe.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(g),clearTimeout(b)},a);this.pendingAcks.set(g,{resolve:()=>{clearTimeout(w)},participantIdentity:n});const b=setTimeout(()=>{this.pendingResponses.delete(g),l(Pe.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(g,{resolve:(P,_)=>{clearTimeout(b),this.pendingAcks.has(g)&&(this.log.warn("RPC response received before ack",g),this.pendingAcks.delete(g),clearTimeout(w)),_?l(_):c(P??"")},participantIdentity:n})}))}registerRpcMethod(e,n){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=n,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const n=this.pendingAcks.get(e);n?(n.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,n,i){const r=this.pendingResponses.get(e);r?(r.resolve(n,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,n,i,r,s){return v(this,void 0,void 0,function*(){const a=new Je({destinationIdentities:[e],kind:ue.RELIABLE,value:{case:"rpcRequest",value:new to({id:n,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(a,ue.RELIABLE)})}handleParticipantDisconnected(e){for(const[n,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(n);for(const[n,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,Pe.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(n=>n.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(n=>{var i,r;const s=this.trackPublications.get(n.sid);if(s){const a=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==n.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),de(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(n.sid,a))}}),!0):!1}setActiveAgent(e){var n,i,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.resolve)===null||i===void 0||i.call(n,e):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new vt),this.activeAgentFuture.promise)}getPublicationForTrack(e){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(Vt(r)||en(r))&&r.mediaStreamTrack===e&&(n=i):e===r&&(n=i))}),n}waitForPendingPublicationOfSource(e){return v(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[a]=s;return a.source===e});if(r)return r[1];yield Ve(20)}})}}class jb extends qt{constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=s=>{this.setTrack(void 0),this.emit(V.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.visible=s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensionsAdaptiveStream=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new mr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Al({participantSid:"",trackSids:[this.trackSid]})]});this.emit(V.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?qt.SubscriptionStatus.Unsubscribed:super.isSubscribed?qt.SubscriptionStatus.Subscribed:qt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?qt.PermissionStatus.Allowed:qt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var n,i;this.isManualOperationAllowed()&&(((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(zr(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&zr(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:dt.HIGH}setTrack(e){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(V.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(V.VisibilityChanged,this.handleVisibilityChange),r.off(V.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(V.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(V.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(V.VisibilityChanged,this.handleVisibilityChange),e.on(V.Ended,this.handleEnded),this.emit(V.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n)}setSubscriptionError(e){this.emit(V.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const n=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):n!==e.muted&&this.emit(e.muted?V.Muted:V.Unmuted)}emitSubscriptionUpdateIfChanged(e){const n=this.subscriptionStatus;e!==n&&this.emit(V.SubscriptionStatusChanged,n,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(V.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return zr(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ql({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===M.Kind.Video){let n=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(n)Ua(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=ey(this.trackInfo,this.requestedMaxQuality);i&&Ua(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(e.width=Math.ceil(n.width),e.height=Math.ceil(n.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:dt.HIGH})),e.quality=dt.HIGH)}this.emit(V.UpdateSettings,e)}}class ar extends $u{static fromParticipantInfo(e,n,i){return new ar(e,n.sid,n.identity,n.name,n.metadata,n.attributes,i,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,n,i,r,s,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:ki.STANDARD;super(n,i||"",r,s,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(V.UpdateSettings,n=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),de(e)),{settings:n})),this.signalClient.sendUpdateTrackSettings(n)}),e.on(V.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),e.on(V.SubscriptionPermissionChanged,n=>{this.emit(H.TrackSubscriptionPermissionChanged,e,n)}),e.on(V.SubscriptionStatusChanged,n=>{this.emit(H.TrackSubscriptionStatusChanged,e,n)}),e.on(V.Subscribed,n=>{this.emit(H.TrackSubscribed,n,e)}),e.on(V.Unsubscribed,n=>{this.emit(H.TrackUnsubscribed,n,e)}),e.on(V.SubscriptionFailed,n=>{this.emit(H.TrackSubscriptionFailed,e.trackSid,n)})}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setVolume(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:M.Source.Microphone;this.volumeMap.set(n,e);const i=this.getTrackPublication(n);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:M.Source.Microphone;const n=this.getTrackPublication(e);return n&&n.track?n.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,n,i,r,s,a){let o=this.getTrackPublicationBySid(n);if(o||n.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),this.emit(H.TrackSubscriptionFailed,n);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,n,i,r,s,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),de(o))),this.emit(H.TrackSubscriptionFailed,n);return}const c=e.kind==="video";let l;return c?l=new Ib(e,n,r,s):l=new Rb(e,n,r,this.audioContext,this.audioOutput),l.source=o.source,l.isMuted=o.isMuted,l.setMediaStream(i),l.start(),o.setTrack(l),this.volumeMap.has(o.source)&&Ps(l)&&Ot(l)&&l.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const n=new Map,i=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{const c=M.kindFromProto(r.type);if(!c)return;o=new jb(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(r),i.set(r.sid,o);const l=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));l&&o.source!==M.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:de(l),newTrack:de(o)})),this.addTrackPublication(o)}n.set(r.sid,o)}),this.trackPublications.forEach(r=>{n.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),de(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(H.TrackPublished,r)}),!0}unpublishTrack(e,n){const i=this.trackPublications.get(e);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case M.Kind.Audio:this.audioTrackPublications.delete(e);break;case M.Kind.Video:this.videoTrackPublications.delete(e);break}n&&this.emit(H.TrackUnpublished,i)}setAudioOutput(e){return v(this,void 0,void 0,function*(){this.audioOutput=e;const n=[];this.audioTrackPublications.forEach(i=>{var r;Ot(i.track)&&Ps(i.track)&&n.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(n)})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var me;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(me||(me={}));const Ub=4*1e3;class Jn extends Lt.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var n,i,r,s,a;if(super(),n=this,this.state=me.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ce,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,c,l)=>v(this,void 0,void 0,function*(){var u;if(!oy())throw Dt()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const d=yield this.disconnectLock.lock();if(this.state===me.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),d(),Promise.resolve();if(this.connectFuture)return d(),this.connectFuture.promise;this.setAndEmitConnectionState(me.Connecting),((u=this.regionUrlProvider)===null||u===void 0?void 0:u.getServerUrl().toString())!==ju(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),$n(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new pe(o,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(m=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(m)}).catch(m=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:m}))}));const h=(m,g,w)=>v(this,void 0,void 0,function*(){var b,P;this.abortController&&this.abortController.abort();const _=new AbortController;this.abortController=_,d==null||d();try{if(yield Wn.getInstance().getBackOffPromise(o),_.signal.aborted)throw ie.cancelled("Connection attempt aborted");yield this.attemptConnection(w??o,c,l,_),this.abortController=void 0,m()}catch(S){if(this.regionUrlProvider&&S instanceof ie&&S.reason!==Ce.Cancelled&&S.reason!==Ce.NotAllowed){let T=null;try{this.log.debug("Fetching next region"),T=yield this.regionUrlProvider.getNextBestRegionUrl((b=this.abortController)===null||b===void 0?void 0:b.signal)}catch(C){if(C instanceof ie&&(C.status===401||C.reason===Ce.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(C);return}}[Ce.InternalError,Ce.ServerUnreachable,Ce.Timeout].includes(S.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Wn.getInstance().addFailedConnectionAttempt(o)),T&&!(!((P=this.abortController)===null||P===void 0)&&P.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(S.message,". Retrying with another region: ").concat(T),this.logContext),this.recreateEngine(),yield h(m,g,T)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ha(S)),g(S))}else{let T=xt.UNKNOWN_REASON;S instanceof ie&&(T=Ha(S)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,T),g(S)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new vt((m,g)=>{h(m,g,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,c,l,u,d,h)=>v(this,void 0,void 0,function*(){var f,m,g;const w=yield l.join(o,c,{autoSubscribe:u.autoSubscribe,adaptiveStream:typeof d.adaptiveStream=="object"?!0:d.adaptiveStream,maxRetries:u.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:u.websocketTimeout},h.signal,!d.singlePeerConnection);let b=w.serverInfo;if(b||(b={version:w.serverVersion,region:w.serverRegion}),this.serverInfo=b,this.log.debug("connected to Livekit Server ".concat(Object.entries(b).map(P=>{let[_,S]=P;return"".concat(_,": ").concat(S)}).join(", ")),{room:(f=w.room)===null||f===void 0?void 0:f.name,roomSid:(m=w.room)===null||m===void 0?void 0:m.sid,identity:(g=w.participant)===null||g===void 0?void 0:g.identity}),!b.version)throw new q0("unknown server version");return b.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),d.dynacast=!1),w}),this.applyJoinResponse=o=>{const c=o.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(l){this.log.error(l instanceof Error?l.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:l}))}this.handleParticipantUpdates([c,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,c,l,u)=>v(this,void 0,void 0,function*(){var d,h;this.state===me.Reconnecting||this.isResuming||!((d=this.engine)===null||d===void 0)&&d.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ko),l),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(o,c,this.engine,this.connOptions,this.options,u);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(U.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const m=u.signal.aborted?ie.cancelled("Signal connection aborted"):ie.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(m.message="".concat(m.message,": ").concat(f.message)),f instanceof ie&&(m.reason=f.reason,m.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),m}if(u.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),ie.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,u)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}nt()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),nt()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(me.Connected),this.emit(U.Connected),Wn.getInstance().resetFailedConnectionAttempts(o),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var o=arguments.length,c=new Array(o),l=0;l<o;l++)c[l]=arguments[l];return v(n,[...c],void 0,function(){var u=this;let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,m;const g=yield u.disconnectLock.lock();try{if(u.state===me.Disconnected){u.log.debug("already disconnected",u.logContext);return}if(u.log.info("disconnect from room",Object.assign({},u.logContext)),u.state===me.Connecting||u.state===me.Reconnecting||u.isResuming){const w="Abort connection attempt due to user initiated disconnect";u.log.warn(w,u.logContext),(h=u.abortController)===null||h===void 0||h.abort(w),(m=(f=u.connectFuture)===null||f===void 0?void 0:f.reject)===null||m===void 0||m.call(f,ie.cancelled("Client initiated disconnect")),u.connectFuture=void 0}u.engine&&(u.engine.client.isDisconnected||(yield u.engine.client.sendLeave()),yield u.engine.close()),u.handleDisconnect(d,xt.CLIENT_INITIATED),u.engine=void 0}finally{g()}})()})},this.onPageLeave=()=>v(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>v(this,void 0,void 0,function*(){const o=[],c=rt();if(c&&c.os==="iOS"){const l="livekit-dummy-audio-el";let u=document.getElementById(l);if(!u){u=document.createElement("audio"),u.id=l,u.autoplay=!0,u.hidden=!0;const d=qr();d.enabled=!0;const h=new MediaStream([d]);u.srcObject=h,document.addEventListener("visibilitychange",()=>{u&&(u.srcObject=document.hidden?null:h,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(u),this.once(U.Disconnected,()=>{u==null||u.remove(),u=null})}o.push(u)}this.remoteParticipants.forEach(l=>{l.audioTrackPublications.forEach(u=>{u.track&&u.track.attachedElements.forEach(d=>{o.push(d)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(l=>(l.muted=!1,l.play()))]),this.handleAudioPlaybackStarted()}catch(l){throw this.handleAudioPlaybackFailed(l),l}}),this.startVideo=()=>v(this,void 0,void 0,function*(){const o=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(l=>{var u;(u=l.track)===null||u===void 0||u.attachedElements.forEach(d=>{o.includes(d)||o.push(d)})});yield Promise.all(o.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(me.Reconnecting)&&this.emit(U.Reconnecting)},this.handleSignalRestarted=o=>v(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(me.Connected),this.emit(U.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(c=>{var l;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(l=this.sidToIdentity.get(c.sid))!==null&&l!==void 0?l:"");let u=this.remoteParticipants.get(c.identity);c.state===Un.DISCONNECTED?this.handleParticipantDisconnected(c.identity,u):u=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=o=>{const c=[],l={};o.forEach(u=>{if(l[u.sid]=!0,u.sid===this.localParticipant.sid)this.localParticipant.audioLevel=u.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const d=this.getRemoteParticipantBySid(u.sid);d&&(d.audioLevel=u.level,d.setIsSpeaking(!0),c.push(d))}}),l[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(u=>{l[u.sid]||(u.audioLevel=0,u.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(U.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=o=>{const c=new Map;this.activeSpeakers.forEach(u=>{const d=this.remoteParticipants.get(u.identity);d&&d.sid!==u.sid||c.set(u.sid,u)}),o.forEach(u=>{let d=this.getRemoteParticipantBySid(u.sid);u.sid===this.localParticipant.sid&&(d=this.localParticipant),d&&(d.audioLevel=u.level,d.setIsSpeaking(u.active),u.active?c.set(u.sid,d):c.delete(u.sid))});const l=Array.from(c.values());l.sort((u,d)=>d.audioLevel-u.audioLevel),this.activeSpeakers=l,this.emitWhenConnected(U.ActiveSpeakersChanged,l)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(c=>{const l=this.getRemoteParticipantBySid(c.participantSid);if(!l)return;const u=l.getTrackPublicationBySid(c.trackSid);if(!u||!u.track)return;const d=M.streamStateFromProto(c.state);u.track.setStreamState(d),d!==u.track.streamState&&(l.emit(H.TrackStreamStateChanged,u,u.track.streamState),this.emitWhenConnected(U.TrackStreamStateChanged,u,u.track.streamState,l))})},this.handleSubscriptionPermissionUpdate=o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(o.trackSid);l&&l.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const c=Array.from(this.remoteParticipants.values()).find(u=>u.trackPublications.has(o.trackSid));if(!c)return;const l=c.getTrackPublicationBySid(o.trackSid);l&&l.setSubscriptionError(o.err)},this.handleDataPacket=(o,c)=>{const l=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(l,o.value.value,o.kind,c);else if(o.value.case==="transcription")this.handleTranscription(l,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(l,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(l,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,l);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o,c);else if(o.value.case==="rpcRequest"){const u=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,u.id,u.method,u.payload,u.responseTimeoutMs,u.version)}},this.handleUserPacket=(o,c,l,u)=>{this.emit(U.DataReceived,c.payload,o,l,c.topic,u),o==null||o.emit(H.DataReceived,c.payload,l,u)},this.handleSipDtmf=(o,c)=>{this.emit(U.SipDTMFReceived,c,o),o==null||o.emit(H.SipDTMFReceived,c)},this.handleTranscription=(o,c)=>{const l=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),u=l==null?void 0:l.trackPublications.get(c.trackId),d=my(c,this.transcriptionReceivedTimes);u==null||u.emit(V.TranscriptionReceived,d),l==null||l.emit(H.TranscriptionReceived,d,u),this.emit(U.TranscriptionReceived,d,l,u)},this.handleChatMessage=(o,c)=>{const l=gy(c);this.emit(U.ChatMessage,l,o)},this.handleMetrics=(o,c)=>{this.emit(U.MetricsReceived,o,c)},this.handleDataStream=(o,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(o,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(U.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(U.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(U.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(U.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>v(this,void 0,void 0,function*(){var o;((o=rt())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(U.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const c=this.roomInfo;this.roomInfo=o,c&&c.metadata!==o.metadata&&this.emitWhenConnected(U.RoomMetadataChanged,o.metadata),(c==null?void 0:c.activeRecording)!==o.activeRecording&&this.emitWhenConnected(U.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const l=this.getRemoteParticipantBySid(c.participantSid);l&&l.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(U.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(U.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(U.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(U.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(U.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var c;(c=o==null?void 0:o.onPublish)===null||c===void 0||c.call(o,this)},this.onLocalTrackPublished=o=>v(this,void 0,void 0,function*(){var c,l,u,d,h,f;(c=o.track)===null||c===void 0||c.on(V.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=o.track)===null||l===void 0||l.on(V.Restarted,this.onLocalTrackRestarted),(h=(d=(u=o.track)===null||u===void 0?void 0:u.getProcessor())===null||d===void 0?void 0:d.onPublish)===null||h===void 0||h.call(d,this),this.emit(U.LocalTrackPublished,o,this.localParticipant),Vt(o.track)&&(yield o.track.checkForSilence())&&this.emit(U.LocalAudioSilenceDetected,o);const m=yield(f=o.track)===null||f===void 0?void 0:f.getDeviceId(!1),g=ws(o.source);g&&m&&m!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,m),this.emit(U.ActiveDeviceChanged,g,m))}),this.onLocalTrackUnpublished=o=>{var c,l;(c=o.track)===null||c===void 0||c.off(V.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=o.track)===null||l===void 0||l.off(V.Restarted,this.onLocalTrackRestarted),this.emit(U.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>v(this,void 0,void 0,function*(){const c=yield o.getDeviceId(!1),l=ws(o.source);l&&c&&c!==this.localParticipant.activeDeviceMap.get(l)&&(this.log.debug("local track restarted, setting ".concat(l," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(l,c),this.emit(U.ActiveDeviceChanged,l,c))}),this.onLocalConnectionQualityChanged=o=>{this.emit(U.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,c)=>{this.emit(U.MediaDevicesError,o,c)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(U.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(U.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Jy),e),this.log=Gt((i=this.options.loggerName)!==null&&i!==void 0?i:_t.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Uu),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Fu),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},$y),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new xb,this.outgoingDataStreamManager=new Pb(this.engine,this.log),this.disconnectLock=new Ye,this.localParticipant=new Lb("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",ln(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",ln(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",ln(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),nt()){const o=new AbortController;(a=(s=navigator.mediaDevices)===null||s===void 0?void 0:s.addEventListener)===null||a===void 0||a.call(s,"devicechange",this.handleDeviceChange,{signal:o.signal}),Jn.cleanupRegistry&&Jn.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,n){return this.incomingDataStreamManager.registerTextStreamHandler(e,n)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,n){return this.incomingDataStreamManager.registerByteStreamHandler(e,n)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,n){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return v(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;const n=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new My(i,n),this.e2eeManager.on(an.ParticipantEncryptionStatusChanged,(r,s)=>{yy(s)&&(this.isE2EEEnabled=r),this.emit(U.ParticipantEncryptionStatusChanged,r,s)}),this.e2eeManager.on(an.EncryptionError,(r,s)=>{const a=s?this.getParticipantByIdentity(s):void 0;this.emit(U.EncryptionError,r,a)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&n!==void 0?n:!1}getSid(){return this.state===me.Disconnected?tt.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?tt.resolve(this.roomInfo.sid):new tt((e,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(z.RoomUpdate,i),e(r.sid))};this.engine.on(z.RoomUpdate,i),this.once(U.Disconnected,()=>{this.engine.off(z.RoomUpdate,i),n(new Re("Room disconnected before room server id was available"))})})}get name(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&n!==void 0?n:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&n!==void 0?n:0}get numPublishers(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&n!==void 0?n:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Cb(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(z.ParticipantUpdate,this.handleParticipantUpdates).on(z.RoomUpdate,this.handleRoomUpdate).on(z.SpeakersChanged,this.handleSpeakersChanged).on(z.StreamStateChanged,this.handleStreamStateUpdate).on(z.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(z.SubscriptionError,this.handleSubscriptionError).on(z.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(z.MediaTrackAdded,(e,n,i)=>{this.onTrackAdded(e,n,i)}).on(z.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(z.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(z.DataPacketReceived,this.handleDataPacket).on(z.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(me.SignalReconnecting)&&this.emit(U.SignalReconnecting)}).on(z.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(me.Connected)&&this.emit(U.Reconnected)}).on(z.SignalResumed,()=>{this.bufferedEvents=[],(this.state===me.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(z.Restarting,this.handleRestarting).on(z.SignalRestarted,this.handleSignalRestarted).on(z.Offline,()=>{this.setAndEmitConnectionState(me.Reconnecting)&&this.emit(U.Reconnecting)}).on(z.DCBufferStatusChanged,(e,n)=>{this.emit(U.DCBufferStatusChanged,e,n)}).on(z.LocalTrackSubscribed,e=>{const n=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!n){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(H.LocalTrackSubscribed,n),this.emitWhenConnected(U.LocalTrackSubscribed,n,this.localParticipant)}).on(z.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((n,i)=>{this.handleParticipantDisconnected(i,n)}),this.emit(U.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Fe.getInstance().getDevices(e,n)}prepareConnection(e,n){return v(this,void 0,void 0,function*(){if(this.state===me.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if($n(new URL(e))&&n){this.regionUrlProvider=new pe(e,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===me.Disconnected&&(this.regionUrl=i,yield fetch(wi(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(wi(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,n){return v(this,void 0,void 0,function*(){let i=()=>v(this,void 0,void 0,function*(){}),r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new Pt({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Pt({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Pt({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Pt({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>v(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Pt({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>v(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Pt({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new Pt({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>v(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new gr({reason:xt.CLIENT_INITIATED,action:Fn.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Pt({scenario:{case:"subscriberBandwidth",value:Sn(n)}});break;case"leave-full-reconnect":r=new Pt({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,n){return v(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,c,l,u,d,h,f;let m=!0,g=!1;const w=a?{exact:r}:r;if(i==="audioinput"){g=s.localParticipant.audioTrackPublications.size===0;const b=(o=s.getActiveDevice(i))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=w;const P=Array.from(s.localParticipant.audioTrackPublications.values()).filter(S=>S.source===M.Source.Microphone);try{m=(yield Promise.all(P.map(S=>{var T;return(T=S.audioTrack)===null||T===void 0?void 0:T.setDeviceId(w)}))).every(S=>S===!0)}catch(S){throw s.options.audioCaptureDefaults.deviceId=b,S}const _=P.some(S=>{var T,C;return(C=(T=S.track)===null||T===void 0?void 0:T.isMuted)!==null&&C!==void 0?C:!1});m&&_&&(g=!0)}else if(i==="videoinput"){g=s.localParticipant.videoTrackPublications.size===0;const b=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=w;const P=Array.from(s.localParticipant.videoTrackPublications.values()).filter(S=>S.source===M.Source.Camera);try{m=(yield Promise.all(P.map(S=>{var T;return(T=S.videoTrack)===null||T===void 0?void 0:T.setDeviceId(w)}))).every(S=>S===!0)}catch(S){throw s.options.videoCaptureDefaults.deviceId=b,S}const _=P.some(S=>{var T,C;return(C=(T=S.track)===null||T===void 0?void 0:T.isMuted)!==null&&C!==void 0?C:!1});m&&_&&(g=!0)}else if(i==="audiooutput"){if(g=!0,!Es()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");s.options.webAudioMix&&(r=(l=yield Fe.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(u=(f=s.options).audioOutput)!==null&&u!==void 0||(f.audioOutput={});const b=(d=s.getActiveDevice(i))!==null&&d!==void 0?d:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(P=>P.setAudioOutput({deviceId:r})))}catch(P){throw s.options.audioOutput.deviceId=b,P}}return g&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(U.ActiveDeviceChanged,i,r)),m})()})}setupLocalParticipantEvents(){this.localParticipant.on(H.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(H.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(H.AttributesChanged,this.onLocalAttributesChanged).on(H.TrackMuted,this.onLocalTrackMuted).on(H.TrackUnmuted,this.onLocalTrackUnmuted).on(H.LocalTrackPublished,this.onLocalTrackPublished).on(H.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(H.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(H.MediaDevicesError,this.onMediaDevicesError).on(H.AudioStreamAcquired,this.startAudio).on(H.ChatMessage,this.onLocalChatMessageSent).on(H.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,n,i){if(this.state===me.Connecting||this.state===me.Reconnecting){const d=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:n.id,tracksInStream:n.getTracks().map(f=>f.id)}),this.onTrackAdded(e,n,i),h()},h=()=>{this.off(U.Reconnected,d),this.off(U.Connected,d),this.off(U.Disconnected,h)};this.once(U.Reconnected,d),this.once(U.Connected,d),this.once(U.Disconnected,h);return}if(this.state===me.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=iy(n.id),s=r[0];let a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(d=>d.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}if(!o.startsWith("TR")){const d=this.engine.getTrackIdForReceiver(i);if(!d){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(s),this.logContext);return}o=d}o.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(s,", streamId: ").concat(a,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:s,streamId:a,trackId:o}));let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={});const u=c.addSubscribedMediaTrack(e,o,n,i,l);u!=null&&u.isEncrypted&&!this.e2eeManager&&this.emit(U.EncryptionError,new Error("Encrypted ".concat(u.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1?arguments[1]:void 0;var i,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==me.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(a=>{s.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var a,o,c;s.track&&this.localParticipant.unpublishTrack(s.track,e),e?((a=s.track)===null||a===void 0||a.detach(),(o=s.track)===null||o===void 0||o.stop()):(c=s.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(H.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(H.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(H.AttributesChanged,this.onLocalAttributesChanged).off(H.TrackMuted,this.onLocalTrackMuted).off(H.TrackUnmuted,this.onLocalTrackUnmuted).off(H.LocalTrackPublished,this.onLocalTrackPublished).off(H.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(H.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(H.MediaDevicesError,this.onMediaDevicesError).off(H.AudioStreamAcquired,this.startAudio).off(H.ChatMessage,this.onLocalChatMessageSent).off(H.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),nt()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||r===void 0||r.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(me.Disconnected),this.emit(U.Disconnected,n)}}}handleParticipantDisconnected(e,n){var i;this.remoteParticipants.delete(e),n&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),n.trackPublications.forEach(r=>{n.unpublishTrack(r.trackSid,!0)}),this.emit(U.ParticipantDisconnected,n),n.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(n.identity))}handleIncomingRpcRequest(e,n,i,r,s,a){return v(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,n),a!==1){yield this.engine.publishRpcResponse(e,n,null,Pe.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,n,null,Pe.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const u=yield o({requestId:n,callerIdentity:e,payload:r,responseTimeout:s});Co(u)>Vu?(c=Pe.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):l=u}catch(u){u instanceof Pe?c=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),c=Pe.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,n,l,c)})}selectDefaultDevices(){return v(this,void 0,void 0,function*(){var e,n,i;const r=Fe.getInstance().previousDevices,s=yield Fe.getInstance().getDevices(void 0,!1),a=rt();if((a==null?void 0:a.name)==="Chrome"&&a.os!=="iOS")for(let c of s){const l=r.find(u=>u.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(U.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const l=$0(c),u=this.localParticipant.getTrackPublication(l);if(u&&(!((e=u.track)===null||e===void 0)&&e.isUserProvided))continue;const d=s.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((n=r.filter(f=>f.kind===c)[0])===null||n===void 0?void 0:n.deviceId)&&d.length>0&&((i=d[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,d[0].deviceId);continue}c==="audioinput"&&!Ti()||c==="videoinput"||d.length>0&&!d.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Ti())&&(yield this.switchActiveDevice(c,d[0].deviceId))}})}acquireAudioContext(){return v(this,void 0,void 0,function*(){var e,n;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Ou())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Ve(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((n=this.audioContext)===null||n===void 0?void 0:n.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(U.AudioPlaybackStatusChanged,i))})}createParticipant(e,n){var i;let r;return n?r=ar.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new ar(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(e,n){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return n&&r.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity),r}const i=this.createParticipant(e,n);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(U.ParticipantConnected,i),i.on(H.TrackPublished,r=>{this.emitWhenConnected(U.TrackPublished,r,i)}).on(H.TrackSubscribed,(r,s)=>{r.kind===M.Kind.Audio?(r.on(V.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(V.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===M.Kind.Video&&(r.on(V.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(V.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(U.TrackSubscribed,r,s,i)}).on(H.TrackUnpublished,r=>{this.emit(U.TrackUnpublished,r,i)}).on(H.TrackUnsubscribed,(r,s)=>{this.emit(U.TrackUnsubscribed,r,s,i)}).on(H.TrackMuted,r=>{this.emitWhenConnected(U.TrackMuted,r,i)}).on(H.TrackUnmuted,r=>{this.emitWhenConnected(U.TrackUnmuted,r,i)}).on(H.ParticipantMetadataChanged,r=>{this.emitWhenConnected(U.ParticipantMetadataChanged,r,i)}).on(H.ParticipantNameChanged,r=>{this.emitWhenConnected(U.ParticipantNameChanged,r,i)}).on(H.AttributesChanged,r=>{this.emitWhenConnected(U.ParticipantAttributesChanged,r,i)}).on(H.ConnectionQualityChanged,r=>{this.emitWhenConnected(U.ConnectionQualityChanged,r,i)}).on(H.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(U.ParticipantPermissionsChanged,r,i)}).on(H.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(U.TrackSubscriptionStatusChanged,r,s,i)}).on(H.TrackSubscriptionFailed,(r,s)=>{this.emit(U.TrackSubscriptionFailed,r,i,s)}).on(H.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(U.TrackSubscriptionPermissionChanged,r,s,i)}).on(H.Active,()=>{this.emitWhenConnected(U.ParticipantActive,i),i.kind===ki.AGENT&&this.localParticipant.setActiveAgent(i)}),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),n=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const n of e.videoTrackPublications.values())n.isSubscribed&&vy(n)&&n.emitTrackUpdate()}getRemoteParticipantBySid(e){const n=this.sidToIdentity.get(e);if(n)return this.remoteParticipants.get(n)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Be.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,xt.STATE_MISMATCH))):e=0},Ub)}clearConnectionReconcile(){this.connectionReconcileInterval&&Be.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(U.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[n,i]=e;this.emit(n,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===me.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===me.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return v(this,void 0,void 0,function*(){var n,i,r,s;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new hr({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:xe.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Tn({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(U.SignalConnected),this.emit(U.Connected),this.setAndEmitConnectionState(me.Connected),a.video){const c=new Ds(M.Kind.Video,new An({source:Ae.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:St.AUDIO,name:"video-dummy"}),new or(a.useRealTracks&&(!((n=window.navigator.mediaDevices)===null||n===void 0)&&n.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Wa(160*((i=o.aspectRatios[0])!==null&&i!==void 0?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(H.LocalTrackPublished,c)}if(a.audio){const c=new Ds(M.Kind.Audio,new An({source:Ae.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:St.AUDIO}),new sr(a.useRealTracks&&(!((r=navigator.mediaDevices)===null||r===void 0)&&r.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:qr(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(H.LocalTrackPublished,c)}for(let c=0;c<o.count-1;c+=1){let l=new Tn({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:Un.ACTIVE,tracks:[],joinedAt:xe.parse(Date.now())});const u=this.getOrCreateParticipant(l.identity,l);if(o.video){const d=Wa(160*((s=o.aspectRatios[c%o.aspectRatios.length])!==null&&s!==void 0?s:1),160,!1,!0),h=new An({source:Ae.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:St.AUDIO});u.addSubscribedMediaTrack(d,h.sid,new MediaStream([d]),new RTCRtpReceiver),l.tracks=[...l.tracks,h]}if(o.audio){const d=qr(),h=new An({source:Ae.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:St.AUDIO});u.addSubscribedMediaTrack(d,h.sid,new MediaStream([d]),new RTCRtpReceiver),l.tracks=[...l.tracks,h]}u.updateInfo(l)}})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(e!==U.ActiveSpeakersChanged&&e!==U.TranscriptionReceived){const s=Ju(i).filter(a=>a!==void 0);(e===U.TrackSubscribed||e===U.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s}))}return super.emit(e,...i)}}Jn.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function Ju(t){return t.map(e=>{if(e)return Array.isArray(e)?Ju(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Ct;(function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"})(Ct||(Ct={}));class mn extends Lt.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Ct.IDLE,this.logs=[],this.options={},this.url=e,this.token=n,this.name=this.constructor.name,this.room=new Jn(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return v(this,void 0,void 0,function*(){if(this.status!==Ct.IDLE)throw Error("check is running already");this.setStatus(Ct.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise(n=>setTimeout(n,500)),this.status!==Ct.SKIPPED&&this.setStatus(this.isSuccess()?Ct.SUCCESS:Ct.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return v(this,void 0,void 0,function*(){return this.room.state===me.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return v(this,void 0,void 0,function*(){this.room&&this.room.state!==me.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Ct.SKIPPED)}switchProtocol(e){return v(this,void 0,void 0,function*(){let n=!1,i=!1;if(this.room.on(U.Reconnecting,()=>{n=!0}),this.room.once(U.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield Ve(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Fb extends mn{get description(){return"Cloud regions"}perform(){return v(this,void 0,void 0,function*(){const e=new pe(this.url,this.token);if(!e.isCloud()){this.skip();return}const n=[],i=new Set;for(let s=0;s<3;s++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),n.push(o)}n.sort((s,a)=>(s.duration-a.duration)*.5+(s.rtt-a.rtt)*.5);const r=n[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return v(this,void 0,void 0,function*(){var n,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(n=this.room.serverInfo)===null||n===void 0?void 0:n.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,l="A".repeat(a),u=Date.now();for(let m=0;m<c;m++)yield s.write(l);yield s.close();const d=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:r,rtt:1e4,duration:d-u};return h==null||h.forEach(m=>{m.type==="candidate-pair"&&m.nominated&&(f.rtt=m.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Qr=1e4;class Bb extends mn{get description(){return"Connection via UDP vs TCP"}perform(){return v(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),n=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-n.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-n.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=n):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(Qr/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Qr/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return v(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const n=document.createElement("canvas");n.width=1280,n.height=720;const i=n.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,n.width,n.height),requestAnimationFrame(s)};s();const o=n.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},d=setInterval(()=>v(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(u.packetsSent=f.packetsSent,u.qualityLimitationDurations=f.qualityLimitationDurations,u.bitrateTotal+=f.targetBitrate,u.count++):f.type==="remote-inbound-rtp"&&(u.packetsLost=f.packetsLost,u.rttTotal+=f.roundTripTime,u.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Qr)),clearInterval(d),o.stop(),n.remove(),yield this.disconnect(),u})}}class Vb extends mn{get description(){return"Can publish audio"}perform(){return v(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield Ab();if(yield Mu(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),n.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let a=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class qb extends mn{get description(){return"Can publish video"}perform(){return v(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield Ob();yield this.checkForVideo(i.mediaStreamTrack),n.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(s+=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return v(this,void 0,void 0,function*(){const n=new MediaStream;n.addTrack(e.clone());const i=document.createElement("video");i.srcObject=n,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,a,o,c;const l=document.createElement("canvas"),u=e.getSettings(),d=(a=(s=u.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=u.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;l.width=d,l.height=h;const f=l.getContext("2d");f.drawImage(i,0,0);const g=f.getImageData(0,0,l.width,l.height).data;let w=!0;for(let b=0;b<g.length;b+=4)if(g[b]!==0||g[b+1]!==0||g[b+2]!==0){w=!1;break}w?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),n.getTracks().forEach(r=>r.stop()),i.remove()})}}class zb extends mn{get description(){return"Resuming connection after interruption"}perform(){return v(this,void 0,void 0,function*(){var e;const n=yield this.connect();let i=!1,r=!1,s;const a=new Promise(l=>{setTimeout(l,5e3),s=l}),o=()=>{i=!0};n.on(U.SignalReconnecting,o).on(U.Reconnecting,o).on(U.Reconnected,()=>{r=!0,s(!0)}),(e=n.engine.client.ws)===null||e===void 0||e.close();const c=n.engine.client.onClose;if(c&&c(""),yield a,i){if(!r||n.state!==me.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class Wb extends mn{get description(){return"Can connect via TURN"}perform(){return v(this,void 0,void 0,function*(){var e,n,i;$n(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new pe(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const r=new go,s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,c=!1;for(let l of s.iceServers)for(let u of l.urls)u.startsWith("turn:")?(o=!0,c=!0):u.startsWith("turns:")&&(o=!0,c=!0,a=!0),u.startsWith("stun:")&&(c=!0);c?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((i=(n=this.connectOptions)===null||n===void 0?void 0:n.rtcConfig)===null||i===void 0)&&i.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(l=>setTimeout(l,0)))})}}class Hb extends mn{get description(){return"Establishing WebRTC connection"}perform(){return v(this,void 0,void 0,function*(){let e=!1,n=!1;this.room.on(U.SignalConnected,()=>{var i;const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,a)=>{if(s.candidate){const o=new RTCIceCandidate(s);let c="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(Kb(o.address)?c+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,c+=" (passive)"):o.protocol==="udp"&&(n=!0)),this.appendMessage(c)}r&&r(s,a)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),ce.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function Kb(t){const e=t.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const n=parseInt(e[1],10);if(n>=16&&n<=31)return!0}}return!1}class Gb extends mn{get description(){return"Connecting to signal connection via WebSocket"}perform(){return v(this,void 0,void 0,function*(){var e,n,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new go,s;try{s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if($n(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const c=yield new pe(this.url,this.token).getNextBestRegionUrl();c&&(s=yield r.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}s?(this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===Nl.Cloud&&(!((n=s.serverInfo)===null||n===void 0)&&n.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}}class yS extends Lt.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=n,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Ct.IDLE,name:"",description:""}),e}updateCheck(e,n){this.checkResults.set(e,n),this.emit("checkUpdate",e,n)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Ct.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return v(this,void 0,void 0,function*(){const n=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(n,a)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return v(this,void 0,void 0,function*(){return this.createAndRunCheck(Gb)})}checkWebRTC(){return v(this,void 0,void 0,function*(){return this.createAndRunCheck(Hb)})}checkTURN(){return v(this,void 0,void 0,function*(){return this.createAndRunCheck(Wb)})}checkReconnect(){return v(this,void 0,void 0,function*(){return this.createAndRunCheck(zb)})}checkPublishAudio(){return v(this,void 0,void 0,function*(){return this.createAndRunCheck(Vb)})}checkPublishVideo(){return v(this,void 0,void 0,function*(){return this.createAndRunCheck(qb)})}checkConnectionProtocol(){return v(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Bb);if(e.data&&"protocol"in e.data){const n=e.data;this.options.protocol=n.protocol}return e})}checkCloudRegion(){return v(this,void 0,void 0,function*(){return this.createAndRunCheck(Fb)})}}function he(t,e,n){return(e=Jb(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function $b(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var i=n.call(t,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Jb(t){var e=$b(t,"string");return typeof e=="symbol"?e:e+""}new TextEncoder;new TextDecoder;class Qe extends Error{constructor(e,n){var i;super(e,n),he(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}he(Qe,"code","ERR_JOSE_GENERIC");class Yb extends Qe{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:n}}),he(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),he(this,"claim",void 0),he(this,"reason",void 0),he(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=n}}he(Yb,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class Qb extends Qe{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:n}}),he(this,"code","ERR_JWT_EXPIRED"),he(this,"claim",void 0),he(this,"reason",void 0),he(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=n}}he(Qb,"code","ERR_JWT_EXPIRED");class Xb extends Qe{constructor(){super(...arguments),he(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}he(Xb,"code","ERR_JOSE_ALG_NOT_ALLOWED");class Zb extends Qe{constructor(){super(...arguments),he(this,"code","ERR_JOSE_NOT_SUPPORTED")}}he(Zb,"code","ERR_JOSE_NOT_SUPPORTED");class ek extends Qe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",n=arguments.length>1?arguments[1]:void 0;super(e,n),he(this,"code","ERR_JWE_DECRYPTION_FAILED")}}he(ek,"code","ERR_JWE_DECRYPTION_FAILED");class tk extends Qe{constructor(){super(...arguments),he(this,"code","ERR_JWE_INVALID")}}he(tk,"code","ERR_JWE_INVALID");class nk extends Qe{constructor(){super(...arguments),he(this,"code","ERR_JWS_INVALID")}}he(nk,"code","ERR_JWS_INVALID");class ik extends Qe{constructor(){super(...arguments),he(this,"code","ERR_JWT_INVALID")}}he(ik,"code","ERR_JWT_INVALID");class rk extends Qe{constructor(){super(...arguments),he(this,"code","ERR_JWK_INVALID")}}he(rk,"code","ERR_JWK_INVALID");class sk extends Qe{constructor(){super(...arguments),he(this,"code","ERR_JWKS_INVALID")}}he(sk,"code","ERR_JWKS_INVALID");class ok extends Qe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",n=arguments.length>1?arguments[1]:void 0;super(e,n),he(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}he(ok,"code","ERR_JWKS_NO_MATCHING_KEY");class ak extends Qe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",n=arguments.length>1?arguments[1]:void 0;super(e,n),he(this,Symbol.asyncIterator,void 0),he(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}he(ak,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class ck extends Qe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",n=arguments.length>1?arguments[1]:void 0;super(e,n),he(this,"code","ERR_JWKS_TIMEOUT")}}he(ck,"code","ERR_JWKS_TIMEOUT");class lk extends Qe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",n=arguments.length>1?arguments[1]:void 0;super(e,n),he(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}he(lk,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const uk="_container_1p2zy_1",dk="_orbContainer_1p2zy_11",hk="_status_1p2zy_22",fk="_instruction_1p2zy_34",pk="_controls_1p2zy_47",mk="_controlButton_1p2zy_58",gk="_muted_1p2zy_86",vk="_backButton_1p2zy_95",tn={container:uk,orbContainer:dk,status:hk,instruction:fk,controls:pk,controlButton:mk,muted:gk,backButton:vk},yk=({tokenUrl:t,agentName:e="voice-agent",onClose:n})=>{const i=q.useRef(null),[r,s]=q.useState(""),[a,o]=q.useState(!1),[c,l]=q.useState(!1),[u,d]=q.useState(!1),h=q.useRef(null),f=q.useRef(null),m=q.useRef(null),g=q.useRef(null),w=q.useRef(null),b=q.useRef(null),P=q.useRef(null),_=q.useRef(0),S=q.useRef(null),T=q.useRef(!1),C=q.useRef(0),O=q.useRef(0),L=q.useRef(null),I=q.useCallback(()=>{let $=0,Q=0;g.current&&b.current&&(g.current.getByteFrequencyData(b.current),$=b.current.reduce((k,K)=>k+K,0)/b.current.length/255),w.current&&P.current&&(w.current.getByteFrequencyData(P.current),Q=P.current.reduce((k,K)=>k+K,0)/P.current.length/255);const ee=Math.max($,Q);return _.current+=(ee-_.current)*.25,_.current},[]),A=async $=>{m.current||(m.current=new(window.AudioContext||window.webkitAudioContext)),m.current.state==="suspended"&&await m.current.resume();try{const Q=new MediaStream([$.mediaStreamTrack]),ee=m.current.createMediaStreamSource(Q);g.current=m.current.createAnalyser(),g.current.fftSize=256,ee.connect(g.current),b.current=new Uint8Array(g.current.frequencyBinCount)}catch(Q){console.error("Failed to set up local audio analyser:",Q)}},R=async $=>{m.current||(m.current=new(window.AudioContext||window.webkitAudioContext)),m.current.state==="suspended"&&await m.current.resume();const Q=$.attach();Q.style.display="none",Q.autoplay=!0,Q.setAttribute("playsinline","true"),document.body.appendChild(Q);try{await Q.play()}catch{console.log("Audio play failed, will retry on interaction")}const ee=new MediaStream([$.mediaStreamTrack]),ne=m.current.createMediaStreamSource(ee);w.current=m.current.createAnalyser(),w.current.fftSize=256,ne.connect(w.current),P.current=new Uint8Array(w.current.frequencyBinCount)};q.useEffect(()=>{if(T.current)return;const $=ee=>new Promise((ne,k)=>{if(ee.includes("three")&&window.THREE){ne();return}if(ee.includes("gsap")&&window.gsap){ne();return}const K=document.createElement("script");K.src=ee,K.onload=()=>ne(),K.onerror=k,document.head.appendChild(K)});(async()=>{try{if(await $("https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"),await $("https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"),!i.current||!window.THREE)return;T.current=!0;const ee=window.THREE,ne=i.current,k=new ee.Scene,K=ne.clientWidth,Z=ne.clientHeight,y=new ee.PerspectiveCamera(75,K/Z,.1,1e3),J=new ee.WebGLRenderer({antialias:!0,alpha:!0});L.current=J,J.setSize(K,Z),J.setPixelRatio(Math.min(window.devicePixelRatio,2)),ne.appendChild(J.domElement),y.position.z=300;const X=12e3,W=new Float32Array(X*3),se=new Float32Array(X*3),De=new Float32Array(X),we=new Float32Array(X*3),Ne=new Float32Array(X*3),Ke=50,$t=22,gn=60;for(let E=0;E<X;E++){const F=Math.random()*Math.PI*2,te=Math.random()*Math.PI*2,oe=$t*Math.sqrt(Math.random());we[E*3]=(Ke+oe*Math.cos(te))*Math.cos(F),we[E*3+1]=(Ke+oe*Math.cos(te))*Math.sin(F),we[E*3+2]=oe*Math.sin(te);const le=gn*Math.cbrt(Math.random()),qe=Math.random()*Math.PI*2,ct=Math.acos(Math.random()*2-1);Ne[E*3]=le*Math.sin(ct)*Math.cos(qe),Ne[E*3+1]=le*Math.sin(ct)*Math.sin(qe),Ne[E*3+2]=le*Math.cos(ct),W[E*3]=we[E*3],W[E*3+1]=we[E*3+1],W[E*3+2]=we[E*3+2];const Ge=.8+Math.random()*.2;se[E*3]=Ge,se[E*3+1]=Ge,se[E*3+2]=Ge,De[E]=1.4+Math.random()*1}const yt=new ee.BufferGeometry;yt.setAttribute("position",new ee.BufferAttribute(W,3)),yt.setAttribute("torusPos",new ee.BufferAttribute(we,3)),yt.setAttribute("spherePos",new ee.BufferAttribute(Ne,3)),yt.setAttribute("color",new ee.BufferAttribute(se,3)),yt.setAttribute("size",new ee.BufferAttribute(De,1));const ot=new ee.ShaderMaterial({uniforms:{time:{value:0},mouse:{value:new ee.Vector3(9999,9999,0)},hoverRadius:{value:35},hoverStrength:{value:30},audioAmplitude:{value:0},audioExpansion:{value:100},isConnected:{value:0}},vertexShader:`
55
+ attribute float size;
56
+ attribute vec3 color;
57
+ attribute vec3 torusPos;
58
+ attribute vec3 spherePos;
59
+ varying vec3 vColor;
60
+ uniform float time;
61
+ uniform vec3 mouse;
62
+ uniform float hoverRadius;
63
+ uniform float hoverStrength;
64
+ uniform float audioAmplitude;
65
+ uniform float audioExpansion;
66
+ uniform float isConnected;
67
+
68
+ float hash(vec3 p) {
69
+ p = fract(p * 0.3183099 + 0.1);
70
+ p *= 17.0;
71
+ return fract(p.x * p.y * p.z * (p.x + p.y + p.z));
72
+ }
73
+
74
+ float noise(vec3 p) {
75
+ vec3 i = floor(p);
76
+ vec3 f = fract(p);
77
+ f = f * f * (3.0 - 2.0 * f);
78
+ return mix(
79
+ mix(mix(hash(i), hash(i + vec3(1,0,0)), f.x),
80
+ mix(hash(i + vec3(0,1,0)), hash(i + vec3(1,1,0)), f.x), f.y),
81
+ mix(mix(hash(i + vec3(0,0,1)), hash(i + vec3(1,0,1)), f.x),
82
+ mix(hash(i + vec3(0,1,1)), hash(i + vec3(1,1,1)), f.x), f.y), f.z);
83
+ }
84
+
85
+ void main() {
86
+ vec3 disconnectedColor = vec3(0.7, 0.85, 0.87);
87
+ vec3 connectedColor = color;
88
+ vColor = mix(disconnectedColor, connectedColor, isConnected);
89
+
90
+ vec3 basePos = mix(torusPos, spherePos, isConnected);
91
+ vec3 pos = basePos;
92
+
93
+ float distFromCenter = length(basePos);
94
+ vec3 dirFromCenter = normalize(basePos);
95
+ float audioNoise = noise(basePos * 0.02 + time * 2.0);
96
+ float expansion = audioAmplitude * audioExpansion * (0.5 + audioNoise);
97
+ pos += dirFromCenter * expansion;
98
+
99
+ float turbulence = audioAmplitude * 40.0;
100
+ pos.x += sin(time * 3.0 + position.y * 0.05) * turbulence * audioNoise;
101
+ pos.y += cos(time * 3.0 + position.x * 0.05) * turbulence * audioNoise;
102
+ pos.z += sin(time * 2.0 + position.z * 0.05) * turbulence * audioNoise;
103
+
104
+ vec3 toMouse = pos - mouse;
105
+ float dist = length(toMouse);
106
+
107
+ float noiseVal = noise(basePos * 0.05 + time * 0.5);
108
+ float featheredRadius = hoverRadius * (0.6 + noiseVal * 0.8);
109
+
110
+ if (dist < featheredRadius && dist > 0.0) {
111
+ vec3 pushDir = normalize(toMouse);
112
+ float falloff = 1.0 - smoothstep(0.0, featheredRadius, dist);
113
+ falloff = pow(falloff, 0.5);
114
+
115
+ float angleNoise = noise(basePos * 0.1 + time) * 2.0 - 1.0;
116
+ pushDir.x += angleNoise * 0.3;
117
+ pushDir.y += noise(basePos * 0.1 - time) * 0.3 - 0.15;
118
+ pushDir = normalize(pushDir);
119
+
120
+ float pushAmount = falloff * hoverStrength * (0.7 + noiseVal * 0.6);
121
+ pos += pushDir * pushAmount;
122
+ }
123
+
124
+ float flowSpeed = 0.3;
125
+ float swirl = time * flowSpeed;
126
+
127
+ float angle = atan(basePos.z, basePos.x);
128
+ float flowOffset = sin(swirl + angle * 2.0) * 4.0;
129
+
130
+ float torusFlow = 1.0 - isConnected;
131
+
132
+ pos.x += sin(time * 0.5 + basePos.y * 0.02 + angle) * 3.0 * torusFlow;
133
+ pos.z += cos(time * 0.5 + basePos.y * 0.02 + angle) * 3.0 * torusFlow;
134
+ pos.y += flowOffset * torusFlow;
135
+
136
+ pos.x += sin(time * 0.8 + basePos.y * 0.05) * 2.0;
137
+ pos.y += cos(time * 0.6 + basePos.x * 0.03) * 2.0;
138
+ pos.z += sin(time * 0.7 + basePos.z * 0.04) * 2.0;
139
+
140
+ vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
141
+ float sizeBoost = 1.0 + audioAmplitude * 0.5;
142
+ gl_PointSize = size * sizeBoost * (200.0 / -mvPosition.z);
143
+ gl_Position = projectionMatrix * mvPosition;
144
+ }
145
+ `,fragmentShader:`
146
+ varying vec3 vColor;
147
+
148
+ void main() {
149
+ float dist = length(gl_PointCoord - vec2(0.5));
150
+ if (dist > 0.5) discard;
151
+
152
+ float alpha = 1.0 - smoothstep(0.3, 0.5, dist);
153
+ gl_FragColor = vec4(vColor, alpha);
154
+ }
155
+ `,transparent:!0,depthWrite:!1,blending:ee.AdditiveBlending});S.current=ot;const ht=new ee.Points(yt,ot);k.add(ht);const Ut=new ee.Vector2,Jt=new ee.Vector3,Et=new ee.Matrix4,Ft=E=>{const F=ne.getBoundingClientRect();Ut.x=(E.clientX-F.left)/F.width*2-1,Ut.y=-((E.clientY-F.top)/F.height)*2+1,Jt.set(Ut.x,Ut.y,.5),Jt.unproject(y);const te=Jt.sub(y.position).normalize(),oe=-y.position.z/te.z,le=y.position.clone().add(te.multiplyScalar(oe));Et.copy(ht.matrixWorld).invert(),le.applyMatrix4(Et),ot.uniforms.mouse.value.copy(le)},Bt=()=>{ot.uniforms.mouse.value.set(9999,9999,0)};ne.addEventListener("mousemove",Ft),ne.addEventListener("mouseleave",Bt);const Pn=()=>{const E=ne.clientWidth,F=ne.clientHeight;y.aspect=E/F,y.updateProjectionMatrix(),J.setSize(E,F)},Xe=new ResizeObserver(Pn);Xe.observe(ne);let at=0;const vn=()=>{f.current=requestAnimationFrame(vn),at+=.01,ot.uniforms.time.value=at;const E=I();ot.uniforms.audioAmplitude.value=E,O.current+=(C.current-O.current)*.05,ot.uniforms.isConnected.value=O.current,ht.updateMatrixWorld(),J.render(k,y)};return vn(),()=>{ne.removeEventListener("mousemove",Ft),ne.removeEventListener("mouseleave",Bt),Xe.disconnect(),f.current&&cancelAnimationFrame(f.current),J.dispose()}}catch(ee){console.error("Failed to initialize scene:",ee)}})()},[I]);const N=async()=>{if(!c){l(!0),s(""),m.current||(m.current=new(window.AudioContext||window.webkitAudioContext)),m.current.state==="suspended"&&await m.current.resume();try{const $={};e&&e.trim()&&($.room_config={agents:[{agentName:e.trim()}]});const ee=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)})).json(),ne=new Jn({adaptiveStream:!0,dynacast:!0});h.current=ne,ne.on(U.Connected,()=>{s(""),o(!0),l(!1),C.current=1}),ne.on(U.Disconnected,()=>{document.querySelectorAll("audio").forEach(Z=>{Z.pause(),Z.srcObject=null,Z.remove()}),s(""),o(!1),l(!1),g.current=null,w.current=null,b.current=null,P.current=null,_.current=0,C.current=0}),ne.on(U.ParticipantConnected,()=>{s("")}),ne.on(U.TrackSubscribed,(K,Z,y)=>{K.kind===M.Kind.Audio&&(R(K),s(""))}),ne.on(U.LocalTrackPublished,K=>{K.track&&K.track.kind===M.Kind.Audio&&A(K.track)}),await ne.connect(ee.server_url,ee.participant_token),await ne.localParticipant.setMicrophoneEnabled(!0),ne.localParticipant.audioTrackPublications.forEach(K=>{K.track&&A(K.track)})}catch($){console.error("Connection failed:",$),s("Connection failed"),l(!1)}}},Y=async()=>{if(h.current){try{await h.current.localParticipant.setMicrophoneEnabled(!1)}catch{}h.current.disconnect(!0),h.current=null}document.querySelectorAll("audio").forEach(Q=>{Q.pause(),Q.srcObject=null,Q.remove()}),g.current=null,w.current=null,b.current=null,P.current=null,_.current=0,o(!1),d(!1),s(""),C.current=0,n()},G=()=>{a?Y():c||N()},j=async $=>{if($.stopPropagation(),h.current){const Q=!u;await h.current.localParticipant.setMicrophoneEnabled(!Q),d(Q),Q||setTimeout(()=>{h.current&&h.current.localParticipant.audioTrackPublications.forEach(ne=>{ne.track&&A(ne.track)})},100)}};return q.useEffect(()=>()=>{h.current&&(h.current.disconnect(!0),h.current=null),f.current&&cancelAnimationFrame(f.current),L.current&&L.current.dispose(),document.querySelectorAll("audio").forEach(Q=>{Q.pause(),Q.srcObject=null,Q.remove()})},[]),p.jsxs("div",{className:tn.container,children:[r&&p.jsx("div",{className:tn.status,children:r}),p.jsx("div",{ref:i,className:tn.orbContainer,onClick:G}),p.jsx("div",{className:tn.instruction,children:c?"Connecting...":a?"Tap orb to end call":"Tap orb to start"}),p.jsxs("div",{className:tn.controls,children:[a&&p.jsx("button",{onClick:j,className:`${tn.controlButton} ${u?tn.muted:""}`,title:u?"Unmute microphone":"Mute microphone",type:"button",children:u?p.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:p.jsx("path",{d:"M19 11h-1.7c0 .74-.16 1.43-.43 2.05l1.23 1.23c.56-.98.9-2.09.9-3.28zm-4.02.17c0-.06.02-.11.02-.17V5c0-1.66-1.34-3-3-3S9 3.34 9 5v.18l5.98 5.99zM4.27 3L3 4.27l6.01 6.01V11c0 1.66 1.33 3 2.99 3 .22 0 .44-.03.65-.08l1.66 1.66c-.71.33-1.5.52-2.31.52-2.76 0-5.3-2.1-5.3-5.1H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c.91-.13 1.77-.45 2.54-.9L19.73 21 21 19.73 4.27 3z"})}):p.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:[p.jsx("path",{d:"M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"}),p.jsx("path",{d:"M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"})]})}),p.jsx("button",{onClick:Y,className:tn.backButton,type:"button",children:"Back to chat"})]})]})},bk="_container_zospk_1",kk="_body_zospk_19",Ck="_confirmationOverlay_zospk_30",Sk="_confirmationDialog_zospk_51",Tk="_confirmationText_zospk_73",wk="_confirmationButtons_zospk_81",xk="_cancelButton_zospk_86",_k="_confirmButton_zospk_87",nn={container:bk,body:kk,confirmationOverlay:Ck,confirmationDialog:Sk,confirmationText:Tk,confirmationButtons:wk,cancelButton:xk,confirmButton:_k},Yu=({config:t,messages:e,toolCalls:n=[],isLoading:i,showTypingIndicator:r=!1,isExpanded:s=!1,headerSubtitle:a,voiceTokenUrl:o,voiceAgentName:c="voice-agent",enableVoiceMode:l=!1,onSendMessage:u,onClose:d,onBack:h,onNewChat:f,onExpandWindow:m})=>{var R;const[g,w]=q.useState(!1),[b,P]=q.useState(!1),_=e.length>0,S=l&&!!o,T=()=>{S&&P(!0)},C=()=>{P(!1)},O=()=>{if(e.length===0)return;const N=e.map($=>{const Q=$.role==="user"?"You":t.agentName||"Assistant";return`[${new Date($.timestamp).toLocaleString()}] ${Q}:
156
+ ${$.content}
157
+ `}).join(`
158
+ `),Y=new Blob([N],{type:"text/plain"}),G=URL.createObjectURL(Y),j=document.createElement("a");j.href=G,j.download=`chat-transcript-${new Date().toISOString().split("T")[0]}.txt`,document.body.appendChild(j),j.click(),document.body.removeChild(j),URL.revokeObjectURL(G)},L=()=>{w(!0)},I=()=>{w(!1),f==null||f()},A=()=>{w(!1)};return p.jsxs("div",{className:nn.container,role:"dialog","aria-label":"Chat window",children:[p.jsx(kc,{agentName:t.agentName,agentLogoUrl:t.agentLogoUrl,headerSubtitle:a,welcomeTitle:t.welcomeMessage||"Hello there.",welcomeSubtitle:t.welcomeMessage?void 0:"How can we help?",onClose:d,onBack:h,onNewChatRequest:L,onExpandWindow:m,onDownloadTranscript:_?O:void 0,showMenuButton:_,isExpanded:s,compact:_}),p.jsx("div",{className:nn.body,children:b&&S?p.jsx(yk,{tokenUrl:o,agentName:c,onClose:C,accentColor:t.primaryColor}):p.jsxs(p.Fragment,{children:[p.jsx(ol,{messages:e,toolCalls:n,isLoading:i,showTypingIndicator:r,agentName:t.agentName,agentRole:t.agentRole,agentLogoUrl:t.agentLogoUrl}),p.jsx(al,{onSend:u,disabled:i,placeholder:"Message...",onAttachment:()=>{},onEmoji:()=>{},onGif:()=>{},onVoice:S?T:void 0})]})}),p.jsx(qg,{showBranding:((R=t.styling)==null?void 0:R.showBranding)??!0}),g&&p.jsx("div",{className:nn.confirmationOverlay,children:p.jsxs("div",{className:nn.confirmationDialog,children:[p.jsx("p",{className:nn.confirmationText,children:"End current chat and start a new conversation?"}),p.jsxs("div",{className:nn.confirmationButtons,children:[p.jsx("button",{className:nn.cancelButton,onClick:A,type:"button",children:"Cancel"}),p.jsx("button",{className:nn.confirmButton,onClick:I,type:"button",children:"End Chat"})]})]})})]})};/**
159
+ * @license lucide-react v0.563.0 - ISC
160
+ *
161
+ * This source code is licensed under the ISC license.
162
+ * See the LICENSE file in the root directory of this source tree.
163
+ */const Qu=(...t)=>t.filter((e,n,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===n).join(" ").trim();/**
164
+ * @license lucide-react v0.563.0 - ISC
165
+ *
166
+ * This source code is licensed under the ISC license.
167
+ * See the LICENSE file in the root directory of this source tree.
168
+ */const Ek=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
169
+ * @license lucide-react v0.563.0 - ISC
170
+ *
171
+ * This source code is licensed under the ISC license.
172
+ * See the LICENSE file in the root directory of this source tree.
173
+ */const Pk=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,i)=>i?i.toUpperCase():n.toLowerCase());/**
174
+ * @license lucide-react v0.563.0 - ISC
175
+ *
176
+ * This source code is licensed under the ISC license.
177
+ * See the LICENSE file in the root directory of this source tree.
178
+ */const pc=t=>{const e=Pk(t);return e.charAt(0).toUpperCase()+e.slice(1)};/**
179
+ * @license lucide-react v0.563.0 - ISC
180
+ *
181
+ * This source code is licensed under the ISC license.
182
+ * See the LICENSE file in the root directory of this source tree.
183
+ */var Rk={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
184
+ * @license lucide-react v0.563.0 - ISC
185
+ *
186
+ * This source code is licensed under the ISC license.
187
+ * See the LICENSE file in the root directory of this source tree.
188
+ */const Ik=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};/**
189
+ * @license lucide-react v0.563.0 - ISC
190
+ *
191
+ * This source code is licensed under the ISC license.
192
+ * See the LICENSE file in the root directory of this source tree.
193
+ */const Mk=q.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:i,className:r="",children:s,iconNode:a,...o},c)=>q.createElement("svg",{ref:c,...Rk,width:e,height:e,stroke:t,strokeWidth:i?Number(n)*24/Number(e):n,className:Qu("lucide",r),...!s&&!Ik(o)&&{"aria-hidden":"true"},...o},[...a.map(([l,u])=>q.createElement(l,u)),...Array.isArray(s)?s:[s]]));/**
194
+ * @license lucide-react v0.563.0 - ISC
195
+ *
196
+ * This source code is licensed under the ISC license.
197
+ * See the LICENSE file in the root directory of this source tree.
198
+ */const He=(t,e)=>{const n=q.forwardRef(({className:i,...r},s)=>q.createElement(Mk,{ref:s,iconNode:e,className:Qu(`lucide-${Ek(pc(t))}`,`lucide-${t}`,i),...r}));return n.displayName=pc(t),n};/**
199
+ * @license lucide-react v0.563.0 - ISC
200
+ *
201
+ * This source code is licensed under the ISC license.
202
+ * See the LICENSE file in the root directory of this source tree.
203
+ */const Ok=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],Ak=He("bot",Ok);/**
204
+ * @license lucide-react v0.563.0 - ISC
205
+ *
206
+ * This source code is licensed under the ISC license.
207
+ * See the LICENSE file in the root directory of this source tree.
208
+ */const Dk=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Nk=He("circle-question-mark",Dk);/**
209
+ * @license lucide-react v0.563.0 - ISC
210
+ *
211
+ * This source code is licensed under the ISC license.
212
+ * See the LICENSE file in the root directory of this source tree.
213
+ */const Lk=[["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M14 2v2",key:"6buw04"}],["path",{d:"M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1",key:"pwadti"}],["path",{d:"M6 2v2",key:"colzsn"}]],jk=He("coffee",Lk);/**
214
+ * @license lucide-react v0.563.0 - ISC
215
+ *
216
+ * This source code is licensed under the ISC license.
217
+ * See the LICENSE file in the root directory of this source tree.
218
+ */const Uk=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]],Fk=He("headphones",Uk);/**
219
+ * @license lucide-react v0.563.0 - ISC
220
+ *
221
+ * This source code is licensed under the ISC license.
222
+ * See the LICENSE file in the root directory of this source tree.
223
+ */const Bk=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],Vk=He("heart",Bk);/**
224
+ * @license lucide-react v0.563.0 - ISC
225
+ *
226
+ * This source code is licensed under the ISC license.
227
+ * See the LICENSE file in the root directory of this source tree.
228
+ */const qk=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],zk=He("mail",qk);/**
229
+ * @license lucide-react v0.563.0 - ISC
230
+ *
231
+ * This source code is licensed under the ISC license.
232
+ * See the LICENSE file in the root directory of this source tree.
233
+ */const Wk=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],Xu=He("message-circle",Wk);/**
234
+ * @license lucide-react v0.563.0 - ISC
235
+ *
236
+ * This source code is licensed under the ISC license.
237
+ * See the LICENSE file in the root directory of this source tree.
238
+ */const Hk=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Kk=He("message-square",Hk);/**
239
+ * @license lucide-react v0.563.0 - ISC
240
+ *
241
+ * This source code is licensed under the ISC license.
242
+ * See the LICENSE file in the root directory of this source tree.
243
+ */const Gk=[["path",{d:"M16 10a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 14.286V4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z",key:"1n2ejm"}],["path",{d:"M20 9a2 2 0 0 1 2 2v10.286a.71.71 0 0 1-1.212.502l-2.202-2.202A2 2 0 0 0 17.172 19H10a2 2 0 0 1-2-2v-1",key:"1qfcsi"}]],$k=He("messages-square",Gk);/**
244
+ * @license lucide-react v0.563.0 - ISC
245
+ *
246
+ * This source code is licensed under the ISC license.
247
+ * See the LICENSE file in the root directory of this source tree.
248
+ */const Jk=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384",key:"9njp5v"}]],Yk=He("phone",Jk);/**
249
+ * @license lucide-react v0.563.0 - ISC
250
+ *
251
+ * This source code is licensed under the ISC license.
252
+ * See the LICENSE file in the root directory of this source tree.
253
+ */const Qk=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Xk=He("send",Qk);/**
254
+ * @license lucide-react v0.563.0 - ISC
255
+ *
256
+ * This source code is licensed under the ISC license.
257
+ * See the LICENSE file in the root directory of this source tree.
258
+ */const Zk=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]],eC=He("smile",Zk);/**
259
+ * @license lucide-react v0.563.0 - ISC
260
+ *
261
+ * This source code is licensed under the ISC license.
262
+ * See the LICENSE file in the root directory of this source tree.
263
+ */const tC=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],nC=He("sparkles",tC);/**
264
+ * @license lucide-react v0.563.0 - ISC
265
+ *
266
+ * This source code is licensed under the ISC license.
267
+ * See the LICENSE file in the root directory of this source tree.
268
+ */const iC=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],rC=He("star",iC);/**
269
+ * @license lucide-react v0.563.0 - ISC
270
+ *
271
+ * This source code is licensed under the ISC license.
272
+ * See the LICENSE file in the root directory of this source tree.
273
+ */const sC=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],oC=He("users",sC);/**
274
+ * @license lucide-react v0.563.0 - ISC
275
+ *
276
+ * This source code is licensed under the ISC license.
277
+ * See the LICENSE file in the root directory of this source tree.
278
+ */const aC=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],cC=He("zap",aC),wo={"message-circle":Xu,"message-square":Kk,"messages-square":$k,"help-circle":Nk,headphones:Fk,bot:Ak,sparkles:nC,send:Xk,mail:zk,phone:Yk,users:oC,heart:Vk,star:rC,zap:cC,coffee:jk,smile:eC},lC=Object.keys(wo);function uC(t){const e=wo[t];return e?p.jsx(e,{}):(console.warn(`[Brainbase Chat] Unknown icon name: "${t}". Available icons: ${lC.join(", ")}`),null)}function dC(t){return t in wo}const hC="_toggleButton_186ig_1",fC="_icon_186ig_54",pC="_customIcon_186ig_59",mC="_agentLogo_186ig_72",gC="_unreadBadge_186ig_79",kn={toggleButton:hC,icon:fC,customIcon:pC,agentLogo:mC,unreadBadge:gC},Ns=({onClick:t,agentLogoUrl:e,unreadCount:n=0,customIcon:i})=>{const r=()=>i?typeof i=="string"?dC(i)?p.jsx("span",{className:kn.customIcon,children:uC(i)}):p.jsx("img",{src:i,alt:"",className:kn.agentLogo}):p.jsx("span",{className:kn.customIcon,children:i}):e?p.jsx("img",{src:e,alt:"",className:kn.agentLogo}):p.jsx(Xu,{className:kn.icon});return p.jsxs("button",{className:kn.toggleButton,onClick:t,"aria-label":"Open chat",type:"button",children:[r(),n>0&&p.jsx("span",{className:kn.unreadBadge,children:n>9?"9+":n})]})},vC="_container_kgfgt_1",yC="_header_kgfgt_25",bC="_logoWrapper_kgfgt_38",kC="_logo_kgfgt_38",CC="_closeButton_kgfgt_51",SC="_content_kgfgt_74",TC="_iconWrapper_kgfgt_84",wC="_errorIcon_kgfgt_95",xC="_title_kgfgt_101",_C="_description_kgfgt_109",EC="_retryButton_kgfgt_117",PC="_footer_kgfgt_139",RC="_poweredBy_kgfgt_146",IC="_footerLogo_kgfgt_160",ze={container:vC,header:yC,logoWrapper:bC,logo:kC,closeButton:CC,content:SC,iconWrapper:TC,errorIcon:wC,title:xC,description:_C,retryButton:EC,footer:PC,poweredBy:RC,footerLogo:IC},MC=({errorType:t,message:e,onRetry:n,onClose:i})=>{const r=()=>{switch(t){case"not_found":return{title:"Chat Not Found",description:e||"This chat widget is not configured correctly. Please check the embed ID.",icon:p.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:ze.errorIcon,children:[p.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"1.5"}),p.jsx("path",{d:"M12 7V13M12 16V16.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})};case"network":return{title:"Connection Error",description:e||"Unable to connect to the chat service. Please check your internet connection.",icon:p.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:ze.errorIcon,children:[p.jsx("path",{d:"M12 21C16.9706 21 21 16.9706 21 12C21 7.02944 16.9706 3 12 3C7.02944 3 3 7.02944 3 12C3 16.9706 7.02944 21 12 21Z",stroke:"currentColor",strokeWidth:"1.5"}),p.jsx("path",{d:"M8 15L16 9M8 9L16 15",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})};default:return{title:"Something Went Wrong",description:e||"An unexpected error occurred. Please try again later.",icon:p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:ze.errorIcon,children:p.jsx("path",{d:"M12 9V13M12 17H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})}}},{title:s,description:a,icon:o}=r();return p.jsxs("div",{className:ze.container,children:[p.jsxs("div",{className:ze.header,children:[p.jsx("div",{className:ze.logoWrapper,children:p.jsx(Kn,{className:ze.logo,color:"white",cutoutColor:"var(--bb-primary-color)"})}),i&&p.jsx("button",{className:ze.closeButton,onClick:i,"aria-label":"Close",type:"button",children:p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:p.jsx("path",{d:"M6 18L18 6M6 6L18 18",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),p.jsxs("div",{className:ze.content,children:[p.jsx("div",{className:ze.iconWrapper,children:o}),p.jsx("h2",{className:ze.title,children:s}),p.jsx("p",{className:ze.description,children:a}),n&&p.jsx("button",{className:ze.retryButton,onClick:n,type:"button",children:"Try Again"})]}),p.jsx("div",{className:ze.footer,children:p.jsxs("a",{href:"https://brainbaselabs.com",target:"_blank",rel:"noopener noreferrer",className:ze.poweredBy,children:["Powered by"," ",p.jsx(Kn,{className:ze.footerLogo,color:"var(--bb-text-tertiary)",cutoutColor:"var(--bb-surface-bg)"}),p.jsx("span",{children:"Brainbase Labs"})]})})]})},OC="_container_cgn0s_1",AC="_header_cgn0s_29",DC="_headerBackground_cgn0s_34",NC="_headerContent_cgn0s_40",LC="_agentInfo_cgn0s_45",jC="_headerLogo_cgn0s_51",UC="_headerLogoPlaceholder_cgn0s_58",FC="_headerBrainbaseLogo_cgn0s_68",BC="_headerAgentName_cgn0s_73",VC="_content_cgn0s_79",qC="_infoCard_cgn0s_89",zC="_clickable_cgn0s_104",WC="_infoImageWrapper_cgn0s_122",HC="_infoImage_cgn0s_122",KC="_infoContent_cgn0s_134",GC="_infoText_cgn0s_142",$C="_infoTitle_cgn0s_150",JC="_infoDescription_cgn0s_158",YC="_infoChevron_cgn0s_169",QC="_askCard_cgn0s_177",XC="_askContent_cgn0s_196",ZC="_askTitle_cgn0s_202",eS="_askSubtitle_cgn0s_208",tS="_askIcon_cgn0s_213",nS="_agentLogo_cgn0s_220",iS="_brainbaseLogo_cgn0s_227",rS="_chevron_cgn0s_232",sS="_footer_cgn0s_238",oS="_navItem_cgn0s_246",aS="_active_cgn0s_265",cS="_navIcon_cgn0s_269",fe={container:OC,header:AC,headerBackground:DC,headerContent:NC,agentInfo:LC,headerLogo:jC,headerLogoPlaceholder:UC,headerBrainbaseLogo:FC,headerAgentName:BC,content:VC,infoCard:qC,clickable:zC,infoImageWrapper:WC,infoImage:HC,infoContent:KC,infoText:GC,infoTitle:$C,infoDescription:JC,infoChevron:YC,askCard:QC,askContent:XC,askTitle:ZC,askSubtitle:eS,askIcon:tS,agentLogo:nS,brainbaseLogo:iS,chevron:rS,footer:sS,navItem:oS,active:aS,navIcon:cS},lS=({agentName:t="AI Assistant",agentLogoUrl:e,homeImage:n,homeTitle:i,homeDescription:r,homeLink:s,onStartChat:a,onNavigate:o,currentPage:c})=>{const l=()=>{s&&window.open(s,"_blank","noopener,noreferrer")};return p.jsxs("div",{className:fe.container,children:[p.jsxs("div",{className:fe.header,children:[p.jsx("div",{className:fe.headerBackground}),p.jsx("div",{className:fe.headerContent,children:p.jsxs("div",{className:fe.agentInfo,children:[e?p.jsx("img",{src:e,alt:t,className:fe.headerLogo}):p.jsx("div",{className:fe.headerLogoPlaceholder,children:p.jsx(Kn,{className:fe.headerBrainbaseLogo,color:"white",cutoutColor:"var(--bb-primary-color)"})}),p.jsx("span",{className:fe.headerAgentName,children:t})]})})]}),p.jsxs("div",{className:fe.content,children:[p.jsxs("button",{className:fe.askCard,onClick:a,type:"button",children:[p.jsxs("div",{className:fe.askContent,children:[p.jsx("span",{className:fe.askTitle,children:"Ask a question"}),p.jsxs("span",{className:fe.askSubtitle,children:[t," and team can help"]})]}),p.jsxs("div",{className:fe.askIcon,children:[e?p.jsx("img",{src:e,alt:"",className:fe.agentLogo}):p.jsx(Kn,{className:fe.brainbaseLogo,color:"currentColor"}),p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:fe.chevron,children:p.jsx("path",{d:"M9 18L15 12L9 6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),(n||i||r)&&p.jsxs("button",{className:`${fe.infoCard} ${s?fe.clickable:""}`,onClick:s?l:void 0,type:"button",disabled:!s,children:[n&&p.jsx("div",{className:fe.infoImageWrapper,children:p.jsx("img",{src:n,alt:"",className:fe.infoImage})}),p.jsxs("div",{className:fe.infoContent,children:[p.jsxs("div",{className:fe.infoText,children:[i&&p.jsx("h3",{className:fe.infoTitle,children:i}),r&&p.jsx("p",{className:fe.infoDescription,children:r})]}),s&&p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:fe.infoChevron,children:p.jsx("path",{d:"M9 18L15 12L9 6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})]}),p.jsxs("nav",{className:fe.footer,children:[p.jsxs("button",{className:`${fe.navItem} ${c==="home"?fe.active:""}`,onClick:()=>o("home"),type:"button",children:[p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:fe.navIcon,children:p.jsx("path",{d:"M3 12L5 10M5 10L12 3L19 10M5 10V20C5 20.5523 5.44772 21 6 21H9M19 10L21 12M19 10V20C19 20.5523 18.5523 21 18 21H15M9 21C9.55228 21 10 20.5523 10 20V16C10 15.4477 10.4477 15 11 15H13C13.5523 15 14 15.4477 14 16V20C14 20.5523 14.4477 21 15 21M9 21H15",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),p.jsx("span",{children:"Home"})]}),p.jsxs("button",{className:`${fe.navItem} ${c==="messages"?fe.active:""}`,onClick:()=>o("messages"),type:"button",children:[p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:fe.navIcon,children:p.jsx("path",{d:"M8 12H8.01M12 12H12.01M16 12H16.01M21 12C21 16.4183 16.9706 20 12 20C10.4607 20 9.01172 19.6565 7.74467 19.0511L3 20L4.39499 16.28C3.51156 15.0423 3 13.5743 3 12C3 7.58172 7.02944 4 12 4C16.9706 4 21 7.58172 21 12Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),p.jsx("span",{children:"Messages"})]})]})]})},uS="_widget_1ntwj_1",dS="_inline_1ntwj_26",hS="_openContainer_1ntwj_43",fS="_collapseButton_1ntwj_51",pS="_buttonAppear_1ntwj_1",rn={widget:uS,"bottom-right":"_bottom-right_1ntwj_11","bottom-left":"_bottom-left_1ntwj_18",inline:dS,openContainer:hS,collapseButton:fS,buttonAppear:pS},mS=({embedId:t,apiBaseUrl:e=vc,mockMode:n=!1,mockResponses:i,position:r="bottom-right",defaultOpen:s=!1,primaryColor:a,accentColor:o,primaryGradient:c=!1,accentGradient:l=!1,headerTextColor:u,streamMessages:d=!1,artificialDelay:h,homeImage:f,homeTitle:m,homeDescription:g,homeLink:w,timeToOpen:b,voiceTokenUrl:P,voiceAgentName:_="voice-agent",enableVoiceMode:S=!1,showCollapseButton:T=!0,agentName:C,agentRole:O,headerSubtitle:L,agentLogoUrl:I,agentNameFontSize:A=16,toggleIcon:R,welcomeMessage:N,showBranding:Y,width:G=440,height:j=720,expandedWidth:$=640,expandedHeight:Q=800,messageFontSize:ee=15,theme:ne="light",className:k,onSessionStart:K,onSessionEnd:Z,onMessage:y,onError:J})=>{const[X,W]=q.useState(s),[se,De]=q.useState(!1),[we,Ne]=q.useState("chat"),[Ke,$t]=q.useState(null),[gn,yt]=q.useState(!0),[ot,ht]=q.useState(null),[Ut,Jt]=q.useState(),Et=q.useRef(!1),Ft=q.useRef(!1),Bt=q.useMemo(()=>n?bc({},i):yc(e),[n,i,e]),Pn=q.useCallback(async()=>{if(!(Et.current&&Ke)){yt(!0),ht(null),Jt(void 0);try{const be=await Bt.getDeploymentConfig(t);$t(be),Et.current=!0}catch(be){const Ei=be instanceof Error?be:new Error("Failed to load config");Ei.message.includes("404")?(ht("not_found"),Jt("The chat widget with this embed ID was not found.")):Ei.message.includes("Failed to fetch")||Ei.message.includes("network")?ht("network"):ht("unknown"),n&&($t({embedId:t,deploymentId:"mock-deployment",workerId:"mock-worker",flowId:"mock-flow",primaryColor:"#1a1a2e",agentName:"AI Assistant",styling:{}}),ht(null),Et.current=!0),J==null||J(Ei)}finally{yt(!1)}}},[t,n,Bt,J,Ke]);q.useEffect(()=>{Et.current=!1,Pn()},[t,n,Bt]);const Xe=q.useMemo(()=>{const be=Ke??{embedId:t,deploymentId:"",workerId:"",flowId:""};return{...be,primaryColor:a??be.primaryColor??"#1a1a2e",agentName:C??be.agentName,agentRole:O??be.agentRole,agentLogoUrl:I??be.agentLogoUrl,welcomeMessage:N??be.welcomeMessage,styling:{...be.styling??{},...Y!==void 0?{showBranding:Y}:{}}}},[Ke,t,a,C,O,I,N,Y]),at=gc({config:Xe,apiClient:Bt,mockMode:n,streamMessages:d,artificialDelay:h,onSessionStart:K,onSessionEnd:Z,onMessage:y,onError:J});q.useEffect(()=>{if(!b||Ft.current||X||gn)return;const be=setTimeout(()=>{!Ft.current&&!X&&(Ft.current=!0,W(!0),Ne("chat"),at.sendTriggerMessage())},b*1e3);return()=>clearTimeout(be)},[b,X,gn,at]);const vn=o??Xe.primaryColor??"#1a1a2e",F=u??(ne==="granite"?"#9ca3af":"#000000"),te=q.useMemo(()=>({"--bb-primary-color":Xe.primaryColor??"#1a1a2e","--bb-accent-color-custom":vn,"--bb-primary-gradient":c?"1":"0","--bb-accent-gradient":l?"1":"0","--bb-header-text-color":F,"--bb-widget-width":se?`${$}px`:`${G}px`,"--bb-widget-height":se?`${Q}px`:`${j}px`,"--bb-message-font-size":`${ee}px`,"--bb-agent-name-font-size":`${A}px`}),[Xe.primaryColor,vn,c,l,F,se,G,j,$,Q,ee,A]),oe=()=>{at.endSession(),at.startNewSession()},le=()=>{W(!1)},qe=()=>{Pn()},ct=()=>{De(!se)},Ge=be=>{Ne(be==="messages"?"chat":be)},yn=()=>{Ne("home")},bn=()=>{Ne("chat")},Me=r==="inline";if(gn)return null;if(ot&&!n)return!Me&&!X?p.jsx("div",{className:`${rn.widget} ${rn[r]} ${k??""}`,style:te,"data-bb-theme":ne,children:p.jsx(Ns,{onClick:()=>W(!0),agentName:C,customIcon:R})}):p.jsx("div",{className:`${rn.widget} ${rn[r]} ${k??""}`,style:te,"data-bb-theme":ne,children:p.jsx(MC,{errorType:ot,message:Ut,onRetry:qe,onClose:Me?void 0:le})});const Yt=[rn.widget,rn[r],k??""].filter(Boolean).join(" ");return p.jsx("div",{className:Yt,style:te,"data-bb-theme":ne,children:X||Me?p.jsxs("div",{className:rn.openContainer,children:[we==="home"?p.jsx(lS,{agentName:Xe.agentName,agentLogoUrl:Xe.agentLogoUrl,homeImage:f,homeTitle:m,homeDescription:g,homeLink:w,onStartChat:bn,onNavigate:Ge,currentPage:"home"}):p.jsx(Yu,{config:Xe,messages:at.messages,isLoading:at.isLoading,showTypingIndicator:at.showTypingIndicator,isExpanded:se,headerSubtitle:L,voiceTokenUrl:P,voiceAgentName:_,enableVoiceMode:S,onSendMessage:at.sendMessage,onClose:Me?void 0:le,onBack:yn,onNewChat:oe,onExpandWindow:Me?void 0:ct}),!Me&&T&&p.jsx("button",{className:rn.collapseButton,onClick:le,"aria-label":"Close chat",type:"button",children:p.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:p.jsx("path",{d:"M6 9L12 15L18 9",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]}):p.jsx(Ns,{onClick:()=>W(!0),agentName:Xe.agentName,agentLogoUrl:Xe.agentLogoUrl,customIcon:R})})};function gS(){if(typeof crypto<"u"&&crypto.randomUUID)return`bb-${crypto.randomUUID()}`;const t=Date.now().toString(36),e=Math.random().toString(36).substring(2,15),n=Math.random().toString(36).substring(2,15);return`bb-${t}-${e}${n}`}exports.ChatContainer=Yu;exports.ChatHeader=kc;exports.ChatToggleButton=Ns;exports.ChatWidget=mS;exports.Message=il;exports.MessageInput=al;exports.MessageList=ol;exports.ToolCallDisplay=rl;exports.TypingIndicator=sl;exports.clearSession=Zr;exports.createAPIClient=yc;exports.createMockAPIClient=bc;exports.generateSessionId=gS;exports.getStoredSession=mc;exports.storeSession=Xr;exports.useChat=gc;