1!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._posthogChunkIds=e._posthogChunkIds||{},e._posthogChunkIds[n]="01a0804f-862a-79d0-9e7a-8ff2b7e3968d")}catch(e){}}();(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,690188,e=>{"use strict";var t=e.i(943306),i=e.i(297068),n=e.i(123334),r=e.i(746632),a=e.i(681891),s=e.i(683452),o=e.i(396312),c=e.i(223788),l=e.i(701049),d=e.i(31200),u=e.i(107850),h=e.i(354559),p=e.i(375842),m=e.i(328982),g=e.i(452520),f=e.i(826261);function v(e){return e?.types.includes("Files")??!1}function b(e){return"dataTransfer"in e}var y=e.i(460692);let k=i.default.memo(i.default.forwardRef(({input:e,handleInputChange:k,handleInputValueChange:T,handleSubmit:S,isLoading:C,hasSuggestionsMarker:E=!1,onAbort:w,placeholderTexts:R,usageWarning:P,usageWarningVariant:_="chat",showFileUpload:I=!0,isFileUploadDisabled:x=!1,fileDropTarget:O="window",fileDropTargetElement:D,fileDropOverlay:M="page",isDisabled:A=!1,useSharedContainer:N=!1,hasFormAbove:L=!1,emptyPlaceholderText:U,warningPortalId:j,isSpeechToTextDisabled:F=!1,draftScopeKey:B,isDraftPending:q=!1,draftAttachments:V,setDraftAttachments:W,isFreshStart:H=!1,scrollContainerRef:G},z)=>{let{fileInputRef:K,attachments:J,isUploading:$,handleFileClick:Q,handleFileChange:X,handleRemoveAttachment:Y,handleFileUpload:Z,clearAttachments:ee,restoreAttachments:et}=(0,c.useFileUpload)({draftAttachments:V,setDraftAttachments:W}),ei=(0,i.useRef)(null),en=(0,s.useIsHydrated)(),er=A||en&&q,[ea,es]=(0,i.useState)(!1),{sttLanguage:eo}=(0,a.useUserPreferences)(),ec=function(e){let[t,n]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{let t=e?.current??(0,d.getChatContainer)();if(!t)return;let i=()=>{n(t.scrollHeight-t.clientHeight-t.scrollTop>window.innerHeight)};return t.addEventListener("scroll",i,{passive:!0}),i(),()=>{t.removeEventListener("scroll",i)}},[e]),t}(G),el=I&&!er&&!x,ed=function({isFileUploadAllowed:e,onFilesDropped:t,target:n,targetElement:r}){let[a,s]=(0,i.useState)(!1),o=(0,i.useRef)(0),[c,l]=(0,i.useState)(e);return c!==e&&(l(e),e||s(!1)),(0,i.useEffect)(()=>{if(!e){o.current=0;return}let i="window"===n?window:r,a="element"===n;if(!i)return;let c=e=>{!b(e)||v(e.dataTransfer)&&(e.preventDefault(),e.stopPropagation(),o.current+=1,1===o.current&&s(!0))},l=e=>{!b(e)||v(e.dataTransfer)&&(e.preventDefault(),e.stopPropagation(),o.current=Math.max(0,o.current-1),0===o.current&&s(!1))},d=e=>{!b(e)||v(e.dataTransfer)&&(e.preventDefault(),e.stopPropagation(),o.current<=0&&(o.current=1),s(function(e){if(!e?.items||0===e.items.length)return!1;for(let t=0;t<e.items.length;t+=1){let i=e.items[t];if(!i||"file"!==i.kind)continue;let n=i.type.toLowerCase();if(n&&(0,f.isAllowedFileType)(n))return!0}return!1}(e.dataTransfer)))},u=e=>{if(!b(e)||!v(e.dataTransfer))return;e.preventDefault(),e.stopPropagation(),s(!1),o.current=0;let i=e.dataTransfer?.files;if(!i)return;let n=Array.from(i);if(0===n.length)return;let r=n.filter(e=>(0,f.isAllowedFileType)(e.type));r.length>0&&t(r)},h=e=>{!b(e)||v(e.dataTransfer)&&e.preventDefault()};return i.addEventListener("dragenter",c),i.addEventListener("dragleave",l),i.addEventListener("dragover",d),i.addEventListener("drop",u),a&&(window.addEventListener("dragover",h),window.addEventListener("drop",h)),()=>{i.removeEventListener("dragenter",c),i.removeEventListener("dragleave",l),i.removeEventListener("dragover",d),i.removeEventListener("drop",u),a&&(window.removeEventListener("dragover",h),window.removeEventListener("drop",h))}},[e,t,n,r]),a}({isFileUploadAllowed:el,onFilesDropped:Z,target:O,targetElement:D}),eu=e.trim().length>0,eh=e.length>0,ep=(0,i.useMemo)(()=>({onTranscriptChange:e=>{T(e),ei.current&&(0,d.adjustTextareaHeight)(ei.current)},onError:e=>{r.toast.error(e)},onStop:()=>{requestAnimationFrame(()=>{if(!ei.current)return;ei.current.focus();let e=ei.current.value.length;ei.current.setSelectionRange(e,e)})}}
1),[T]),{audioLevelRef:em,isRecording:eg,isConnecting:ef,isAwaitingPermission:ev,isPermissionBlocked:eb,error:ey,startRecording:ek,stopRecording:eT,toggleRecording:eS,dismissBlocked:eC}=(0,l.useSpeechToText)({...ep,languageCode:eo}),eE=!U&&!L&&!eh&&0===J.length&&!eg,{markComposerPreferred:ew,rememberSelection:eR}=(0,o.useChatTypeToFocus)({handleInputValueChange:T,hasFormAbove:L,input:e,isDisabled:er,isRecording:eg,textareaRef:ei}),eP=ea||C&&!E&&!eu&&0===J.length,e_=(0,i.useRef)(0);(0,i.useEffect)(()=>{e_.current=J.length},[J.length]),(0,i.useImperativeHandle)(z,()=>{let e=ei.current;if(!e)throw Error("ChatInput textarea must be mounted before exposing its handle");return Object.assign(e,{focus:t=>{HTMLTextAreaElement.prototype.focus.call(e,t);let i=e.value.length;e.setSelectionRange(i,i)},restoreAttachments:e=>{let t=Date.now();et(e.map((e,i)=>{let n=e.uid??`restored-${t}-${i}`;return{uid:n,order:e.order??`${t.toString().padStart(13,"0")}:${i.toString().padStart(2,"0")}:${n}`,file:new File([],e.name||"attachment",{type:e.contentType}),uploadState:"done",uploadedData:{url:e.url,name:e.name||"attachment",contentType:e.contentType,id:e.id||`restored-${i}`,inlineContent:e.inlineContent,uploadedAt:e.uploadedAt??t}}}))},getStagedAttachmentCount:()=>e_.current})},[et]),(0,i.useEffect)(()=>{ei.current&&(0,d.adjustTextareaHeight)(ei.current)},[e]);let[eI,ex]=(0,i.useState)(C);eI!==C&&(ex(C),C&&es(!1));let eO=(0,i.useCallback)(e=>{if(!L||!e)return;let t=e.closest('[data-chat-composer-shell="true"]'),i=t?.querySelector('[data-chat-form-portal="true"]')??null;i?.id&&window.dispatchEvent(new CustomEvent("chat-form-portal-dismiss",{detail:{portalId:i.id}}))},[L]),eD=(0,i.useCallback)(e=>{!("Enter"!==e.key||(0,d.isTouchPrimaryDevice)())&&(e.shiftKey||(e.preventDefault(),e.currentTarget.closest("form")?.requestSubmit()))},[]),eM=(0,i.useCallback)(e=>{(0,d.adjustTextareaHeight)(e.currentTarget)},[]),eA=(0,i.useCallback)(()=>{ew()},[ew]),eN=(0,i.useCallback)(()=>{eR()},[eR]),eL=(0,i.useCallback)(async e=>{if(!el)return;let t=Array.from(e.clipboardData?.items??[]);if(0===t.length)return;let i=t.filter(e=>"file"===e.kind).map(e=>e.getAsFile()).filter(e=>!!e);0!==i.length&&(e.preventDefault(),await Z(i))},[Z,el]),eU=(0,i.useCallback)(async t=>{if(t.preventDefault(),er)return;let i=t.currentTarget;(eg||ef)&&eT({commitTail:!1});let n=J.flatMap(e=>"done"===e.uploadState&&e.uploadedData?[e.uploadedData]:[]);if(!(e.trim().length>0||n.length>0))return void es(!1);eO(i);let r=J.map(e=>({...e}));es(!0),ee();try{await S(t,{attachments:n.length>0?n:void 0})}catch(e){es(!1),et(r)}},[J,ee,eO,S,e,er,ef,eg,et,eT]),ej=(0,i.useCallback)(t=>{if(er)return void t.preventDefault();if(!H&&!e.trim()&&0===J.length&&ec){t.preventDefault(),G?.current?.dispatchEvent(new CustomEvent(y.FOLLOW_STREAM_REQUEST_EVENT)),(0,d.scrollChatContainerToBottom)({container:G?.current,behavior:"auto"});return}C&&w&&!eu&&0===J.length&&(t.preventDefault(),eO(t.currentTarget.closest("form")),w())},[J.length,eO,eu,e,er,H,C,w,ec,G]),eF=(0,i.useCallback)(e=>{!e.target.closest("textarea")&&ei.current&&e.preventDefault()},[]),eB=(0,i.useCallback)(e=>{!e.target.closest("button, textarea, input")&&ei.current&&document.activeElement!==ei.current&&ei.current.focus()},[]),eq=(0,i.useMemo)(()=>(0,t.jsx)(u.ChatInputAttachmentLane,{fileInputRef:K,isDisabled:er||x,isUploading:$,onFileChange:X,onFileClick:Q,showFileUpload:I}),[K,X,Q,er,x,$,I]),eV=(0,i.useMemo)(()=>(0,t.jsx)(p.ChatInputSubmitControls,{audioLevelRef:em,existingText:e,hasSpeechError:!!ey,isAwaitingPermission:ev,isConnecting:ef,isDisabled:er,isSpeechToTextDisabled:F,isLoading:eP,isPermissionBlocked:eb,isRecording:eg,onDismissBlocked:eC,onStart:ek,onStop:eT,onSubmitClick:ej,onToggle:eS,rotate:!H&&!e.trim()&&0===J.length&&ec,submitDisabled:!!er||!eP&&!H&&($||!e.trim()&&0===J.length&&!ec)}),[J.length,em,eC,ej,e,ev,er,ef,F,H,eb,eg,$,ec,eP,ey,ek,eT,eS]),eW=((e,t)=>{if(!t)return e;if(!en)return null;let i=document.getElementById(t);return i?(0,n.createPortal)(e,i):e})((0,t.jsx)(m.ChatInputUsageWarning,{usageWarning:P,variant:_}),j),eH=ed?(0,t.jsx)(g.DragOverlay,{variant:M,portalContainer:"panel"===M?D??null:null}):null;return(0,t.jsxs)(t.Fragment,{children:[eH,eW,(0,t.jsx)("form",{onSubmit:eU,className:N||L?void 0:"pb-4",children:(0,t.jsx)(h.ChatInputShell,{actionLane:eq,attachments:J,draftScopeKey:B,handleInputChange:k,hasFormAbove:L,input:e,isDisabled:er,isDraftPending:q,isFreshStart:H,isRecording:eg,onBlur:eN,onFocus:eA,onInput:eM,onKeyDown:eD,onPaste:eL,onRemoveAttachment:Y,onSurfaceClick:eB,onSurfaceMouseDown:eF,placeholderTexts:R,emptyPlaceholderText:U,showCustomPlaceholder:eE,submitControls:eV,textareaRef:ei,useSharedContainer:N})})]})}));k.displayName="ChatInput",e.s(["ChatInput",0,k],690188)},107850,e=>{"use strict";var t=e.i(943306),i=e.i(826261),n=e.i(687179);e.s(["ChatInputAttachmentLane",0,function({fileInputRef:e,isDisabled:r,isUploading:a,onFileChange:s,onFileClick:o,showFileUpload:c}){return(0,t.jsx)("div",{className:"flex gap-2",children:c&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("input",{type:"file",ref:e,onChange:s,className:"hidden",multiple:!0,accept:i.FILE_TYPES.INPUT_ACCEPT,disabled:r,"aria-label":"Attach files"}),(0,t.jsx)(n.FileButton,{onClick:o,isUploading:a,isDisabled:r})]})})}])},354559,e=>{"use strict";var t=e.i(943306),i=e.i(839221),n=e.i(838696),r=e.i(654452);e.s(["ChatInputShell",0,function({actionLane:e,attachments:a,draftScopeKey:s,handleInputChange:o,hasFormAbove:c,input:l,isDisabled:d,isDraftPending:u,isFreshStart:h,isRecording:p,onBlur:m,onFocus:g,onInput:f,onKeyDown:v,onPaste:b,onRemoveAttachment:y,onSurfaceClick:k,onSurfaceMouseDown:T,placeholderTexts:S,emptyPlaceholderText:C,showCustomPlaceholder:E,submitControls:w,textareaRef:R,useSharedContainer:P}){let _=!P&&!c;return(0,t.jsxs)("div",{onClick:k,onMouseDown:T,className:(0,i.cn)("relative cursor-text text-xl",_&&"chat-composer-frame overflow-hidden rounded-3xl bg-(--chat-input-bg) shadow-(--chat-input-shadow) backdrop-blur-2xl backdrop-saturate-150 transition-[background-color,box-shadow] duration-300 focus-within:bg-(--chat-input-bg-focus) focus-within:shadow-(--chat-input-shadow-focus)",P&&!c&&"overflow-hidden bg-(--chat-input-bg) transition-[background-color] duration-300 focus-within:bg-(--chat-input-bg-focus)",c&&"overflow-hidden bg-transparent"),style:c?{backgroundImage:"linear-gradient(180deg, oklch(from var(--card) l c h / 0.42) 0%, var(--chat-input-bg) 75%, var(--chat-input-bg) 100%)",borderTopLeftRadius:0,borderTopRightRadius:0}:void 0,children:[a.length>0&&(0,t.jsx)(r.FilePreview,{files:a,onRemove:y}),(0,t.jsx)(n.ChatInputTextControls,{attachmentsCount:a.length,draftScopeKey:s,handleInputChange:o,hasFormAbove:c,input:l,isDisabled:d,isDraftPending:u,isFreshStart:h,isRecording:p,onBlur:m,onFocus:g,onInput:f,onKeyDown:v,onPaste:b,placeholderTexts:S,emptyPlaceholderText:C,showCustomPlaceholder:E,textareaRef:R}),(0,t.jsxs)("div",{className:"flex items-center justify-between p-3",children:[e,w]})]})}])},375842,328982,e=>{"use strict";var t=e.i(943306),i=e.i(872143),n=e.i(870616);e.s(["ChatInputSubmitControls",0,function({audioLevelRef:e,existingText:r,hasSpeechError:a,isAwaitingPermission:s,isConnecting:o,isDisabled:c,isSpeechToTextDisabled:l=!1,isLoading:d,isPermissionBlocked:u,isRecording:h,onDismissBlocked:p,onStart:m,onStop:g,onSubmitClick:f,onToggle:v,rotate:b,submitDisabled:y}){return(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(i.SpeechToTextButton,{audioLevelRef:e,isRecording:h,isConnecting:o,isAwaitingPermission:s,isPermissionBlocked:u,hasError:a,existingText:r,isDisabled:c||l,onToggle:v,onStart:m,onStop:g,onDismissBlocked:p}),(0,t.jsx)(n.SubmitButton,{onClick:f,isLoading:d,isDisabled:y,rotate:b})]})}],375842);var r=e.i(720576),a=e.i(788794),s=e.i(689034);let o={chat:{exceeded:"Out of credits",approaching:"Running low on credits"},builder:{exceeded:"Out of building credits",approaching:"Running low on credits"}};e.s(["ChatInputUsageWarning",0,function({usageWarning:e,variant:i="chat"}){let{openPricingModal:n}=(0,s.usePricingModal)(),{requiresPlus:c,trialEnabled:l,isResolved:d}=(0,r.useSignupAccess)(),u=(0,a.shouldShowPlusOnly)({requiresPlus:c,isResolved:d}),h=(0,a.getPlusCtaLabel)({requiresPlus:u,trialEnabled:l});return e?(0,t.jsxs)("div",{role:"alert",className:`mb-3 flex w-fit items-center gap-2 rounded-lg px-3 py-2 text-sm shadow-xs ${e.exceeded?"bg-error-soft text-error":"bg-warning-soft text-warning"}`,children:[(0,t.jsxs)("span",{children:[(0,t.jsx)("span",{className:"font-medium",children:e.exceeded?o[i].exceeded:o[i].approaching}),null!==e.resetTime&&(0,t.jsxs)("span",{className:`ml-1 ${e.exceeded?"text-error-muted":"text-warning-muted"}
1`,children:["(resets in ",function(e){let t=e-Date.now();if(t<=0)return"soon";let i=Math.ceil(t/6e4);if(i<60)return`${i}m`;let n=Math.floor(i/60);if(n>=24){let e=Math.ceil(n/24);return 1===e?"1 day":`${e} days`}let r=i%60;return 0===r?`${n}h`:`${n}h ${r}m`}(e.resetTime),")"]})]}),"free"===e.tier&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:e.exceeded?"text-error-muted opacity-60":"text-warning-muted opacity-60",children:"·"}),(0,t.jsxs)("span",{children:[(0,t.jsx)("button",{type:"button",onClick:n,className:`font-medium underline underline-offset-2 transition-colors ${e.exceeded?"text-error decoration-error-muted hover:opacity-80":"text-warning decoration-warning-muted hover:opacity-80"}`,children:u?"Upgrade":h})," ",e.exceeded?"builder"===i?"to keep building":"to keep chatting":"for higher limits"]})]})]}):null}],328982)},838696,e=>{"use strict";var t=e.i(943306),i=e.i(472178),n=e.i(839221),r=e.i(680022);let a={minHeight:"44px"};e.s(["ChatInputTextControls",0,function({attachmentsCount:e,draftScopeKey:s,handleInputChange:o,hasFormAbove:c,input:l,isDisabled:d,isDraftPending:u,isFreshStart:h,isRecording:p,emptyPlaceholderText:m,onBlur:g,onFocus:f,onInput:v,onKeyDown:b,onPaste:y,placeholderTexts:k,showCustomPlaceholder:T,textareaRef:S}){let C=T&&!m,E=e>0?r.STATIC_PLACEHOLDER:c?m??"or type here...":m;return(0,t.jsxs)(t.Fragment,{children:[C?(0,t.jsx)(r.PlaceholderAnimator,{placeholderTexts:k,showCustomPlaceholder:!0,isFreshStart:h}):null,(0,t.jsx)(i.Textarea,{ref:S,"data-chat-draft-scope":s,suppressHydrationWarning:!0,value:l,onChange:o,onKeyDown:b,onInput:v,onFocus:f,onBlur:g,onPaste:y,disabled:p||d||u,rows:1,placeholder:p?"Listening...":E,className:(0,n.cn)("resize-none rounded-2xl border-0 bg-transparent px-4 pt-4 text-xl! font-semibold placeholder:text-muted-foreground placeholder-shown:h-auto! focus:ring-0 focus:outline-hidden focus-visible:ring-transparent focus-visible:ring-offset-0 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-muted-foreground/30 [&::-webkit-scrollbar-track]:bg-transparent",p&&"cursor-not-allowed",c&&"rounded-t-none rounded-b-2xl"),style:a})]})}])},452520,e=>{"use strict";var t=e.i(943306),i=e.i(297068),n=e.i(801315),r=e.i(123334),a=e.i(826261);let s=i.default.memo(({variant:e="page",portalContainer:i=null})=>{let s="page"===e?(0,t.jsxs)("div",{className:"pointer-events-none fixed inset-0 z-50",children:[(0,t.jsx)("div",{className:"absolute inset-0 bg-background/70 backdrop-blur-md"}),(0,t.jsx)("div",{className:"absolute inset-8 rounded-3xl border-2 border-dashed border-primary/40 dark:border-primary/30"}),(0,t.jsxs)("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-8",children:[(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)("div",{className:"absolute -inset-4 animate-pulse rounded-full bg-primary/5 dark:bg-primary/10"}),(0,t.jsx)(n.Upload,{className:"size-14 text-primary/80"})]}),(0,t.jsxs)("div",{className:"flex flex-col items-center gap-3",children:[(0,t.jsx)("div",{className:"text-2xl font-medium text-primary/90",children:"Drop to upload"}),(0,t.jsxs)("div",{className:"rounded-full bg-background/50 px-4 py-2 text-sm text-muted-foreground/90 backdrop-blur-xs",children:["Images and text files ⢠Up to ",a.CHAT_CONSTANTS.MAX_FILE_SIZE_MB,"MB each ⢠Max ",a.CHAT_CONSTANTS.MAX_ATTACHMENTS_PER_MESSAGE," per message"]})]})]})]}):(0,t.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-20",children:[(0,t.jsx)("div",{className:"absolute inset-0 bg-background/70 backdrop-blur-md"}),(0,t.jsx)("div",{className:"absolute inset-4 rounded-3xl border-2 border-dashed border-primary/40 dark:border-primary/30"}),(0,t.jsxs)("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 px-4",children:[(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)("div",{className:"absolute -inset-3 animate-pulse rounded-full bg-primary/5 dark:bg-primary/10"}),(0,t.jsx)(n.Upload,{className:"size-10 text-primary/80"})]}),(0,t.jsxs)("div",{className:"flex flex-col items-center gap-2 text-center",children:[(0,t.jsx)("div",{className:"text-lg font-medium text-primary/90",children:"Drop to upload"}),(0,t.jsxs)("div",{className:"rounded-full bg-background/50 px-4 py-2 text-sm text-muted-foreground
1/90 backdrop-blur-xs",children:["Images and text files ⢠Up to ",a.CHAT_CONSTANTS.MAX_FILE_SIZE_MB,"MB each"]})]})]})]});return"page"===e?(0,r.createPortal)(s,document.body):i?(0,r.createPortal)(s,i):null});s.displayName="DragOverlay",e.s(["DragOverlay",0,s])},687179,e=>{"use strict";var t=e.i(943306),i=e.i(297068),n=e.i(980719),r=e.i(809382);let a=i.default.memo(({onClick:e,isUploading:i,isDisabled:a=!1})=>(0,t.jsx)(r.Button,{type:"button",variant:"soft",size:"icon",disabled:a||i,onClick:t=>{t.stopPropagation(),i||e(t)},"aria-label":"Attach files",children:(0,t.jsx)(n.Plus,{className:"size-5"})}));a.displayName="FileButton",e.s(["FileButton",0,a])},654452,e=>{"use strict";var t=e.i(943306),i=e.i(297068),n=e.i(60409),r=e.i(145895),a=e.i(92470),s=e.i(176300),o=e.i(100889),c=e.i(809382),l=e.i(826261);let d=i.default.memo(({files:e,onRemove:d})=>{let[u,h]=(0,i.useState)([]),[p,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{let t=e.map(e=>({src:e.uploadedData?.url?e.uploadedData.url:URL.createObjectURL(e.file),alt:e.uploadedData?.name||e.file.name,type:e.uploadedData?.contentType||e.file.type}));return h(t),()=>{t.forEach((t,i)=>{e[i]?.uploadedData?.url||URL.revokeObjectURL(t.src)})}},[e]),(0,i.useEffect)(()=>{if(!p||!(0,l.isTextBasedType)(p.type)){f(null),b(!1);return}let t=e.find(e=>e.uid===p.uid),i=t?.uploadedData?.inlineContent;if("string"==typeof i){f(i),b(!1);return}let n=!1;return b(!0),(t&&t.file.size>0?t.file.text():fetch(p.src).then(e=>{if(!e.ok)throw Error(`Failed to fetch attachment: ${e.status}`);return e.text()})).then(e=>{n||(f(e),b(!1))}).catch(()=>{n||(f("Failed to load attachment content"),b(!1))}),()=>{n=!0}},[p,e]),(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"flex flex-wrap gap-2 px-3 pt-3",children:u.map((i,o)=>{let l=e[o];return l?(0,t.jsxs)("div",{className:"group relative",children:[i.type.startsWith("image/")?(0,t.jsxs)("div",{className:`relative h-16 w-16 cursor-pointer overflow-hidden rounded-xl border border-border/60 bg-card/50 backdrop-blur-xs dark:bg-muted/80 ${"uploading"===l.uploadState?"after:absolute after:inset-0 after:rounded-xl after:bg-black/30":""} ${"error"===l.uploadState?"border-error-solid":""}`,onClick:()=>"uploading"!==l.uploadState&&m({uid:l.uid,src:i.src,alt:i.alt,type:i.type}),children:[(0,t.jsx)(n.default,{src:i.src,alt:i.alt,fill:!0,sizes:"64px",className:`object-cover transition-opacity ${"uploading"===l.uploadState?"opacity-70":""}`,unoptimized:!0}),"uploading"===l.uploadState&&(0,t.jsx)("div",{className:"absolute inset-0 z-10 flex items-center justify-center",children:(0,t.jsx)(a.Loader2,{className:"size-5 animate-spin text-white"})})]}):(0,t.jsxs)("div",{className:`relative flex cursor-pointer items-center gap-2 rounded-xl border border-border/60 bg-card/50 px-3 py-2 backdrop-blur-xs dark:bg-muted/80 ${"uploading"===l.uploadState?"opacity-50":""}`,onClick:()=>"uploading"!==l.uploadState&&m({uid:l.uid,src:i.src,alt:i.alt,type:i.type}),children:[(0,t.jsx)(r.FileText,{className:"size-4 text-muted-foreground"}),(0,t.jsx)("span",{className:"text-sm text-muted-foreground",children:(e=>{if(e.length<=30)return e;let t=e.lastIndexOf("."),i=-1===t?"":e.slice(t),n=-1===t?e:e.slice(0,t),r=Math.floor(13.5),a=n.slice(0,r),s=n.slice(-r)+i;return`${a}...${s}`})(i.alt)}),"uploading"===l.uploadState&&(0,t.jsx)("div",{className:"absolute inset-0 flex items-center justify-center rounded-xl bg-black/30",children:(0,t.jsx)(a.Loader2,{className:"size-5 animate-spin text-white"})})]}),(0,t.jsx)(c.Button,{variant:"outline",size:"icon-xs",onClick:e=>{e.stopPropagation(),d(l.uid)},className:"absolute -top-1.5 -right-1.5 z-10 rounded-full",children:(0,t.jsx)(s.X,{className:"size-3"})})]},l.uid):null})}),p&&(0,t.jsx)(o.AttachmentPreviewModal,{src:p.src,alt:p.alt,contentType:p.type,content:g,isLoadingContent:v,onClose:()=>{m(null),f(null),b(!1)}})]})});d.displayName="FilePreview",e.s(["FilePreview",0,d])},680022,e=>{"use strict";var t=e.i(943306),i=e.i(297068);let n="Message Snow...",r="absolute top-4 block w-full overflow-hidden text-ellipsis whitespace-nowrap text-muted-foreground",a="translate 400ms linear",s=`${a}, opacity 260ms linear`,o=`${a}, opacity 340ms linear 60ms`;function c({currentText:e,nextText:i,isAnimating:n,transitionKey:a}){return(0,t.jsx)("div",{"data-chat-placeholder":"true",className:"pointer-events-none absolute inset-0 flex h-14 items-center overflow-hidden rounded-[inherit] px-4",children:(0,t.jsxs)("div",{className:"relative h-full w-full",children:[(0,t.jsx)("span",{style:{transition:s},className:`${r} ${n?"-translate-y-1.5 opacity-0":"translate-y-0 opacity-100"}`,children:e},`ph-current-${a}`),(0,t.jsx)("span",{style:{transition:o},className:`${r} ${n?"translate-y-0 opacity-100":"translate-y-1.5 opacity-0"}`,children:i},`ph-next-${a}`)]})})}e.s(["PLACEHOLDER_SLIDE_MS",0,400,"PlaceholderAnimator",0,function({placeholderTexts:e,showCustomPlaceholder:r,isFreshStart:a}){let[s,o]=(0,i.useState)(0),[l,d]=(0,i.useState)(!1),[u,h]=(0,i.useState)(!1),p=(0,i.useMemo)(()=>(e??[]).filter(e=>"string"==typeof e&&e.trim().length>0&&e!==n),[e]),m=(0,i.useMemo)(()=>a||0===p.length?[n]:[...p,n],[a,p]),g=(0,i.useRef)([]);(0,i.useEffect)(()=>{let e=!1;return p.length===g.current.length&&p.every((e,t)=>e===g.current[t])||(g.current=p,queueMicrotask(()=>{e||(h(!1),o(0),d(!1))})),()=>{e=!0}}
1,[p]);let f=r&&m.length>1&&s<m.length-1&&!u;if((0,i.useEffect)(()=>{if(!f){m.length>1&&s>=m.length-1&&!u&&queueMicrotask(()=>{h(!0)});return}let e=setTimeout(()=>{d(!0)},4e3);return()=>clearTimeout(e)},[f,s,m.length,u]),(0,i.useEffect)(()=>{if(!l)return;let e=setTimeout(()=>{o(e=>e+1),d(!1)},400);return()=>clearTimeout(e)},[l]),!r)return null;let v=Math.min(s,m.length-1),b=m[v]??n,y=Math.min(v+1,m.length-1),k=m[y]??n;return(0,t.jsx)(c,{currentText:b,nextText:k,isAnimating:l,transitionKey:v})},"PlaceholderSlide",0,c,"STATIC_PLACEHOLDER",0,n])},872143,870616,e=>{"use strict";var t=e.i(943306),i=e.i(297068),n=e.i(92470),r=e.i(100914),a=e.i(427418),s=e.i(809382),o=e.i(965917);let c=i.default.memo(({audioLevelRef:e,isRecording:c,isConnecting:l,isAwaitingPermission:d,isPermissionBlocked:u,hasError:h,existingText:p,isDisabled:m=!1,onToggle:g,onStart:f,onStop:v,onDismissBlocked:b})=>{let y=(0,i.useRef)(null),k=(0,i.useRef)(!1),T=(0,i.useRef)(!1),S=(0,i.useRef)(!1),C=(0,i.useRef)(0),E=(0,i.useRef)(null),w=(0,i.useRef)(c),R=(0,i.useRef)(l),P=(0,i.useRef)(p),_=(0,i.useRef)(f),I=(0,i.useRef)(v);(0,i.useEffect)(()=>{w.current=c},[c]),(0,i.useEffect)(()=>{R.current=l},[l]),(0,i.useEffect)(()=>{P.current=p},[p]),(0,i.useEffect)(()=>{_.current=f},[f]),(0,i.useEffect)(()=>{I.current=v},[v]),(0,i.useEffect)(()=>()=>{y.current&&(clearTimeout(y.current),y.current=null)},[]);let x=c&&!d&&!u,O=l&&!c&&!d&&!u;(0,i.useEffect)(()=>{let t=E.current;if(!x||!e||!t||window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;let i=0,n=0,r=()=>{n=Math.max(e.current??0,.85*n),t.style.transform=`scale(${1+1.6*n})`,t.style.opacity=`${.25+.55*n}`,i=requestAnimationFrame(r)};return i=requestAnimationFrame(r),()=>cancelAnimationFrame(i)},[x,e]);let D=(0,i.useCallback)(()=>{if(!m){if(k.current=!0,T.current=!1,S.current=!1,!w.current&&!R.current&&!u&&!d){let e=Date.now();if(e-C.current<300)return;C.current=e,S.current=!0,_.current(P.current)}y.current=setTimeout(()=>{T.current=!0},200)}},[m,u,d]),M=(0,i.useCallback)(()=>{!m&&(k.current=!1,y.current&&(clearTimeout(y.current),y.current=null),T.current&&S.current&&(w.current||R.current)&&(C.current=Date.now(),I.current(),T.current=!1,S.current=!1))},[m]),A=(0,i.useCallback)(e=>{if(e.stopPropagation(),m)return;if(S.current){S.current=!1;return}let t=Date.now();if(!(t-C.current<300)){if(C.current=t,u){b(),setTimeout(()=>{_.current(P.current)},50);return}d||g(p)}},[d,u,g,b,p,m]),N=(0,i.useCallback)(()=>{y.current&&(clearTimeout(y.current),y.current=null),S.current&&(S.current=!1,T.current=!1,C.current=Date.now(),I.current())},[]),L=(0,i.useCallback)(()=>{m||k.current&&(k.current=!1,N())},[N,m]),U=(0,i.useCallback)(()=>{m||(k.current=!1,N())},[N,m]),j=(0,t.jsx)(s.Button,{type:"button",variant:"soft",size:"icon",className:`relative ${u?"bg-error-soft text-error outline-error-solid/40 hover:bg-error-soft-hover":d?"animate-pulse bg-primary/10 text-primary outline-primary/40 hover:bg-primary/15":x?"bg-success-soft text-success outline-success-solid/40 hover:bg-success-soft-hover":h&&!u?"bg-warning-soft text-warning outline-warning-solid/40 hover:bg-warning-soft-hover":""} ${m?"opacity-50":""}`,onClick:A,onPointerDown:D,onPointerUp:M,onPointerLeave:L,onPointerCancel:U,disabled:m,"aria-label":u?"Microphone blocked - click to retry":d?"Allow microphone access in your browser":x?"Stop recording":O?"Cancel voice input":"Start voice input",children:u?(0,t.jsx)(a.MicOff,{className:"size-5"}):O?(0,t.jsx)(n.Loader2,{className:"size-5 animate-spin"}):d?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(r.Mic,{className:"size-5"}),(0,t.jsx)("span",{className:"absolute -top-0.5 -right-0.5 flex size-3 items-center justify-center rounded-full bg-primary text-[8px] font-bold text-primary-foreground shadow-xs",children:"?"})]}):x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(r.Mic,{className:"size-5"}),(0,t.jsxs)("span",{className:"absolute -top-0.5 -right-0.5 size-2.5",children:[(0,t.jsx)("span",{ref:E,className:"absolute inset-0 rounded-full bg-success-solid opacity-25 will-change-transform"}),(0,t.jsx)("span",{className:"absolute inset-0 rounded-full bg-success-solid shadow-xs"})]})]}):(0,t.jsx)(r.Mic,{className:"size-5"})});return u?(0,t.jsx)(o.TooltipProvider,{delay:0,children:(0,t.jsxs)(o.Tooltip,{defaultOpen:!0,children:[(0,t.jsx)(o.TooltipTrigger,{render:j}),(0,t.jsxs)(o.TooltipContent,{side:"top",className:"max-w-62.5 text-center",sideOffset:8,children:[(0,t.jsx)("p",{className:"font-medium",children:"Microphone access blocked"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Click the lock icon in your browser's address bar to enable microphone access, then click the microphone to try again."})]})]})}):d?(0,t.jsx)(o.TooltipProvider,{delay:0,children:(0,t.jsxs)(o.Tooltip,{open:!0,children:[(0,t.jsx)(o.TooltipTrigger,{render:j}),(0,t.jsx)(o.TooltipContent,{side:"top",className:"max-w-50 text-center",sideOffset:8,children:(0,t.jsx)("p",{className:"text-sm",children:"Allow microphone access in your browser"})})]})}):j});c.displayName="SpeechToTextButton",e.s(["SpeechToTextButton",0,c],872143);let l=i.default.memo(({onClick:e,isLoading:i,isDisabled:n,rotate:r})=>(0,t.jsx)(s.Button,{type:"submit",size:"icon",className:"group",disabled:n,onClick:e,"aria-label":i?"Stop":r?"Scroll to bottom":"Send message",children:i?(0,t.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",className:"message-submit-button-spinner size-6 animate-spin",style:{animationDuration:"3s"},fill:"currentColor",children:(0,t.jsx)("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12 1.25C6.06294 1.25 1.25 6.06294 1.25 12C1.25 17.9371 6.06294 22.7
15 12 22.75C17.9371 22.75 22.75 17.9371 22.75 12C22.75 6.06294 17.9371 1.25 12 1.25ZM12 16C10.3949 16 9.59235 16 9.01584 15.6148C8.76626 15.448 8.55198 15.2337 8.38521 14.9842C8 14.4076 8 13.6051 8 12C8 10.3949 8 9.59235 8.38521 9.01584C8.55198 8.76626 8.76626 8.55197 9.01584 8.38521C9.59235 8 10.3949 8 12 8C13.6051 8 14.4076 8 14.9842 8.38521C15.2337 8.55197 15.448 8.76626 15.6148 9.01584C16 9.59235 16 10.3949 16 12C16 13.6051 16 14.4076 15.6148 14.9842C15.448 15.2337 15.2337 15.448 14.9842 15.6148C14.4076 16 13.6051 16 12 16Z"})}):(0,t.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 384 512",className:`size-4.5 transition-transform duration-200 ease-out ${r?"rotate-180 group-hover:translate-y-px":"group-hover:-translate-y-px"}`,fill:"currentColor",children:(0,t.jsx)("path",{d:"M214.6 41.4c-12.5-12.5-32.8-12.5-45.3 0l-160 160c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L160 141.2 160 448c0 17.7 14.3 32 32 32s32-14.3 32-32l0-306.7L329.4 246.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3l-160-160z"})})}));l.displayName="SubmitButton",e.s(["SubmitButton",0,l],870616)},396312,547568,223788,701049,e=>{"use strict";let t,i,n,r,a,s;var o,c,l,d,u,h,p,m,g,f,v,b,y,k,T,S,C,E,w,R,P,_,I,x,O,D,M,A,N,L,U,j,F,B,q,V,W,H,G,z,K,J,$,Q,X,Y,Z,ee,et,ei,en,er,ea,es,eo,ec,el,ed,eu,eh,ep,em,eg,ef,ev,eb,ey,ek,eT,eS,eC,eE,ew,eR,eP,e_,eI,ex=e.i(297068);let eO=0,eD=[],eM=null;e.s(["useChatTypeToFocus",0,function({handleInputValueChange:e,hasFormAbove:t,input:i,isDisabled:n,isRecording:r,textareaRef:a}){let s=(0,ex.useRef)(null),o=(0,ex.useRef)(null),c=(0,ex.useRef)(null);null===s.current&&(s.current=`chat-composer-${eO++}`);let l=(0,ex.useCallback)(()=>{let e=a.current;e&&(o.current={end:e.selectionEnd??e.value.length,start:e.selectionStart??e.value.length})},[a]),d=(0,ex.useCallback)(()=>{s.current&&(eM=s.current,l())},[l]);return(0,ex.useEffect)(()=>{let e=s.current;if(e)return eD.push(e),()=>{let t=eD.indexOf(e);-1!==t&&eD.splice(t,1),eM===e&&(eM=null)}},[]),(0,ex.useEffect)(()=>{let e=c.current,t=a.current;if(!e||!t||i!==e.value)return;let n=window.requestAnimationFrame(()=>{t.focus({preventScroll:!0}),t.setSelectionRange(e.start,e.end),o.current={end:e.end,start:e.start},c.current=null});return()=>{window.cancelAnimationFrame(n)}},[i,a]),(0,ex.useEffect)(()=>{let l=l=>{var d,u;let h,p=a.current;if(!p||n||r||t)return;let m=document.activeElement;if(l.defaultPrevented||m===p||!(1===l.key.length&&l.key.trim().length>0&&!l.metaKey&&!l.ctrlKey&&!l.isComposing&&"Dead"!==l.key)||m?.tagName==="IFRAME"||m instanceof HTMLElement&&(m.isContentEditable||null!==m.closest("input, textarea, select")||null!==m.closest('[contenteditable="true"]'))||Array.from(document.querySelectorAll('[data-slot="dialog-content"]:not([data-closed]), [data-slot="sheet-content"]:not([data-closed]), [data-slot="drawer-popup"]:not([data-closed]), [data-slot="popover-content"]:not([data-closed]), [data-slot="select-content"]:not([data-closed]), [data-slot="dropdown-menu-content"]:not([data-closed]), [data-slot="dropdown-menu-sub-content"]:not([data-closed]), [aria-modal="true"]:not([hidden])')).some(e=>!e.contains(p))||(eM??eD[0]??null)!==s.current)return;l.preventDefault();let g=(d=i.length,u=o.current,{end:Math.max(h=u?.start??p.selectionStart??d,u?.end??p.selectionEnd??d),start:Math.max(0,h)}),f=i.slice(0,g.start)+l.key+i.slice(g.end),v=g.start+l.key.length;p.focus({preventScroll:!0}),c.current={end:v,start:v,value:f},o.current={end:v,start:v},e(f)};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l)}},[e,t,i,n,r,a]),{markComposerPreferred:d,rememberSelection:l}}],396312);var eA=e.i(156419),eN=e.i(779786);async function eL(e){return new Promise((t,i)=>{let n=new Image,r=URL.createObjectURL(e);n.onload=()=>{URL.revokeObjectURL(r);let e=document.createElement("canvas");e.width=n.width,e.height=n.height;let a=e.getContext("2d");a?(a.drawImage(n,0,0),e.toBlob(e=>{e?t(e):i(Error("Failed to convert image to WebP"))},"image/webp",.8)):i(Error("Failed to get canvas context"))},n.onerror=()=>{URL.revokeObjectURL(r),i(Error("Failed to load image"))},n.src=r})}async function eU(e,t){let i=e,n=e.type,r=e.name;if(e.type.startsWith("image/")&&"image/webp"!==e.type)try{let t=await eL(e);if(t.size>1.5*e.size)i=e,n=e.type;else{i=t,n="image/webp";let a=e.name.replace(/\.[^.]+$/,"");r=`${a}.webp`}}catch{}let a=new FormData;i instanceof Blob&&!(i instanceof File)&&(i=new File([i],r,{type:n})),a.append("file",i);let s=await (0,eA.runWorkspaceMutation)(async e=>{let t=await (0,eA.workspaceFetchFor)(e,"/api/upload",{method:"POST",body:a});if(!t.ok){let e=await t.json().catch(()=>null);throw Error((0,eN.isObjectRecord)(e)&&"string"==typeof e.error?e.error:`Upload failed: ${t.status}`)}return await t.json()},t);
1if(!(0,eN.isObjectRecord)(s)||"string"!=typeof s.url||"string"!=typeof s.id||"string"!=typeof s.contentType)throw Error("Invalid response from upload API");let{url:o,id:c,contentType:l}=s;return{url:o,name:e.name,contentType:l,id:c}}var ej=e.i(826261);let eF="snow:chat-draft:v1:",eB=":attachments",eq=":attachment:";function eV(e){return`${eF}${encodeURIComponent(e)}`}function eW(e){return`${eV(e)}:text`}function eH(e){return`${eV(e)}${eB}`}function eG(e){return`${eV(e)}${eq}`}function ez(e,t){return`${eG(e)}${encodeURIComponent(t)}`}let eK={attachments:[],expiredAttachments:[]},eJ="draft-pending",e$="draft-ready:",eQ=new Map,eX=new Map,eY=new Set,eZ=new Map,e0=!1;function e1(e){return`${e$}${e}`}function e2(e){return e.startsWith(e$)?{value:e.slice(e$.length),isReady:!0}:{value:"",isReady:!1}}function e3(e){try{let t=JSON.parse(e);if(!(0,eN.isObjectRecord)(t)||1!==t.version)return null;return function(e){if(!(0,eN.isObjectRecord)(e))return null;let{uid:t,order:i,url:n,name:r,contentType:a,id:s,inlineContent:o,uploadedAt:c}=e;return"string"==typeof t&&"string"==typeof i&&"string"==typeof n&&"string"==typeof r&&"string"==typeof a&&"string"==typeof s&&"number"==typeof c&&Number.isFinite(c)&&(void 0===o||"string"==typeof o)?{uid:t,order:i,url:n,name:r,contentType:a,id:s,uploadedAt:c,inlineContent:o}:null}(t.attachment)}catch{return null}}function e6(e,t){if(0===e.length)return eK;try{let i=JSON.parse(e);if(!Array.isArray(i))return eK;let n=i.filter(e=>"string"==typeof e).map(e3).filter(e=>!!e).sort((e,t)=>e.order.localeCompare(t.order)),r=[],a=[];for(let e of n)t-e.uploadedAt>=6048e5?a.push(e):r.push(e);return{attachments:r,expiredAttachments:a}}catch{return eK}}function e4(e){return JSON.stringify({version:1,attachment:e})}function e5(e,t){let i=new Set(e.map(e=>e.uid)),n=new Set(e.map(e=>e.id)),r=[];for(let e of t)i.has(e.uid)||n.has(e.id)||(i.add(e.uid),n.add(e.id),r.push(e));let a=Math.max(0,ej.CHAT_CONSTANTS.MAX_ATTACHMENTS_PER_MESSAGE-e.length);return[...e,...r.slice(0,a)].sort((e,t)=>e.order.localeCompare(t.order))}function e8(e){let t=eQ.get(e);if(void 0!==t)return t;try{let t=window.localStorage.getItem(e);return null!==t&&eQ.set(e,t),t}catch{return null}}function e9(e){if(!e)return null;let t=Reflect.get(window,"__snowChatDraftBootstrap");return(0,eN.isObjectRecord)(t)&&t.scopeKey===e&&"string"==typeof t.text&&"boolean"==typeof t.hasAttachments?{scopeKey:e,text:t.text,hasAttachments:t.hasAttachments}:null}function e7(e){let t=eH(e),i=eZ.get(t);if(void 0!==i)return i;let n=eG(e),r=new Set;for(let e of eQ.keys())e.startsWith(n)&&r.add(e);try{for(let e=0;e<window.localStorage.length;e+=1){let t=window.localStorage.key(e);t?.startsWith(n)&&r.add(t)}}catch{}let a=[];for(let e of[...r].sort()){let t=e8(e);if(null!==t){if(!e3(t)){ti(e,null);continue}a.push(t)}}let s=a.length>0?JSON.stringify(a):"";return eZ.set(t,s),s}function te(e){for(let t of eX.get(e)??[])t()}function tt(e,t){e0||(e0=!0,window.addEventListener("storage",e=>{var t;let i;if(null===e.key){for(let e of(eQ.clear(),eZ.clear(),eX.keys()))te(e);return}if(!e.key.startsWith(eF))return;null===e.newValue?eQ.delete(e.key):eQ.set(e.key,e.newValue),te(e.key);let n=(i=(t=e.key).indexOf(eq))<0?null:`${t.slice(0,i)}${eB}`;n&&(eZ.delete(n),te(n))}));let i=eX.get(e)??new Set;return i.add(t),eX.set(e,i),()=>{i.delete(t),0===i.size&&eX.delete(e)}}function ti(e,t){null===t?eQ.delete(e):eQ.set(e,t);try{null===t?window.localStorage.removeItem(e):window.localStorage.setItem(e,t)}catch{}}function tn(e,t,i){let n=new Map(t.map(e=>[e.uid,e])),r=new Map(i.map(e=>[e.uid,e]));for(let i of t)r.has(i.uid)||ti(ez(e,i.uid),null);for(let t of i){let i=n.get(t.uid);i&&e4(i)===e4(t)||ti(ez(e,t.uid),e4(t))}let a=eH(e);eZ.delete(a),te(a)}function tr(e){return e.order??e.uid}function ta(e){return{uid:e.uid,order:e.order,file:new File([],e.name,{type:e.contentType}),uploadState:"done",uploadedData:{url:e.url,name:e.name,contentType:e.contentType,id:e.id,inlineContent:e.inlineContent,uploadedAt:e.uploadedAt}}}e.s(["mergeChatDraftAttachments",0,e5,"useChatDraft",0,function(e){let t,i,n,r,a=e?eW(e):null,[s]=(0,ex.useState)(()=>Date.now()),o=(t=e?eW(e):null,{text:(i=e2((0,ex.useSyncExternalStore)((0,ex.useCallback)(e=>t?tt(t,e):()=>void 0,[t]),(0,ex.useCallback)(()=>t?e1(e8(t)??""):null===e?e1(""):eJ,[e,t]),(0,ex.useCallback)(()=>{let t=e9(e);return t?e1(t.text):eJ},[e])))).value,isReady:i.isReady}),c=(n=e?eH(e):null,{snapshot:(r=e2((0,ex.useSyncExternalStore)((0,ex.useCallback)(e=>n?tt(n,e):()=>void 0,[n]),(0,ex.useCallback)(()=>e?e1(e7(e)):null===e?e1(""):eJ,[e]),(0,ex.useCallback)(()=>{let t=e9(e);return t&&!t.hasAttachments?e1(""):eJ},[e])))).value,isReady:r.isReady}),l=(0,ex.useMemo)(()=>e6(c.snapshot,s),[c.snapshot,s]),d=(0,ex.useCallback)(e=>{if(!a)return;let t=e8(a)??"",i="function"==typeof e?e(t):e;ti(a,i.length>0?i:null),te(a)},[a]),u=(0,ex.useCallback)(t=>{if(!e)return;let i=e6(e7(e),Date.now()).attachments,n="function"==typeof t?t(i):t;tn(e,i,n)},[e]),h=(0,ex.useCallback)(()=>{e&&0!==l.expiredAttachments.length&&tn(e,[...l.attachments,...l.expiredAttachments],l.attachments)},[l,e]),p=(0,ex.useCallback)(()=>
1{if(!e||0===l.expiredAttachments.length)return!1;let t=`${eH(e)}:${l.expiredAttachments.map(e=>e.id).sort().join(",")}`;return!eY.has(t)&&(eY.add(t),!0)},[l.expiredAttachments,e]);return{text:o.text,attachments:l.attachments,isReady:o.isReady&&c.isReady,expiredAttachmentCount:l.expiredAttachments.length,setText:d,setAttachments:u,discardExpiredAttachments:h,claimExpiredAttachmentNotice:p}}],547568),e.s(["useFileUpload",0,function({draftAttachments:e,setDraftAttachments:t}={}){let i=(0,ex.useRef)(null),n=(0,ex.useRef)(new Set);(0,ex.useEffect)(()=>()=>{n.current.clear()},[]);let[r,a]=(0,ex.useState)([]),[s,o]=(0,ex.useState)([]),[c,l]=(0,ex.useState)(!1),d=e??s,u=t??o,h=(0,ex.useMemo)(()=>d.map(ta),[d]),p=(0,ex.useMemo)(()=>[...r,...h].sort((e,t)=>tr(e).localeCompare(tr(t))),[h,r]),m=(0,ex.useCallback)(()=>{i.current?.click()},[]),g=(0,ex.useCallback)(async e=>{try{let t=await e.text();if(t.length<=ej.CHAT_CONSTANTS.MAX_CONTENT_LENGTH)return t;let i=` 2 3[File truncated after ${ej.CHAT_CONSTANTS.MAX_CONTENT_LENGTH.toLocaleString()} characters]`;return t.slice(0,ej.CHAT_CONSTANTS.MAX_CONTENT_LENGTH-i.length)+i}catch{return}},[]),f=(0,ex.useCallback)(async e=>{let t;if(p.length+e.length>ej.CHAT_CONSTANTS.MAX_ATTACHMENTS_PER_MESSAGE){let t=ej.CHAT_CONSTANTS.MAX_ATTACHMENTS_PER_MESSAGE-p.length;t<=0?alert(`Maximum ${ej.CHAT_CONSTANTS.MAX_ATTACHMENTS_PER_MESSAGE} attachments per message. Please remove some files before adding more.`):alert(`Cannot add ${e.length} file${e.length>1?"s":""}. You can only add ${t} more attachment${t>1?"s":""} (max ${ej.CHAT_CONSTANTS.MAX_ATTACHMENTS_PER_MESSAGE} per message).`);return}if(e.filter(e=>!(0,ej.isAllowedFileType)(e.type)).length>0)return void alert("Only image and text files are supported");let r=1024*ej.CHAT_CONSTANTS.MAX_FILE_SIZE_MB*1024;if(e.filter(e=>e.size>r).length>0)return void alert(`Files must be smaller than ${ej.CHAT_CONSTANTS.MAX_FILE_SIZE_MB}MB`);try{t=(0,eA.getActiveWorkspaceRef)()}catch{alert("Attachments are not ready yet. Try again in a moment.");return}l(!0);let s=Date.now(),o=e.map((e,t)=>{let i=crypto.randomUUID();return{uid:i,order:`${s.toString().padStart(13,"0")}
3:${t.toString().padStart(2,"0")}:${i}`,file:e,uploadState:"uploading"}});for(let e of o)n.current.add(e.uid);a(e=>[...e,...o]);let c=await Promise.all(o.map(e=>(0,ej.isTextBasedType)(e.file.type)?g(e.file):Promise.resolve(void 0)));try{await Promise.all(o.map(async(e,i)=>{try{var r;let s=await eU(e.file,t);if(e.file.type.startsWith("image/")&&await (r=s.url,new Promise((e,t)=>{let i=new Image;i.onload=()=>e(),i.onerror=t,i.src=`/_next/image?url=${encodeURIComponent(r)}&w=640&q=75`})).catch(()=>{}),!n.current.delete(e.uid))return;let o=Date.now(),l={uid:e.uid,order:tr(e),...s,inlineContent:c[i],uploadedAt:o};u(e=>e5(e,[l])),a(t=>t.filter(t=>t.uid!==e.uid))}catch{if(!n.current.delete(e.uid))return;a(t=>t.map(t=>t.uid===e.uid?{...t,uploadState:"error"}:t))}}))}finally{l(!1),i.current&&(i.current.value="")}},[p.length,g,u]),v=(0,ex.useCallback)(async e=>{let t=e.target.files;t&&await f(Array.from(t))},[f]),b=(0,ex.useCallback)(e=>{n.current.delete(e),a(t=>t.filter(t=>t.uid!==e)),u(t=>t.filter(t=>t.uid!==e))},[u]);return{fileInputRef:i,attachments:p,isUploading:c,handleFileClick:m,handleFileChange:v,handleRemoveAttachment:b,handleFileUpload:f,clearAttachments:(0,ex.useCallback)(()=>{n.current.clear(),a([]),u([])},[u]),restoreAttachments:(0,ex.useCallback)(e=>{let t=Date.now(),i=[],n=[];e.forEach((e,r)=>{"done"===e.uploadState&&e.uploadedData?i.push({uid:e.uid,order:e.order??`${t.toString().padStart(13,"0")}
3:${r.toString().padStart(2,"0")}:${e.uid}`,url:e.uploadedData.url,name:e.uploadedData.name,contentType:e.uploadedData.contentType,id:e.uploadedData.id,inlineContent:e.uploadedData.inlineContent,uploadedAt:e.uploadedData.uploadedAt??t}):n.push({...e,uploadState:"error"})}),a(e=>{let t=new Set(e.map(e=>e.uid));return[...e,...n.filter(e=>!t.has(e.uid))].sort((e,t)=>tr(e).localeCompare(tr(t)))}),u(e=>e5(e,[...i].sort((e,t)=>e.order.localeCompare(t.order))))},[u])}}],223788);let ts="Microphone access denied. Click the lock icon in your browser's address bar to enable it.",to=Object.freeze({name:"js_sdk",version:"1.15.2"});class tc{queue=[];disconnectionDetails=null;onDisconnectCallback=null;onMessageCallback=null;onModeChangeCallback=null;onDebug;constructor(e={}){this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;let t=this.queue;this.queue=[],t.length>0&&queueMicrotask(()=>{t.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;let t=this.disconnectionDetails;t&&queueMicrotask(()=>{e(t)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){this.onModeChangeCallback?.(e)}disconnect(e){this.disconnectionDetails||(this.disconnectionDetails=e,this.onDisconnectCallback?.(e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}}function tl(e){let[t,i]=e.split("_");if(!["pcm","ulaw"].includes(t))throw Error(`Invalid format: ${e}`);let n=Number.parseInt(i);if(Number.isNaN(n))throw Error(`Invalid sample rate: ${i}`);return{format:t,sampleRate:n}}class td extends Error{closeCode;closeReason;constructor(e,t){super(e),this.name="SessionConnectionError",this.closeCode=t?.closeCode,this.closeReason=t?.closeReason}}function tu(e){return!!e.type}var th=e.i(941034),tp=Object.defineProperty,tm=(e,t,i)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?tp(e,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[n]=i};class tg{constructor(){tm(this,"_locking"),tm(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;let t=new Promise(t=>e=()=>{this._locks-=1,t()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function tf(e,t){if(!e)throw Error(t)}function tv(e){if("number"!=typeof e)throw Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>0x7fffffff||e<-0x80000000)throw Error("invalid int 32: "+e)}function tb(e){if("number"!=typeof e)throw Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>0xffffffff||e<0)throw Error("invalid uint 32: "+e)}function ty(e){if("number"!=typeof e)throw Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw Error("invalid float 32: "+e)}let tk=Symbol("@bufbuild/protobuf/enum-type");function tT(e,t,i,n){e[tk]=tS(t,i.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function tS(e,t,i){let n=Object.create(null),r=Object.create(null),a=[];for(let e of t){let t=tC(e);a.push(t),n[e.name]=t,r[e.no]=t}return{typeName:e,values:a,findName:e=>n[e],findNumber:e=>r[e]}}function tC(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class tE{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){let i=this.getType(),n=i.runtime.json,r=n.makeReadOptions(t);return n.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(i,t)}toBinary(e){let t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){let t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;return JSON.stringify(this.toJson(e),null,null!=(t=null==e?void 0:e.prettySpaces)?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function tw(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,(128&i)==0)return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}throw Error("invalid varint")}function tR(e,t,i){for(let n=0;n<28;n+=7){let r=e>>>n,a=r>>>
37!=0||0!=t,s=(a?128|r:r)&255;if(i.push(s),!a)return}let n=e>>>28&15|(7&t)<<4,r=t>>3!=0;if(i.push((r?128|n:n)&255),r){for(let e=3;e<31;e+=7){let n=t>>>e,r=n>>>7!=0,a=(r?128|n:n)&255;if(i.push(a),!r)return}i.push(t>>>31&1)}}function tP(e){let t="-"===e[0];t&&(e=e.slice(1));let i=0,n=0;function r(t,r){let a=Number(e.slice(t,r));n*=1e6,(i=1e6*i+a)>=0x100000000&&(n+=i/0x100000000|0,i%=0x100000000)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?tx(i,n):tI(i,n)}function t_(e,t){if({lo:e,hi:t}={lo:e>>>0,hi:t>>>0},t<=2097151)return String(0x100000000*t+e);let i=0xffffff&e,n=(e>>>24|t<<8)&0xffffff,r=t>>16&65535,a=i+6777216*n+6710656*r,s=n+8147497*r,o=2*r;return a>=1e7&&(s+=Math.floor(a/1e7),a%=1e7),s>=1e7&&(o+=Math.floor(s/1e7),s%=1e7),o.toString()+tO(s)+tO(a)}function tI(e,t){return{lo:0|e,hi:0|t}}function tx(e,t){return t=~t,e?e=~e+1:t+=1,tI(e,t)}let tO=e=>{let t=String(e);return"0000000".slice(t.length)+t};function tD(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function tM(){let e=this.buf[this.pos++],t=127&e;if((128&e)==0||(t|=(127&(e=this.buf[this.pos++]))<<7,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<14,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<21,(128&e)==0))return this.assertBounds(),t;t|=(15&(e=this.buf[this.pos++]))<<28;for(let t=5;(128&e)!=0&&t<10;t++)e=this.buf[this.pos++];if((128&e)!=0)throw Error("invalid varint");return this.assertBounds(),t>>>0}let tA=function(){let e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof th.default||"object"!=typeof th.default.env||"1"!==th.default.env.BUF_BIGINT_DISABLE)){let t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){let n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw Error("int64 invalid: ".concat(e));return n},uParse(e){let t="bigint"==typeof e?e:BigInt(e);if(t>r||t<n)throw Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}let t=e=>tf(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>tf(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),tP(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),tP(e)),dec:(e,t)=>{let i,n,r;return(n=0x80000000&(i=tI(e,t)).hi)&&(i=tx(i.lo,i.hi)),r=t_(i.lo,i.hi),n?"-"+r:r},uDec:(e,t)=>t_(e,t)}}();function tN(e,t,i){if(t===i)return!0;if(e==z.BYTES){if(!(t instanceof Uint8Array)||!(i instanceof Uint8Array)||t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case z.UINT64:case z.FIXED64:case z.INT64:case z.SFIXED64:case z.SINT64:return t==i}return!1}function tL(e,t){switch(e){case z.BOOL:return!1;case z.UINT64:case z.FIXED64:case z.INT64:case z.SFIXED64:case z.SINT64:return 0==t?tA.zero:"0";case z.DOUBLE:case z.FLOAT:return 0;case z.BYTES:return new Uint8Array(0);case z.STRING:return"";default:return 0}}function tU(e,t){switch(e){case z.BOOL:return!1===t;case z.STRING:return""===t;case z.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(o=z||(z={}))[o.DOUBLE=1]="DOUBLE",o[o.FLOAT=2]="FLOAT",o[o.INT64=3]="INT64",o[o.UINT64=4]="UINT64",o[o.INT32=5]="INT32",o[o.FIXED64=6]="FIXED64",o[o.FIXED32=7]="FIXED32",o[o.BOOL=8]="BOOL",o[o.STRING=9]="STRING",o[o.BYTES=12]="BYTES",o[o.UINT32=13]="UINT32",o[o.SFIXED32=15]="SFIXED32",o[o.SFIXED64=16]="SFIXED64",o[o.SINT32=17]="SINT32",o[o.SINT64=18]="SINT64",(c=K||(K={}))[c.BIGINT=0]="BIGINT",c[c.STRING=1]="STRING",(l=J||(J={}))[l.Varint=0]="Varint",l[l.Bit64=1]="Bit64",l[l.LengthDelimited=2]="LengthDelimited",l[l.StartGroup=3]="StartGroup",l[l.EndGroup=4]="EndGroup",l[l.Bit32=5]="Bit32";class tj{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(tb(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return tv(e),tD(e,this.buf),this}bool(e){return this.buf.push(+!!e),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){ty(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){tb(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){tv(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return tv(e),tD(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=tA.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=tA.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=tA.enc(e);return tR(t.lo,t.hi,this.buf),this}sint64(e){let t=tA.enc(e),i=t.hi>>31;return tR(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=tA.uEnc(e);return tR(t.lo,t.hi,this.buf),this}}class tF{constructor(e,t){this.varint64=tw,this.uint32=tM,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;
vendor: 4,998 bytes, line 3
3if(t<=0||i<0||i>5)throw Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case J.Varint:for(;128&this.buf[this.pos++];);break;case J.Bit64:this.pos+=4;case J.Bit32:this.pos+=4;break;case J.LengthDelimited:let n=this.uint32();this.pos+=n;break;case J.StartGroup:for(;;){let[e,i]=this.tag();if(i===J.EndGroup){if(void 0!==t&&e!==t)throw Error("invalid end group tag");break}this.skip(i,e)}break;default:throw Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return tA.dec(...this.varint64())}uint64(){return tA.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,tA.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return tA.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return tA.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(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function tB(e){let t=e.field.localName,i=Object.create(null);return i[t]=function(e){let t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return tL(t.T,t.L);case"message":let i=t.T,n=new i;return i.fieldWrapper?i.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let tq="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),tV=[];for(let e=0;e<tq.length;e++)tV[tq[e].charCodeAt(0)]=e;tV[45]=tq.indexOf("+"),tV[95]=tq.indexOf("/");let tW={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i=new Uint8Array(t),n=0,r=0,a,s=0;for(let t=0;t<e.length;t++){if(void 0===(a=tV[e.charCodeAt(t)]))switch(e[t]){case"=":r=0;case"\n":case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:s=a,r=1;break;case 1:i[n++]=s<<2|(48&a)>>4,s=a,r=2;break;case 2:i[n++]=(15&s)<<4|(60&a)>>2,s=a,r=3;break;case 3:i[n++]=(3&s)<<6|a,r=0}}if(1==r)throw Error("invalid base64 string.");return i.subarray(0,n)},enc(e){let t="",i=0,n,r=0;for(let a=0;a<e.length;a++)switch(n=e[a],i){case 0:t+=tq[n>>2],r=(3&n)<<4,i=1;break;case 1:t+=tq[r|n>>4],r=(15&n)<<2,i=2;break;case 2:t+=tq[r|n>>6],t+=tq[63&n],i=0}return i&&(t+=tq[r],t+="=",1==i&&(t+="=")),t}};function tH(e,t){let i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function tG(e,t){tf(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function tz(e,t){let i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":if(e.opt||e.req)return void 0!==t[i];if("enum"==e.kind)return t[i]!==e.T.values[0].no;return!tU(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function tK(e,t){let i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?tL(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function tJ(e,t){if(null===e||"object"!=typeof e||!Object.getOwnPropertyNames(tE.prototype).every(t=>t in e&&"function"==typeof e[t]))return!1;let i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function t$(e,t){return tJ(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}z.DOUBLE,z.FLOAT,z.INT64,z.UINT64,z.INT32,z.UINT32,z.BOOL,z.STRING,z.BYTES;let tQ={ignoreUnknownFields:!1},tX={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},tY=Symbol(),tZ=Symbol();function t0(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function t1(e,t,i,n,r){let a=i.localName;if(i.repeated){if(tf("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(t0(t)));let s=e[a];for(let e of t){if(null===e)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(t0(e)));switch(i.kind){case"message":s.push(i.T.fromJson(e,n));break;case"enum":let t=t3(i.T,e,n.ignoreUnknownFields,!0);t!==tZ&&s.push(t);break;
3case"scalar":try{s.push(t2(i.T,e,i.L,!0))}catch(n){let t="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(t0(e));throw n instanceof Error&&n.message.length>0&&(t+=": ".concat(n.message)),Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(t0(t)));let s=e[a];for(let[e,a]of Object.entries(t)){let o;if(null===a)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: map value null"));try{o=function(e,t){if(e===z.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return t2(e,t,K.BIGINT,!0).toString()}(i.K,e)}catch(n){let e="cannot decode map key for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(t0(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}switch(i.V.kind){case"message":s[o]=i.V.T.fromJson(a,n);break;case"enum":let c=t3(i.V.T,a,n.ignoreUnknownFields,!0);c!==tZ&&(s[o]=c);break;case"scalar":try{s[o]=t2(i.V.T,a,K.BIGINT,!0)}catch(n){let e="cannot decode map value for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(t0(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:a},a="value"),i.kind){case"message":let s=i.T;if(null===t&&"google.protobuf.Value"!=s.typeName)return;let o=e[a];tJ(o)?o.fromJson(t,n):(e[a]=o=s.fromJson(t,n),s.fieldWrapper&&!i.oneof&&(e[a]=s.fieldWrapper.unwrapField(o)));break;case"enum":let c=t3(i.T,t,n.ignoreUnknownFields,!1);switch(c){case tY:tK(i,e);break;case tZ:break;default:e[a]=c}break;case"scalar":try{let n=t2(i.T,t,i.L,!1);n===tY?tK(i,e):e[a]=n}catch(n){let e="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(t0(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}function t2(e,t,i,n){if(null===t)return n?tL(e,i):tY;switch(e){case z.DOUBLE:case z.FLOAT:if("NaN"===t)return NaN;if("Infinity"===t)return 1/0;if("-Infinity"===t)return-1/0;if(""===t||"string"==typeof t&&t.trim().length!==t.length||"string"!=typeof t&&"number"!=typeof t)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==z.FLOAT&&ty(r),r;case z.INT32:case z.FIXED32:case z.SFIXED32:case z.SINT32:case z.UINT32:let a;if("number"==typeof t?a=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(a=Number(t)),void 0===a)break;return e==z.UINT32||e==z.FIXED32?tb(a):tv(a),a;case z.INT64:case z.SFIXED64:case z.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;let s=tA.parse(t);return i?s.toString():s;case z.FIXED64:case z.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;let o=tA.uParse(t);return i?o.toString():o;case z.BOOL:if("boolean"!=typeof t)break;return t;case z.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw Error("invalid UTF8")}return t;case z.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return tW.dec(t)}throw Error()}function t3(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:tY;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":let r=e.findName(t);if(void 0!==r)return r.no;if(i)return tZ}throw Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(t0(t)))}function t6(e,t,i){if("map"==e.kind){tf("object"==typeof t&&null!=t);let n={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(let[t,i]of r)n[t.toString()]=t5(e.V.T,i);break;case"message":for(let[e,t]of r)n[e.toString()]=t.toJson(i);break;case"enum":let a=e.V.T;for(let[e,t]of r)n[e.toString()]=t4(a,t,i.enumAsInteger)}return i.emitDefaultValues||r.length>0?n:void 0}if(e.repeated){tf(Array.isArray(t));let n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(t5(e.T,t[i]));break;case"enum":for(let r=0;r<t.length;r++)n.push(t4(e.T,t[r],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return t5(e.T,t);case"enum":return t4(e.T,t,i.enumAsInteger);case"message":return t$(e.T,t).toJson(i)}}function t4(e,t,i){var n;if(tf("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;let r=e.findNumber(t);return null!=(n=null==r?void 0:r.name)?n:t}function t5(e,t){switch(e){case z.INT32:case z.SFIXED32:case z.SINT32:case z.FIXED32:case z.UINT32:return tf("number"==typeof t),t;case z.FLOAT:case z.DOUBLE:if(tf("number"==typeof t),Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";return t;case z.STRING:return tf("string"==typeof t),t;case z.BOOL:return tf("boolean"==typeof t),t;case z.UINT64:case z.FIXED64:case z.INT64:case z.SFIXED64:case z.SINT64:return tf("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case z.BYTES:return tf(t instanceof Uint8Array),tW.enc(t)}}let t8=Symbol("@bufbuild/protobuf/unknown-fields"),t9={readUnknownFields:!0,readerFactory:e=>new tF(e)},t7={writeUnknownFields:!0,writerFactory:()=>new tj};function ie(e,t,i,n,r){let{repeated:a,localName:s}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=s&&delete e.value,e.case=s,s="value"),i.kind){case"scalar":case"enum":let o="enum"==i.kind?z.INT32:i.T,c=ir;if("scalar"==i.kind&&i.L>0&&(c=ii),a){let i=e[s];if(n==J.LengthDelimited&&o!=z.STRING&&o!=z.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,o))}else i.push(c(t,o))}else e[s]=c(t,o);break;case"message":let l=i.T;a?e[s].push(it(t,new l,r,i)):tJ(e[s])?it(t,e[s],r,i):(e[s]=it(t,new l,r,i),!l.fieldWrapper||i.oneof||i.repeated||(e[
3s]=l.fieldWrapper.unwrapField(e[s])));break;case"map":let[d,u]=function(e,t,i){let n,r,a=t.uint32(),s=t.pos+a;for(;t.pos<s;){let[a]=t.tag();switch(a){case 1:n=ir(t,e.K);break;case 2:switch(e.V.kind){case"scalar":r=ir(t,e.V.T);break;case"enum":r=t.int32();break;case"message":r=it(t,new e.V.T,i,void 0)}}}if(void 0===n&&(n=tL(e.K,K.BIGINT)),"string"!=typeof n&&"number"!=typeof n&&(n=n.toString()),void 0===r)switch(e.V.kind){case"scalar":r=tL(e.V.T,K.BIGINT);break;case"enum":r=e.V.T.values[0].no;break;case"message":r=new e.V.T}return[n,r]}(i,t,r);e[s][d]=u}}function it(e,t,i,n){let r=t.getType().runtime.bin,a=null==n?void 0:n.delimited;return r.readMessage(t,e,a?n.no:e.uint32(),i,a),t}function ii(e,t){let i=ir(e,t);return"bigint"==typeof i?i.toString():i}function ir(e,t){switch(t){case z.STRING:return e.string();case z.BOOL:return e.bool();case z.DOUBLE:return e.double();case z.FLOAT:return e.float();case z.INT32:return e.int32();case z.INT64:return e.int64();case z.UINT64:return e.uint64();case z.FIXED64:return e.fixed64();case z.BYTES:return e.bytes();case z.FIXED32:return e.fixed32();case z.SFIXED32:return e.sfixed32();case z.SFIXED64:return e.sfixed64();case z.SINT64:return e.sint64();case z.UINT32:return e.uint32();case z.SINT32:return e.sint32()}}function ia(e,t,i,n){tf(void 0!==t);let r=e.repeated;switch(e.kind){case"scalar":case"enum":let a="enum"==e.kind?z.INT32:e.T;if(r)if(tf(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,J.LengthDelimited).fork();let[,r]=ic(t);for(let t=0;t<n.length;t++)e[r](n[t]);e.join()}(i,a,e.no,t);else for(let n of t)io(i,a,e.no,n);else io(i,a,e.no,t);break;case"message":if(r)for(let r of(tf(Array.isArray(t)),t))is(i,n,e,r);else is(i,n,e,t);break;case"map":for(let[r,a]of(tf("object"==typeof t&&null!=t),Object.entries(t)))!function(e,t,i,n,r){e.tag(i.no,J.LengthDelimited),e.fork();let a=n;switch(i.K){case z.INT32:case z.FIXED32:case z.UINT32:case z.SFIXED32:case z.SINT32:a=Number.parseInt(n);break;case z.BOOL:tf("true"==n||"false"==n),a="true"==n}switch(io(e,i.K,1,a),i.V.kind){case"scalar":io(e,i.V.T,2,r);break;case"enum":io(e,z.INT32,2,r);break;case"message":tf(void 0!==r),e.tag(2,J.LengthDelimited).bytes(r.toBinary(t))}e.join()}(i,n,e,r,a)}}function is(e,t,i,n){let r=t$(i.T,n);i.delimited?e.tag(i.no,J.StartGroup).raw(r.toBinary(t)).tag(i.no,J.EndGroup):e.tag(i.no,J.LengthDelimited).bytes(r.toBinary(t))}function io(e,t,i,n){tf(void 0!==n);let[r,a]=ic(t);e.tag(i,r)[a](n)}function ic(e){let t=J.Varint;switch(e){case z.BYTES:case z.STRING:t=J.LengthDelimited;break;case z.DOUBLE:case z.FIXED64:case z.SFIXED64:t=J.Bit64;break;case z.FIXED32:case z.SFIXED32:case z.FLOAT:t=J.Bit32}return[t,z[e].toLowerCase()]}function il(e){if(void 0===e)return e;if(tJ(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function id(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class iu{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}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,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){let e;this.members=[];let t=this.members;for(let i of this.list())i.oneof?i.oneof!==e&&(e=i.oneof,t.push(e)):t.push(i)}return this.members}}function ih(e,t){let i=im(e);return t?i:iy(ib(i))}let ip=im;function im(e){let t=!1,i=[];for(let n=0;n<e.length;n++){let r=e.charAt(n);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),i.push(r)}}return i.join("")}let ig=new Set(["constructor","toString","toJSON","valueOf"]),iv=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),ib=e=>{if(iv.has(e))return"".concat(e,"$");return e},iy=e=>{if(ig.has(e))return"".concat(e,"$");return e};class ik{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=function(e){return ih(e,!1)}(e)}addField(e){tf(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 e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}let iT=(d=e=>new iu(e,e=>(function(e){var t,i,n,r,a,s;let o,c=[];for(let l of"function"==typeof e?e():e){if(l.localName=ih(l.name,void 0!==l.oneof),l.jsonName=null!=(t=l.jsonName)?t:ip(l.name),l.repeated=null!=(i=l.repeated)&&i,"scalar"==l.kind&&(l.L=null!=(n=l.L)?n:K.BIGINT),l.delimited=null!=(r=l.delimited)&&r,l.req=null!=(a=l.req)&&a,l.opt=null!=(s=l.opt)&&s,void 0===l.packed&&(l.packed="enum"==l.kind||"scalar"==l.kind&&l.T!=z.BYTES&&l.T!=z.STRING),void 0!==l.oneof){let e="string"==typeof l.oneof?l.oneof:l.oneof.name;o&&o.name==e||(o=new ik(e)),l.oneof=o,o.addField(l)}c.push(l)}return c})(e)),u=e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let i=t.localName;if(t.repeated){e[i]=[];continue}switch(t.kind){case"oneof":e[i]={case:void 0};break;case"enum":e[i]=0;break;case"map":e[i]={};break;case"scalar":e[i]=tL(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},tQ),e):tQ},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},tX),e):tX},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(t0(t)));n=null!=n?n:new e;let r=new Map,a=i.typeRegistry;for(let[s,o]of Object.entries(t)){let t=e.fields.findJsonName(s);if(t){if(t.oneof){if(null===o&&"scalar"==t.kind)continue;let i=r.get(t.oneof);if(void 0!==i)throw Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(s,'"'));r.set(t.oneof,s)}t1(n,o,t,i,e)}else{let t=!1;if((null==a?void 0:a.findExtension)&&s.startsWith("[")&&s.endsWith("]")){let r=a.findExtension(s.substring(1,s.length-1));if(r&&r.extendee.typeName==e.typeName){t=!0;let[e,a]=tB(r);t1(e,o,r.field,i,r),function(e,t,i,n){tG(t,e);let r=t.runtime.bin.makeReadOptions(n),a=t.runtime.bin.makeWriteOptions(n);if(tH(e,t)){let i=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);for(let t of(e.getType().runtime.bin.discardUnknownFields(e),i))e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let s=a.writerFactory(),o=t.field;o.opt||o.repeated||"enum"!=o.kind&&"scalar"!=o.kind||(o=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(o,i,s,a);let c=r.readerFactory(s.finish());for(;c.pos<c.len;){let[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}(n,r,a(),i)}}if(!t&&!i.ignoreUnknownFields)throw Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(s,'" is unknown'))}}return n},writeMessage(e,t){let i,n=e.getType(),r={};try{for(i of n.fields.byNumber()){if(!tz(i,e)){var a;if(i.req)throw"required field not set";if(!t.emitDefaultValues||!((a=i).repeated||"map"==a.kind||!a.oneof&&"message"!=a.kind&&!a.opt&&!
3a.req))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],s=t6(i,n,t);void 0!==s&&(r[t.useProtoFieldName?i.name:i.jsonName]=s)}let s=t.typeRegistry;if(null==s?void 0:s.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let a=s.findExtensionFor(n.typeName,i.no);if(a&&tH(e,a)){let i=function(e,t,i){tG(t,e);let n=t.runtime.bin.makeReadOptions(i),r=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter(e=>e.no===t.no)}(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,s]=tB(t);for(let e of r)t.runtime.bin.readField(a,n.readerFactory(e.data),t.field,e.wireType,n);return s()}(e,a,t),n=t6(a.field,i,t);void 0!==n&&(r[a.field.jsonName]=n)}}}catch(r){let e=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw Error(e+(t.length>0?": ".concat(t):""))}return r},readScalar:(e,t,i)=>t2(e,t,null!=i?i:K.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t&&(i||tU(e,t)))return t5(e,t)},debug:t0},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},t9),e):t9},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},t7),e):t7},listUnknownFields(e){var t;return null!=(t=e[t8])?t:[]},discardUnknownFields(e){delete e[t8]},writeUnknownFields(e,t){let i=e[t8];if(i)for(let e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){Array.isArray(e[t8])||(e[t8]=[]),e[t8].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,r){let a,s,o=e.getType(),c=r?t.len:t.pos+i;for(;t.pos<c&&([a,s]=t.tag(),!0!==r||s!=J.EndGroup);){let i=o.fields.find(a);if(!i){let i=t.skip(s,a);n.readUnknownFields&&this.onUnknownField(e,a,s,i);continue}ie(e,t,i,s,n)}if(r&&(s!=J.EndGroup||a!==i))throw Error("invalid end group tag")},readField:ie,writeMessage(e,t,i){let n=e.getType();for(let r of n.fields.byNumber()){if(!tz(r,e)){if(r.req)throw Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));continue}let a=r.oneof?e[r.oneof.localName].value:e[r.localName];ia(r,a,t,i)}return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&ia(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:tT,initPartial(e,t){if(void 0!==e)for(let i of t.getType().fields.byMember()){let n=i.localName;if(null!=e[n])switch(i.kind){case"oneof":let r=e[n].case;if(void 0===r)continue;let a=i.findField(r),s=e[n].value;a&&"message"==a.kind&&!tJ(s,a.T)?s=new a.T(s):a&&"scalar"===a.kind&&a.T===z.BYTES&&(s=id(s)),t[n]={case:r,value:s};break;case"scalar":case"enum":let o=e[n];i.T===z.BYTES&&(o=i.repeated?o.map(id):id(o)),t[n]=o;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===z.BYTES)for(let[i,r]of Object.entries(e[n]))t[n][i]=id(r);else Object.assign(t[n],e[n]);break;case"message":let c=i.V.T;for(let i of Object.keys(e[n])){let r=e[n][i];c.fieldWrapper||(r=new c(r)),t[n][i]=r}}break;case"message":let l=i.T;if(i.repeated)t[n]=e[n].map(e=>tJ(e,l)?e:new l(e));else{let i=e[n];l.fieldWrapper?"google.protobuf.BytesValue"===l.typeName?t[n]=id(i):t[n]=i:t[n]=tJ(i,l)?i:new l(i)}}}},equals:(e,t,i)=>t===i||!!t&&!!i&&e.fields.byMember().every(e=>{let n=t[e.localName],r=i[e.localName];if(e.repeated){if(n.length!==r.length)return!1;switch(e.kind){case"message":return n.every((t,i)=>e.T.equals(t,r[i]));case"scalar":return n.every((t,i)=>tN(e.T,t,r[i]));case"enum":return n.every((e,t)=>tN(z.INT32,e,r[t]))}throw Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let a=n,s=r;return e.T.fieldWrapper&&(void 0===a||tJ(a)||(a=e.T.fieldWrapper.wrapField(a)),void 0===s||tJ(s)||(s=e.T.fieldWrapper.wrapField(s))),e.T.equals(a,s);case"enum":return tN(z.INT32,n,r);case"scalar":return tN(e.T,n,r);case"oneof":if(n.case!==r.case)return!1;let o=e.findField(n.case);if(void 0===o)return!0;switch(o.kind){case"message":return o.T.equals(n.value,r.value);case"enum":return tN(z.INT32,n.value,r.value);case"scalar":return tN(o.T,n.value,r.value)}throw Error("oneof cannot contain ".concat(o.kind));case"map":let c=Object.keys(n).concat(Object.keys(r));switch(e.V.kind){case"message":let l=e.V.T;return c.every(e=>l.equals(n[e],r[e]));case"enum":return c.every(e=>tN(z.INT32,n[e],r[e]));case"scalar":let d=e.V.T;return c.every(e=>tN(d,n[e],r[e]))}}}),clone(e){let t=e.getType(),i=new t;for(let n of t.fields.byMember()){let t,r=e[n.localName];if(n.repeated)t=r.map(il);else if("map"==n.kind)for(let[e,a]of(t=i[n.localName],Object.entries(r)))t[e]=il(a);else t="oneof"==n.kind?n.findField(r.case)?{case:r.case,value:il(r.value)}:{case:void 0}:il(r);i[n.localName]=t}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return i}}),{newFieldList:d,initFields:u}),makeMessageType(e,t,i){var n,r;let a,s;return n=this,Object.setPrototypeOf((s=({[a=null!=(r=null==i?void 0:i.localName)?r:e.substring(e.lastIndexOf(".")+1)]:function(e){n.util.initFields(this),n.util.initPartial(e,this)}})[a]).prototype,new tE),Object.assign(s,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary:(e,t)=>new s().fromBinary(e,t),fromJson:(e,t)=>new s().fromJson(e,t),fromJsonString:(e,t)=>
vendor: 16,384 bytes, line 3
3new s().fromJsonString(e,t),equals:(e,t)=>n.util.equals(s,e,t)}),s},makeEnum:function(e,t,i){let n={};for(let e of t){let t=tC(e);n[t.localName]=t.no,n[t.no]=t.localName}return tT(n,e,t),n},makeEnumType:tS,getEnumType:function(e){let t=e[tk];return tf(t,"missing enum type on enum object"),t},makeExtension(e,t,i){var n;let r;return n=this,{typeName:e,extendee:t,get field(){if(!r){let t="function"==typeof i?i():i;t.name=e.split(".").pop(),t.jsonName="[".concat(e,"]"),r=n.util.newFieldList([t]).list()[0]}return r},runtime:n}}});class iS extends tE{constructor(e){super(),this.seconds=tA.zero,this.nanos=0,iT.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(iT.json.debug(e)));let 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 Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");let n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw 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=tA.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){let t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw 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 Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return iS.fromDate(new Date)}static fromDate(e){let t=e.getTime();return new iS({seconds:tA.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new iS().fromBinary(e,t)}static fromJson(e,t){return new iS().fromJson(e,t)}static fromJsonString(e,t){return new iS().fromJsonString(e,t)}static equals(e,t){return iT.util.equals(iS,e,t)}}iS.runtime=iT,iS.typeName="google.protobuf.Timestamp",iS.fields=iT.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);let iC=iT.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:iS},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:iE,repeated:!0},{no:5,name:"events",kind:"message",T:iR,repeated:!0}]),iE=iT.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:iw,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),iw=iT.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:iS},{no:3,name:"value",kind:"scalar",T:2}]),iR=iT.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:iS},{no:7,name:"normalized_end_timestamp",kind:"message",T:iS,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),iP=iT.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),i_=iT.makeEnum("livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]),iI=iT.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),ix=iT.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),iO=iT.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),iD=iT.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"}]),iM=iT.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),iA=iT.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),iN=iT.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),iL=iT.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"}]),iU=iT.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"}]),ij=iT.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),iF=iT.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"}]),iB=iT.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:iq,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:nu}]),iq=iT.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),iV=iT.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:iT.getEnumType(iD),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}]),iW=iT.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:iT.getEnumType(iH)},{no:4,name:"tracks",kind:"message",T:i$,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:iV},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:iT.getEnumType(iG)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:iT.getEnumType(iL)},{no:18,name:"kind_details",kind:"enum",T:iT.getEnumType(iz),repeated:!0}]),iH=iT.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),iG=iT.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"}]),iz=iT.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),iK=iT.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),iJ=iT.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:iQ,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:iT.getEnumType(iX)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),i$=iT.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:iT.getEnumType(iO)},{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:iT.getEnumType(iD)},{no:10,name:"layers",kind:"message",T:iQ,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:iJ,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:iT.getEnumType(iK)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:nu},{no:19,name:"audio_features",kind:"enum",T:iT.getEnumType(iF),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:iT.getEnumType(ix)}]),iQ=iT.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:iT.getEnumType(iM)},{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}]),iX=iT.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"}]),iY=iT.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:iT.getEnumType(iZ)},{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:i6,oneof:"value"},{no:3,name:"speaker",kind:"message",T:i2,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:i4,oneof:"value"},{no:7,name:"transcription",kind:"message",T:i5,oneof:"value"},{no:8,name:"metrics",kind:"message",T:iC,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:i9,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:i7,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:ne,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:nt,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:ng,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:nf,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:nv,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:i0,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),iZ=iT.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),i0=iT.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:iT.getEnumType(iK)},{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}]),i1=iT.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:i6,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:i9,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:i7,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:ne,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:nt,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:ng,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:nf,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:nv,oneof:"value"}]),i2=iT.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:i3,repeated:!0}]),i3=iT.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}]),i6=iT.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}]),i4=iT.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),i5=iT.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:i8,repeated:!0}]),i8=iT.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}]),i9=iT.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}]),i7=iT.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}]),ne=iT.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),nt=iT.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:ni,oneof:"value"}]),ni=iT.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}]),nn=iT.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),nr=iT.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:iT.getEnumType(na)},{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}]),na=iT.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),ns=iT.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:iT.getEnumType(no)},{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},{
vendor: 16,384 bytes, line 3
3no:11,name:"other_sdks",kind:"scalar",T:9}]),no=iT.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"}]),nc=iT.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:nl},{no:2,name:"screen",kind:"message",T:nl},{no:3,name:"resume_connection",kind:"enum",T:iT.getEnumType(iN)},{no:4,name:"disabled_codecs",kind:"message",T:nd},{no:5,name:"force_relay",kind:"enum",T:iT.getEnumType(iN)}]),nl=iT.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:iT.getEnumType(iN)}]),nd=iT.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:iq,repeated:!0},{no:2,name:"publish",kind:"message",T:iq,repeated:!0}]),nu=iT.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),nh=iT.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),np=iT.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:iT.getEnumType(nh)},{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"}),nm=iT.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),ng=iT.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:iT.getEnumType(iK)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:np,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:nm,oneof:"content_header"}],{localName:"DataStream_Header"}),nf=iT.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"}),nv=iT.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"}),nb=iT.makeMessageType("livekit.FilterParams",()=>[{no:1,name:"include_events",kind:"scalar",T:9,repeated:!0},{no:2,name:"exclude_events",kind:"scalar",T:9,repeated:!0}]),ny=iT.makeMessageType("livekit.WebhookConfig",()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"signing_key",kind:"scalar",T:9},{no:3,name:"filter_params",kind:"message",T:nb}]),nk=iT.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),nT=iT.makeMessageType("livekit.RoomAgentDispatch",()=>[{no:1,name:"agent_name",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9}]),nS=iT.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),nC=iT.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),nE=iT.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),nw=iT.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),nR=iT.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"}]),nP=iT.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),n_=iT.makeEnum("livekit.EncodingOptionsPreset",[{no:0,name:"H264_720P_30"},{no:1,name:"H264_720P_60"},{no:2,name:"H264_1080P_30"},{no:3,name:"H264_1080P_60"},{no:4,name:"PORTRAIT_H264_720P_30"},{no:5,name:"PORTRAIT_H264_720P_60"},{no:6,name:"PORTRAIT_H264_1080P_30"},{no:7,name:"PORTRAIT_H264_1080P_60"}]),nI=iT.makeMessageType("livekit.RoomCompositeEgressRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9},{no:3,name:"audio_only",kind:"scalar",T:8},{no:15,name:"audio_mixing",kind:"enum",T:iT.getEnumType(nP)},{no:4,name:"video_only",kind:"scalar",T:8},{no:5,name:"custom_base_url",kind:"scalar",T:9},{no:6,name:"file",kind:"message",T:nx,oneof:"output"},{no:7,name:"stream",kind:"message",T:nj,oneof:"output"},{no:10,name:"segments",kind:"message",T:nO,oneof:"output"},{no:8,name:"preset",kind:"enum",T:iT.getEnumType(n_),oneof:"options"},{no:9,name:"advanced",kind:"message",T:nF,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:nx,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:nj,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:nO,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:nD,repeated:!0},{no:16,name:"webhooks",kind:"message",T:ny,repeated:!0}]),nx=iT.makeMessageType("livekit.EncodedFileOutput",()=>[{no:1,name:"file_type",kind:"enum",T:iT.getEnumType(nS)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:nM,oneof:"output"},{no:4,name:"gcp",kind:"message",T:nA,oneof:"output"},{no:5,name:"azure",kind:"message",T:nN,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:nL,oneof:"output"}]),nO=iT.makeMessageType("livekit.SegmentedFileOutput",()=>[{no:1,name:"protocol",kind:"enum",T:iT.getEnumType(nC)},{no:2,name:"filename_prefix",kind:"scalar",T:9},{no:3,name:"playlist_name",kind:"scalar",T:9},{no:11,name:"live_playlist_name",kind:"scalar",T:9},{no:4,name:"segment_duration",kind:"scalar",T:13},{no:10,name:"filename_suffix",kind:"enum",T:iT.getEnumType(nE)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:nM,oneof:"output"},{no:6,name:"gcp",kind:"message",T:nA,oneof:"output"},{no:7,name:"azure",kind:"message",T:nN,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:nL,oneof:"output"}]),nD=iT.makeMessageType("livekit.ImageOutput",()=>[{no:1,name:"capture_interval",kind:"scalar",T:13},{no:2,name:"width",kind:"scalar",T:5},{no:3,name:"height",kind:"scalar",T:5},{no:4,name:"filename_prefix",kind:"scalar",T:9},{no:5,name:"filename_suffix",kind:"enum",T:iT.getEnumType(nw)},{no:6,name:"image_codec",kind:"enum",T:iT.getEnumType(iI)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:nM,oneof:"output"},{no:9,name:"gcp",kind:"message",T:nA,oneof:"output"},{no:10,name:"azure",kind:"message",T:nN,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:nL,oneof:"output"}]),nM=iT.makeMessageType("livekit.S3Upload",()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:11,name:"session_token",kind:"scalar",T:9},{no:12,name:"assume_role_arn",kind:"scalar",T:9},{no:13,name:"assume_role_external_id",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9},{no:6,name:"force_path_style",kind:"scalar",T:8},{no:7,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:8,name:"tagging",kind:"scalar",T:9},{no:9,name:"content_disposition",kind:"scalar",T:9},{no:10,name:"proxy",kind:"message",T:nU}]),nA=iT.makeMessageType("livekit.GCPUpload",()=>[{no:1,name:"credentials",kind:"scalar",T:9},{no:2,name:"bucket",kind:"scalar",T:9},{no:3,name:"proxy",kind:"message",T:nU}]),nN=iT.makeMessageType("livekit.AzureBlobUpload",()=>[{no:1,name:"account_name",kind:"scalar",T:9},{no:2,name:"account_key",kind:"scalar",T:9},{no:3,name:"container_name",kind:"scalar",T:9}]),nL=iT.makeMessageType("livekit.AliOSSUpload",()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9}]),nU=iT.makeMessageType("livekit.ProxyConfig",()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"password",kind:"scalar",T:9}]),nj=iT.makeMessageType("livekit.StreamOutput",()=>[{no:1,name:"protocol",kind:"enum",T:iT.getEnumType(nR)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}]),nF=iT.makeMessageType("livekit.EncodingOptions",()=>[{no:1,name:"width",kind:"scalar",T:5},{no:2,name:"height",kind:"scalar",T:5},{no:3,name:"depth",kind:"scalar",T:5},{no:4,name:"framerate",kind:"scalar",T:5},{no:5,name:"audio_codec",kind:"enum",T:iT.getEnumType(iP)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:iT.getEnumType(i_)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1}]),nB=iT.makeMessageType("livekit.AutoParticipantEgress",()=>[{no:1,name:"preset",kind:"enum",T:iT.getEnumType(n_),oneof:"options"},{no:2,name:"advanced",kind:"message",T:nF,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:nx,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:nO,repeated:!0}]),nq=iT.makeMessageType("livekit.AutoTrackEgress",()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:nM,oneof:"output"},{no:3,name:"gcp",kind:"message",T:nA,oneof:"output"},{no:4,name:"azure",kind:"message",T:nN,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:nL,oneof:"output"}]),nV=iT.makeMessageType("livekit.RoomEgress",()=>[{no:1,name:"room",kind:"message",T:nI},{no:3,name:"participant",kind:"message",T:nB},{no:2,name:"tracks",kind:"message",T:nq}]),nW=(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"empty_timeout",kind:"scalar",T:13},{no:3,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:11,name:"metadata",kind:"scalar",T:9},{no:5,name:"egress",kind:"message",T:nV},{no:7,name:"min_playout_delay",kind:"scalar",T:13},{no:8,name:"max_playout_delay",kind:"scalar",T:13},{no:9,name:"sync_streams",kind:"scalar",T:8},{no:10,name:"agents",kind:"message",T:nT,repeated:!0}],iT.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}])),nH=iT.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),nG=iT.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),nz=iT.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:n2,oneof:"message"},{no:2,name:"answer",kind:"message",T:n2,oneof:"message"},{no:3,name:"trickle",kind:"message",T:nQ,oneof:"message"},{no:4,name:"add_track",kind:"message",T:n$,oneof:"message"},{no:5,name:"mute",kind:"message",T:nX,oneof:"message"},{no:6,name:"subscription",kind:"message",T:n6,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:n4,oneof:"message"},{no:8,name:"leave",kind:"message",T:n9,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:re,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:rm,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:rv,oneof:"message"},{no:13,name:"simulate",kind:"message",T:rk,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:rt,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:rT,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:n5,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:n8,oneof:"message"}]),nK=iT.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:nY,oneof:"message"},{no:2,name:"answer",kind:"message",T:n2,oneof:"message"},{no:3,name:"offer",kind:"message",T:n2,oneof:"message"},{no:4,name:"trickle",kind:"message",T:nQ,oneof:"message"},{no:5,name:"update",kind:"message",T:n3,oneof:"message"},{no:6,name:"track_published",kind:"message",T:n0,oneof:"message"},{no:8,name:"leave",kind:"message",T:n9,oneof:"message"},{no:9,name:"mute",kind:"message",T:nX,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:rn,oneof:"message"},{no:11,name:"room_update",kind:"message",T:rr,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:rs,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:rc,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:ru,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:rg,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:n1,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:nZ,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:rS,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:rw,oneof:"message"},{no:22,name:"request_response",kind:"message",T:rR,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:r_,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:rf,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:rM,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:rh,oneof:"message"}]),nJ=iT.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:iQ,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:iT.getEnumType(iX)}]),n$=iT.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:iT.getEnumType(iO)},{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:iT.getEnumType(iD)},{no:9,name:"layers",kind:"message",T:iQ,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:nJ,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:iT.getEnumType(iK)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:iT.getEnumType(ix)},{no:17,name:"audio_features",kind:"enum",T:iT.getEnumType(iF),repeated:!0}]),nQ=iT.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:iT.getEnumType(nW)},{no:3,name:"final",kind:"scalar",T:8}]),nX=iT.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),nY=iT.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:iB},{no:2,name:"participant",kind:"message",T:iW},{no:3,name:"other_participants",kind:"message",T:iW,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ri,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:nc},{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:nr},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:iq,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),nZ=iT.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:ri,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:nc},{no:3,name:"server_info",kind:"message",T:nr},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),n0=iT.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",
vendor: 10,776 bytes, line 3
3kind:"message",T:i$}]),n1=iT.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),n2=iT.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}}]),n3=iT.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:iW,repeated:!0}]),n6=iT.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:nn,repeated:!0}]),n4=iT.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:iT.getEnumType(iM)},{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}]),n5=iT.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:iT.getEnumType(iF),repeated:!0}]),n8=iT.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}]),n9=iT.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:iT.getEnumType(iL)},{no:3,name:"action",kind:"enum",T:iT.getEnumType(n7)},{no:4,name:"regions",kind:"message",T:rC}]),n7=iT.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),re=iT.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:iQ,repeated:!0}]),rt=iT.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}]),ri=iT.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}]),rn=iT.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:i3,repeated:!0}]),rr=iT.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:iB}]),ra=iT.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:iT.getEnumType(iA)},{no:3,name:"score",kind:"scalar",T:2}]),rs=iT.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:ra,repeated:!0}]),ro=iT.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:iT.getEnumType(nH)}]),rc=iT.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:ro,repeated:!0}]),rl=iT.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:iT.getEnumType(iM)},{no:2,name:"enabled",kind:"scalar",T:8}]),rd=iT.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:rl,repeated:!0}]),ru=iT.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:rl,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:rd,repeated:!0}]),rh=iT.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:nk,repeated:!0}]),rp=iT.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}]),rm=iT.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:rp,repeated:!0}]),rg=iT.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}]),rf=iT.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:iB},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:iW},{no:4,name:"other_participants",kind:"message",T:iW,repeated:!0}]),rv=iT.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:n2},{no:2,name:"subscription",kind:"message",T:n6},{no:3,name:"publish_tracks",kind:"message",T:n0,repeated:!0},{no:4,name:"data_channels",kind:"message",T:ry,repeated:!0},{no:5,name:"offer",kind:"message",T:n2},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:rb,repeated:!0}]),rb=iT.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),ry=iT.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:iT.getEnumType(nW)}]),rk=iT.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:iT.getEnumType(nG),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"}]),rT=iT.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),rS=iT.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),rC=iT.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:rE,repeated:!0}]),rE=iT.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}]),rw=iT.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:iT.getEnumType(ij)}]),rR=iT.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:iT.getEnumType(rP)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:nQ,oneof:"request"},{no:5,name:"add_track",kind:"message",T:n$,oneof:"request"},{no:6,name:"mute",kind:"message",T:nX,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:rt,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:n5,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:n8,oneof:"request"}]),rP=iT.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"}]),r_=iT.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),rI=iT.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}]),rx=iT.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:ns},{no:2,name:"connection_settings",kind:"message",T:rI},{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:n$,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:n2},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:iT.getEnumType(iU)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:rv}]),rO=iT.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:iT.getEnumType(rD)},{no:2,name:"join_request",kind:"scalar",T:12}]),rD=iT.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),rM=iT.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);var rA={exports:{}},rN=rA.exports,rL=function(){var e;return $?rA.exports:($=1,e=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],r={},a=null;function s(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),r=0;r<n.length;r++){var a=n[r];this[a]=r<i?e:this.methodFactory(a,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function l(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function d(n,r,a){var c;return"debug"===(c=n)&&(c="log"),typeof console!==t&&("trace"===c&&i?o:void 0!==console[c]?s(console,c):void 0!==console.log?s(console,"log"):e)||l.apply(this,arguments)}function u(e,i){var s,o,l,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),r=i.indexOf(n+"=");-1!==r&&(e=/^([^;]+)/.exec(i.slice(r+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;
3throw TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||d,u.getLevel=function(){return null!=l?l:null!=o?o:s},u.setLevel=function(e,i){return l=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{window.localStorage[h]=i;return}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(l),c.call(u)},u.setDefaultLevel=function(e){o=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){if(l=null,typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(a!==u&&(s=m(a.getLevel())),c.call(u),a===u)for(var e in r)r[e].rebuild()},s=m(a?a.getLevel():"WARN");var g=p();null!=g&&(l=m(g)),c.call(u)}(a=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw TypeError("You must supply a name when creating a logger.");var t=r[e];return t||(t=r[e]=new u(e,a.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=h),a},a.getLoggers=function(){return r},a.default=a,a},rA.exports?rA.exports=e():rN.log=e(),rA.exports)}();(h=Q||(Q={}))[h.trace=0]="trace",h[h.debug=1]="debug",h[h.info=2]="info",h[h.warn=3]="warn",h[h.error=4]="error",h[h.silent=5]="silent",(p=X||(X={})).Default="livekit",p.Room="livekit-room",p.TokenSource="livekit-token-source",p.Participant="livekit-participant",p.Track="livekit-track",p.Publication="livekit-track-publication",p.Engine="livekit-engine",p.Signal="livekit-signal",p.PCManager="livekit-pc-manager",p.PCTransport="livekit-pc-transport",p.E2EE="lk-e2ee";let rU=rL.getLogger("livekit");function rj(e){let t=rL.getLogger(e);return t.setDefaultLevel(rU.getLevel()),t}Object.values(X).map(e=>rL.getLogger(e)),rU.setDefaultLevel(Q.info);let rF=rL.getLogger("lk-e2ee"),rB=[0,300,1200,2700,4800,7e3,7e3,7e3,7e3,7e3];function rq(e,t,i,n){return new(i||(i=Promise))(function(r,a){function s(e){try{c(n.next(e))}catch(e){a(e)}}function o(e){try{c(n.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(s,o)}c((n=n.apply(e,t||[])).next())})}function rV(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,r){var a,s,o;a=n,s=r,o=(t=e[i](t)).done,Promise.resolve(t.value).then(function(e){a({value:e,done:o})},s)})}}}"function"==typeof SuppressedError&&SuppressedError;var rW={exports:{}},rH=function(){if(Y)return rW.exports;Y=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}rW.exports=r,rW.exports.once=function(e,t){return new Promise(function(i,n){var r,a,s;function o(i){e.removeListener(t,c),n(i)}function c(){"function"==typeof e.removeListener&&e.removeListener("error",o),i([].slice.call(arguments))}m(e,t,c,{once:!0}),"error"!==t&&(r=e,a=o,s={once:!0},"function"==typeof r.on&&m(r,"error",a,s))})},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function s(e){if("function"!=typeof e)throw TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function o(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){if(s(i),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),a=e._events),c=a[t]),void 0===c)c=a[t]=i,++e._eventsCount;else if("function"==typeof c?c=a[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(r=o(e))>0&&c.length>r&&!c.warned){c.warned=!0;var r,a,c,l=Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,console&&console.warn&&console.warn(l)}return e}function l(){if(!this.fired)return(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0==arguments.length)?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=l.bind(n);return r.listener=i,n.wrapFn=r,r}function u(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):p(r,r.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else if("function"==typeof e.addEventListener)e.addEventListener(t,function r(a){n.once&&e.removeEventListener(t,r),i(a)});else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a}
3,set:function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),r.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return o(this)},r.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,a=this._events;if(void 0!==a)r=r&&void 0===a.error;else if(!r)return!1;if(r){if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var s,o=Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var c=a[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else for(var l=c.length,d=p(c,l),n=0;n<l;++n)i(d[n],this,t);return!0},r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},r.prototype.removeListener=function(e,t){var i,n,r,a,o;if(s(t),void 0===(n=this._events)||void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,a=i.length-1;a>=0;a--)if(i[a]===t||i[a].listener===t){o=i[a].listener,r=a;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0==arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0==arguments.length){var r,a=Object.keys(i);for(n=0;n<a.length;++n)"removeListener"!==(r=a[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},r.prototype.listenerCount=h,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},rW.exports}();let rG=!0,rz=!0;function rK(e,t,i){let n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function rJ(e,t,i){if(!e.RTCPeerConnection)return;let n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);let a=e=>{let t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,a),r.apply(this,[e,a])};let a=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(i))return a.apply(this,arguments);let n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,a.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function r$(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(rG=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function rQ(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(rz=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function rX(){"object"==typeof window&&!rG&&"u">typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}function rY(e,t){rz&&console.warn(e+" is deprecated, please use "+t+" instead.")}function rZ(e){return"[object Object]"===Object.prototype.toString.call(e)}function r0(e,t,i){let n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;let a=[];
vendor: 42,332 bytes, line 3
3return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&function e(t,i,n){!i||n.has(i.id)||(n.set(i.id,i),Object.keys(i).forEach(r=>{r.endsWith("Id")?e(t,t.get(i[r]),n):r.endsWith("Ids")&&i[r].forEach(i=>{e(t,t.get(i),n)})}))}(e,i,r)})}),r}function r1(e,t){let i=e&&e.navigator;if(!i.mediaDevices)return;let n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;let n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);let r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),(e={})[r("max",i)]=n.ideal):e[r("",i)]=n.ideal,t.optional.push(e)}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){let t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let a=e.video.facingMode;a=a&&("object"==typeof a?a:{ideal:a});let s=t.version<66;if(a&&("user"===a.exact||"environment"===a.exact||"user"===a.ideal||"environment"===a.ideal)&&!(i.mediaDevices.getSupportedConstraints&&i.mediaDevices.getSupportedConstraints().facingMode&&!s)){let t;if(delete e.video.facingMode,"environment"===a.exact||"environment"===a.ideal?t=["back","rear"]:("user"===a.exact||"user"===a.ideal)&&(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{let s=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=a.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),rX("chrome: "+JSON.stringify(e)),r(e)})}e.video=n(e.video)}return rX("chrome: "+JSON.stringify(e)),r(e)},a=function(e){return t.version>=64?e:{name:({PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"})[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=(function(e,t,n){r(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(a(e))})})}).bind(i),i.mediaDevices.getUserMedia){let e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(a(e))))}}}function r2(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function r3(e){if("object"!=typeof e||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)rJ(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e));else{Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};let r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};let r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}}function r6(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};let n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);let t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function r4(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>r0(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),rJ(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>r0(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype))return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e,t,i,n=arguments[0];return(this.getSenders().forEach(t=>{t.track===n&&(e?i=!0:e=t)}),this.getReceivers().forEach(e=>(e.track===n&&(t?i=!0:t=e),e.track===n)),i||e&&t)?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():t?t.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function r5(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});let t=this.getSenders();i.apply(this,arguments);let n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),r.apply(this,arguments)}}function r8(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return r5(e);let i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){let i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};let r=e.RTCPeerConnection.prototype.removeStream;function a(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(RegExp(r.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))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(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){let e=arguments,t=arguments.length&&"function"==typeof arguments[0];return t?i.apply(this,[t=>{let i=a(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>a(this,e))}})[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){var e,t;let i;return arguments.length&&arguments[0].type?(arguments[0]=(e=this,t=arguments[0],i=t.sdp,Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(RegExp(n.id,"g"),r.id)}),new RTCSessionDescription({type:t.type,sdp:i})),s.apply(this,arguments)):s.apply(this,arguments)};let o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=o.get.apply(this);return""===e.type?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){let t;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function r9(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]})}function r7(e,t){rJ(e,"negotiationneeded",e=>{let i=e.target;if(!(t.version<72)&&(!i.getConfiguration||"plan-b"!==i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var ae=Object.freeze({__proto__:null,fixNegotiationNeeded:r7,shimAddTrackRemoveTrack:r8,shimAddTrackRemoveTrackWithNative:r5,shimGetSendersWithDtmf:r6,shimGetUserMedia:r1,shimMediaStream:r2,shimOnTrack:r3,shimPeerConnection:r9,shimSenderReceiverGetStats:r4});function at(e,t){let i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){rY("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){let e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(e((i=JSON.parse(JSON.stringify(i))).audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){let t=n.prototype.getSettings;n.prototype.getSettings=function(){let i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){let t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(e(i=JSON.parse(JSON.stringify(i)),"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function ai(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function an(e,t){if("object"!=typeof e||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]});let i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,r,a]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(r,a)}}function ar(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function aa(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),rJ(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function as(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){rY("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function ao(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function ac(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]);let i=(e=[...e]).length>0;i&&e.forEach(e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError("max_framerate must be >= 0.0")});let n=t.apply(this,arguments);if(i){let{sender:t}=n,i=t.getParameters();"encodings"in i&&(1!==i.encodings.length||0!==Object.keys(i.encodings[0]).length)||(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function al(e){if(!("object"==typeof e&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function ad(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function au(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var ah=Object.freeze({__proto__:null,shimAddTransceiver:ac,shimCreateAnswer:au,shimCreateOffer:ad,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){let e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:al,shimGetUserMedia:at,shimOnTrack:ai,shimPeerConnection:an,shimRTCDataChannel:ao,shimReceiverGetStats:aa,shimRemoveStream:as,shimSenderGetStats:ar});function ap(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);let t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);let i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function am(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function ag(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,a=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){let i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let o=function(e,t,i){let n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=o,t.setRemoteDescription=o=function(e,t,i){let n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=function(e,t,i){let n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n}}function af(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(av(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}).bind(t))}function av(e){return e&&void 0!==e.video?Object.assign({},e,{video:function e(t){return rZ(t)?Object.keys(t).reduce(function(i,n){let r=rZ(t[n]),a=r?e(t[n]):t[n],s=r&&!Object.keys(a).length;return void 0===a||s?i:Object.assign(i,{[n]:a})},{}):t}(e.video)}):e}function ab(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){let t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(rY("RTCIceServer.url","RTCIceServer.urls"),(n=JSON.parse(JSON.stringify(n))).urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function ay(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ak(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function aT(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var aS=Object.freeze({__proto__:null,shimAudioContext:aT,shimCallbacksAPI:ag,shimConstraints:av,shimCreateOfferLegacy:ak,shimGetUserMedia:af,shimLocalStreamsAPI:ap,shimRTCIceServerUrls:ab,shimRemoteStreamsAPI:am,shimTrackEventTransceiver:ay}),aC={exports:{}},aE=function(){let e;return Z?aC.exports:(Z=1,(e={}).generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},e.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},e.getDescription=function(t){let i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){let i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(e=>0===e.indexOf(i))},e.parseCandidate=function(e){let t,i={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},e.writeCandidate=function(e){let t=[];t.push(e.foundation);let i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},e.parseIceOptions=function(e){return e.substring(14).split(" ")},e.parseRtpMap=function(e){let t=e.substring(9).split(" "),i={payloadType:parseInt(t.shift(),10)};return i.name=(t=t[0].split("/"))[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},e.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);let i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},e.parseExtmap=function(e){let t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},e.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},e.parseFmtp=function(e){let t,i={},n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i[(t=n[e].trim().split("="))[0].trim()]=t[1];return i},e.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){let n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},e.parseRtcpFb=function(e){let t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},e.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},e.parseSsrcMedia=function(e){let t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},e.parseSsrcGroup=function(e){let t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},e.getMid=function(t){let i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(e){let t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},e.parseCryptoLine=function(e){let t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+("object"==typeof t.keyParams?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+"\r\n"},e.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;let t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){let n=e.matchPrefix(t+i,"a=ice-ufrag:")[0],r=e.matchPrefix(t+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},e.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},e.parseRtpParameters=function(t){let i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=e.splitLines(t)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){let a=n[r],s=e.matchPrefix(t,"a=rtpmap:"+a+" ")[0];if(s){let n=e.parseRtpMap(s),r=e.matchPrefix(t,"a=fmtp:"+a+" ");switch(n.parameters=r.length?e.parseFmtp(r[0]):{},n.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+a+" ").map(e.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}e.matchPrefix(t,"a=extmap:").forEach(t=>{i.headerExtensions.push(e.parseExtmap(t))});let r=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(e=>{r.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),i},e.writeRtpDescription=function(t,i){let n="";n+="m="+t+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(t=>{n+=e.writeRtpMap(t),n+=e.writeFmtp(t),n+=e.writeRtcpFb(t)});let r=0;return i.codecs.forEach(e=>{e.maxptime>r&&(r=e.maxptime)}),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(t=>{n+=e.writeExtmap(t)}),n},e.parseRtpEncodingParameters=function(t){let i,n=[],r=e.parseRtpParameters(t),a=-1!==r.fecMechanisms.indexOf("RED"),s=-1!==r.fecMechanisms.indexOf("ULPFEC"),o=e.matchPrefix(t,"a=ssrc:").map(t=>e.parseSsrcMedia(t)).filter(e=>"cname"===e.attribute),c=o.length>0&&o[0].ssrc,l=e.matchPrefix(t,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));l.length>0&&l[0].length>1&&l[0][0]===c&&(i=l[0][1]),r.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&i&&(t.rtx={ssrc:i}),n.push(t),a&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:s?"red+ulpfec":"red"},n.push(t))}}),0===n.length&&c&&n.push({ssrc:c});let d=e.matchPrefix(t,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,n.forEach(e=>{e.maxBitrate=d})),n},e.parseRtcpParameters=function(t){let i={},n=e.matchPrefix(t,"a=ssrc:").map(t=>e.parseSsrcMedia(t)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);let r=e.matchPrefix(t,"a=rtcp-rsize");return i.reducedSize=r.length>0,i.compound=0===r.length,i.mux=e.matchPrefix(t,"a=rtcp-mux").length>0,i},e.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},e.parseMsid=function(t){let i,n=e.matchPrefix(t,"a=msid:");if(1===n.length)return{stream:(i=n[0].substring(7).split(" "))[0],track:i[1]};let r=e.matchPrefix(t,"a=ssrc:").map(t=>e.parseSsrcMedia(t)).filter(e=>"msid"===e.attribute);if(r.length>0)return{stream:(i=r[0].value.split(" "))[0],track:i[1]}},e.parseSctpDescription=function(t){let i,n=e.parseMLine(t),r=e.matchPrefix(t,"a=max-message-size:");r.length>0&&(i=parseInt(r[0].substring(19),10)),isNaN(i)&&(i=65536);let a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};let s=e.matchPrefix(t,"a=sctpmap:");if(s.length>0){let e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},e.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,i,n){return"v=0\r\no="+(n||"thisisadapterortc")+" "+(t||e.generateSessionId())+" "+(void 0!==i?i:2)+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},e.getDirection=function(t,i){let n=e.splitLines(t);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(e){return"0"===e.split(" ",2)[1]},e.parseMLine=function(t){let i=e.splitLines(t)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},e.parseOLine=function(t){let i=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},e.isValidSDP=function(t){if("string"!=typeof t||0===t.length)return!1;let i=e.splitLines(t);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},aC.exports=e,aC.exports)}(),aw=aE&&aE.__esModule&&Object.prototype.hasOwnProperty.call(aE,"default")?aE.default:aE,aR=(m={__proto__:null,default:aw},[aE].forEach(function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach(function(t){if("default"!==t&&!(t in m)){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(m,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})}})}),Object.freeze(m));function aP(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let i=new t(e),n=aw.parseCandidate(e.candidate);for(let e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,rJ(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function a_(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||rJ(e,"icecandidate",e=>{if(e.candidate){let t=aw.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol=({0:"tls",1:"tcp",2:"udp"})[t.priority>>24])}return e})}function aI(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});let i=function(e){if(!e||!e.sdp)return!1;let t=aw.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=aw.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})},n=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return -1;let i=parseInt(t[1],10);return i!=i?-1:i},r=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:0x7ffffff5:t.version<60?57===t.version?65535:65536:0x7ffffff5),i},a=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);let r=aw.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=0x7ffffff5),n},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){let{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){let e,t=n(arguments[0]),i=r(t),s=a(arguments[0],t);e=0===i&&0===s?1/0:0===i||0===s?Math.max(i,s):Math.min(i,s);let o={};Object.defineProperty(o,"maxMessageSize",{get:()=>e}),this._sctp=o}return s.apply(this,arguments)}}function ax(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){let i=e.send;e.send=function(){let n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}let i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=i.apply(this,arguments);return t(e,this),e},rJ(e,"datachannel",e=>(t(e.channel,e.target),e))}function aO(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return({completed:"connected",checking:"connecting"})[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}
3),["setLocalDescription","setRemoteDescription"].forEach(e=>{let i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function aD(e,t){if(!e.RTCPeerConnection||"chrome"===t.browser&&t.version>=71||"safari"===t.browser&&t._safariVersion>=13.1)return;let i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){let i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function aM(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function aA(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(!(e={type:e.type,sdp:e.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]))})}var aN=Object.freeze({__proto__:null,removeExtmapAllowMixed:aD,shimAddIceCandidateNullOrEmpty:aM,shimConnectionState:aO,shimMaxMessageSize:aI,shimParameterlessSetLocalDescription:aA,shimRTCIceCandidate:aP,shimRTCIceCandidateRelayProtocol:a_,shimSendThrowTypeError:ax});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},i=function(e){let t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;let{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){let e=i.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}return i.mozGetUserMedia?(t.browser="firefox",t.version=parseInt(rK(i.userAgent,/Firefox\/(\d+)\./,1))):i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection?(t.browser="chrome",t.version=parseInt(rK(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2))):e.RTCPeerConnection&&i.userAgent.match(/AppleWebKit\/(\d+)\./)?(t.browser="safari",t.version=parseInt(rK(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=rK(i.userAgent,/Version\/(\d+(\.?\d+))/,1)):t.browser="Not a supported browser.",t}(e),n={browserDetails:i,commonShim:aN,extractVersion:rK,disableLog:r$,disableWarnings:rQ,sdp:aR};switch(i.browser){case"chrome":if(!ae||!r9||!t.shimChrome){rX("Chrome shim is not included in this adapter release.");break}if(null===i.version){rX("Chrome shim can not determine version, not shimming.");break}rX("adapter.js shimming chrome."),n.browserShim=ae,aM(e,i),aA(e),r1(e,i),r2(e),r9(e,i),r3(e),r8(e,i),r6(e),r4(e),r7(e,i),aP(e),a_(e),aO(e),aI(e,i),ax(e),aD(e,i);break;case"firefox":if(!ah||!an||!t.shimFirefox){rX("Firefox shim is not included in this adapter release.");break}rX("adapter.js shimming firefox."),n.browserShim=ah,aM(e,i),aA(e),at(e,i),an(e,i),ai(e),as(e),ar(e),aa(e),ao(e),ac(e),al(e),ad(e),au(e),aP(e),aO(e),aI(e,i),ax(e);break;case"safari":if(!aS||!t.shimSafari){rX("Safari shim is not included in this adapter release.");break}rX("adapter.js shimming safari."),n.browserShim=aS,aM(e,i),aA(e),ab(e),ak(e),ag(e),ap(e),am(e),ay(e),af(e),aT(e),aP(e),a_(e),aI(e,i),ax(e),aD(e,i);break;default:rX("Unsupported browser!")}}({window:"u"<typeof window?void 0:window});let aL=/version\/(\d+(\.?_?\d+)+)/i;function aU(e){let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(void 0===e&&"u"<typeof navigator)return;let n=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===t||i){let e=aj.find(e=>{let{test:t}=e;return t.test(n)});t=null==e?void 0:e.describe(n)}return t}let aj=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:aF(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:aB(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:aF(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:aB(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:aF(aL,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:aB(e)})}];function aF(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=t.match(e);return n&&n.length>=i&&n[i]||""}function aB(e){return e.includes("mac os")?aF(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}
3class aq extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}(g=ee||(ee={}))[g.NotAllowed=0]="NotAllowed",g[g.ServerUnreachable=1]="ServerUnreachable",g[g.InternalError=2]="InternalError",g[g.Cancelled=3]="Cancelled",g[g.LeaveRequest=4]="LeaveRequest",g[g.Timeout=5]="Timeout",g[g.WebSocket=6]="WebSocket";class aV extends aq{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=ee[t]}static notAllowed(e,t,i){return new aV(e,ee.NotAllowed,t,i)}static timeout(e){return new aV(e,ee.Timeout)}static leaveRequest(e,t){return new aV(e,ee.LeaveRequest,void 0,t)}static internal(e,t){return new aV(e,ee.InternalError,void 0,t)}static cancelled(e){return new aV(e,ee.Cancelled)}static serverUnreachable(e,t){return new aV(e,ee.ServerUnreachable,t)}static websocket(e,t,i){return new aV(e,ee.WebSocket,t,i)}}class aW extends aq{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class aH extends aq{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class aG extends aq{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class az extends aq{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class aK extends aq{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class aJ extends aq{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class a$ extends aq{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:rP[t]}}(f=et||(et={}))[f.AlreadyOpened=0]="AlreadyOpened",f[f.AbnormalEnd=1]="AbnormalEnd",f[f.DecodeFailed=2]="DecodeFailed",f[f.LengthExceeded=3]="LengthExceeded",f[f.Incomplete=4]="Incomplete",f[f.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",f[f.EncryptionTypeMismatch=8]="EncryptionTypeMismatch";class aQ extends aq{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=et[t]}}class aX extends aq{constructor(e){super(18,e),this.name="SignalReconnectError"}}(v=ei||(ei={})).PermissionDenied="PermissionDenied",v.NotFound="NotFound",v.DeviceInUse="DeviceInUse",v.Other="Other",(b=ei||(ei={})).getFailure=function(e){if(e&&"name"in e)return"NotFoundError"===e.name||"DevicesNotFoundError"===e.name?b.NotFound:"NotAllowedError"===e.name||"PermissionDeniedError"===e.name?b.PermissionDenied:"NotReadableError"===e.name||"TrackStartError"===e.name?b.DeviceInUse:b.Other};class aY{}aY.setTimeout=function(){return setTimeout(...arguments)},aY.setInterval=function(){return setInterval(...arguments)},aY.clearTimeout=function(){return clearTimeout(...arguments)},aY.clearInterval=function(){return clearInterval(...arguments)},(y=en||(en={})).Connected="connected",y.Reconnecting="reconnecting",y.SignalReconnecting="signalReconnecting",y.Reconnected="reconnected",y.Disconnected="disconnected",y.ConnectionStateChanged="connectionStateChanged",y.Moved="moved",y.MediaDevicesChanged="mediaDevicesChanged",y.ParticipantConnected="participantConnected",y.ParticipantDisconnected="participantDisconnected",y.TrackPublished="trackPublished",y.TrackSubscribed="trackSubscribed",y.TrackSubscriptionFailed="trackSubscriptionFailed",y.TrackUnpublished="trackUnpublished",y.TrackUnsubscribed="trackUnsubscribed",y.TrackMuted="trackMuted",y.TrackUnmuted="trackUnmuted",y.LocalTrackPublished="localTrackPublished",y.LocalTrackUnpublished="localTrackUnpublished",y.LocalAudioSilenceDetected="localAudioSilenceDetected",y.ActiveSpeakersChanged="activeSpeakersChanged",y.ParticipantMetadataChanged="participantMetadataChanged",y.ParticipantNameChanged="participantNameChanged",y.ParticipantAttributesChanged="participantAttributesChanged",y.ParticipantActive="participantActive",y.RoomMetadataChanged="roomMetadataChanged",y.DataReceived="dataReceived",y.SipDTMFReceived="sipDTMFReceived",y.TranscriptionReceived="transcriptionReceived",y.ConnectionQualityChanged="connectionQualityChanged",y.TrackStreamStateChanged="trackStreamStateChanged",y.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",y.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",y.AudioPlaybackStatusChanged="audioPlaybackChanged",y.VideoPlaybackStatusChanged="videoPlaybackChanged",y.MediaDevicesError="mediaDevicesError",
3y.ParticipantPermissionsChanged="participantPermissionsChanged",y.SignalConnected="signalConnected",y.RecordingStatusChanged="recordingStatusChanged",y.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",y.EncryptionError="encryptionError",y.DCBufferStatusChanged="dcBufferStatusChanged",y.ActiveDeviceChanged="activeDeviceChanged",y.ChatMessage="chatMessage",y.LocalTrackSubscribed="localTrackSubscribed",y.MetricsReceived="metricsReceived",(k=er||(er={})).TrackPublished="trackPublished",k.TrackSubscribed="trackSubscribed",k.TrackSubscriptionFailed="trackSubscriptionFailed",k.TrackUnpublished="trackUnpublished",k.TrackUnsubscribed="trackUnsubscribed",k.TrackMuted="trackMuted",k.TrackUnmuted="trackUnmuted",k.LocalTrackPublished="localTrackPublished",k.LocalTrackUnpublished="localTrackUnpublished",k.LocalTrackCpuConstrained="localTrackCpuConstrained",k.LocalSenderCreated="localSenderCreated",k.ParticipantMetadataChanged="participantMetadataChanged",k.ParticipantNameChanged="participantNameChanged",k.DataReceived="dataReceived",k.SipDTMFReceived="sipDTMFReceived",k.TranscriptionReceived="transcriptionReceived",k.IsSpeakingChanged="isSpeakingChanged",k.ConnectionQualityChanged="connectionQualityChanged",k.TrackStreamStateChanged="trackStreamStateChanged",k.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",k.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",k.TrackCpuConstrained="trackCpuConstrained",k.MediaDevicesError="mediaDevicesError",k.AudioStreamAcquired="audioStreamAcquired",k.ParticipantPermissionsChanged="participantPermissionsChanged",k.PCTrackAdded="pcTrackAdded",k.AttributesChanged="attributesChanged",k.LocalTrackSubscribed="localTrackSubscribed",k.ChatMessage="chatMessage",k.Active="active",(T=ea||(ea={})).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",(S=es||(es={})).Message="message",S.Muted="muted",S.Unmuted="unmuted",S.Restarted="restarted",S.Ended="ended",S.Subscribed="subscribed",S.Unsubscribed="unsubscribed",S.CpuConstrained="cpuConstrained",S.UpdateSettings="updateSettings",S.UpdateSubscription="updateSubscription",S.AudioPlaybackStarted="audioPlaybackStarted",S.AudioPlaybackFailed="audioPlaybackFailed",S.AudioSilenceDetected="audioSilenceDetected",S.VisibilityChanged="visibilityChanged",S.VideoDimensionsChanged="videoDimensionsChanged",S.VideoPlaybackStarted="videoPlaybackStarted",S.VideoPlaybackFailed="videoPlaybackFailed",S.ElementAttached="elementAttached",S.ElementDetached="elementDetached",S.UpstreamPaused="upstreamPaused",S.UpstreamResumed="upstreamResumed",S.SubscriptionPermissionChanged="subscriptionPermissionChanged",S.SubscriptionStatusChanged="subscriptionStatusChanged",S.SubscriptionFailed="subscriptionFailed",S.TrackProcessorUpdate="trackProcessorUpdate",S.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",S.TranscriptionReceived="transcriptionReceived",S.TimeSyncUpdate="timeSyncUpdate",S.PreConnectBufferFlushed="preConnectBufferFlushed";class aZ{constructor(e,t,i,n,r){if("object"==typeof e)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(void 0!==t&&void 0!==i)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:r};else throw 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}}}let a0=["vp8","h264"],a1=["vp8","h264","vp9","av1","h265"],a2=function(e){return!!a0.find(t=>t===e)};(C=eo||(eo={}))[C.PREFER_REGRESSION=0]="PREFER_REGRESSION",C[C.SIMULCAST=1]="SIMULCAST",C[C.REGRESSION=2]="REGRESSION",(E=ec||(ec={})).telephone={maxBitrate:12e3}
3,E.speech={maxBitrate:24e3},E.music={maxBitrate:48e3},E.musicStereo={maxBitrate:64e3},E.musicHighQuality={maxBitrate:96e3},E.musicHighQualityStereo={maxBitrate:128e3};let a3={h90:new aZ(160,90,9e4,20),h180:new aZ(320,180,16e4,20),h216:new aZ(384,216,18e4,20),h360:new aZ(640,360,45e4,20),h540:new aZ(960,540,8e5,25),h720:new aZ(1280,720,17e5,30),h1080:new aZ(1920,1080,3e6,30),h1440:new aZ(2560,1440,5e6,30),h2160:new aZ(3840,2160,8e6,30)},a6={h120:new aZ(160,120,7e4,20),h180:new aZ(240,180,125e3,20),h240:new aZ(320,240,14e4,20),h360:new aZ(480,360,33e4,20),h480:new aZ(640,480,5e5,20),h540:new aZ(720,540,6e5,25),h720:new aZ(960,720,13e5,30),h1080:new aZ(1440,1080,23e5,30),h1440:new aZ(1920,1440,38e5,30)},a4={h360fps3:new aZ(640,360,2e5,3,"medium"),h360fps15:new aZ(640,360,4e5,15,"medium"),h720fps5:new aZ(1280,720,8e5,5,"medium"),h720fps15:new aZ(1280,720,15e5,15,"medium"),h720fps30:new aZ(1280,720,2e6,30,"medium"),h1080fps15:new aZ(1920,1080,25e5,15,"medium"),h1080fps30:new aZ(1920,1080,5e6,30,"medium"),original:new aZ(0,0,7e6,30,"medium")};function a5(e,t,i){var n,r;let{optionsWithoutProcessor:a,audioProcessor:s,videoProcessor:o}=sr(null!=e?e:{}),c=null==t?void 0:t.processor,l=null==i?void 0:i.processor,d=null!=a?a:{};return!0===d.audio&&(d.audio={}),!0===d.video&&(d.video={}),d.audio&&(a8(d.audio,t),null!=(n=d.audio).deviceId||(n.deviceId={ideal:"default"}),(s||c)&&(d.audio.processor=null!=s?s:c)),d.video&&(a8(d.video,i),null!=(r=d.video).deviceId||(r.deviceId={ideal:"default"}),(o||l)&&(d.video.processor=null!=o?o:l)),d}function a8(e,t){return Object.keys(t).forEach(i=>{void 0===e[i]&&(e[i]=t[i])}),e}function a9(e){var t,i;let n={};if(e.video)if("object"==typeof e.video){let i={},r=e.video;Object.keys(r).forEach(e=>{"resolution"===e?a8(i,r.resolution):i[e]=r[e]}),n.video=i,null!=(t=n.video).deviceId||(t.deviceId={ideal:"default"})}else n.video=!!e.video&&{deviceId:{ideal:"default"}};else n.video=!1;return e.audio?"object"==typeof e.audio?(n.audio=e.audio,null!=(i=n.audio).deviceId||(i.deviceId={ideal:"default"})):n.audio={deviceId:{ideal:"default"}}:n.audio=!1,n}function a7(e){return rq(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){let i=se();if(i){let n=i.createAnalyser();n.fftSize=2048;let r=new Uint8Array(n.frequencyBinCount);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield su(t),n.getByteTimeDomainData(r);let a=r.some(e=>128!==e&&0!==e);return i.close(),!a}return!1}()})}function se(){var e;let t="u">typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){let i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"u">typeof window&&(null==(e=window.document)?void 0:e.body)){let e=()=>rq(this,void 0,void 0,function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null==(t=window.document.body)||t.removeEventListener("click",e)}});i.addEventListener("statechange",()=>{var t;"closed"===i.state&&(null==(t=window.document.body)||t.removeEventListener("click",e))}),window.document.body.addEventListener("click",e)}return i}}function st(e){return e===so.Source.Microphone?"audioinput":e===so.Source.Camera?"videoinput":void 0}function si(e){return e.split("/")[1].toLowerCase()}function sn(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?sn(e.track):{})}}function sr(e){let t,i,n=Object.assign({},e);return"object"==typeof n.audio&&n.audio.processor&&(t=n.audio.processor,n.audio=Object.assign(Object.assign({},n.audio),{processor:void 0})),"object"==typeof n.video&&n.video.processor&&(i=n.video.processor,n.video=Object.assign(Object.assign({},n.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:void 0===n?n:"function"!=typeof structuredClone?JSON.parse(JSON.stringify(n)):"object"==typeof n&&null!==n?structuredClone(Object.assign({},n)):structuredClone(n)}}function sa(e,t){return e.width*e.height<t.width*t.height}let ss=[];(w=el||(el={}))[w.LOW=0]="LOW",w[w.MEDIUM=1]="MEDIUM",w[w.HIGH=2]="HIGH";class so extends rH.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){var i;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=so.StreamState.Active,this.isInBackgroun
3d=!1,this._currentBitrate=0,this.log=rU,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),5e3):this.handleAppVisibilityChanged()},this.log=rj(null!=(i=n.loggerName)?i:X.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=so.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null==(e=this.loggerContextCb)?void 0:e.call(this)),sn(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===so.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===so.Kind.Video&&this.addAppVisibilityListener(),!e&&("audio"===t&&(ss.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&ss.splice(ss.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),sc(this.mediaStreamTrack,e);let i=e.srcObject.getTracks(),n=i.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(n?es.AudioPlaybackStarted:es.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(n?es.AudioPlaybackFailed:es.VideoPlaybackFailed,t):"AbortError"===t.name?rU.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):rU.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(es.ElementAttached,e),e}detach(e){try{if(e){sl(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(es.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{sl(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(es.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&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=rj(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ss.forEach(e=>{e.parentElement||(t=!1)}),t&&ss.push(e)}}handleAppVisibilityChanged(){return rq(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==so.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){sT()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){sT()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function sc(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,(n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks()).includes(e)||(n.forEach(e=>{i.removeTrack(e)}),i.addTrack(e)),sb()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(sb()||sf())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=i,t.play().catch(()=>{})},0))}function sl(e,t){if(t.srcObject instanceof MediaStream){let i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}(P=r=(R=so||(so={})).Kind||(R.Kind={})).Audio="audio",P.Video="video",P.Unknown="unknown",(_=a=R.Source||(R.Source={})).Camera="camera",_.Microphone="microphone",_.ScreenShare="screen_share",_.ScreenShareAudio="screen_share_audio",_.Unknown="unknown",(I=s=R.StreamState||(R.StreamState={})).Active="active",I.Paused="paused",I.Unknown="unknown",R.kindToProto=function(e){switch(e){case r.Audio:return iO.AUDIO;case r.Video:return iO.VIDEO;default:return iO.DATA}},R.kindFromProto=function(e){switch(e){case iO.AUDIO:return r.Audio;case iO.VIDEO:return r.Video;default:return r.Unknown}},R.sourceToProto=function(e){switch(e){case a.Camera:return iD.CAMERA;case a.Microphone:return iD.MICROPHONE;case a.ScreenShare:return iD.SCREEN_SHARE;case a.ScreenShareAudio:return iD.SCREEN_SHARE_AUDIO;default:return iD.UNKNOWN}},R.sourceFromProto=function(e){switch(e){case iD.CAMERA:return a.Camera;case iD.MICROPHONE:return a.Microphone;case iD.SCREEN_SHARE:return a.ScreenShare;case iD.SCREEN_SHARE_AUDIO:return a.ScreenShareAudio;default:return a.Unknown}},R.streamStateFromProto=function(e){switch(e){case nH.ACTIVE:return s.Active;case nH.PAUSED:return s.Paused;default:return s.Unknown}};let sd="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function su(e){return rq(this,void 0,void 0,function*(){return new Promise(t=>aY.setTimeout(t,e))})}function sh(){return"addTransceiver"in RTCPeerConnection.prototype}function sp(){return"addTrack"in RTCPeerConnection.prototype}function sm(e){return"av1"===e||"vp9"===e}function sg(e){return!(!document||sy())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function sf(){var e;return(null==(e=aU())?void 0:e.name)==="Firefox"}function sv(){let e=aU();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}
3function sb(){var e;return(null==(e=aU())?void 0:e.name)==="Safari"}function sy(){let e=aU();return(null==e?void 0:e.name)==="Safari"||(null==e?void 0:e.os)==="iOS"}function sk(){var e,t;return!!sT()&&(null!=(t=null==(e=navigator.userAgentData)?void 0:e.mobile)?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function sT(){return"u">typeof document}function sS(){return"ReactNative"==navigator.product}function sC(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function sE(e){return sC(e)?e.hostname.split(".")[0]:null}function sw(){if(e.g&&e.g.LiveKitReactNativeGlobal)return e.g.LiveKitReactNativeGlobal}function sR(){if(!sS())return;let e=sw();if(e)return e.platform}function sP(){if(sT())return window.devicePixelRatio;if(sS()){let e=sw();if(e)return e.devicePixelRatio}return 1}function s_(e,t){let i=e.split("."),n=t.split("."),r=Math.min(i.length,n.length);for(let e=0;e<r;++e){let t=parseInt(i[e],10),a=parseInt(n[e],10);if(t>a)return 1;if(t<a)return -1;if(e===r-1&&t===a)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function sI(e){for(let t of e)t.target.handleResize(t)}function sx(e){for(let t of e)t.target.handleVisibilityChanged(t)}let sO=null,sD=()=>(sO||(sO=new ResizeObserver(sI)),sO),sM=null,sA=()=>(sM||(sM=new IntersectionObserver(sx,{root:null,rootMargin:"0px"})),sM);function sN(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=document.createElement("canvas");r.width=e,r.height=t;let a=r.getContext("2d");null==a||a.fillRect(0,0,r.width,r.height),n&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,2*Math.PI,!0),a.closePath(),a.fillStyle="grey",a.fill());let[s]=r.captureStream().getTracks();if(!s)throw Error("Could not get empty media stream video track");return s.enabled=i,s}function sL(){if(!i){let e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);let r=e.createMediaStreamDestination();if(t.connect(n),n.connect(r),t.start(),[i]=r.stream.getAudioTracks(),!i)throw Error("Could not get empty media stream audio track");i.enabled=!1}return i.clone()}class sU{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,i)=>rq(this,void 0,void 0,function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})).finally(()=>{var e;this._isResolved=!0,null==(e=this.onFinally)||e.call(this)})}}function sj(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function sF(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function sB(e){switch(e.reason){case ee.LeaveRequest:return e.context;case ee.Cancelled:return iL.CLIENT_INITIATED;case ee.NotAllowed:return iL.USER_REJECTED;case ee.ServerUnreachable:return iL.JOIN_FAILURE;default:return iL.UNKNOWN_REASON}}function sq(e){return void 0!==e?Number(e):void 0}function sV(e){return void 0!==e?BigInt(e):void 0}function sW(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function sH(e){return!!e&&e.kind==so.Kind.Audio}function sG(e){return!!e&&e.kind==so.Kind.Video}function sz(e){return sW(e)&&sG(e)}function sK(e){return sW(e)&&sH(e)}function sJ(e){return!!e&&!e.isLocal}function s$(e){return sJ(e)&&sG(e)}function sQ(e){return e.endsWith("/")?e:"".concat(e,"/")}function sX(e,t){return e.pathname="".concat(sQ(e.pathname)).concat(t),e.toString()}function sY(e){if("string"==typeof e)return nK.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return nK.fromBinary(new Uint8Array(e));throw Error("could not decode websocket message: ".concat(typeof e))}let sZ="lk_e2ee";function s0(){return void 0!==window.RTCRtpScriptTransform}(x=ed||(ed={})).SetKey="setKey",x.RatchetRequest="ratchetRequest",x.KeyRatcheted="keyRatcheted",(eu||(eu={})).KeyRatcheted="keyRatcheted",(O=eh||(eh={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",O.EncryptionError="encryptionError",(ep||(ep={})).Error="cryptorError",rH.EventEmitter,(D=em||(em={}))[D.InvalidKey=0]="InvalidKey",D[D.MissingKey=1]="MissingKey",D[D.InternalError=2]="InternalError";class s1 extends rH.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,i;let{kind:n,data:r}=e.data;switch(n){case"error":if(rU.error(r.error.message),r.uuid){let e=this.decryptDataRequests.get(r.uuid);if(null==e?void 0:e.reject){e.reject(r.error);break}let t=this.encryptDataRequests.get(r.uuid);if(null==t?void 0:t.reject){t.reject(r.error);break}}
3this.emit(eh.EncryptionError,r.error,r.participantIdentity);break;case"initAck":r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)});break;case"enable":if(r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)}),this.encryptionEnabled!==r.enabled&&r.participantIdentity===(null==(t=this.room)?void 0:t.localParticipant.identity))this.emit(eh.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){let e=null==(i=this.room)?void 0:i.getParticipantByIdentity(r.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(r.participantIdentity));this.emit(eh.ParticipantEncryptionStatusChanged,r.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(ed.KeyRatcheted,r.ratchetResult,r.participantIdentity,r.keyIndex);break;case"decryptDataResponse":let a=this.decryptDataRequests.get(r.uuid);(null==a?void 0:a.resolve)&&a.resolve(r);break;case"encryptDataResponse":let s=this.encryptDataRequests.get(r.uuid);(null==s?void 0:s.resolve)&&s.resolve(r)}},this.onWorkerError=e=>{rU.error("e2ee worker encountered an error:",{error:e.error}),this.emit(eh.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||s0()))throw new aW("tried to setup end-to-e
3nd encryption on an unsupported browser");if(rU.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:rF.getLevel()}};this.worker&&(rU.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){rU.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):rU.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(ea.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(en.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==iK.NONE,t.identity)),e.on(en.ConnectionStateChanged,t=>{t===ew.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==iK.NONE,e.identity)})})}).on(en.TrackUnsubscribed,(e,t,i)=>{var n;let r={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null==(n=this.worker)||n.postMessage(r)}).on(en.TrackSubscribed,(e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)}).on(en.SignalConnected,()=>{if(!this.room)throw TypeError("expected room to be present on signal connect");t.getKeys().forEach(e=>{this.postKey(e)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(er.LocalSenderCreated,(e,t)=>rq(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(er.LocalTrackPublished,e=>{if(!sG(e.track)||!sy())return;let t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:si(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(ed.SetKey,e=>this.postKey(e)).on(ed.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return rq(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");let t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},n=new sU;return n.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,n),this.worker.postMessage(i),n.promise})}handleEncryptedData(e,t,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");let r=crypto.randomUUID(),a=new sU;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage({kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:n}}),a.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");this.worker.postMessage({kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}})}postKey(e){var t;let{key:i,participantIdentity:n,keyIndex:r}=e;if(!this.worker)throw Error("could not set key, worker is missing");let a={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null==(t=this.room)?void 0:t.localParticipant.identity),key:i,keyIndex:r}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker)this.worker.postMessage({kind:"enable",data:{enabled:e,participantIdentity:t}});else throw ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null==(t=this.room)?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");let 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");this.worker.postMessage({kind:"setSifTrailer",data:{trailer:e}})}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?si(i.mimeType):void 0)}}setupE2EESender(e,t){if(!sW(e)||!t){t||rU.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,n){return rq(this,void 0,void 0,function*(){if(this.worker){if(s0()&&
3!sv())e.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:i,trackId:t,codec:n});else{if(sZ in e&&n)return void this.worker.postMessage({kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}});let r=e.writableStream,a=e.readableStream;if(!r||!a){let t=e.createEncodedStreams();e.writableStream=t.writable,r=t.writable,e.readableStream=t.readable,a=t.readable}let s={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:n,participantIdentity:i,isReuse:sZ in e}};this.worker.postMessage(s,[a,r])}e[sZ]=!0}})}handleSender(e,t,i){var n;if(!(sZ in e)&&this.worker){if(!(null==(n=this.room)?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(s0()&&!sv()){rU.info("initialize script transform");let n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{rU.info("initialize encoded streams");let n=e.createEncodedStreams(),r={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(r,[n.readable,n.writable])}e[sZ]=!0}}}class s2{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new s2),this._instance}addFailedConnectionAttempt(e){var t;let i=sE(new URL(e));if(!i)return;let n=null!=(t=this.failedConnectionAttempts.get(i))?t:0;this.failedConnectionAttempts.set(i,n+1),this.backOffPromises.set(i,su(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(e){let t=new URL(e),i=t&&sE(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),i=t&&sE(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}s2._instance=null;let s3="default";class s6{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new s6),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return rq(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;if((null==(n=s6.userMediaPromiseMap)?void 0:n.size)>0){rU.debug("awaiting getUserMedia promise");try{e?yield s6.userMediaPromiseMap.get(e):yield Promise.all(s6.userMediaPromiseMap.values())}catch(e){rU.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(i&&!(sb()&&t.hasDeviceInUse(e))&&(0===r.filter(t=>t.kind===e).length||r.some(t=>{let i=""===t.label,n=!e||t.kind===e;return i&&n}))){let t=yield navigator.mediaDevices.getUserMedia({video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}});r=yield navigator.mediaDevices.enumerateDevices(),t.getTracks().forEach(e=>{e.stop()})}return t._previousDevices=r,e&&(r=r.filter(t=>t.kind===e)),r}()})}normalizeDeviceId(e,t,i){return rq(this,void 0,void 0,function*(){if(t!==s3)return t;let n=yield this.getDevices(e),r=n.find(e=>e.deviceId===s3);if(!r)return void rU.warn("could not reliably determine default device");let a=n.find(e=>e.deviceId!==s3&&e.groupId===(null!=i?i:r.groupId));return a?null==a?void 0:a.deviceId:void rU.warn("could not reliably determine default device")})}hasDeviceInUse(e){return e?s6.userMediaPromiseMap.has(e):s6.userMediaPromiseMap.size>0}}s6.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],s6.userMediaPromiseMap=new Map,(M=eg||(eg={}))[M.WAITING=0]="WAITING",M[M.RUNNING=1]="RUNNING",M[M.COMPLETED=2]="COMPLETED";class s4{constructor(){this.pendingTasks=new Map,this.taskMutex=new tg,this.nextTaskIndex=0}run(e){return rq(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:eg.WAITING};this.pendingTasks.set(t.id,t);let i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=eg.RUNNING,yield e()}finally{t.status=eg.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return rq(this,void 0,void 0,function*(){return this.run(()=>rq(this,void 0,void 0,function*(){}))})}
3snapshot(){return Array.from(this.pendingTasks.values())}}class s5{get readyState(){return this.ws.readyState}constructor(e){var t,i;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null==(t=n.signal)?void 0:t.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,null!=(i=n.protocols)?i:[]);r.binaryType="arraybuffer",this.ws=r;const a=function(){let{closeCode:e,reason:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return r.close(e,t)};this.opened=new Promise((e,t)=>{r.onopen=()=>{e({readable:new ReadableStream({start(e){r.onmessage=t=>{let{data:i}=t;return e.enqueue(i)},r.onerror=t=>e.error(t)},cancel:a}),writable:new WritableStream({write(e){r.send(e)},abort(){r.close()},close:a}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",t)},r.addEventListener("error",t)}),this.closed=new Promise((e,t)=>{let i=()=>rq(this,void 0,void 0,function*(){let i=new Promise(e=>{r.readyState===WebSocket.CLOSED||r.addEventListener("close",t=>{e(t)},{once:!0})}),n=yield Promise.race([su(250),i]);n?e(n):t(Error("Encountered unspecified websocket error without a timely close event"))});r.onclose=t=>{let{code:n,reason:a}=t;e({closeCode:n,reason:a}),r.removeEventListener("error",i)},r.addEventListener("error",i)}),n.signal&&(n.signal.onabort=()=>r.close()),this.close=a}}let s8=["syncState","trickle","offer","answer","simulate","leave"];(A=ef||(ef={}))[A.CONNECTING=0]="CONNECTING",A[A.CONNECTED=1]="CONNECTED",A[A.RECONNECTING=2]="RECONNECTING",A[A.DISCONNECTING=3]="DISCONNECTING",A[A.DISCONNECTED=4]="DISCONNECTED";class s9{get currentState(){return this.state}get isDisconnected(){return this.state===ef.DISCONNECTING||this.state===ef.DISCONNECTED}get isEstablishingConnection(){return this.state===ef.CONNECTING||this.state===ef.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){var e;let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.rtt=0,this.state=ef.DISCONNECTED,this.log=rU,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=rj(null!=(e=i.loggerName)?e:X.Signal),this.loggerContextCb=i.loggerContextCb,this.useJSON=t,this.requestQueue=new s4,this.queuedRequests=[],this.closingLock=new tg,this.connectionLock=new tg,this.state=ef.DISCONNECTED}get logContext(){var e,t;return null!=(t=null==(e=this.loggerContextCb)?void 0:e.call(this))?t:{}}join(e,t,i,n){return rq(this,void 0,void 0,function*(){return this.state=ef.CONNECTING,this.options=i,yield this.connect(e,t,i,n)})}reconnect(e,t,i,n){return rq(this,void 0,void 0,function*(){return this.options?(this.state=ef.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))):void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)})}connect(e,t,i,n){return rq(this,void 0,void 0,function*(){var r,a,s,o,c,l,d,u;let h,p,m,g,f,v,b=yield this.connectionLock.lock();this.connectOptions=i;let y=(f=new ns({sdk:no.JS,protocol:16,version:"2.16.1"}),sS()&&(f.os=null!=(r=sR())?r:""),f),k=i.singlePeerConnection?(a=t,s=y,o=i,(h=new URLSearchParams).set("access_token",a),p=new rx({clientInfo:s,connectionSettings:new rI({autoSubscribe:!!o.autoSubscribe,adaptiveStream:!!o.adaptiveStream}),reconnect:!!o.reconnect,participantSid:o.sid?o.sid:void 0}),o.reconnectReason&&(p.reconnectReason=o.reconnectReason),m=new rO({joinRequest:p.toBinary()}),h.set("join_request",btoa(new TextDecoder("utf-8").decode(m.toBinary()))),h):(c=t,l=y,d=i,(g=new URLSearchParams).set("access_token",c),d.reconnect&&(g.set("reconnect","1"),d.sid&&g.set("sid",d.sid)),g.set("auto_subscribe",d.autoSubscribe?"1":"0"),g.set("sdk",sS()?"reactnative":"js"),g.set("version",l.version),g.set("protocol",l.protocol.toString()),l.deviceModel&&g.set("device_model",l.deviceModel),l.os&&g.set("os",l.os),l.osVersion&&g.set("os_version",l.osVersion),l.browser&&g.set("browser",l.browser),l.browserVersion&&g.set("browser_version",l.browserVersion),d.adaptiveStream&&g.set("adaptive_stream","1"),d.reconnectReason&&g.set("reconnect_reason",d.reconnectReason.toString()),(null==(u=navigator.connection)?void 0:u.type)&&g.set("network",navigator.connection.type),g),T=(v=new
3URL(e.startsWith("http")?e.replace(/^(http)/,"ws"):e),k.forEach((e,t)=>{v.searchParams.set(t,e)}),sX(v,"rtc")),S=sX(new URL(sF(T)),"validate");return new Promise((e,t)=>rq(this,void 0,void 0,function*(){var r,a;try{let s=!1,o=e=>rq(this,void 0,void 0,function*(){if(s)return;s=!0;let i=e instanceof Event?e.currentTarget:e,n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(e instanceof AbortSignal))return t;let i=e.reason;switch(typeof i){case"string":return i;case"object":return i instanceof Error?i.message:t;default:return"toString"in i?i.toString():t}}(i,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(n)).catch(e=>{this.log.error(e),this.close()}):this.close(),c(),t(aV.cancelled(n))});null==n||n.addEventListener("abort",o);let c=()=>{clearTimeout(l),null==n||n.removeEventListener("abort",o)},l=setTimeout(()=>{o(aV.timeout("room connection has timed out (signal)"))},i.websocketTimeout),d=(e,t)=>{this.handleSignalConnected(e,l,t)},u=new URL(T);u.searchParams.has("access_token")&&u.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(u),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new s5(T);try{this.ws.closed.then(e=>{var i;this.isEstablishingConnection&&t(aV.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),1e3!==e.closeCode&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state})),this.state===ef.CONNECTED&&this.handleOnClose(null!=(i=e.reason)?i:"Unexpected WS error"))}).catch(e=>{this.isEstablishingConnection&&t(aV.internal("Websocket error during a (re)connection attempt: ".concat(e)))});let n=yield this.ws.opened.catch(e=>rq(this,void 0,void 0,function*(){if(this.state!==ef.CONNECTED){this.state=ef.DISCONNECTED,clearTimeout(l);let i=yield this.handleConnectionError(e,S);t(i);return}this.handleWSError(e),t(e)}));if(clearTimeout(l),!n)return;let s=n.readable.getReader();this.streamWriter=n.writable.getWriter();let o=yield s.read();if(s.releaseLock(),!o.value)throw aV.internal("no message received as first message");let c=sY(o.value),u=this.validateFirstMessage(c,null!=(r=i.reconnect)&&r);if(!u.isValid)return void t(u.error);(null==(a=c.message)?void 0:a.case)==="join"&&(this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})));let h=u.shouldProcessFirstMessage?c:void 0;d(n,h),e(u.response)}catch(e){t(e)}finally{c()}}finally{b()}}))})}startReadingLoop(e,t){return rq(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield su(this.signalLatency));let{done:t,value:i}=yield e.read();if(t)break;let n=sY(i);this.handleSignalResponse(n)}})}close(){return rq(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){if([ef.DISCONNECTING||ef.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");let n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=ef.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});let t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,su(250)])}}catch(t){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=ef.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:oe(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:oe(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new nQ({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new nX({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return rq(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){let r=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new rt({requestId:r,metadata:e,name:t,attributes:n}
vendor: 4,207 bytes, line 3
3)}),r}()})}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,t){return this.sendRequest({case:"updateLayers",value:new re({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new rm({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:tA.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new rT({timestamp:tA.parse(Date.now()),rtt:tA.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new n5({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new n9({reason:iL.CLIENT_INITIATED,action:n7.DISCONNECT})})}sendRequest(e){return rq(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){let n;if(!i&&(n=s8.indexOf(e.case)>=0,rU.trace("request allowed to bypass queue:",{canPass:n,req:e}),!n)&&t.state===ef.RECONNECTING)return void t.queuedRequests.push(()=>rq(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield su(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);let r=new nz({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){var t,i;let n=e.message;if(void 0==n)return void this.log.debug("received unsupported message",this.logContext);let r=!1;if("answer"===n.case){let e=s7(n.value);this.onAnswer&&this.onAnswer(e,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){let e=s7(n.value);this.onOffer&&this.onOffer(e,n.value.id,n.value.midToTrackId)}else if("trickle"===n.case){let e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!=(t=n.value.participants)?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!=(i=n.value.speakers)?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):"mediaSectionsRequirement"===n.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement
3(n.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return rq(this,void 0,void 0,function*(){if(this.state===ef.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){(this.clearPingTimeout(),this.pingTimeoutDuration)?this.pingTimeout=aY.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&aY.clearTimeout(this.pingTimeout)}startPingInterval(){(this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration)?(this.log.debug("start ping interval",this.logContext),this.pingInterval=aY.setInterval(()=>{this.sendPing()},1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&aY.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=ef.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,n,r,a,s;if((null==(i=e.message)?void 0:i.case)==="join")return{isValid:!0,response:e.message.value};if(this.state===ef.RECONNECTING&&(null==(n=e.message)?void 0:n.case)!=="leave")if((null==(r=e.message)?void 0:r.case)==="reconnect")return{isValid:!0,response:e.message.value};else return this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0};return this.isEstablishingConnection&&(null==(a=e.message)?void 0:a.case)==="leave"?{isValid:!1,error:aV.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:aV.internal("Unexpected first message")}:{isValid:!1,error:aV.internal("did not receive join response, got ".concat(null==(s=e.message)?void 0:s.case," instead"))}}handleConnectionError(e,t){return rq(this,void 0,void 0,function*(){try{let i=yield fetch(t);if(i.status.toFixed(0).startsWith("4")){let e=yield i.text();return aV.notAllowed(e,i.status)}if(e instanceof aV)return e;return aV.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(e){return e instanceof aV?e:aV.serverUnreachable(e instanceof Error?e.message:"server was not reachable")}})}}function s7(e){let t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function oe(e,t){return new n2({sdp:e.sdp,type:e.type,id:t})}class ot{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;)if(this.buffer[0].sequence<=e)this.pop();else break}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class oi{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();let n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){let t=this._map.get(e);if(t)return t.expiresAt<Date.now()?void this._map.delete(e):t.value}has(e){let t=this._map.get(e);
3return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){for(let[t,i]of(this.cleanup(),this._map.entries()))i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],i=this.asValueMap();for(let[n,r]of i.entries())t.push(e(r,n,i));return t}asValueMap(){let e=new Map;for(let[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var on={},or={},oa={exports:{}};function os(){if(ev)return oa.exports;ev=1;var e=oa.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 null!=e.address?"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 null!=e.subtype?"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 null!=e.sessionConfig?"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 t="candidate:%s %d %s %d %s %d typ %s";return t+=(null!=e.raddr?" raddr %s rport %d":"%v%v")+(null!=e.tcptype?" tcptype %s":"%v"),null!=e.generation&&(t+=" generation %d"),t+=(null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{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 t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{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","max
3MessageSize"],format:function(e){return null!=e.maxMessageSize?"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: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: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"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+((null!=e.id?"id=%s %s":"%v%s")+(null!=e.mediaClockValue?"=%s":"")+(null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":""))}},{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(e).forEach(function(t){e[t].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),oa.exports}var oo=function(){if(eT)return on;eT=1;var e=function(){var e,t,i,n,r,a;return eb?or:(eb=1,e=function(e){return String(Number(e))===e?Number(e):e},t=function(t,i,n,r){if(r&&!n)i[r]=e(t[1]);else for(var a=0;a<n.length;a+=1)null!=t[a+1]&&(i[n[a]]=e(t[a+1]))},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var a=e.push?{}:r?i[e.name]:i;t(n.match(e.reg),a,e.names,e.name),e.push&&i[e.push].push(a)},n=os(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/),or.parse=function(e){var t={},a=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach(function(e){var t=e[0],r=e.slice(2);"m"===t&&(a.push({rtp:[],fmtp:[]}),s=a[a.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var c=n[t][o];if(c.reg.test(r))return i(c,s,r)}}),t.media=a,t},a=function(t,i){var n=i.split(/=(.+)/,2);return 2===n.length?t[n[0]]=e(n[1]):1===n.length&&i.length>1&&(t[n[0]]=void 0),t},or.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},or.parseFmtpConfig=or.parseParams,or.parsePayloads=function(e){return e.toString().split(" ").map(Number)},or.parseRemoteCandidates=function(t){for(var i=[],n=t.split(" ").map(e),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},or.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(a,{})})},or.parseSimulcastStreamList=function(t){return t.split(";").map(function(t){return t.split(",").map(function(t){var i,n=!1;return"~"!==t[0]?i=e(t):(i=e(t.substring(1,t.length)),n=!0),{scid:i,paused:n}})})},or)}(),t=function(){if(ek)return ey;ek=1;var e=os(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,r=n.length;return e.replace(t,function(e){if(i>=r)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}})},n=function(e,t,n){var r=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var a=0;a<t.names.length;a+=1){var s=t.names[a];t.name?r.push(n[t.name][s]):r.push(n[t.names[a]])}else r.push(n[t.name]);return i.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];return ey=function(t,i){i=i||{}
3,null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var s=i.outerOrder||r,o=i.innerOrder||a,c=[];return s.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})}),t.media.forEach(function(t){c.push(n("m",e.m[0],t)),o.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})})}),c.join("\r\n")+"\r\n"}}();return on.grammar=os(),on.write=t,on.parse=e.parse,on.parseParams=e.parseParams,on.parseFmtpConfig=e.parseFmtpConfig,on.parsePayloads=e.parsePayloads,on.parseRemoteCandidates=e.parseRemoteCandidates,on.parseImageAttributes=e.parseImageAttributes,on.parseSimulcastStreamList=e.parseSimulcastStreamList,on}();function oc(e,t,i){void 0===t&&(t=50),void 0===i&&(i={});var n,r,a,s=null!=(n=i.isImmediate)&&n,o=null!=(r=i.callback)&&r,c=i.maxWait,l=Date.now(),d=[],u=function(){var i=[].slice.call(arguments),n=this;return new Promise(function(r,u){var h=s&&void 0===a;if(void 0!==a&&clearTimeout(a),a=setTimeout(function(){if(a=void 0,l=Date.now(),!s){var t=e.apply(n,i);o&&o(t),d.forEach(function(e){return(0,e.resolve)(t)}),d=[]}},function(){if(void 0!==c){var e=Date.now()-l;if(e+t>=c)return c-e}return t}()),h){var p=e.apply(n,i);return o&&o(p),r(p)}d.push({resolve:r,reject:u})})};return u.cancel=function(e){void 0!==a&&clearTimeout(a),d.forEach(function(t){return(0,t.reject)(e)}),d=[]},u}let ol="negotiationStarted",od="negotiationComplete",ou="rtpVideoPayloadTypes";class oh extends rH.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.log=rU,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=oc(e=>rq(this,void 0,void 0,function*(){this.emit(ol);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),20),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=rj(null!=(t=i.loggerName)?t:X.PCTransport),this.loggerOptions=i,this.config=e,this._pc=this.createPC(),this.offerLock=new tg}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null==(t=this.onIceCandidate)||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null==(t=this.onIceCandidateError)||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null==(t=this.onIceConnectionStateChange)||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null==(t=this.onSignalingStatechange)||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null==(t=this.onConnectionStateChange)||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null==(t=this.onDataChannel)||t.call(this,e)},e.ontrack=e=>{var t;null==(t=this.onTrack)||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null==(t=(e=this.loggerOptions).loggerContextCb)?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return rq(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return rq(this,void 0,void 0,function*(){var i,n,r;let a;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;if("offer"===e.type){let t,i,a,s,{stereoMids:o,nackMids:c}=(n=e,t=[],i=[],a=oo.parse(null!=(r=n.sdp)?r:""),s=0,a.media.forEac
3h(e=>{var n;let r=og(e.mid);"audio"===e.type&&(e.rtp.some(e=>"opus"===e.codec&&(s=e.payload,!0)),(null==(n=e.rtcpFb)?void 0:n.some(e=>e.payload===s&&"nack"===e.type))&&i.push(r),e.fmtp.some(e=>e.payload===s&&(e.config.includes("sprop-stereo=1")&&t.push(r),!0)))}),{stereoMids:t,nackMids:i});this.remoteStereoMids=o,this.remoteNackMids=c}else if("answer"===e.type){let t=oo.parse(null!=(i=e.sdp)?i:"");t.media.forEach(e=>{let t=og(e.mid);"audio"===e.type&&this.trackBitrates.some(i=>{if(!i.transceiver||t!=i.transceiver.mid)return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===i.codec.toUpperCase()&&(n=e.payload,!0)),0===n)return!0;let r=!1;for(let t of e.fmtp)if(t.payload===n){t.config=t.config.split(";").filter(e=>!e.includes("maxaveragebitrate")).join(";"),i.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),r=!0;break}return!r&&i.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0})}),a=oo.write(t)}return yield this.setMungedSDP(e,a,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit
3(od),e.sdp&&oo.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(ou,e.rtp)})),!0})}createAndSendOffer(e){return rq(this,void 0,void 0,function*(){var t;let i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){let t=this._pc.remoteDescription;if((null==e?void 0:e.iceRestart)&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0;return}}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);let i=this.latestOfferId+1;this.latestOfferId=i;let n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));let r=oo.parse(null!=(t=n.sdp)?t:"");if(r.media.forEach(e=>{om(e),"audio"===e.type?op(e,["all"],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i||(sm(t.codec)&&!sb()&&this.ensureVideoDDExtensionForSVC(e,r),!sm(t.codec)))return!0;let n=Math.round(.7*t.maxbr);for(let t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));yield this.setMungedSDP(n,oo.write(r)),this.onOffer(n,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return rq(this,void 0,void 0,function*(){var e;let t=yield this.pc.createAnswer(),i=oo.parse(null!=(e=t.sdp)?e:"");return i.media.forEach(e=>{om(e),"audio"===e.type&&op(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,oo.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new az("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new az("PC closed, cannot configure");return null==(t=this._pc)?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null==(e=this._pc)?void 0:e.removeTrack)}removeTrack(e){var t;return null==(t=this._pc)?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.connectionState)?t:"closed"}getICEConnectionState(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.iceConnectionState)?t:"closed"}getSignallingState(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.signalingState)?t:"closed"}getTransceivers(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.getTransceivers())?t:[]}getSenders(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.getSenders())?t:[]}getLocalDescription(){var e;return null==(e=this._pc)?void 0:e.localDescription}getRemoteDescription(){var e;return null==(e=this.pc)?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return rq(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="",i=new Map,n=new Map;if((yield this._pc.getStats()).forEach(e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}}),""===t)return;let r=null==(e=i.get(t))?void 0:e.remoteCandidateId;if(void 0!==r)return n.get(r)})}setMungedSDP(e,t,i){return rq(this,void 0,void 0,function*(){if(t){let n=e.sdp;e.sdp=t;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(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let t="unknown error";r instanceof Error?t=r.message:"string"==typeof r&&(t=r);let n={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(n.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:n})),new aK(t)}})}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null==(i=e.ext)?void 0:i.some(e=>e.uri===sd))){if(0===this.ddExtID){let e=0;
3t.media.forEach(t=>{var i;"video"===t.type&&(null==(i=t.ext)||i.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}null==(n=e.ext)||n.push({value:this.ddExtID,uri:sd})}}}function op(e,t,i){let n=og(e.mid),r=0;e.rtp.some(e=>"opus"===e.codec&&(r=e.payload,!0)),r>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(n)&&!e.rtcpFb.some(e=>e.payload===r&&"nack"===e.type)&&e.rtcpFb.push({payload:r,type:"nack"}),(t.includes(n)||1===t.length&&"all"===t[0])&&e.fmtp.some(e=>e.payload===r&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function om(e){if(e.connection){let t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function og(e){return"number"==typeof e?e.toFixed(0):e}let of={audioPreset:ec.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:a4.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!0,preConnectBuffer:!1},ov={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ob={deviceId:{ideal:"default"},resolution:a3.h720.resolution},oy={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:rB}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!1},ok={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};(N=eS||(eS={}))[N.NEW=0]="NEW",N[N.CONNECTING=1]="CONNECTING",N[N.CONNECTED=2]="CONNECTED",N[N.FAILED=3]="FAILED",N[N.CLOSING=4]="CLOSING",N[N.CLOSED=5]="CLOSED";class oT{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=ok.peerConnectionTimeout,this.log=rU,this.updateState=()=>{var e,t;let i=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>"connected"===e)?this.state=eS.CONNECTED:n.some(e=>"failed"===e)?this.state=eS.FAILED:n.some(e=>"connecting"===e)?this.state=eS.CONNECTING:n.every(e=>"closed"===e)?this.state=eS.CLOSED:n.some(e=>"closed"===e)?this.state=eS.CLOSING:n.every(e=>"new"===e)&&(this.state=eS.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(eS[i]," to ").concat(eS[this.state]),this.logContext),null==(e=this.onStateChange)||e.call(this,this.state,this.publisher.getConnectionState(),null==(t=this.subscriber)?void 0:t.getConnectionState()))},this.log=rj(null!=(n=i.loggerName)?n:X.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new oh(e,i),"publisher-only"!==t&&(this.subscriber=new oh(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;null==(t=this.onIceCandidate)||t.call(this,e,nW.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null==(t=this.onDataChannel)||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null==(t=this.onTrack)||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null==(t=this.onIceCandidate)||t.call(this,e,nW.PUBLISHER)},this.publisher.onTrack=e=>{var t;null==(t=this.onTrack)||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null==(i=this.onPublisherOffer)||i.call(this,e,t)},this.state=eS.NEW,this.connectionLock=new tg,this.remoteOfferLock=new tg}get logContext(){var e,t;return Object.assign({},null==(t=(e=this.loggerOptions).loggerContextCb)?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return rq(this,void 0,void 0,function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),null==(e=this.subscriber)?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return rq(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return rq(this,void 0,void 0,function*(){var i;t===nW.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null==(i=this.subscriber)?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return rq(this,void 0,void 0,function*(){var i,n,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null==(i=this.subscriber)?void 0:i.getSignallingState().toString()}));let a=yield this.remoteOfferLock.lock();try{if(!(yield null==(n=this.subscriber)?void 0:n.setRemoteDescription(e,t)))return;return yield null==(r=this.subscriber)?void 0:r.createAndSetAnswer()}finally{a()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),null==(i=this.subscriber)||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return rq(this,void 0,void 0,function*(){var i;let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null==(i=this.requiredTransports)?void 0:i.map(i=>
3this.ensureTransportConnected(i,e,t)))}finally{n()}})}negotiate(e){return rq(this,void 0,void 0,function*(){return new Promise((t,i)=>rq(this,void 0,void 0,function*(){let n=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout);e.signal.addEventListener("abort",()=>{clearTimeout(n),i("negotiation aborted")}),this.publisher.once(ol,()=>{e.signal.aborted||this.publisher.once(od,()=>{clearTimeout(n),t()})}),yield this.publisher.negotiate(e=>{clearTimeout(n),i(e)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){let t=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e);return null==t?void 0:t.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===nW.PUBLISHER||e===nW.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return rq(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise((e,r)=>rq(i,void 0,void 0,function*(){let i=()=>{this.log.warn("abort transport connection",this.logContext),aY.clearTimeout(a),r(aV.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);let a=aY.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",i),r(aV.internal("could not establish pc connection"))},n);for(;this.state!==eS.CONNECTED;)if(yield su(50),null==t?void 0:t.signal.aborted)return void r(aV.cancelled("room connection has been cancelled"));aY.clearTimeout(a),null==t||t.signal.removeEventListener("abort",i),e()}))}()})}}class oS{static fetchRegionSettings(e,t,i){return rq(this,void 0,void 0,function*(){let n=yield oS.fetchLock.lock();try{var r;let n=yield fetch("".concat((r=e,"".concat(r.protocol.replace("ws","http"),"//").concat(r.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(n.ok){let e=function(e){var t;let i=e.get("Cache-Control");if(i){let e=null==(t=i.match(/(?:^|[,\s])max-age=(\d+)/))?void 0:t[1];if(e)return parseInt(e,10)}}(n.headers);return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:e?1e3*e:5e3}}if(401===n.status)throw aV.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status);throw aV.internal("Could not fetch region settings: ".concat(n.statusText))}catch(e){if(e instanceof aV)throw e;if(null==i?void 0:i.aborted)throw aV.cancelled("Region fetching was aborted");throw aV.serverUnreachable("Could not fetch region settings, ".concat(e instanceof Error?"".concat(e.name,": ").concat(e.message):e))}finally{n()}})}static scheduleRefetch(e,t,i){return rq(this,void 0,void 0,function*(){clearTimeout(oS.settingsTimeouts.get(e.hostname)),oS.settingsTimeouts.set(e.hostname,setTimeout(()=>rq(this,void 0,void 0,function*(){try{let i=yield oS.fetchRegionSettings(e,t);oS.updateCachedRegionSettings(e,t,i)}catch(n){if(n instanceof aV&&n.reason===ee.NotAllowed)return void rU.debug("token is not valid, cancelling auto region refresh");rU.debug("auto refetching of region settings failed",{error:n}),oS.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){oS.cache.set(e.hostname,i),oS.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){let t=oS.settingsTimeouts.get(e);t&&(clearTimeout(t),oS.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=oS.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{let t=oS.connectionTrackers.get(e);t&&0===t.connectionCount&&(rU.debug("stopping region refetch after disconnect delay",{hostname:e}),oS.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)},3e4))}static cancelCleanup(e){let t=oS.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){let e=this.serverUrl.hostname,t=oS.connectionTrackers.get(e);t||(t={connectionCount:0},oS.connectionTrackers.set(e,t)),t.connectionCount++,oS.cancelCleanup(e)}notifyDisconnected(){let e=this.serverUrl.hostname,t=oS.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&oS.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return sC(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return rq(this,void 0,void 0,function*(){return oS.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return rq(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");
3let t=oS.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),oS.updateCachedRegionSettings(this.serverUrl,this.token,t));let i=t.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(!(i.length>0))return null;{let e=i[0];return this.attemptedRegions.push(e),rU.debug("next region: ".concat(e.region)),e.url}})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){oS.updateCachedRegionSettings(this.serverUrl,this.token,e)}}oS.cache=new Map,oS.settingsTimeouts=new Map,oS.connectionTrackers=new Map,oS.fetchLock=new tg;class oC extends Error{constructor(e,t,i){super(t),this.code=e,this.message=ow(t,oC.MAX_MESSAGE_BYTES),this.data=i?ow(i,oC.MAX_DATA_BYTES):void 0}static fromProto(e){return new oC(e.code,e.message,e.data)}toProto(){return new ni({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new oC(oC.ErrorCode[e],oC.ErrorMessage[e],t)}}function oE(e){return new TextEncoder().encode(e).length}function ow(e,t){if(oE(e)<=t)return e;let i=0,n=e.length,r=new TextEncoder;for(;i<n;){let a=Math.floor((i+n+1)/2);r.encode(e.slice(0,a)).length<=t?i=a:n=a-1}return e.slice(0,i)}function oR(e,t){let i,n;return t?("bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp)?0:(i-n)*8e3/(e.timestamp-t.timestamp):0}oC.MAX_MESSAGE_BYTES=256,oC.MAX_DATA_BYTES=15360,oC.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},oC.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"};let oP="u">typeof MediaRecorder,o_=oP?MediaRecorder:class{constructor(){throw Error("MediaRecorder is not available in this environment")}};class oI extends o_{constructor(e,t){let i,n;if(!oP)throw Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);const r=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",r),this.removeEventListener("error",a),null==n||n.close(),n=void 0},a=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",r),this.removeEventListener("error",a),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>rq(this,void 0,void 0,function*(){let i;if(t.data.arrayBuffer)i=new Uint8Array((yield t.data.arrayBuffer()));else if(t.data.byteArray)i=t.data.byteArray;else throw Error("no data available!");void 0!==n&&e.enqueue(i)}),this.addEventListener("dataavailable",i)},cancel:()=>{r()}}),this.addEventListener("stop",r),this.addEventListener("error",a)}}class ox extends so{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4?arguments[4]:void 0;super(e,t,r),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=oc(()=>rq(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>rq(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>
3{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(es.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new tg,this.pauseUpstreamLock=new tg,this.trackChangeLock=new tg,this.trackChangeLock.lock().then(t=>rq(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==so.Kind.Video)return;let{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!=(t=null==(e=this.processor)?void 0:e.processedTrack)?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return rq(this,void 0,void 0,function*(){var i;let n;if(e!==this._mediaStreamTrack||t){if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{sl(this._mediaStreamTrack,e)}),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()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(sc(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}this.sender&&(null==(i=this.sender.transport)?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{sc(null!=n?n:e,t)}))}})}waitForDimensions(){return rq(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===so.Kind.Audio)throw Error("cannot get dimensions for audio tracks");(null==(i=aU())?void 0:i.os)==="iOS"&&(yield su(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield su(50)}throw new aH("unable to get track dimensions after timeout")}()})}setDeviceId(e){return rq(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===sj(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),sj(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return rq(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){if(e.source===so.Source.ScreenShare)return;let{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),r=e.kind===so.Kind.Audio?"audioinput":"videoinput";return t?s6.getInstance().normalizeDeviceId(r,i,n):i}()})}mute(){return rq(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return rq(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return rq(this,void 0,void 0,function*(){let i=yield this.trackChangeLock.lock();try{let i,n;if(!this.sender)throw new aH("unable to replace an unpublished track");return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return rq(this,void 0,void 0,function*(){this.manuallyStopped=!1;let t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);let{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,n=Object.getOwnPropertySymbols(e);r<n.length;r++)0>t.indexOf(n[r])&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]]);return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));let r={audio:!1,video:!1};this.kind===so.Kind.Video?r.video=!t&&!i||{deviceId:t,facingMode:i}:r.audio=!t||Object.assign({deviceId:t}
3,n),this.attachedElements.forEach(e=>{sl(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();let a=(yield navigator.mediaDevices.getUserMedia(r)).getTracks()[0];return this.kind===so.Kind.Video&&(yield a.applyConstraints(n)),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(es.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}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?es.Muted:es.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return rq(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),sk()&&(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),null==(e=this.processor)||e.destroy(),this.processor=void 0}pauseUpstream(){return rq(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(es.UpstreamPaused,this);let t=aU();if((null==t?void 0:t.name)==="Safari"&&0>s_(t.version,"12.0"))throw new aW("pauseUpstream is not supported on Safari < 12.");(null==(e=this.sender.transport)?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return rq(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(es.UpstreamResumed,this),(null==(e=this.sender.transport)?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return rq(this,void 0,void 0,function*(){var e;if(null==(e=this.sender)?void 0:e.getStats)return yield this.sender.getStats()})}setProcessor(e){return rq(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;let r=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);let r=document.createElement(t.kind),a={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(a),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(sc(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&i&&(sl(t._mediaStreamTrack,e),sc(t.processor.processedTrack,e));yield null==(n=t.sender)?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(es.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return rq(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){let i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}}()})}internalStopProcessor(){return rq(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null==(i=e.processor.processedTrack)||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null==(n=e.processorElement)||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(es.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(!oP)return void this.log.warn("MediaRecorder is not available, cannot start prec
3onnect buffer",this.logContext);if(this.localTrackRecorder)return void this.log.warn("preconnect buffer already started");{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new oI(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},1e4)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null==(e=this.localTrackRecorder)?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null==(e=this.localTrackRecorder)?void 0:e.mimeType}}class oO extends ox{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,so.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>rq(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=oR(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(es.AudioTrackFeatureUpdate,this,iF.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(es.AudioTrackFeatureUpdate,this,iF.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return rq(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source===so.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return rq(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;let t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==sj(this._constraints.deviceId);return this.source===so.Source.Microphone&&(this.stopOnMute||"ended"===this._mediaStreamTrack.readyState||t)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return rq(this,void 0,void 0,function*(){let t;if(e){let i=a9({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)})}restart(e){let t=Object.create(null,{restart:{get:()=>super.restart}});return rq(this,void 0,void 0,function*(){let i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){!sT()||this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}setProcessor(e){return rq(this,void 0,void 0,function*(){var t;let i=yield this.trackChangeLock.lock();try{if(!sS()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());let i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null==(t=this.sender)?void 0:t.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
3(es.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return rq(this,void 0,void 0,function*(){var e;let t;if(null==(e=this.sender)?void 0:e.getStats)return(yield this.sender.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return rq(this,void 0,void 0,function*(){let e=yield a7(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(es.AudioSilenceDetected)),e})}}let oD=Object.values(a3),oM=Object.values(a6),oA=Object.values(a4),oN=[a3.h180,a3.h360],oL=[a6.h180,a6.h360],oU=["q","h","f"];function oj(e,t,i,n){var r,a,s;let o,c=null==n?void 0:n.videoEncoding;e&&(c=null==n?void 0:n.screenShareEncoding);let l=null==n?void 0:n.simulcast,d=null==n?void 0:n.scalabilityMode,u=null==n?void 0:n.videoCodec;if(!c&&!l&&!d||!t||!i)return[{}];c||(c=function(e,t,i,n){let r=function(e,t,i){if(e)return oA;let n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?oD:oM}(e,t,i),{encoding:a}=r[0],s=Math.max(t,i);for(let e=0;e<r.length;e+=1){let t=r[e];if(a=t.encoding,t.width>=s)break}if(n)switch(n){case"av1":case"h265":(a=Object.assign({},a)).maxBitrate=.7*a.maxBitrate;break;case"vp9":(a=Object.assign({},a)).maxBitrate=.85*a.maxBitrate}return a}(e,t,i,u),rU.debug("using video encoding",c));let h=c.maxFramerate,p=new aZ(t,i,c.maxBitrate,c.maxFramerate,c.priority);if(d&&sm(u)){let e=new oV(d),t=[];if(e.spatial>3)throw Error("unsupported scalabilityMode: ".concat(d));let i=aU();if(sy()||sS()||(null==i?void 0:i.name)==="Chrome"&&0>s_(null==i?void 0:i.version,"113")){let n="h"==e.suffix?2:3,r=((s=i)||(s=aU()),(null==s?void 0:s.name)==="Safari"&&s_(s.version,"18.3")>0||(null==s?void 0:s.os)==="iOS"&&!!(null==s?void 0:s.osVersion)&&s_(s.osVersion,"18.3")>0);for(let i=0;i<e.spatial;i+=1)t.push({rid:oU[2-i],maxBitrate:c.maxBitrate/Math.pow(n,i),maxFramerate:p.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,i):void 0});t[0].scalabilityMode=d}else t.push({maxBitrate:c.maxBitrate,maxFramerate:p.encoding.maxFramerate,scalabilityMode:d});return p.encoding.priority&&(t[0].priority=p.encoding.priority,t[0].networkPriority=p.encoding.priority),rU.debug("using svc encoding",{encodings:t}),t}if(!l)return[c];let m=[];if((m=e?null!=(r=oq(null==n?void 0:n.screenShareSimulcastLayers))?r:oF(e,p):null!=(a=oq(null==n?void 0:n.videoSimulcastLayers))?a:oF(e,p)).length>0){let e=m[0];m.length>1&&([,o]=m);let n=Math.max(t,i);if(n>=960&&o)return oB(t,i,[e,o,p],h);if(n>=480)return oB(t,i,[e,p],h)}return oB(t,i,[p])}function oF(e,t){if(e)return[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(e=>{var i,n;return new aZ(Math.floor(t.width/e.scaleResolutionDownBy),Math.floor(t.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!=(i=t.encoding.maxFramerate)?i:30)/(null!=(n=e.fps)?n:30))))),e.fps,t.encoding.priority)});let{width:i,height:n}=t,r=i>n?i/n:n/i;return Math.abs(r-16/9)<Math.abs(r-4/3)?oN:oL}function oB(e,t,i,n){let r=[];if(i.forEach((i,a)=>{if(a>=oU.length)return;let s=Math.min(e,t),o={rid:oU[a],scaleResolutionDownBy:Math.max(1,s/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(o.maxFramerate=c);let l=sf()||0===a;i.encoding.priority&&l&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),r.push(o)}),sS()&&"ios"===sR()){let e;r.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;r.forEach(i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,rU.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),rU.info('Setting framerate of encoding "'.concat(null!=(n=i.rid)?n:"",'" to ').concat(e)),i.maxFramerate=e)})}return r}function oq(e){if(e)return e.sort((e,t)=>{let{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0})}class oV{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!=(e=this.suffix
3)?e:"")}}class oW extends ox{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,so.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>rq(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),i=e.some(e=>"cpu"===e.qualityLimitationReason);if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(es.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,i)=>{var n;let r=null==(n=this.prevStats)?void 0:n.get(i);e+=oR(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new tg}get isSimulcast(){return!!this.sender&&!!(this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!sT())return;let i=null==(t=this.sender)?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return rq(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var t,i,n,r,a,s,o=!0,c=rV(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);o=!0)r=s.value,o=!1,yield null==(a=r.sender)?void 0:a.replaceTrack(null)}catch(e){i={error:e}}finally{try{!o&&!t&&(n=c.return)&&(yield n.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return rq(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var t,i,n,r,a,s,o=!0,c=rV(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);o=!0)r=s.value,o=!1,yield null==(a=r.sender)?void 0:a.replaceTrack(r.mediaStreamTrack)}catch(e){i={error:e}}finally{try{!o&&!t&&(n=c.return)&&(yield n.call(c))}finally{if(i)throw i.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return rq(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source!==so.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return rq(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;return this.source!==so.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}setTrackMuted(e){for(let t of(super.setTrackMuted(e),this.simulcastCodecs.values()))t.mediaStreamTrack.enabled=!e}getSenderStats(){return rq(this,void 0,void 0,function*(){var e;if(!(null==(e=this.sender)?void 0:e.getStats))return[];let t=[],i=yield this.sender.getStats();return i.forEach(e=>{var n;if("outbound-rtp"===e.type){let r={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!=(n=e.rid)?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},a=i.get(e.remoteId);a&&(r.jitter=a.jitter,r.packetsLost=a.packetsLost,r.roundTripTime=a.roundTripTime),t.push(r)}}),t.sort((e,t)=>
3{var i,n;return(null!=(i=t.frameWidth)?i:0)-(null!=(n=e.frameWidth)?n:0)}),t})}setPublishingQuality(e){let t=[];for(let i=el.LOW;i<=el.HIGH;i+=1)t.push(new rl({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(sm(this.codec),t)}restartTrack(e){return rq(this,void 0,void 0,function*(){let t;if(e){let i=a9({video:e});"boolean"!=typeof i.video&&(t=i.video)}yield this.restart(t),this.isCpuConstrained=!1;try{for(var i,n,r,a,s,o,c=!0,l=rV(this.simulcastCodecs.values());!(i=(o=yield l.next()).done);c=!0)a=o.value,c=!1,a.sender&&(null==(s=a.sender.transport)?void 0:s.state)!=="closed"&&(a.mediaStreamTrack=this.mediaStreamTrack.clone(),yield a.sender.replaceTrack(a.mediaStreamTrack))}catch(e){n={error:e}}finally{try{!c&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(n)throw n.error}}})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return rq(this,arguments,void 0,function(e){var i=this;let n=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){if(yield t.setProcessor.call(i,e,n),null==(c=i.processor)?void 0:c.processedTrack)try{for(var r,a,s,o,c,l,d,u=!0,h=rV(i.simulcastCodecs.values());!(r=(d=yield h.next()).done);u=!0)o=d.value,u=!1,yield null==(l=o.sender)?void 0:l.replaceTrack(i.processor.processedTrack)}catch(e){a={error:e}}finally{try{!u&&!r&&(s=h.return)&&(yield s.call(h))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return rq(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);let i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){let i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return rq(this,void 0,void 0,function*(){var t,i,n,r,a,s,o;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(sm(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,i=rV(e);!(r=(n=yield i.next()).done);t=!0)if(o=n.value,t=!1,this.codec&&this.codec!==o.codec){let e=this.simulcastCodecs.get(o.codec);if(this.log.debug("try setPublishingCodec for ".concat(o.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:e})),e&&e.sender)e.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(o.codec),this.logContext),yield oH(e.sender,e.encodings,o.qualities,this.senderLock,sm(o.codec),this.log,this.logContext));else for(let e of o.qualities)if(e.enabled){c.push(o.codec);break}}else yield this.setPublishingLayers(sm(o.codec),o.qualities)}catch(e){a={error:e}}finally{try{!t&&!r&&(s=i.return)&&(yield s.call(i))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return rq(this,void 0,void 0,function*(){this.optimizeForPerformance?this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield oH(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))})}prioritizePerformance(){return rq(this,void 0,void 0,function*(){if(!this.sender)throw Error("sender not found");let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!=(i=this.mediaStreamTrack.getSettings().height)?i:360)/360)),scalabilityMode:0===t&&sm(this.codec)?"L1T3":void 0,maxFramerate:15*(0===t),maxBitrate:0===t?e.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return rq(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),sk()&&this.isInBackgroun
3d&&this.source===so.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function oH(e,t,i,n,r,a,s){return rq(this,void 0,void 0,function*(){let o=yield n.lock();a.debug("setPublishingLayersForSender",Object.assign(Object.assign({},s),{sender:e,qualities:i,senderEncodings:t}));try{let n=e.getParameters(),{encodings:o}=n;if(!o)return;if(o.length!==t.length)return void a.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:o,senderEncodings:t}));let c=!1;r&&i.some(e=>e.enabled)&&i.forEach(e=>e.enabled=!0),o.forEach((e,n)=>{var r;let o=null!=(r=e.rid)?r:"";""===o&&(o="q");let l=oG(o),d=i.find(e=>e.quality===l);d&&e.active!==d.enabled&&(c=!0,e.active=d.enabled,a.debug("setting layer ".concat(d.quality," to ").concat(e.active?"enabled":"disabled"),s),sf()&&(d.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(n.encodings=o,a.debug("setting encodings",Object.assign(Object.assign({},s),{encodings:n.encodings})),yield e.setParameters(n))}finally{o()}})}function oG(e){switch(e){case"f":default:return el.HIGH;case"h":return el.MEDIUM;case"q":return el.LOW}}function oz(e,t,i,n){if(!i)return[new iQ({quality:el.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){let n=new oV(i[0].scalabilityMode),r=[],a="h"==n.suffix?1.5:2,s="h"==n.suffix?2:3;for(let o=0;o<n.spatial;o+=1)r.push(new iQ({quality:Math.min(el.HIGH,n.spatial-1)-o,width:Math.ceil(e/Math.pow(a,o)),height:Math.ceil(t/Math.pow(a,o)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(s,o)):0,ssrc:0}));return r}return i.map(i=>{var n,r,a;let s=null!=(n=i.scaleResolutionDownBy)?n:1;return new iQ({quality:oG(null!=(r=i.rid)?r:""),width:Math.ceil(e/s),height:Math.ceil(t/s),bitrate:null!=(a=i.maxBitrate)?a:0,ssrc:0})})}let oK="_lossy",oJ="_reliable",o$="leave-reconnect";(L=eC||(eC={}))[L.New=0]="New",L[L.Connected=1]="Connected",L[L.Disconnected=2]="Disconnected",L[L.Reconnecting=3]="Reconnecting",L[L.Closed=4]="Closed";class oQ extends rH.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=ok.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=eC.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=rU,this.reliableDataSequence=1,this.reliableMessageBuffer=new ot,this.reliableReceivedState=new oi(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>rq(this,[e],void 0,function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===oJ)t.reliableDCSub=i;else{if(i.label!==oK)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()}),this.handleDataMessage=e=>rq(this,void 0,void 0,function*(){var t,i,n,r,a;let s=yield this.dataProcessLock.lock();try{let s;if(e.data instanceof ArrayBuffer)s=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));s=yield e.data.arrayBuffer()}let o=iY.fromBinary(new Uint8Array(s));if(o.sequence>0&&""!==o.participantSid){let e=this.reliableReceivedState.get(o.participantSid);if(e&&o.sequence<=e)return;this.reliableReceivedState.set(o.participantSid,o.sequence)}if((null==(t=o.value)?void 0:t.case)==="speaker")this.emit(ea.ActiveSpeakersUpdate,o.value.value.speakers);else if((null==(i=o.value)?void 0:i.case)==="encryptedPacket"){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up",this.logContext);let e=yield null==(n=this.e2eeManager)?void 0:n.handleEncryptedData(o.value.value.encryptedValue,o.value.value.iv,o.participantIdentity,o.value.value.keyIndex),t=i1.fromBinary(e.payload),i=new iY({value:t.value,participantIdentity:o.participantIdentity,participantSid:o.participantSid});(null==(r=i.value)?void 0:r.case)==="user"&&oX(i,i.value.value),this.emit
3(ea.DataPacketReceived,i,o.value.value.encryptionType)}else(null==(a=o.value)?void 0:a.case)==="user"&&oX(o,o.value.value),this.emit(ea.DataPacketReceived,o,iK.NONE)}finally{s()}}),this.handleDataError=e=>{let t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){let{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{let t=0===e.currentTarget.maxRetransmits?iZ.LOSSY:iZ.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());let i=e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(ea.Disconnected),this.close()},n=Date.now()-this.reconnectStart,r=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null===r?i(n):(e===o$&&(r=0),this.log.debug("reconnecting in ".concat(r,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=aY.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),r))},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===eC.Connected&&e();let i=()=>{this.off(ea.Disconnected,n),e()},n=()=>{this.off(ea.Restarted,i),t()};this.once(ea.Restarted,i),this.once(ea.Disconnected,n)}),this.updateAndEmitDCBufferStatus=e=>{if(e===iZ.RELIABLE){let t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}let t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(ea.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>rq(this,void 0,void 0,function*(){!this.url||(yield fetch(sF(this.url),{method:"HEAD"}).then(e=>e.ok).catch(()=>!1))&&(this.log.info("detected network reconnected"),(this.client.currentState===ef.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===ef.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(iU.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>rq(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(sF(this.url),{method:"HEAD"}),su(4e3).then(()=>Promise.reject())])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=rj(null!=(t=e.loggerName)?t:X.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new s9(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new tg,this.dataProcessLock=new tg,this.dcBufferStatus=new Map([[iZ.LOSSY,!0],[iZ.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(ea.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(ea.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(ea.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(ea.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(ea.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(ea.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(ea.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(ea.SignalRequestResponse,e)}get logContext(){var e,t,i,n,r,a;return{room:null==(t=null==(e=this.latestJoinResponse)?void 0:e.room)?void 0:t.name,roomID:null==(n=null==(i=this.latestJoinResponse)?void 0:i.room)?void 0:n.sid,participant:null==(a=null==(r=this.latestJoinResponse)?void 0:r.participant)?void 0:a.identity,pID:this.participantSid}}join(e,t,i,n){return rq(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();let r=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate().catch(e=>{rU.error(e,this.logContext)}),this.registerOnLineListener(),this.clientConfiguration=r.clientConfiguration,this.emit
3(ea.SignalConnected,r),r}catch(r){if(r instanceof aV&&r.reason===ee.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw r}})}close(){return rq(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed)return void e();try{this._isClosed=!0,this.joinAttempts=0,this.emit(ea.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return rq(this,void 0,void 0,function*(){var e;yield null==(e=this.pcManager)?void 0:e.close(),this.pcManager=void 0;let t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new ot,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 rq(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new aH("a track with the same ID has already been published");return new Promise((t,i)=>{let n=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(aV.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null==(e=this.reliableDCSub)?void 0:e.readyState}getConnectedServerAddress(){return rq(this,void 0,void 0,function*(){var e;return null==(e=this.pcManager)?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return rq(this,void 0,void 0,function*(){var t,i,n;if(this.pcManager&&this.pcManager.currentState!==eS.NEW)return;this.participantSid=null==(t=e.participant)?void 0:t.sid;let r=this.makeRTCConfiguration(e);this.pcManager=new oT(r,this.options.singlePeerConnection?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(ea.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>rq(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===eS.CONNECTED){let t=this.pcState===eC.New;this.pcState=eC.Connected,t&&this.emit(ea.Connected,e)}else t===eS.FAILED&&(this.pcState===eC.Connected||this.pcState===eC.Reconnecting)&&(this.pcState=eC.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?iU.RR_SUBSCRIBER_FAILED:iU.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===ef.RECONNECTING,a=[eS.FAILED,eS.CLOSING,eS.CLOSED].includes(t);r&&a&&!this._isClosed&&this.emit(ea.Offline)}),this.pcManager.onTrack=e=>
3{0!==e.streams.length&&this.emit(ea.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(n=null==(i=e.serverInfo)?void 0:i.protocol)&&n>13||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>rq(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,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>rq(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;let n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null==(t=e.track)?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));let{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(ea.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(ea.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,null==(t=this.regionUrlProvider)||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(ea.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(ea.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null==(t=e.participant)?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(ea.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;let n={direction:"recvonly"};for(let i=0;i<e.numAudios;i++)null==(t=this.pcManager)||t.addPublisherTransceiverOfKind("audio",n);for(let t=0;t<e.numVideos;t++)null==(i=this.pcManager)||i.addPublisherTransceiverOfKind("video",n);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",iU.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:5e3,regionSettings:e.regions})),e.action){case n7.DISCONNECT:this.emit(ea.Disconnected,null==e?void 0:e.reason),this.close();break;case n7.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(o$);break;case n7.RESUME:this.handleDisconnect(o$)}}}makeRTCConfiguration(e){var t;let i=Object.assign({},this.rtcConfig);if((null==(t=this.signalOpts)?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){let t=[];e.iceServers.forEach(e=>{let i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)}),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===iN.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(oK,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(oJ,{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;let e=this.dataChannelForKind(iZ.LOSSY);e&&(e.bufferedAmountLowThreshold=Math.min(Math.max(this.lossyDataStatByterate/10,8192),262144))},1e3))}createSender(e,t,i){return rq(this,void 0,void 0,function*(){if(sh())return yield this.createTransceiverRTCRtpSender(e,t,i);if(sp())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new az("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,n){return rq(this,void 0,void 0,function*(){if(sh())return this.createSimulcastTransceiverSender(e,t,i,n);if(sp())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new az("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return rq(this,void 0,void 0,function*(){if(!this.pcManager)throw new az("publisher is closed");let n=[];e.mediaStream&&n.push(e.mediaStream),sG(e)&&(e.codec=t.videoCodec);let r={direction:"sendonly",streams:n};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,n){return rq(this,void 0,void 0,function*(){if(!this.pcManager)throw new az("publisher is closed");let r={direction:"sendonly"};n&&(r.sendEncodings=n);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return rq(this,void 0,void 0,function*(){if(!this.pcManager)throw new az("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return rq(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed){if(this.attemptingReconnect)return void rU.warn("already attempting reconnect, returning early",this.logContext);((null==(t=this.clientConfiguration)?void 0:t.resumeConnection)===iN.DISABLED||(null!=(n=null==(i=this.pcManager)?void 0:i.currentState)?n:eS.NEW)===eS.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let e=!0;t instanceof az?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),e=!1):t instanceof aX||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",iU.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
3(ea.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return rq(this,void 0,void 0,function*(){var t,i,n;try{let i;if(!this.url||!this.token)throw new az("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(ea.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new aX;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof aV&&e.reason===ee.NotAllowed)throw new az("could not reconnect, token might be expired");throw new aX}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(this.client.setReconnected(),this.emit(ea.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==ef.CONNECTED)throw new aX("Signal connection got severed during reconnect");null==(t=this.regionUrlProvider)||t.resetAttempts(),this.emit(ea.Restarted)}catch(t){let e=yield null==(i=this.regionUrlProvider)?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null==(n=this.regionUrlProvider)||n.resetAttempts(),t}})}resumeConnection(e){return rq(this,void 0,void 0,function*(){var t;let i;if(!this.url||!this.token)throw new az("could not reconnect, url or token not saved");if(!this.pcManager)throw new az("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(ea.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(t){let e="";if(t instanceof Error&&(e=t.message,this.log.error(t.message,Object.assign(Object.assign({},this.logContext),{error:t}))),t instanceof aV&&t.reason===ee.NotAllowed)throw new az("could not reconnect, token might be expired");if(t instanceof aV&&t.reason===ee.LeaveRequest)throw t;throw new aX(e)}
3if(this.emit(ea.SignalResumed),i){let e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),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,Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==ef.CONNECTED)throw new aX("Signal connection got severed during reconnect");this.client.setReconnected(),(null==(t=this.reliableDC)?void 0:t.readyState)==="open"&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(ea.Resumed)})}waitForPCInitialConnection(e,t){return rq(this,void 0,void 0,function*(){if(!this.pcManager)throw new az("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return rq(this,void 0,void 0,function*(){this.pcState=eC.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield su(2e3),!this.pcManager)throw new az("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=eC.Connected}catch(e){throw this.pcState=eC.Disconnected,aV.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,n){return rq(this,void 0,void 0,function*(){let r=new iY({destinationIdentities:[e],kind:iZ.RELIABLE,value:{case:"rpcResponse",value:new nt({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(r,iZ.RELIABLE)})}publishRpcAck(e,t){return rq(this,void 0,void 0,function*(){let i=new iY({destinationIdentities:[e],kind:iZ.RELIABLE,value:{case:"rpcAck",value:new ne({requestId:t})}});yield this.sendDataPacket(i,iZ.RELIABLE)})}sendDataPacket(e,t){return rq(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=function(e){var t,i,n,r,a;if((null==(t=e.value)?void 0:t.case)!=="sipDtmf"&&(null==(i=e.value)?void 0:i.case)!=="metrics"&&(null==(n=e.value)?void 0:n.case)!=="speaker"&&(null==(r=e.value)?void 0:r.case)!=="transcription"&&(null==(a=e.value)?void 0:a.case)!=="encryptedPacket")return new i1({value:e.value})}(e);if(t){let i=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new i0({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}t===iZ.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let i=e.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===iZ.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){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;n.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return rq(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(iZ.RELIABLE);let t=this.dataChannelForKind(iZ.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(iZ.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((t,i)=>rq(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{let n=()=>i("Engine closed");for(this.once(ea.Closing,n);!this.dcBufferStatus.get(e);)yield su(10);this.off(ea.Closing,n),t()}}))}ensureDataTransportConnected(e){return rq(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new az("PC manager is closed");let r=i?t.pcManager.subscriber:t.pcManager.publisher,a=i?"Subscriber":"Publisher";if(!r)throw aV.internal("".concat(a," connection not set"));let s=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),s=!0),s||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(s=!0),s&&t.negotiate().catch(e=>{rU.error(e,t.logContext)});let o=t.dataChannelForKind(e,i);if((null==o?void 0:o.readyState)==="open")return;let c=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<c;){if(r.isICEConnected&&(null==(n=t.dataChannelForKind(e,i))?void 0:n.readyState)==="open")return;yield su(50)}throw aV.internal("could not establish ".concat(a," connection, state: ").concat(r.getICEConnectionState()))}()})}ensurePublisherConnected(e){return rq(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===eS.CONNECTED&&!!this.client.ws&&this.client.ws.readyState!==WebSocket.CLOSED}negotiate(){return rq(this,void 0,void 0,function*(){return new Promise((e,t)=>
3rq(this,void 0,void 0,function*(){if(!this.pcManager)return void t(new aK("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();let i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(ea.Closing,n),this.pcManager.publisher.once(ou,e=>{let t=new Map;e.forEach(e=>{let i=e.codec.toLowerCase();a1.includes(i)&&t.set(e.payload,i)}),this.emit(ea.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(i),e()}catch(e){e instanceof aK&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",iU.RR_UNKNOWN),t(e)}finally{this.off(ea.Closing,n)}}))})}dataChannelForKind(e,t){if(t){if(e===iZ.LOSSY)return this.lossyDCSub;if(e===iZ.RELIABLE)return this.reliableDCSub}else{if(e===iZ.LOSSY)return this.lossyDC;if(e===iZ.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n,r,a;let s;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);let o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=null==(i=this.pcManager.subscriber)?void 0:i.getRemoteDescription(),d=null==(n=this.pcManager.subscriber)?void 0:n.getLocalDescription(),u=null==(a=null==(r=this.signalOpts)?void 0:r.autoSubscribe)||a,h=[],p=[];e.forEach(e=>{e.isDesired!==u&&h.push(e.trackSid),e.isEnabled||p.push(e.trackSid)}),this.client.sendSyncState(new rv({answer:this.options.singlePeerConnection?c?oe({sdp:c.sdp,type:c.type}):void 0:d?oe({sdp:d.sdp,type:d.type}):void 0,offer:this.options.singlePeerConnection?o?oe({sdp:o.sdp,type:o.type}):void 0:l?oe({sdp:l.sdp,type:l.type}):void 0,subscription:new n6({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:(s=[],t.forEach(e=>{void 0!==e.track&&s.push(new n0({cid:e.track.mediaStreamID,track:e.trackInfo}))}),s),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new rb({publisherSid:t,lastSeq:e}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){let e=[],t=(t,i)=>{(null==t?void 0:t.id)!==void 0&&null!==t.id&&e.push(new ry({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(iZ.LOSSY),nW.PUBLISHER),t(this.dataChannelForKind(iZ.RELIABLE),nW.PUBLISHER),t(this.dataChannelForKind(iZ.LOSSY,!0),nW.SUBSCRIBER),t(this.dataChannelForKind(iZ.RELIABLE,!0),nW.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&aY.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){sT()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){sT()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;let i=null==(t=this.pcManager)?void 0:t.getMidForReceiver(e);if(i){let e=Object.entries(this.midToTrackId).find(e=>{let[t]=e;return t===i});if(e)return e[1]}}}function oX(e,t){let i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;let n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}class oY{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(e&&this.bytesReceived<this.totalByteSize)throw new aQ("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),et.Incomplete);else if(this.bytesReceived>this.totalByteSize)throw new aQ("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),et.LengthExceeded)}}constructor(e,t,i,n){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class oZ extends oY{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null==(t=this.onProgress)||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader(),t=new sU,i=null,n=null;if(this.signal){let e=this.signal;n=()=>{var i;null==(i=t.reject)||i.call(t,e.reason)},e.addEventListener("abort",n),i=e}let r=()=>{e.releaseLock(),i&&n&&i.removeEventListener("abort",n),this.signal=void 0};return{next:()=>rq(this,void 0,void 0,function*(){var i,n;try{let{done:r,value:a}=yield Promise.race([e.read(),t.promise,null!=(n=null==(i=this.outOfBandFailureRejectingFuture)?void 0:i.promise)?n:new Promise(()=>{})]);if(r)return this.validateBytesReceived(!0),{done:!0,value:void 0};return this.handleChunkReceived(a),{done:!1,value:a.content}}catch(e){throw r(),e}}),return(){return rq(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return rq(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,r,a;let s=new Set,o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,l=!0,d=rV(o);!(i=(c=yield d.next()).done);l=!0)a=c.value,l=!1,s.add(a)}catch(e){n={error:e}}finally{try{!l&&!i&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}return Array.from(s)}()})}}
3class o0 extends oY{constructor(e,t,i,n){super(e,t,i,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;let i=sq(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null==(t=this.onProgress)||t.call(this,r)}[Symbol.asyncIterator](){let e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0}),i=new sU,n=null,r=null;if(this.signal){let e=this.signal;r=()=>{var t;null==(t=i.reject)||t.call(i,e.reason)},e.addEventListener("abort",r),n=e}let a=()=>{e.releaseLock(),n&&r&&n.removeEventListener("abort",r),this.signal=void 0};return{next:()=>rq(this,void 0,void 0,function*(){var n,r;try{let{done:a,value:s}=yield Promise.race([e.read(),i.promise,null!=(r=null==(n=this.outOfBandFailureRejectingFuture)?void 0:n.promise)?r:new Promise(()=>{})]);if(a)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(s);try{e=t.decode(s.content)}catch(e){throw new aQ("Cannot decode datastream chunk ".concat(s.chunkIndex," as text: ").concat(e),et.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw a(),e}}),return(){return rq(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return rq(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,r,a;let s="",o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,l=!0,d=rV(o);!(i=(c=yield d.next()).done);l=!0)a=c.value,l=!1,s+=a}catch(e){n={error:e}}finally{try{!l&&!i&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}return s}()})}}class o1{constructor(){this.log=rU,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new aQ('A text stream handler for topic "'.concat(e,'" has already been set.'),et.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new aQ('A byte stream handler for topic "'.concat(e,'" has already been set.'),et.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,n,r;let a=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),s=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(a.length>0||s.length>0){let o=new aQ("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),et.AbnormalEnd);for(let[e,n]of s)null==(i=(t=n.outOfBandFailureRejectingFuture).reject)||i.call(t,o),this.byteStreamControllers.delete(e);for(let[e,t]of a)null==(r=(n=t.outOfBandFailureRejectingFuture).reject)||r.call(n,o),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return rq(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return rq(this,void 0,void 0,function*(){var n;if("byteHeader"===e.contentHeader.case){let r,a=this.byteStreamHandlers.get(e.topic);if(!a)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s=new sU;s.promise.catch(e=>{this.log.error(e)});let o={id:e.streamId,name:null!=(n=e.contentHeader.value.name)?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:sq(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(e.streamId))throw new aQ("A data stream read is already in progress for a stream with i
3d ".concat(e.streamId,"."),et.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:s})}});a(new oZ(o,c,sq(e.totalLength),s),{identity:t})}else if("textHeader"===e.contentHeader.case){let n,r=this.textStreamHandlers.get(e.topic);if(!r)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let a=new sU;a.promise.catch(e=>{this.log.error(e)});let s={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},o=new ReadableStream({start:i=>{if(n=i,this.textStreamControllers.has(e.streamId))throw new aQ("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),et.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new o0(s,o,sq(e.totalLength),a),{identity:t})}})}handleStreamChunk(e,t){let i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new aQ("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),et.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new aQ("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),et.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e))}handleStreamTrailer(e,t){let i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new aQ("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),et.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new aQ("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),et.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class o2{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return rq(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null==(e=this.onClose)||e.call(this)})}}class o3 extends o2{}class o6 extends o2{}class o4{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return rq(this,void 0,void 0,function*(){var i;let n=crypto.randomUUID(),r=new TextEncoder().encode(e).byteLength,a=null==(i=null==t?void 0:t.attachments)?void 0:i.map(()=>crypto.randomUUID()),s=Array(a?a.length+1:1).fill(0),o=(e,i)=>{var n;s[i]=e;let r=s.reduce((e,t)=>e+t,0);null==(n=null==t?void 0:t.onProgress)||n.call(t,r)},c=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:a,attributes:null==t?void 0:t.attributes});return yield c.write(e),o(1,0),yield c.close(),(null==t?void 0:t.attachments)&&a&&(yield Promise.all(t.attachments.map((e,i)=>rq(this,void 0,void 0,function*(){return this._sendFile(a[i],e,{topic:t.to
3pic,mimeType:e.type,onProgress:e=>{o(e,i+1)}})})))),c.info})}streamText(e){return rq(this,void 0,void 0,function*(){var t,i,n;let r=null!=(t=null==e?void 0:e.streamId)?t:crypto.randomUUID(),a={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:null!=(i=null==e?void 0:e.topic)?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes,encryptionType:(null==(n=this.engine.e2eeManager)?void 0:n.isDataChannelEncryptionEnabled)?iK.GCM:iK.NONE},s=new ng({streamId:r,mimeType:a.mimeType,topic:a.topic,timestamp:sV(a.timestamp),totalLength:sV(null==e?void 0:e.totalSize),attributes:a.attributes,contentHeader:{case:"textHeader",value:new np({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:(null==e?void 0:e.type)==="update"?nh.UPDATE:nh.CREATE})}}),o=null==e?void 0:e.destinationIdentities,c=new iY({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(c,iZ.RELIABLE);let l=0,d=this.engine,u=new WritableStream({write(e){return rq(this,void 0,void 0,function*(){for(let t of function(e){let t=[],i=new TextEncoder().encode(e);for(;i.length>15e3;){let e=15e3;for(;e>0;){let t=i[e];if(void 0!==t&&(192&t)!=128)break;e--}t.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&t.push(i),t}(e)){let e=new iY({destinationIdentities:o,value:{case:"streamChunk",value:new nf({content:t,streamId:r,chunkIndex:sV(l)})}});yield d.sendDataPacket(e,iZ.RELIABLE),l+=1}})},close(){return rq(this,void 0,void 0,function*(){let e=new iY({destinationIdentities:o,value:{case:"streamTrailer",value:new nv({streamId:r})}});yield d.sendDataPacket(e,iZ.RELIABLE)})},abort(e){console.log("Sink error:",e)}}),h=()=>rq(this,void 0,void 0,function*(){yield p.close()});d.once(ea.Closing,h);let p=new o3(u,a,()=>this.engine.off(ea.Closing,h));return p})}sendFile(e,t){return rq(this,void 0,void 0,function*(){let i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return rq(this,void 0,void 0,function*(){var n;let r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!=(n=null==i?void 0:i.mimeType)?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),a=t.stream().getReader();for(;;){let{done:e,value:t}=yield a.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return rq(this,void 0,void 0,function*(){var t,i,n,r,a,s;let o=null!=(t=null==e?void 0:e.streamId)?t:crypto.randomUUID(),c=null==e?void 0:e.destinationIdentities,l={id:o,mimeType:null!=(i=null==e?void 0:e.mimeType)?i:"application/octet-stream",topic:null!=(n=null==e?void 0:e.topic)?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!=(r=null==e?void 0:e.name)?r:"unknown",encryptionType:(null==(a=this.engine.e2eeManager)?void 0:a.isDataChannelEncryptionEnabled)?iK.GCM:iK.NONE},d=new iY({destinationIdentities:c,value:{case:"streamHeader",value:new ng({totalLength:sV(null!=(s=l.size)?s:0),mimeType:l.mimeType,streamId:o,topic:l.topic,timestamp:sV(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new nm({name:l.name})}})}});yield this.engine.sendDataPacket(d,iZ.RELIABLE);let u=0,h=new tg,p=this.engine,m=this.log;return new o6(new WritableStream({write(e){return rq(this,void 0,void 0,function*(){let t=yield h.lock(),i=0;try{for(;i<e.byteLength;){let t=e.slice(i,i+15e3),n=new iY({destinationIdentities:c,value:{case:"streamChunk",value:new nf({content:t,streamId:o,chunkIndex:sV(u)})}});yield p.sendDataPacket(n,iZ.RELIABLE),u+=1,i+=t.byteLength}}finally{t()}})},close(){return rq(this,void 0,void 0,function*(){let e=new iY({destinationIdentities:c,value:{case:"streamTrailer",value:new nv({streamId:o})}});yield p.sendDataPacket(e,iZ.RELIABLE)})},abort(e){m.error("Sink error:",e)}}),l)})}}class o5 extends so{constructor(e,t,i,n,r){super(e,i,r),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit
3(e?es.Muted:es.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(es.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return rq(this,void 0,void 0,function*(){var e;if(null==(e=this.receiver)?void 0:e.getStats)return yield this.receiver.getStats()})}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;else 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(),2e3)),"u">typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());let i=null==(t=this.receiver)?void 0:t.getSynchronizationSources()[0];if(i){let{timestamp:e,rtpTimestamp:t}=i;
vendor: 5,356 bytes, line 3
3t&&this.rtpTimestamp!==t&&(this.emit(es.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class o8 extends o5{constructor(e,t,i,n,r,a){super(e,t,so.Kind.Audio,i,a),this.monitorReceiver=()=>rq(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=oR(e,this.prevStats)),this.prevStats=e}),this.audioContext=n,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(let i of this.attachedElements)this.audioContext?null==(t=this.gainNode)||t.gain.setTargetAtTime(e,0,.1):i.volume=e;sS()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(sS())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return rq(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(sg(t))return t.setSinkId(e)}))})}attach(e){let t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&sg(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)}),this.audioContext&&t&&(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 t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}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,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{i.connect(e),i=e}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(es.AudioPlaybackFailed,Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(es.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null==(e=this.gainNode)||e.disconnect(),null==(t=this.sourceNode)||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return rq(this,void 0,void 0,function*(){let e;if(this.receiver&&this.receiver.getStats)return(yield this.receiver.getStats()).forEach(t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})}),e})}}class o9 extends o5{constructor(e,t,i,n,r){super(e,t,so.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>rq(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=oR(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=oc(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===so.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?sl(this._mediaStreamTrack,t):sc(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){let t=new o7(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t===e)?(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)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);for(let t of this.elementInfos.filter(t=>t===e))t.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);for(let e of t=super.detach())this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null==(e=this.prevStats)?void 0:e.decoderImplementation}getReceiverStats(){return rq(this,void 0,void 0,function*(){let e;if(!this.receiver||!this.receiver.getStats)return;let t=yield this.receiver.getStats(),i="",n=new Map;return t.forEach(t=>
3{"inbound-rtp"===t.type?(i=t.codecId,e={type:"video",streamId:t.id,framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation}):"codec"===t.type&&n.set(t.id,t)}),e&&""!==i&&n.get(i)&&(e.mimeType=n.get(i).mimeType),e})}stopObservingElement(e){for(let t of this.elementInfos.filter(t=>t.element===e))this.stopObservingElementInfo(t)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return rq(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;let n=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),r=(null==(i=null==(t=this.adaptiveStreamSettings)?void 0:t.pauseVideoInBackground)||!!i)&&this.isInBackground,a=this.elementInfos.some(e=>e.pictureInPicture),s=this.elementInfos.some(e=>e.visible)&&!r||a;if(this.lastVisible!==s||e){if(!s&&Date.now()-n<100)return void aY.setTimeout(()=>{this.updateVisibility()},100);this.lastVisible=s,this.emit(es.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let i=0,n=0,r=this.getPixelDensity();for(let e of this.elementInfos){let t=e.width()*r,a=e.height()*r;t+a>i+n&&(i=t,n=a)}((null==(e=this.lastDimensions)?void 0:e.width)!==i||(null==(t=this.lastDimensions)?void 0:t.height)!==n)&&(this.lastDimensions={width:i,height:n},this.emit(es.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;let t=null==(e=this.adaptiveStreamSettings)?void 0:e.pixelDensity;return"screen"===t?sP():t?t:sP()>2?2:1}}class o7{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=ce(this.element),this.visibilityChangedAt=Date.now(),null==(t=this.handleVisibilityChanged)||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null==(t=null==(e=window.documentPictureInPicture)?void 0:e.window)||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ce(this.element),null==(i=this.handleVisibilityChanged)||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=ce(this.element),null==(e=this.handleVisibilityChanged)||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:ct(e),this.isPiP=sT()&&ce(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=ct(this.element),this.isPiP=ce(this.element),this.element.handleResize=()=>{var e;null==(e=this.handleResize)||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,sA().observe(this.element),sD().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null==(e=window.documentPictureInPicture)||e.addEventListener("enter",this.onEnterPiP),null==(i=null==(t=window.documentPictureInPicture)?void 0:t.window)||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,r;null==(e=sA())||e.unobserve(this.element),null==(t=sD())||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null==(i=window.documentPictureInPicture)||i.removeEventListener("enter",this.onEnterPiP),null==(r=null==(n=window.documentPictureInPicture)?void 0:n.window)||r.removeEventListener("pagehide",this.onLeavePiP)}}function ce(e){var t,i;return document.pictureInPictureElement===e||null!=(t=window.documentPictureInPicture)&&!!t.window&&ct(e,null==(i=window.documentPictureInPicture)?void 0:i.window)}function ct(e,t){let i=t||window,n=e.offsetTop,r=e.offsetLeft,a=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&r<i.pageXOffset+i.innerWidth&&n+s>i.pageYOffset&&r+a>i.pageXOffset&&!o&&"none"!==c}class ci extends rH.EventEmitter{constructor(e,t,i,n){var r;super(),this.metadataMuted=!1,this.encryption=iK.NONE,this.log=rU,this.handleMuted=()=>
3{this.emit(es.Muted)},this.handleUnmuted=()=>{this.emit(es.Unmuted)},this.log=rj(null!=(r=null==n?void 0:n.loggerName)?r:X.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=so.Source.Unknown}setTrack(e){this.track&&(this.track.off(es.Muted,this.handleMuted),this.track.off(es.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(es.Muted,this.handleMuted),e.on(es.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null==(e=this.loggerContextCb)?void 0:e.call(this)),sn(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==iK.NONE}get audioTrack(){if(sH(this.track))return this.track}get videoTrack(){if(sG(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=so.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===so.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}))}}(j=(U=ci||(ci={})).SubscriptionStatus||(U.SubscriptionStatus={})).Desired="desired",j.Subscribed="subscribed",j.Unsubscribed="unsubscribed",(F=U.PermissionStatus||(U.PermissionStatus={})).Allowed="allowed",F.NotAllowed="not_allowed";class cn extends ci{get isUpstreamPaused(){var e;return null==(e=this.track)?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(es.Ended)},this.handleCpuConstrained=()=>{this.track&&sG(this.track)&&this.emit(es.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(es.Ended,this.handleTrackEnded),this.track.off(es.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(es.Ended,this.handleTrackEnded),e.on(es.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 rq(this,void 0,void 0,function*(){var e;return null==(e=this.track)?void 0:e.mute()})}unmute(){return rq(this,void 0,void 0,function*(){var e;return null==(e=this.track)?void 0:e.unmute()})}pauseUpstream(){return rq(this,void 0,void 0,function*(){var e;yield null==(e=this.track)?void 0:e.pauseUpstream()})}resumeUpstream(){return rq(this,void 0,void 0,function*(){var e;yield null==(e=this.track)?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(!sH(this.track))return[];{let t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(iF.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(iF.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(iF.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(iF.TF_STEREO),(null==(e=this.options)?void 0:e.dtx)||i.add(iF.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(iF.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}}}function cr(e,t){return rq(this,void 0,void 0,function*(){null!=e||(e={});let i=!1,{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:a}=sr(e),s=a.audio,o=a.video;if(n&&"object"==typeof a.audio&&(a.audio.processor=n),r&&"object"==typeof a.video&&(a.video.processor=r),e.audio&&"object"==typeof a.audio&&"string"==typeof a.audio.deviceId){let e=a.audio.deviceId;a.audio.deviceId={exact:e},i=!0,s=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:e}})}if(a.video&&"object"==typeof a.video&&"string"==typeof a.video.deviceId){let e=a.video.deviceId;a.video.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},a.video),{deviceId:{ideal:e}})}!0===a.audio?a.audio={deviceId:"default"}:"object"==typeof a.audio&&null!==a.audio&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),!0===a.video?a.video={deviceId:"default"}:"object"!=typeof a.video||a.video.deviceId||(a.video.deviceId="default");let c=a5(a,ov,ob),l=a9(c),d=navigator.mediaDevices.getUserMedia(l);
3a.audio&&(s6.userMediaPromiseMap.set("audioinput",d),d.catch(()=>s6.userMediaPromiseMap.delete("audioinput"))),a.video&&(s6.userMediaPromiseMap.set("videoinput",d),d.catch(()=>s6.userMediaPromiseMap.delete("videoinput")));try{let e=yield d;return yield Promise.all(e.getTracks().map(i=>rq(this,void 0,void 0,function*(){let a,s="audio"===i.kind,o=s?c.audio:c.video;"boolean"!=typeof o&&o||(o={});let d=s?l.audio:l.video;"boolean"!=typeof d&&(a=d);let u=i.getSettings().deviceId;(null==a?void 0:a.deviceId)&&sj(a.deviceId)!==u?a.deviceId=u:a||(a={deviceId:u});let h=function(e,t,i){switch(e.kind){case"audio":return new oO(e,t,!1,void 0,i);case"video":return new oW(e,t,!1,i);default:throw new aH("unsupported track type: ".concat(e.kind))}}(i,a,t);return h.kind===so.Kind.Video?h.source=so.Source.Camera:h.kind===so.Kind.Audio&&(h.source=so.Source.Microphone),h.mediaStream=e,sH(h)&&n?yield h.setProcessor(n):sG(h)&&r&&(yield h.setProcessor(r)),h})))}catch(n){if(!i)throw n;return cr(Object.assign(Object.assign({},e),{audio:s,video:o}),t)}})}(B=eE||(eE={})).Excellent="excellent",B.Good="good",B.Poor="poor",B.Lost="lost",B.Unknown="unknown";class ca extends rH.EventEmitter{get logContext(){var e,t;return Object.assign({},null==(t=null==(e=this.loggerOptions)?void 0:e.loggerContextCb)?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return(null==(e=this.permissions)?void 0:e.agent)||this.kind===iG.AGENT}get isActive(){var e;return(null==(e=this.participantInfo)?void 0:e.state)===iH.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,r,a){var s;let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:iG.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=eE.Unknown,this.log=rU,this.log=rj(null!=(s=null==a?void 0:a.loggerName)?s:X.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=r?r:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(let[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new sU,this.once(er.Active,()=>{var e,t;null==(t=null==(e=this.activeFuture)?void 0:e.resolve)||t.call(e),this.activeFuture=void 0})),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;let t=this.getTrackPublication(so.Source.Camera);return!(null==(e=null==t?void 0:t.isMuted)||e)}get isMicrophoneEnabled(){var e;let t=this.getTrackPublication(so.Source.Microphone);return!(null==(e=null==t?void 0:t.isMuted)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(so.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return(!this.participantInfo||this.participantInfo.sid!==e.sid||!(this.participantInfo.version>e.version))&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===iH.ACTIVE&&(null==(t=this.participantInfo)?void 0:t.state)!==iH.ACTIVE&&this.emit(er.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(er.ParticipantMetadataChanged,i)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(er.ParticipantNameChanged,e)}_setAttributes(e){let t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let a of n)e[a]!==t[a]&&(r[a]=null!=(i=t[a])?i:"");return r}(this.attributes,e);this._attributes=e,Object.keys(t).length>
30&&this.emit(er.AttributesChanged,t)}setPermissions(e){var t,i,n,r,a,s;let o=this.permissions,c=e.canPublish!==(null==(t=this.permissions)?void 0:t.canPublish)||e.canSubscribe!==(null==(i=this.permissions)?void 0:i.canSubscribe)||e.canPublishData!==(null==(n=this.permissions)?void 0:n.canPublishData)||e.hidden!==(null==(r=this.permissions)?void 0:r.hidden)||e.recorder!==(null==(a=this.permissions)?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var i;return e!==(null==(i=this.permissions)?void 0:i.canPublishSources[t])})||e.canSubscribeMetrics!==(null==(s=this.permissions)?void 0:s.canSubscribeMetrics);return this.permissions=e,c&&this.emit(er.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(er.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case iA.EXCELLENT:return eE.Excellent;case iA.GOOD:return eE.Good;case iA.POOR:return eE.Poor;case iA.LOST:return eE.Lost;default:return eE.Unknown}}(e),t!==this._connectionQuality&&this.emit(er.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null==(t=(e=this.activeFuture).reject)||t.call(e,Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>sH(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){switch(e.on(es.Muted,()=>{this.emit(er.TrackMuted,e)}),e.on(es.Unmuted,()=>{this.emit(er.TrackUnmuted,e)}),e.track&&(e.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case so.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case so.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class cs extends ca{constructor(e,t,i,n,r,a){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=iK.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new sU)},this.handleReconnected=()=>{var e,t;null==(t=null==(e=this.reconnectFuture)?void 0:e.resolve)||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,i,n,r,a;this.reconnectFuture&&(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),null==(t=null==(e=this.reconnectFuture)?void 0:e.reject)||t.call(e,Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null==(n=(i=this.signalConnectedFuture).reject)||n.call(i,Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null==(a=null==(r=this.activeAgentFuture)?void 0:r.reject)||a.call(r,Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new sU),null==(i=(t=this.signalConnectedFuture).resolve)||i.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:i,message:n}=e,r=this.pendingSignalRequests.get(t);r&&(i!==rP.OK&&r.reject(new a$(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=oC.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let r=e.value.value;this.handleIncomingRpcAck(r.requestId)}},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(e=>(function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new rp({participantIdentity:null!=(t=e.participantIdentity)?t:"",participantSid:null!=(i=e.participantSid)?i:"",allTracks:null!=(n=e.allowAll)&&n,trackSids:e.allowedTrackSids||[]})})(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{(void 0===t&&(t=!0),e.sid)?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),sn(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),sn(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),sn(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({}
3,this.logContext),sn(t))),this.emit(er.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>rq(this,void 0,void 0,function*(){if(!(null==(o=this.roomOptions)?void 0:o.dynacast))return;let t=this.videoTrackPublications.get(e.trackSid);if(!t)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!t.videoTrack)return;let i=yield t.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var n,r,a,s,o,c,l=!0,d=rV(i);!(n=(c=yield d.next()).done);l=!0)s=c.value,l=!1,a2(s)&&(this.log.debug("publish ".concat(s," for ").concat(t.videoTrack.sid),Object.assign(Object.assign({},this.logContext),sn(t))),yield this.publishAdditionalCodecForTrack(t.videoTrack,s,t.options))}catch(e){r={error:e}}finally{try{!l&&!n&&(a=d.return)&&(yield a.call(d))}finally{if(r)throw r.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>rq(this,void 0,void 0,function*(){if(e.source===so.Source.ScreenShare||e.source===so.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),sn(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(sK(e)||sz(e))try{if(sT())try{let t=yield null==navigator?void 0:navigator.permissions.query({name:e.source===so.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),sn(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),sn(e))),sK(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),sn(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=a}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==iK.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(ea.RemoteMute,(e,t)=>{let i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())}),(null==(t=this.signalConnectedFuture)?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(ea.Connected,this.handleReconnected).on(ea.SignalConnected,this.handleSignalConnected).on(ea.SignalRestarted,this.handleReconnected).on(ea.SignalResumed,this.handleReconnected).on(ea.Restarting,this.handleReconnecting).on(ea.Resuming,this.handleReconnecting).on(ea.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(ea.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(ea.Closing,this.handleClosing).on(ea.SignalRequestResponse,this.handleSignalRequestResponse).on(ea.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return rq(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return rq(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return rq(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return rq(this,arguments,void 0,function(e){var t=this;let{metadata:i,name:n,attributes:r}=e;return function*(){return new Promise((e,a)=>rq(t,void 0,void 0,function*(){var t,s;try{let o=!1,c=yield this.engine.client.sendUpdateLocalMetadata(null!=(t=null!=i?i:this.metadata)?t:"",null!=(s=null!=n?n:this.name)?s:"",r),l=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{a(e),o=!0}
3,values:{name:n,metadata:i,attributes:r}});performance.now()-l<5e3&&!o;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!r||Object.entries(r).every(e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))){this.pendingSignalRequests.delete(c),e();return}yield su(50)}a(new a$("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&a(e)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(so.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(so.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(so.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return rq(this,void 0,void 0,function*(){this.encryptionType=e?iK.GCM:iK.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,n){return rq(this,void 0,void 0,function*(){this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let r=this.getTrackPublication(e);if(t)if(r)yield r.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case so.Source.Camera:t=yield this.createTracks({video:null==i||i});break;case so.Source.Microphone:t=yield this.createTracks({audio:null==i||i});break;case so.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new aH(e)}}catch(i){throw null==t||t.forEach(e=>{e.stop()}),i instanceof Error&&this.emit(er.MediaDevicesError,i,st(e)),this.pendingPublishing.delete(e),i}for(let n of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===so.Source.Microphone&&sH(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{let e=[];for(let i of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),sn(i))),e.push(this.publishTrack(i,n));let i=yield Promise.all(e);[r]=i}catch(e){throw null==t||t.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!(null==r?void 0:r.track)&&this.pendingPublishing.has(e)&&((r=yield this.waitForPendingPublicationOfSource(e))||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),r&&r.track)if(e===so.Source.ScreenShare){r=yield this.unpublishTrack(r.track);let e=this.getTrackPublication(so.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield r.mute();return r})}enableCameraAndMicrophone(){return rq(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(so.Source.Camera)||this.pendingPublishing.has(so.Source.Microphone))){this.pendingPublishing.add(so.Source.Camera),this.pendingPublishing.add(so.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(so.Source.Camera),this.pendingPublishing.delete(so.Source.Microphone)}}})}createTracks(e){return rq(this,void 0,void 0,function*(){var t,i;null!=e||(e={});let n=a5(e,null==(t=this.roomOptions)?void 0:t.audioCaptureDefaults,null==(i=this.roomOptions)?void 0:i.videoCaptureDefaults);try{return(yield cr(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(sH(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=so.Source.Microphone,this.emit(er.AudioStreamAcquired)),sG(e)&&(this.cameraError=void 0,e.source=so.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return rq(this,void 0,void 0,function*(){var t,i,n;let r,a;if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new aW("getDisplayMedia not supported");void 0!==e.resolution||(null==(r=aU())?void 0:r.name)==="Safari"&&r.version.startsWith("17.")||(null==r?void 0:r.os)==="iOS"&&(null==r?void 0:r.osVersion)&&s_(r.osVersion,"17")>=0||(e.resolution=a4.h1080fps30.resolution);let s=(a=null==(i=(t=e).video)||i,t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(a="boolean"==typeof a?{}:a,a=sb()?Object.assign(Object.assign({},a),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):Object.assign(Object.assign({},a),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:null!=(n=t.audio)&&n,video:a,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}),o=yield navigator.mediaDevices.getDisplayMedia(s),c=o.getVideoTracks();if(0===c.length)throw new aH("no video track found");let l=new oW(c[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});l.source=so.Source.ScreenShare,e.contentHint&&(l.mediaStreamTrack.contentHint=e.contentHint);let d=[l];if(o.getAudioTracks().length>
30){this.emit(er.AudioStreamAcquired);let e=new oO(o.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=so.Source.ScreenShareAudio,d.push(e)}return d})}publishTrack(e,t){return rq(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return rq(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var r,a;let s,o;if(sK(e)&&e.setAudioContext(i.audioContext),yield null==(r=i.reconnectFuture)?void 0:r.promise,i.republishPromise&&!n&&(yield i.republishPromise),sW(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)s=e.getConstraints();else{let t;switch(s=e.constraints,e.source){case so.Source.Microphone:t="audioinput";break;case so.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(s=Object.assign(Object.assign({},s),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new oO(e,s,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new oW(e,s,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new aH("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach(t=>{t.track&&t.track===e&&(o=t)}),o)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),sn(o))),o;let c=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,d=null!=(a=c.forceStereo)?a:l;d&&(void 0===c.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),sn(e))),void 0===c.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!=c.dtx||(c.dtx=!1),null!=c.red||(c.red=!1)),!function(){let e=aU(),t="17.2";if(e)if("Safari"!==e.name&&"iOS"!==e.os)return!0;else if("iOS"===e.os&&e.osVersion&&s_(e.osVersion,t)>=0)return!0;else if("Safari"===e.name&&s_(e.version,t)>=0)return!0;else return!1}()&&i.roomOptions.e2ee&&(i.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({},i.logContext)),c.simulcast=!1),c.source&&(e.source=c.source);let u=new Promise((t,n)=>rq(i,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ef.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:sn(e)}));let i=!1,r=setTimeout(()=>{i=!0,e.stop(),n(new aJ("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(r),i)return;let a=yield this.publish(e,c,d);t(a)}else try{let i=yield this.publish(e,c,d);t(i)}catch(e){n(e)}}catch(e){n(e)}}));i.pendingPublishPromises.set(e,u);try{return yield u}catch(e){throw e}finally{i.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new sU),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),sn(e))),!1;let{canPublish:t,canPublishSources:i}=this.permissions;return!!(t&&(0===i.length||i.map(e=>(function(e){switch(e){case iD.CAMERA:return so.Source.Camera;case iD.MICROPHONE:return so.Source.Microphone;case iD.SCREEN_SHARE:return so.Source.ScreenShare;case iD.SCREEN_SHARE_AUDIO:return so.Source.ScreenShareAudio;default:return so.Source.Unknown}})(e)).includes(e.source)))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),sn(e))),!1)}publish(e,t,i){return rq(this,void 0,void 0,function*(){var n,r,a,s,o,c,l,d,u,h;let p,m;if(!this.hasPermissionsToPublish(e))throw new aJ("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>sW(e)&&t.source===e.source)&&e.source!==so.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),sn(e))),t.stopMicTrackOnMute&&sH(e)&&(e.stopOnMute=!0),e.source===so.Source.ScreenShare&&sf()&&(t.simulcast=!1),"av1"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||sb()||sf())return!1;let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/av1"===i.mimeType.toLowerCase()){t=!0;break}}return t}()&&(t.videoCodec=void 0),"vp9"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||sf())return!1;if(sb()){let e=aU();if((null==e?void 0:e.version)&&0>s_(e.version,"16")||(null==e?void 0:e.os)==="iOS"&&(null==e?void 0:e.osVersion)&&0>s_(e.osVersion,"16"))return!1}let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/vp9"===i.mimeType.toLowerCase()){t=!0;break}}return t}()&&(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec="vp8"),this.enabledPublishVideoCodecs.length>0&&!this.enabledPublishVideoCodecs.some(e=>t.videoCodec===si(e.mime))&&(t.videoCodec=si(this.enabledPublishVideoCodecs[0].mime));let g=t.videoCodec;e.on(es.Muted,this.onTrackMuted),e.on(es.Unmuted,this.onTrackUnmuted),e.on(es.Ended,this.handleTrackEnded),e.on(es.UpstreamPaused,this.onTrackUpstreamPaused),e.on(es.UpstreamResumed,this.onTrackUpstreamResumed),e.on(es.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let f=[],v=!(null==(n=t.dtx)||n),b=e.getSourceTrackSettings();b.autoGainControl&&f.push(iF.TF_AUTO_GAIN_CONTROL),b.echoCancellation&&f.push(iF.TF_ECHO_CANCELLATION),b.noiseSuppression&&f.push(iF.TF_NOISE_SUPPRESSION),b.channelCount&&b.channelCount>
31&&f.push(iF.TF_STEREO),v&&f.push(iF.TF_NO_DTX),sK(e)&&e.hasPreConnectBuffer&&f.push(iF.TF_PRECONNECT_BUFFER);let y=new n$({cid:e.mediaStreamTrack.id,name:t.name,type:so.kindToProto(e.kind),muted:e.isMuted,source:so.sourceToProto(e.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null==(r=t.red)||r),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:f});if(e.kind===so.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(n){let t=null!=(s=null==(a=this.roomOptions.videoCaptureDefaults)?void 0:a.resolution)?s:a3.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),sn(e)),{dims:i}))}y.width=i.width,y.height=i.height,sz(e)&&(sm(g)&&(e.source===so.Source.ScreenShare&&(t.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),sn(e))))),t.scalabilityMode=null!=(o=t.scalabilityMode)?o:"L3T3_KEY"),y.simulcastCodecs=[new nJ({codec:g,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:"vp8"}),t.backupCodec&&g!==t.backupCodec.codec&&y.encryption===iK.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),y.simulcastCodecs.push(new nJ({codec:t.backupCodec.codec,cid:""})))),p=oj(e.source===so.Source.ScreenShare,y.width,y.height,t),y.layers=oz(y.width,y.height,p,sm(t.videoCodec))}else e.kind===so.Kind.Audio&&(p=[{maxBitrate:null==(c=t.audioPreset)?void 0:c.maxBitrate,priority:null!=(d=null==(l=t.audioPreset)?void 0:l.priority)?d:"high",networkPriority:null!=(h=null==(u=t.audioPreset)?void 0:u.priority)?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new az("cannot publish track when not connected");let k=()=>rq(this,void 0,void 0,function*(){var i,n;if(!this.engine.pcManager)throw new az("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,p),this.emit(er.LocalSenderCreated,e.sender,e),sz(e)&&(null!=t.degradationPreference||(t.degradationPreference=e.source===so.Source.ScreenShare||e.constraints.height&&sj(e.constraints.height)>=1080?"maintain-resolution":"balanced"),e.setDegradationPreference(t.degradationPreference)),p)if(sf()&&e.kind===so.Kind.Audio){let t;for(let i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null==(i=p[0])?void 0:i.maxBitrate)?p[0].maxBitrate/1e3:0})}else e.codec&&sm(e.codec)&&(null==(n=p[0])?void 0:n.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:y.cid,codec:e.codec,maxbr:p[0].maxBitrate/1e3});yield this.engine.negotiate()}),T=new Promise((t,i)=>rq(this,void 0,void 0,function*(){var n;try{m=yield this.engine.addTrack(y),t(m)}catch(t){e.sender&&(null==(n=this.engine.pcManager)?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),sn(e)),{error:t}))})),i(t)}}));if(this.enabledPublishVideoCodecs.length>0)m=(yield Promise.all([T,k()]))[0];else{let i;if((m=yield T).codecs.forEach(e=>{void 0===i&&(i=e.mimeType)}),i&&e.kind===so.Kind.Video){let n=si(i);n!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),sn(e)),{codec:n})),t.videoCodec=n,p=oj(e.source===so.Source.ScreenShare,y.width,y.height,t))}yield k()}let S=new cn(e.kind,m,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(S.on(es.CpuConstrained,e=>this.onTrackCpuConstrained(e,S)),S.options=t,e.sid=m.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:p,trackInfo:m})),sz(e)?e.startMonitor(this.engine.client):sK(e)&&e.startMonitor(),this.addTrackPublication(S),this.emit
3(er.LocalTrackPublished,S),sK(e)&&m.audioFeatures.includes(iF.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();this.on(er.LocalTrackSubscribed,t=>{if(t.trackSid===m.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),sn(e))),e.stopPreConnectBuffer()}}),t&&new Promise((n,r)=>rq(this,void 0,void 0,function*(){try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),sn(e)));let m=setTimeout(()=>{r(Error("agent not active within 10 seconds"))},1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),sn(e)));let f=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:S.trackSid,sampleRate:String(null!=(l=b.sampleRate)?l:"48000"),channels:String(null!=(d=b.channelCount)?d:"1")}});try{for(var a,s,o,c,l,d,u,h=!0,p=rV(t);!(a=(u=yield p.next()).done);h=!0)c=u.value,h=!1,yield f.write(c)}catch(e){s={error:e}}finally{try{!h&&!a&&(o=p.return)&&(yield o.call(p))}finally{if(s)throw s.error}}yield f.close(),n()}catch(e){r(e)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),sn(e)))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),sn(e)),{error:t}))})}return S})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return rq(this,void 0,void 0,function*(){var n;let r;if(this.encryptionType!==iK.NONE)return;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new aH("track is not published");if(!sz(e))throw new aH("track is not a video track");let a=Object.assign(Object.assign({},null==(n=this.roomOptions)?void 0:n.publishDefaults),i),s=function(e,t,i){var n,r,a,s;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&rU.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;let o=e.mediaStreamTrack.getSettings(),c=null!=(n=o.width)?n:null==(r=e.dimensions)?void 0:r.width,l=null!=(a=o.height)?a:null==(s=e.dimensions)?void 0:s.height;return e.source===so.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),oj(e.source===so.Source.ScreenShare,c,l,i)}(e,t,a);if(!s)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),sn(e)));let o=e.addSimulcastTrack(t,s);if(!o)return;let c=new n$({cid:o.mediaStreamTrack.id,type:so.kindToProto(e.kind),muted:e.isMuted,source:so.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:o.mediaStreamTrack.id}]});if(c.layers=oz(c.width,c.height,s),!this.engine||this.engine.isClosed)throw new az("cannot publish track when not connected");let l=()=>rq(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,a,s),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:s,trackInfo:d}))})}unpublishTrack(e,t){return rq(this,void 0,void 0,function*(){var i,n;if(sW(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),sn(e))),yield t)}let r=this.getPublicationForTrack(e),a=r?sn(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));(e=r.track).off(es.Muted,this.onTrackMuted),e.off(es.Unmuted,this.onTrackUnmuted),e.off(es.Ended,this.handleTrackEnded),e.off(es.UpstreamPaused,this.onTrackUpstreamPaused),e.off(es.UpstreamResumed,this.onTrackUpstreamResumed),e.off(es.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null==(n=null==(i=this.roomOptions)?void 0:i.stopLocalTrackOnUnpublish)||n),t?e.stop():e.stopMonitor();let s=!1,o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<eS.FAILED&&o)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===o&&(e.direction="inactive",s=!0);if(this.engine.removeTrack(o)&&(s=!0),sz(e)){for(let[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(s=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case so.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case so.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}
3return this.emit(er.LocalTrackUnpublished,r),r.setTrack(void 0),s&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return rq(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return rq(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise((n,r)=>rq(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))}),yield Promise.all(t.map(e=>rq(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),i&&!t.isMuted&&t.source!==so.Source.ScreenShare&&t.source!==so.Source.ScreenShareAudio&&(sK(t)||sz(t))&&!t.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),n()}catch(e){r(e)}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return rq(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){let n=i.reliable?iZ.RELIABLE:iZ.LOSSY,r=i.destinationIdentities,a=i.topic,s=new iY({kind:n,value:{case:"user",value:new i6({participantIdentity:t.identity,payload:e,destinationIdentities:r,topic:a})}});yield t.engine.sendDataPacket(s,n)}()})}publishDtmf(e,t){return rq(this,void 0,void 0,function*(){let i=new iY({kind:iZ.RELIABLE,value:{case:"sipDtmf",value:new i4({code:e,digit:t})}});yield this.engine.sendDataPacket(i,iZ.RELIABLE)})}sendChatMessage(e,t){return rq(this,void 0,void 0,function*(){let i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new iY({value:{case:"chatMessage",value:new i9(Object.assign(Object.assign({},i),{timestamp:tA.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,iZ.RELIABLE),this.emit(er.ChatMessage,i),i})}editChatMessage(e,t){return rq(this,void 0,void 0,function*(){let i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new iY({value:{case:"chatMessage",value:new i9(Object.assign(Object.assign({},i),{timestamp:tA.parse(i.timestamp),editTimestamp:tA.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,iZ.RELIABLE),this.emit(er.ChatMessage,i),i})}sendText(e,t){return rq(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return rq(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return rq(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return rq(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return rq(this,arguments,void 0,function(e){var t=this;let{destinationIdentity:i,method:n,payload:r,responseTimeout:a=15e3}=e;return function*(){return new Promise((e,s)=>rq(t,void 0,void 0,function*(){var t,o,c,l;if(oE(r)>15360)return void s(oC.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null==(o=null==(t=this.engine.latestJoinResponse)?void 0:t.serverInfo)?void 0:o.version)&&0>s_(null==(l=null==(c=this.engine.latestJoinResponse)?void 0:c.serverInfo)?void 0:l.version,"1.8.0"))return void s(oC.builtIn("UNSUPPORTED_SERVER"));let d=Math.max(a,8e3),u=crypto.randomUUID();yield this.publishRpcRequest(i,u,n,r,d);let h=setTimeout(()=>{this.pendingAcks.delete(u),s(oC.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(u),clearTimeout(p)},7e3);this.pendingAcks.set(u,{resolve:()=>{clearTimeout(h)},participantIdentity:i});let p=setTimeout(()=>{this.pendingResponses.delete(u),s(oC.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(u,{resolve:(t,i)=>{clearTimeout(p),this.pendingAcks.has(u)&&(this.log.warn("RPC response received before ack",u),this.pendingAcks.delete(u),clearTimeout(h)),i?s(i):e(null!=t?t:"")},participantIdentity:i})}))}()})}
3registerRpcMethod(e,t){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,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){let n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,r){return rq(this,void 0,void 0,function*(){let a=new iY({destinationIdentities:[e],kind:iZ.RELIABLE,value:{case:"rpcRequest",value:new i7({id:t,method:i,payload:n,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,iZ.RELIABLE)})}handleParticipantDisconnected(e){for(let[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(let[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,oC.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>"video"===e.mime.split("/")[0].toLowerCase())}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach(e=>{var t,i;let n=this.trackPublications.get(e.sid);if(n){let r=n.isMuted||null!=(i=null==(t=n.track)?void 0:t.isUpstreamPaused)&&i;r!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),sn(n)),{mutedOnServer:r})),this.engine.client.sendMuteTrack(e.sid,r))}}),!0)}setActiveAgent(e){var t,i,n,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null==(i=null==(t=this.activeAgentFuture)?void 0:t.resolve)||i.call(t,e):null==(r=null==(n=this.activeAgentFuture)?void 0:n.reject)||r.call(n,Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new sU),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{let n=i.track;n&&(e instanceof MediaStreamTrack?(sK(n)||sz(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))}),t}waitForPendingPublicationOfSource(e){return rq(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[i]=t;return i.source===e});if(t)return t[1];yield su(20)}})}}class co extends ci{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(es.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let n=new n6({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new nn({participantSid:"",trackSids:[this.trackSid]})]});this.emit(es.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?ci.SubscriptionStatus.Unsubscribed:super.isSubscribed?ci.SubscriptionStatus.Subscribed:ci.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?ci.PermissionStatus.Allowed:ci.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&!e!==this.requestedDisabled&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null==(t=this.requestedVideoDimensions)?void 0:t.width)!==e.width||(null==(i=this.requestedVideoDimensions)?void 0:i.height)!==e.height)&&(s$(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate())}setVideoFPS(e){this.isManualOperationAllowed()&&s$(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!=(e=this.requestedMaxQuality)?e:el.HIGH}setTrack(e){let t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(es.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(es.VisibilityChanged,this.handleVisibilityChange),n.off(es.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit
vendor: 4,253 bytes, line 3
3(es.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(es.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(es.VisibilityChanged,this.handleVisibilityChange),e.on(es.Ended,this.handleEnded),this.emit(es.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(es.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?es.Muted:es.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(es.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(es.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return s$(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new n4({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===so.Kind.Video){let r=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(r)sa(this.videoDimensionsAdaptiveStream,r)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){var t,i,n;let e=(t=this.trackInfo,i=this.requestedMaxQuality,null==(n=t.layers)?void 0:n.find(e=>e.quality===i));e&&sa(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream;r?(e.width=Math.ceil(r.width),e.height=Math.ceil(r.height)):void 0!==this.requestedMaxQuality?(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:el.HIGH})),e.quality=el.HIGH)}this.emit(es.UpdateSettings,e)}}class cc extends ca{static fromParticipantInfo(e,t,i){return new cc(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,r,a,s){let o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:iG.STANDARD;super(t,i||"",n,r,a,s,o),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(es.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),sn(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(es.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(es.SubscriptionPermissionChanged,t=>{this.emit(er.TrackSubscriptionPermissionChanged,e,t)}),e.on(es.SubscriptionStatusChanged,t=>{this.emit(er.TrackSubscriptionStatusChanged,e,t)}),e.on(es.Subscribed,t=>{this.emit(er.TrackSubscribed,t,e)}),e.on(es.Unsubscribed,t=>{this.emit(er.TrackUnsubscribed,t,e)}),e.on(es.SubscriptionFailed,t=>{this.emit(er.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:so.Source.Microphone;this.volumeMap.set(t,e);let i=this.getTrackPublication(t);
3i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:so.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,r,a){let s,o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(t=>{o||e.kind!==t.kind.toString()||(o=t)}),!o){if(0===a){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(er.TrackSubscriptionFailed,t);return}void 0===a&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,n,r,a-1)},150);return}if("ended"===e.readyState){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),sn(o))),this.emit(er.TrackSubscriptionFailed,t);return}return(s="video"===e.kind?new o9(e,t,n,r):new o8(e,t,n,this.audioContext,this.audioOutput)).source=o.source,s.isMuted=o.isMuted,s.setMediaStream(i),s.start(),o.setTrack(s),this.volumeMap.has(o.source)&&sJ(s)&&sH(s)&&s.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;let t=new Map,i=new Map;return e.tracks.forEach(e=>{var n,r;let a=this.getTrackPublicationBySid(e.sid);if(a)a.updateInfo(e);else{let t=so.kindFromProto(e.type);if(!t)return;(a=new co(t,e,null==(n=this.signalClient.connectOptions)?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null==(r=this.loggerOptions)?void 0:r.loggerName})).updateInfo(e),i.set(e.sid,a);let s=Array.from(this.trackPublications.values()).find(e=>e.source===(null==a?void 0:a.source));s&&a.source!==so.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:sn(s),newTrack:sn(a)})),this.addTrackPublication(a)}t.set(e.sid,a)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),sn(e))),this.unpublishTrack(e.trackSid,!0))}
3),i.forEach(e=>{this.emit(er.TrackPublished,e)}),!0}unpublishTrack(e,t){let i=this.trackPublications.get(e);if(!i)return;let{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case so.Kind.Audio:this.audioTrackPublications.delete(e);break;case so.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(er.TrackUnpublished,i)}setAudioOutput(e){return rq(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(i=>{var n;sH(i.track)&&sJ(i.track)&&t.push(i.track.setSinkId(null!=(n=e.deviceId)?n:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}(q=ew||(ew={})).Disconnected="disconnected",q.Connecting="connecting",q.Connected="connected",q.Reconnecting="reconnecting",q.SignalReconnecting="signalReconnecting";class cl extends rH.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,i,n,r;if(super(),t=this,this.state=ew.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=rU,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,i)=>rq(this,void 0,void 0,function*(){var n;if(!(!("u"<typeof RTCPeerConnection)&&(sh()||sp())))if(sS())throw Error("WebRTC isn't detected, have you called registerGlobals?");else throw 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.");let r=yield this.disconnectLock.lock();if(this.state===ew.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(ew.Connecting),(null==(n=this.regionUrlProvider)?void 0:n.getServerUrl().toString())!==sQ(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),sC(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new oS(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null==(t=this.regionUrlProvider)||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))}));let a=(n,s,o)=>rq(this,void 0,void 0,function*(){var c,l;this.abortController&&this.abortController.abort();let d=new AbortController;this.abortController=d,null==r||r();try{if(yield s2.getInstance().getBackOffPromise(e),d.signal.aborted)throw aV.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=o?o:e,t,i,d),this.abortController=void 0,n()}catch(t){if(this.regionUrlProvider&&t instanceof aV&&t.reason!==ee.Cancelled&&t.reason!==ee.NotAllowed){let i=null;try{this.log.debug("Fetching next region"),i=yield this.regionUrlProvider.getNextBestRegionUrl(null==(c=this.abortController)?void 0:c.signal)}catch(e){if(e instanceof aV&&(401===e.status||e.reason===ee.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(e);return}}[ee.InternalError,ee.ServerUnreachable,ee.Timeout].includes(t.reason)&&(this.log.debug("Adding failed connection attempt to back off"),s2.getInstance().addFailedConnectionAttempt(e)),!i||(null==(l=this.abortController)?void 0:l.signal.aborted)?(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,sB(t)),s(t)):(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i),this.logContext),this.recreateEngine(),yield a(n,s,i))}else{let e=iL.UNKNOWN_REASON;t instanceof aV&&(e=sB(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),s(t)}}}),s=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new sU((e,t)=>{a(e,t,s)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,i,n,r,a)=>rq(this,void 0,void 0,function*(){var s,o,c;let l=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout,singlePeerConnection:r.singlePeerConnection},a.signal),d=l.serverInfo;if(d||(d={version:l.serverVersion,region:l.serverRegion}),this.serverInfo=d,this.log.debug("connected to Livekit Server ".concat(Object.entries(d).map(e=>{let[t,i]=e;return"".concat(t,": ").concat(i)}).join(", ")),{room:null==(s=l.room)?void 0:s.name,roomSid:null==(o=l.room)?void 0:o.sid,identity:null==(c=l.participant)?void 0:c.identity}),!d.version)throw new aG("unknown server version");return"0.15.1"===d.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),r.dynacast=!1),l}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>rq(this,void 0,void 0,function*(){var r,a;this.state===ew.Reconnecting||this.isResuming||(null==(r=this.engine)?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null==(a=this.regionUrlProvider)?void 0:a.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ok),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit
3(en.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();let e=n.signal.aborted?aV.cancelled("Signal connection aborted"):aV.serverUnreachable("could not establish signal connection");throw t instanceof Error&&(e.message="".concat(e.message,": ").concat(t.message)),t instanceof aV&&(e.reason=t.reason,e.status=t.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:t})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),aV.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}sT()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),sT()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ew.Connected),this.emit(en.Connected),s2.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var e=arguments.length,i=Array(e),n=0;n<e;n++)i[n]=arguments[n];return rq(t,[...i],void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n,r;let a=yield e.disconnectLock.lock();try{if(e.state===ew.Disconnected)return void e.log.debug("already disconnected",e.logContext);if(e.log.info("disconnect from room",Object.assign({},e.logContext)),e.state===ew.Connecting||e.state===ew.Reconnecting||e.isResuming){let t="Abort connection attempt due to user initiated disconnect";e.log.warn(t,e.logContext),null==(i=e.abortController)||i.abort(t),null==(r=null==(n=e.connectFuture)?void 0:n.reject)||r.call(n,aV.cancelled("Client initiated disconnect")),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,iL.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>rq(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>rq(this,void 0,void 0,function*(){let e=[],t=aU();if(t&&"iOS"===t.os){let t="livekit-dummy-audio-el",i=document.getElementById(t);if(!i){(i=document.createElement("audio")).id=t,i.autoplay=!0,i.hidden=!0;let e=sL();e.enabled=!0;let n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(i),this.once(en.Disconnected,()=>{null==i||i.remove(),i=null})}e.push(i)}
3this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>rq(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var i;null==(i=t.track)||i.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{for(let e of(this.clearConnectionReconcile(),this.isResuming=!1,this.remoteParticipants.values()))this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(ew.Reconnecting)&&this.emit(en.Reconnecting)},this.handleSignalRestarted=e=>rq(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(ew.Connected),this.emit(en.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{e.forEach(e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!=(t=this.sidToIdentity.get(e.sid))?t:"");let i=this.remoteParticipants.get(e.identity);e.state===iH.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)})},this.handleActiveSpeakersUpdate=e=>{let t=[],i={};e.forEach(e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}}),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEac
3h(e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(en.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))});let i=Array.from(t.values());i.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=i,this.emitWhenConnected(en.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;let n=so.streamStateFromProto(e.state);i.track.setStreamState(n),n!==i.track.streamState&&(t.emit(er.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(en.TrackStreamStateChanged,i,i.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let i=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(i,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(i,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(i,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(i,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,i);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){let t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i,n)=>{this.emit(en.DataReceived,t.payload,e,i,t.topic,n),null==e||e.emit(er.DataReceived,t.payload,i,n)},this.handleSipDtmf=(e,t)=>{this.emit(en.SipDTMFReceived,t,e),null==e||e.emit(er.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{var i;let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),r=null==n?void 0:n.trackPublications.get(t.trackId),a=(i=this.transcriptionReceivedTimes,t.segments.map(e=>{var t;let{id:n,text:r,language:a,startTime:s,endTime:o,final:c}=e,l=null!=(t=i.get(n))?t:Date.now(),d=Date.now();return c?i.delete(n):i.set(n,l),{id:n,text:r,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(o.toString()),final:c,language:a,firstReceivedTime:l,lastReceivedTime:d}}));null==r||r.emit(es.TranscriptionReceived,a),null==n||n.emit(er.TranscriptionReceived,a,r),this.emit(en.TranscriptionReceived,a,n,r)},this.handleChatMessage=(e,t)=>{let i=function(e){let{id:t,timestamp:i,message:n,editTimestamp:r}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}(t);this.emit(en.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(en.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(en.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(en.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(en.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit
3(en.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>rq(this,void 0,void 0,function*(){var e;(null==(e=aU())?void 0:e.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(en.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(en.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(en.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(en.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(en.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(en.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(en.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(en.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null==(t=null==e?void 0:e.onPublish)||t.call(e,this)},this.onLocalTrackPublished=e=>rq(this,void 0,void 0,function*(){var t,i,n,r,a,s;null==(t=e.track)||t.on(es.TrackProcessorUpdate,this.onTrackProcessorUpdate),null==(i=e.track)||i.on(es.Restarted,this.onLocalTrackRestarted),null==(a=null==(r=null==(n=e.track)?void 0:n.getProcessor())?void 0:r.onPublish)||a.call(r,this),this.emit(en.LocalTrackPublished,e,this.localParticipant),sK(e.track)&&(yield e.track.checkForSilence())&&this.emit(en.LocalAudioSilenceDetected,e);let o=yield null==(s=e.track)?void 0:s.getDeviceId(!1),c=st(e.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,o),this.emit(en.ActiveDeviceChanged,c,o))}),this.onLocalTrackUnpublished=e=>{var t,i;null==(t=e.track)||t.off(es.TrackProcessorUpdate,this.onTrackProcessorUpdate),null==(i=e.track)||i.off(es.Restarted,this.onLocalTrackRestarted),this.emit(en.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>rq(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),i=st(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(en.ActiveDeviceChanged,i,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(en.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(en.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(en.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(en.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},oy),e),this.log=rj(null!=(i=this.options.loggerName)?i:X.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},ov),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ob),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},of),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new o1,this.outgoingDataStreamManager=new o4(this.engine,this.log),this.disconnectLock=new tg,this.localParticipant=new cs("","",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",sj(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",sj(this.options.audioCaptureDefaults.deviceId)),(null==(n=this.options.audioOutput)?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",sj(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),sT()){const e=new AbortController;null==(r=navigator.mediaDevices)||r.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),cl.cleanupRegistry&&cl.cleanupRegistry.register(this,()=>{e.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}
3registerRpcMethod(e,t){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,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return rq(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;let t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new s1(i,t),this.e2eeManager.on(eh.ParticipantEncryptionStatusChanged,(e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(en.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(eh.EncryptionError,(e,t)=>{let i=t?this.getParticipantByIdentity(t):void 0;this.emit(en.EncryptionError,e,i)}),null==(e=this.e2eeManager)||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null==(e=this.roomInfo)?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.activeRecording)&&t}getSid(){return rq(this,void 0,void 0,function*(){return this.state===ew.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise((e,t)=>{let i=t=>{""!==t.sid&&(this.engine.off(ea.RoomUpdate,i),e(t.sid))};this.engine.on(ea.RoomUpdate,i),this.once(en.Disconnected,()=>{this.engine.off(ea.RoomUpdate,i),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.name)?t:""}get metadata(){var e;return null==(e=this.roomInfo)?void 0:e.metadata}get numParticipants(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.numParticipants)?t:0}get numPublishers(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.numPublishers)?t:0}maybeCreateEngine(){(!this.engine||this.engine.isClosed)&&(this.engine=new oQ(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(ea.ParticipantUpdate,this.handleParticipantUpdates).on(ea.RoomUpdate,this.handleRoomUpdate).on(ea.SpeakersChanged,this.handleSpeakersChanged).on(ea.StreamStateChanged,this.handleStreamStateUpdate).on(ea.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(ea.SubscriptionError,this.handleSubscriptionError).on(ea.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(ea.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(ea.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(ea.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(ea.DataPacketReceived,this.handleDataPacket).on(ea.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ew.SignalReconnecting)&&this.emit(en.SignalReconnecting)}).on(ea.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ew.Connected)&&this.emit(en.Reconnected)}).on(ea.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ew.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(ea.Restarting,this.handleRestarting).on(ea.SignalRestarted,this.handleSignalRestarted).on(ea.Offline,()=>{this.setAndEmitConnectionState(ew.Reconnecting)&&this.emit(en.Reconnecting)}).on(ea.DCBufferStatusChanged,(e,t)=>{this.emit(en.DCBufferStatusChanged,e,t)}).on(ea.LocalTrackSubscribed,e=>{let t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:i}=t;return i===e});t?(this.localParticipant.emit(er.LocalTrackSubscribed,t),this.emitWhenConnected(en.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)}).on(ea.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEac
3h((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(en.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 t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return s6.getInstance().getDevices(e,t)}prepareConnection(e,t){return rq(this,void 0,void 0,function*(){if(this.state===ew.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(sC(new URL(e))&&t){this.regionUrlProvider=new oS(e,t);let i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ew.Disconnected&&(this.regionUrl=i,yield fetch(sF(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(sF(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return rq(this,void 0,void 0,function*(){let i,n=()=>rq(this,void 0,void 0,function*(){});switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new rk({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new rk({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new rk({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new rk({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":n=()=>rq(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new rk({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>rq(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new rk({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":i=new rk({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>rq(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new n9({reason:iL.CLIENT_INITIATED,action:n7.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw Error("subscriber-bandwidth requires a number as argument");i=new rk({scenario:{case:"subscriberBandwidth",value:sV(t)}});break;case"leave-full-reconnect":i=new rk({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return rq(this,arguments,void 0,function(e,t){var i=this;let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];return function*(){var r,a,s,o,c,l;let d=!0,u=!1,h=n?{exact:t}:t;if("audioinput"===e){u=0===i.localParticipant.audioTrackPublications.size;let t=null!=(r=i.getActiveDevice(e))?r:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=h;let n=Array.from(i.localParticipant.audioTrackPublications.values()).filter(e=>e.source===so.Source.Microphone);try{d=(yield Promise.all(n.map(e=>{var t;return null==(t=e.audioTrack)?void 0:t.setDeviceId(h)}))).every(e=>!0===e)}catch(e){throw i.options.audioCaptureDefaults.deviceId=t,e}let a=n.some(e=>{var t,i;return null!=(i=null==(t=e.track)?void 0:t.isMuted)&&i});d&&a&&(u=!0)}else if("videoinput"===e){u=0===i.localParticipant.videoTrackPublications.size;let t=null!=(a=i.getActiveDevice(e))?a:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=h;let n=Array.from(i.localParticipant.videoTrackPublications.values()).filter(e=>e.source===so.Source.Camera);try{d=(yield Promise.all(n.map(e=>{var t;return null==(t=e.videoTrack)?void 0:t.setDeviceId(h)}
3))).every(e=>!0===e)}catch(e){throw i.options.videoCaptureDefaults.deviceId=t,e}let r=n.some(e=>{var t,i;return null!=(i=null==(t=e.track)?void 0:t.isMuted)&&i});d&&r&&(u=!0)}else if("audiooutput"===e){if(u=!0,!sg()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!=(s=yield s6.getInstance().normalizeDeviceId("audiooutput",t))?s:""),null!=(l=i.options).audioOutput||(l.audioOutput={});let n=null!=(o=i.getActiveDevice(e))?o:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null==(c=i.audioContext)||c.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw i.options.audioOutput.deviceId=n,e}}return u&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(en.ActiveDeviceChanged,e,t)),d}()})}setupLocalParticipantEvents(){this.localParticipant.on(er.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(er.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(er.AttributesChanged,this.onLocalAttributesChanged).on(er.TrackMuted,this.onLocalTrackMuted).on(er.TrackUnmuted,this.onLocalTrackUnmuted).on(er.LocalTrackPublished,this.onLocalTrackPublished).on(er.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(er.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(er.MediaDevicesError,this.onMediaDevicesError).on(er.AudioStreamAcquired,this.startAudio).on(er.ChatMessage,this.onLocalChatMessageSent).on(er.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null==(e=this.engine)||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){var n;let r,a;if(this.state===ew.Connecting||this.state===ew.Reconnecting){let n=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,i),r()},r=()=>{this.off(en.Reconnected,n),this.off(en.Connected,n),this.off(en.Disconnected,r)};this.once(en.Reconnected,n),this.once(en.Connected,n),this.once(en.Disconnected,r);return}if(this.state===ew.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);let s=(a=(n=t.id).split("|")).length>1?[a[0],n.substr(a[0].length+1)]:[n,""],o=s[0],c=s[1],l=e.id;if(c&&c.startsWith("TR")&&(l=c),o===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);let d=Array.from(this.remoteParticipants.values()).find(e=>e.sid===o);if(!d)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(o),this.logContext);if(!l.startsWith("TR")){let e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(o),this.logContext);l=e}l.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(o,", streamId: ").concat(c,", trackId: ").concat(l),Object.assign(Object.assign({},this.logContext),{rpID:o,streamId:c,trackId:l})),this.options.adaptiveStream&&(r="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});let u=d.addSubscribedMediaTrack(e,l,t,i,r);(null==u?void 0:u.isEncrypted)&&!this.e2eeManager&&this.emit(en.EncryptionError,Error("Encrypted ".concat(u.source," track received from participant ").concat(d.sid,", but room does not have encryption enabled!")))}handleDisconnect(){var e;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0],i=arguments.length>1?arguments[1]:void 0;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==ew.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();
3try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(e=>{var i,n,r;e.track&&this.localParticipant.unpublishTrack(e.track,t),t?(null==(i=e.track)||i.detach(),null==(n=e.track)||n.stop()):null==(r=e.track)||r.stopMonitor()}),this.localParticipant.off(er.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(er.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(er.AttributesChanged,this.onLocalAttributesChanged).off(er.TrackMuted,this.onLocalTrackMuted).off(er.TrackUnmuted,this.onLocalTrackUnmuted).off(er.LocalTrackPublished,this.onLocalTrackPublished).off(er.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(er.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(er.MediaDevicesError,this.onMediaDevicesError).off(er.AudioStreamAcquired,this.startAudio).off(er.ChatMessage,this.onLocalChatMessageSent).off(er.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&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),sT()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null==(e=navigator.mediaDevices)||e.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ew.Disconnected),this.emit(en.Disconnected,i)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(en.ParticipantDisconnected,t),t.setDisconnected(),null==(i=this.localParticipant)||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,n,r,a){return rq(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),1!==a)return void(yield this.engine.publishRpcResponse(e,t,null,oC.builtIn("UNSUPPORTED_VERSION")));let s=this.rpcHandlers.get(i);if(!s)return void(yield this.engine.publishRpcResponse(e,t,null,oC.builtIn("UNSUPPORTED_METHOD")));let o=null,c=null;try{let a=yield s({requestId:t,callerIdentity:e,payload:n,responseTimeout:r});oE(a)>15360?(o=oC.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=a}catch(e){e instanceof oC?o=e:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),e),o=oC.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,o)})}selectDefaultDevices(){return rq(this,void 0,void 0,function*(){var e,t,i;let n=s6.getInstance().previousDevices,r=yield s6.getInstance().getDevices(void 0,!1),a=aU();if((null==a?void 0:a.name)==="Chrome"&&"iOS"!==a.os)for(let e of r){let t=n.find(t=>t.deviceId===e.deviceId);t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(en.ActiveDeviceChanged,e.kind,e.deviceId)}for(let a of["audiooutput","audioinput","videoinput"]){let s="audioinput"===a?so.Source.Microphone:"videoinput"===a?so.Source.Camera:so.Source.Unknown,o=this.localParticipant.getTrackPublication(s);if(o&&(null==(e=o.track)?void 0:e.isUserProvided))continue;let c=r.filter(e=>e.kind===a),l=this.getActiveDevice(a);if(l===(null==(t=n.filter(e=>e.kind===a)[0])?void 0:t.deviceId)&&c.length>0&&(null==(i=c[0])?void 0:i.deviceId)!==l){yield this.switchActiveDevice(a,c[0].deviceId);continue}("audioinput"!==a||sy())&&"videoinput"!==a&&(!(c.length>0)||c.find(e=>e.deviceId===this.getActiveDevice(a))||"audiooutput"===a&&sy()||(yield this.switchActiveDevice(a,c[0].deviceId)))}})}acquireAudioContext(){return rq(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!=(e=se())?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEac
3h(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),su(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}let i=(null==(t=this.audioContext)?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(en.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let n;return n=t?cc.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new cc(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null==(i=this.options.audioOutput)?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}let i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(en.ParticipantConnected,i),i.on(er.TrackPublished,e=>{this.emitWhenConnected(en.TrackPublished,e,i)}).on(er.TrackSubscribed,(e,t)=>{e.kind===so.Kind.Audio?(e.on(es.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(es.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===so.Kind.Video&&(e.on(es.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(es.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(en.TrackSubscribed,e,t,i)}).on(er.TrackUnpublished,e=>{this.emit(en.TrackUnpublished,e,i)}).on(er.TrackUnsubscribed,(e,t)=>{this.emit(en.TrackUnsubscribed,e,t,i)}).on(er.TrackMuted,e=>{this.emitWhenConnected(en.TrackMuted,e,i)}).on(er.TrackUnmuted,e=>{this.emitWhenConnected(en.TrackUnmuted,e,i)}).on(er.ParticipantMetadataChanged,e=>{this.emitWhenConnected(en.ParticipantMetadataChanged,e,i)}).on(er.ParticipantNameChanged,e=>{this.emitWhenConnected(en.ParticipantNameChanged,e,i)}).on(er.AttributesChanged,e=>{this.emitWhenConnected(en.ParticipantAttributesChanged,e,i)}).on(er.ConnectionQualityChanged,e=>{this.emitWhenConnected(en.ConnectionQualityChanged,e,i)}).on(er.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(en.ParticipantPermissionsChanged,e,i)}).on(er.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(en.TrackSubscriptionStatusChanged,e,t,i)}).on(er.TrackSubscriptionFailed,(e,t)=>{this.emit(en.TrackSubscriptionFailed,e,i,t)}).on(er.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(en.TrackSubscriptionPermissionChanged,e,t,i)}).on(er.Active,()=>{this.emitWhenConnected(en.ParticipantActive,i),i.kind===iG.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(let t of this.remoteParticipants.values())for(let i of t.videoTrackPublications.values()){var e;i.isSubscribed&&(e=i)&&!e.isLocal&&i.emitTrackUpdate()}}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=aY.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(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,iL.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&aY.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit
3(en.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===ew.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ew.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return rq(this,void 0,void 0,function*(){var t,i;let n=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new iB({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:tA.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new iW({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(en.SignalConnected),this.emit(en.Connected),this.setAndEmitConnectionState(ew.Connected),n.video){let e=new cn(so.Kind.Video,new i$({source:iD.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:iO.AUDIO,name:"video-dummy"}),new oW(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:sN(160*(null!=(t=r.aspectRatios[0])?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(er.LocalTrackPublished,e)}if(n.audio){let e=new cn(so.Kind.Audio,new i$({source:iD.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:iO.AUDIO}),new oO(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:sL(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(er.LocalTrackPublished,e)}for(let e=0;e<r.count-1;e+=1){let t=new iW({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:iH.ACTIVE,tracks:[],joinedAt:tA.parse(Date.now())}),n=this.getOrCreateParticipant(t.identity,t);if(r.video){let a=sN(160*(null!=(i=r.aspectRatios[e%r.aspectRatios.length])?i:1),160,!1,!0),s=new i$({source:iD.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:iO.AUDIO});n.addSubscribedMediaTrack(a,s.sid,new MediaStream([a]),new RTCRtpReceiver),t.tracks=[...t.tracks,s]}if(r.audio){let e=sL(),i=new i$({source:iD.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:iO.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}})}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==en.ActiveSpeakersChanged&&e!==en.TranscriptionReceived){let t=(function e(t){return t.map(t=>{if(t)return Array.isArray(t)?e(t):"object"==typeof t?"logContext"in t?t.logContext:void 0:t})})(i).filter(e=>void 0!==e);(e===en.TrackSubscribed||e===en.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}cl.cleanupRegistry="u">typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),(V=eR||(eR={}))[V.IDLE=0]="IDLE",V[V.RUNNING=1]="RUNNING",V[V.SKIPPED=2]="SKIPPED",V[V.SUCCESS=3]="SUCCESS",V[V.FAILED=4]="FAILED";class cd extends rH.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=eR.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new cl(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return rq(this,void 0,void 0,function*(){if(this.status!==eR.IDLE)throw Error("check is running already");this.setStatus(eR.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise(e=>setTimeout(e,500)),this.status!==eR.SKIPPED&&this.setStatus(this.isSuccess()?eR.SUCCESS:eR.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>"error"===e.level)}connect(e){return rq(this,void 0,void 0,function*(){return this.room.state===ew.Connected||(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions)),this.room})}disconnect(){return rq(this,void 0,void 0,function*(){this.room&&this.room.state!==ew.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(eR.SKIPPED)}switchProtocol(e){return rq(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(en.Reconnecting,()=>{t=!0}),this.room.once(en.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(e=>setTimeout(e,1e3)),!t)return;let n=Date.now()+1e4;for(;Date.now()<n;){if(i)return;yield su(100)}throw Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}
3),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 null==(e=this.room)?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}function cu(e,t,i){var n;return(t="symbol"==typeof(n=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"))?n:n+"")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}rH.EventEmitter,new TextEncoder,new TextDecoder;class ch extends Error{constructor(e,t){var i;super(e,t),cu(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null==(i=Error.captureStackTrace)||i.call(Error,this,this.constructor)}}cu(ch,"code","ERR_JOSE_GENERIC"),cu(class extends ch{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),cu(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),cu(this,"claim",void 0),cu(this,"reason",void 0),cu(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),cu(class extends ch{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),cu(this,"code","ERR_JWT_EXPIRED"),cu(this,"claim",void 0),cu(this,"reason",void 0),cu(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_EXPIRED"),cu(class extends ch{constructor(){super(...arguments),cu(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED"),cu(class extends ch{constructor(){super(...arguments),cu(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED"),cu(class extends ch{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),cu(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED"),cu(class extends ch{constructor(){super(...arguments),cu(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID"),cu(class extends ch{constructor(){super(...arguments),cu(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID"),cu(class extends ch{constructor(){super(...arguments),cu(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID"),cu(class extends ch{constructor(){super(...arguments),cu(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID"),cu(class extends ch{constructor(){super(...arguments),cu(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID"),cu(class extends ch{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),cu(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY"),cu(class extends ch{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),cu(this,Symbol.asyncIterator,void 0),cu(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS"),cu(class extends ch{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),cu(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT"),cu(class extends ch{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;
3super(e,t),cu(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");let cp="conversation_initiation_client_data";function cm(e){let t={type:cp};return e.overrides&&(t.conversation_config_override={agent:{prompt:e.overrides.agent?.prompt,first_message:e.overrides.agent?.firstMessage,language:e.overrides.agent?.language},tts:{voice_id:e.overrides.tts?.voiceId,speed:e.overrides.tts?.speed,stability:e.overrides.tts?.stability,similarity_boost:e.overrides.tts?.similarityBoost},...e.overrides.asr?.keywords!==void 0?{asr:{keywords:e.overrides.asr.keywords}}:{},conversation:{text_only:e.overrides.conversation?.textOnly}}),e.customLlmExtraBody&&(t.custom_llm_extra_body=e.customLlmExtraBody),e.dynamicVariables&&(t.dynamic_variables=e.dynamicVariables),e.userId&&(t.user_id=e.userId),t.source_info={source:to.name,version:to.version},e.toolMockConfig&&(t.tool_mock_config={mocking_strategy:e.toolMockConfig.mockingStrategy,mocked_tool_names:e.toolMockConfig.mockedToolNames,fallback_strategy:e.toolMockConfig.fallbackStrategy}),t}function cg(e){return btoa(String.fromCharCode(...new Uint8Array(e)))}function cf(e,t,i){let n=e.length,r=i/2/n,a=Math.floor(100/r),s=Math.min(Math.ceil(8e3/r),n),o=s-a,c=t.length;for(let i=0;i<c;i++){let n=i/c*o,r=a+Math.floor(n),l=Math.min(r+1,s-1),d=n-Math.floor(n);t[i]=Math.round(e[r]*(1-d)+e[l]*d)}}class cv extends tc{socket;conversationId;inputFormat;outputFormat;outputListeners=new Set;pendingAudioEvents=[];constructor(e,t,i,n){super(),this.socket=e,this.conversationId=t,this.inputFormat=i,this.outputFormat=n,this.socket.addEventListener("error",e=>{setTimeout(()=>this.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:{type:e.type}}),0)}),this.socket.addEventListener("close",e=>{let t=e.code,i=e.reason||void 0,n={type:e.type,code:t,reason:i};this.disconnect(1e3===t?{reason:"agent",context:n,closeCode:t,closeReason:i}:{reason:"error",message:i||"The connection was closed by the server.",context:n,closeCode:t,closeReason:i})}),this.socket.addEventListener("message",e=>{try{let t=JSON.parse(e.data);if(!tu(t))return void this.debug({type:"invalid_event",message:"Received invalid socket event",data:e.data});this.handleMessage(t)}catch(t){this.debug({type:"parsing_error",message:"Failed to parse socket message",error:t instanceof Error?t.message:String(t),data:e.data})}})}static async create(e){let t=null;try{let i,n=e.origin??"wss://api.elevenlabs.io",{name:r,version:a}=to;if(e.signedUrl){let t=e.signedUrl.includes("?")?"&":"?";i=`${e.signedUrl}${t}source=${r}&version=${a}`}else i=`${n}/v1/convai/conversation?agent_id=${e.agentId}&source=${r}&version=${a}`;e.environment&&(i+=`&environment=${encodeURIComponent(e.environment)}`);let s=["convai"];e.authorization&&s.push(`bearer.${e.authorization}`),t=new WebSocket(i,s);let{conversation_id:o,agent_output_audio_format:c,user_input_audio_format:l}=await new Promise((i,n)=>{t.addEventListener("open",()=>{let i=cm(e);t?.send(JSON.stringify(i))},{once:!0}),t.addEventListener("error",e=>{setTimeout(()=>n(new td("The connection was closed due to a socket error.")),0)}),t.addEventListener("close",e=>{let t=e.reason||(1e3===e.code?"Connection closed normally before session could be established.":"Connection closed unexpectedly before session could be established.");n(new td(t,{closeCode:e.code,closeReason:e.reason||void 0}))}),t.addEventListener("message",e=>{let t=JSON.parse(e.data);tu(t)&&("conversation_initiation_metadata"===t.type?i(t.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))},{once:!0})}),d=tl(l??"pcm_16000"),u=tl(c);return new cv(t,o,d,u)}catch(e){throw t?.close(),e}}close(){this.pendingAudioEvents=[],this.socket.close(1e3,"User ended conversation")}sendMessage(e){this.socket.send(JSON.stringify(e))}addListener(e){let t=this.outputListeners.size>0;if(this.outputListeners.add(e),t||0===this.pendingAudioEvents.length)return;let i=this.pendingAudioEvents;for(let t of(this.pendingAudioEvents=[],i))e(t)}removeListener(e){this.outputListeners.delete(e)}handleMessage(e){if(super.handleMessage(e),"audio"===e.type&&e.audio_event.audio_base_64){let t={audio_base_64:e.audio_event.audio_base_64};if(0===this.outputListeners.size)return void this.pendingAudioEvents.push(t);
3this.outputListeners.forEach(e=>e(t))}}}let cb=new Map;function cy(e,t){return async(i,n)=>{let r=cb.get(e);if(r)return i.addModule(r);if(n)try{await i.addModule(n),cb.set(e,n);return}catch(t){throw Error(`Failed to load the ${e} worklet module from path: ${n}. Error: ${t}`)}let a=new Blob([t],{type:"application/javascript"}),s=URL.createObjectURL(a);try{await i.addModule(s),cb.set(e,s);return}catch{URL.revokeObjectURL(s)}try{let n=btoa(t),r=`data:application/javascript;base64,${n}`;await i.addModule(r),cb.set(e,r)}catch(t){throw Error(`Failed to load the ${e} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}cy("audioConcatProcessor",`/* 4 * ulaw decoding logic taken from the wavefile library 5 * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js 6 * USED BY @elevenlabs/client 7 */ 8 9const decodeTable = [0, 132, 396, 924, 1980, 4092, 8316, 16764]; 10 11function decodeSample(muLawSample) { 12 let sign; 13 let exponent; 14 let mantissa; 15 let sample; 16 muLawSample = ~muLawSample; 17 sign = muLawSample & 0x80; 18 exponent = (muLawSample >> 4) & 0x07; 19 mantissa = muLawSample & 0x0f; 20 sample = decodeTable[exponent] + (mantissa << (exponent + 3)); 21 if (sign !== 0) sample = -sample; 22 23 return sample; 24} 25 26class AudioConcatProcessor extends AudioWorkletProcessor { 27 constructor() { 28 super(); 29 this.buffers = []; // Initialize an empty buffer 30 this.cursor = 0; 31 this.currentBuffer = null; 32 this.wasInterrupted = false; 33 this.finished = false; 34 35 this.port.onmessage = ({ data }) => { 36 switch (data.type) { 37 case "setFormat": 38 this.format = data.format; 39 if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) { 40 globalThis.LibSampleRate.create( 41 1, 42 data.sampleRate, 43 sampleRate 44 ).then(resampler => { 45 this.resampler = resampler; 46 }); 47 } 48 break; 49 case "buffer": 50 this.wasInterrupted = false; 51 this.buffers.push( 52 this.format === "ulaw" 53 ? new Uint8Array(data.buffer) 54 : new Int16Array(data.buffer) 55 ); 56 break; 57 case "interrupt": 58 this.wasInterrupted = true; 59 break; 60 case "clearInterrupted": 61 if (this.wasInterrupted) { 62 this.wasInterrupted = false; 63 this.buffers = []; 64 this.currentBuffer = null; 65 } 66 } 67 }; 68 } 69 process(_, outputs) { 70 let finished = false; 71 const output = outputs[0][0]; 72 for (let i = 0; i < output.length; i++) { 73 if (!this.currentBuffer) { 74 if (this.buffers.length === 0) { 75 finished = true; 76 break; 77 } 78 this.currentBuffer = this.buffers.shift(); 79 if (this.resampler) { 80 this.currentBuffer = this.resampler.full(this.currentBuffer); 81 } 82 this.cursor = 0; 83 } 84 85 let value = this.currentBuffer[this.cursor]; 86 if (this.format === "ulaw") { 87 value = decodeSample(value); 88 } 89 output[i] = value / 32768; 90 this.cursor++; 91 92 if (this.cursor >= this.currentBuffer.length) { 93 this.currentBuffer = null; 94 } 95 } 96 97 if (this.finished !== finished) { 98 this.finished = finished; 99 this.port.postMessage({ type: "process", finished }); 100 } 101 102 return true; // Continue processing 103 } 104} 105 106registerProcessor("audioConcatProcessor", AudioConcatProcessor); 107`);function ck(e,t){let i,n,r=e.frequencyBinCount;return{getVolume(){i??=new Uint8Array(r),n??=new Uint8Array(r),e.getByteFrequencyData(i),cf(i,n,t);if(0===n.length)return 0;let a=0;for(let e=0;e<n.length;e++)a+=n[e]/255;return(a/=n.length)<0?0:a>1?1:a},getByteFrequencyData(n){i??=new Uint8Array(r),e.getByteFrequencyData(i),cf(i,n,t)}}}function cT(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}let cS=cy("rawAudioProcessor",`/* 108 * ulaw encoding logic taken from the wavefile library 109 * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js 110 * USED BY @elevenlabs/client 111 */ 112 113const BIAS = 0x84; 114const CLIP = 32635; 115const encodeTable = [ 116 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3, 117 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 118 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 119 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 120 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 121 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 122 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 123 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 124 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 125 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 126 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 127 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 128 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 129 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 130 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 131 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7 132]; 133 134function encodeSample(sample) { 135 let sign; 136 let exponent; 137 let mantissa; 138 let muLawSample; 139 sign = (sample >> 8) & 0x80; 140 if (sign !== 0) sample = -sample; 141 sample = sample + BIAS; 142 if (sample > CLIP) sample = CLIP; 143 exponent = encodeTable[(sample>>7) & 0xFF]; 144 mantissa = (sample >> (exponent+3)) & 0x0F; 145 muLawSample = ~(sign | (exponent << 4) | mantissa); 146 147 return muLawSample; 148} 149 150class RawAudioProcessor extends AudioWorkletProcessor { 151 constructor() { 152 super(); 153 154 this.port.onmessage = ({ data }) => { 155 switch (data.type) { 156 case "setFormat": 157 this.isMuted = false;
158 this.buffer = []; // Initialize an empty buffer 159 const chunkDurationMs = data.chunkDurationMs ?? 25; 160 this.bufferSize = Math.max( 161 1, 162 Math.round((data.sampleRate * chunkDurationMs) / 1000) 163 ); 164 this.format = data.format; 165 166 if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) { 167 globalThis.LibSampleRate.create(1, sampleRate, data.sampleRate).then(resampler => { 168 this.resampler = resampler; 169 }); 170 } 171 break; 172 case "setMuted": 173 this.isMuted = data.isMuted; 174 break; 175 } 176 }; 177 } 178 process(inputs) { 179 if (!this.buffer) { 180 return true; 181 } 182 183 const input = inputs[0]; // Get the first input node 184 if (input.length > 0) { 185 let channelData = input[0]; // Get the first channel's data 186 187 // Resample the audio if necessary 188 if (this.resampler) { 189 channelData = this.resampler.full(channelData); 190 } 191 192 // Add channel data to the buffer 193 this.buffer.push(...channelData); 194 // Get max volume 195 let sum = 0.0; 196 for (let i = 0; i < channelData.length; i++) { 197 sum += channelData[i] * channelData[i]; 198 } 199 const maxVolume = Math.sqrt(sum / channelData.length); 200 // Check if buffer size has reached or exceeded the threshold 201 if (this.buffer.length >= this.bufferSize) { 202 const float32Array = this.isMuted 203 ? new Float32Array(this.buffer.length) 204 : new Float32Array(this.buffer); 205 206 let encodedArray = this.format === "ulaw" 207 ? new Uint8Array(float32Array.length) 208 : new Int16Array(float32Array.length); 209 210 // Iterate through the Float32Array and convert each sample to PCM16 211 for (let i = 0; i < float32Array.length; i++) { 212 // Clamp the value to the range [-1, 1] 213 let sample = Math.max(-1, Math.min(1, float32Array[i])); 214 215 // Scale the sample to the range [-32768, 32767] 216 let value = sample < 0 ? sample * 32768 : sample * 32767; 217 if (this.format === "ulaw") { 218 value = encodeSample(Math.round(value)); 219 } 220 221 encodedArray[i] = value; 222 } 223 224 // Send the buffered data to the main script 225 this.port.postMessage([encodedArray, maxVolume]); 226 227 // Clear the buffer after sending 228 this.buffer = []; 229 } 230 } 231 return true; // Continue processing 232 } 233} 234registerProcessor("rawAudioProcessor", RawAudioProcessor); 235`),cC={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},cE=["touchstart","touchend","click"],cw=null,cR=null,cP=!1;function c_(){cR&&(clearTimeout(cR),cR=null)}function cI(){cw&&(cw.close().catch(()=>{}),cw=null,c_())}class cx{audioElements=[];inputAudioContext=null;audioCaptureContext=null;async attachRemoteTrack(e,t){let i=e.attach();if(i.autoplay=!0,i.controls=!1,t&&i.setSinkId)try{await i.setSinkId(t)}catch(e){console.warn("Failed to set output device for new audio element:",e)}i.style.display="none",document.body.appendChild(i),this.audioElements.push(i)}setupInputAnalysis(e){this.inputAudioContext&&(this.inputAudioContext.close().catch(()=>{}),this.inputAudioContext=null);let t=new AudioContext,i=t.createAnalyser();return t.createMediaStreamSource(new MediaStream([e])).connect(i),this.inputAudioContext=t,{volumeProvider:ck(i,t.sampleRate),analyser:i}}async setupOutputAnalysis(e,t,i){this.audioCaptureContext&&(this.audioCaptureContext.close().catch(()=>{}),this.audioCaptureContext=null);let n=new AudioContext;this.audioCaptureContext=n;let r=n.createAnalyser();r.fftSize=2048,r.smoothingTimeConstant=.8;let a=new MediaStream([e.mediaStreamTrack]),s=n.createMediaStreamSource(a),o=ck(r,n.sampleRate);await cS(n.audioWorklet);let c=new AudioWorkletNode(n,"rawAudioProcessor");return c.port.postMessage({type:"setFormat",format:t.format,sampleRate:t.sampleRate}),c.port.onmessage=e=>{let[t,n]=e.data;i(t.buffer,n)},s.connect(r),r.connect(c),{volumeProvider:o,analyser:r}}setVolume(e){for(let t of this.audioElements)t.volume=e}async setOutputDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw Error("setSinkId is not supported in this browser");await Promise.all(this.audioElements.map(async t=>{try{await t.setSinkId(e)}catch(e){throw console.error("Failed to set sink ID for audio element:",e),e}}))}cleanup(){for(let e of(this.inputAudioContext&&(this.inputAudioContext.close().catch(e=>{console.warn("Error closing input audio context:",e)}),this.inputAudioContext=null),this.audioCaptureContext&&(this.audioCaptureContext.close().catch(e=>{console.warn("Error closing audio capture context:",e)}),this.audioCaptureContext=null),this.audioElements))e.remove();this.audioElements=[]}}let cO=null,cD=cy("scribeAudioProcessor",`/* 236 * Scribe Audio Processor for converting microphone audio to PCM16 format 237 * Supports resampling for browsers like Firefox that don't support 238 * AudioContext sample rate constraints. 239 * USED BY @elevenlabs/client 240 */ 241 242class ScribeAudioProcessor extends AudioWorkletProcessor { 243 constructor() { 244 super(); 245 this.buffer = []; 246 this.bufferSize = 4096; // Buffer size for optimal chunk transmission 247 248 // Resampling state 249 this.inputSampleRate = null; 250 this.outputSampleRate = null; 251 this.resampleRatio = 1; 252 this.lastSample = 0; 253 this.resampleAccumulator = 0; 254 255 this.port.onmessage = ({ data }) => { 256 if (data.type === "configure") { 257 this.inputSampleRate = data.inputSampleRate; 258 this.outputSampleRate = data.outputSampleRate; 259 if (this.inputSampleRate && this.outputSampleRate) { 260 this.resampleRatio = this.inputSampleRate / this.outputSampleRate; 261 } 262 } 263 }; 264 } 265 266 // Linear interpolation resampling 267 resample(inputData) { 268 if (this.resampleRatio === 1 || !this.inputSampleRate) { 269 return inputData; 270 } 271 272 const outputSamples = []; 273 274 for (let i = 0; i < inputData.length; i++) { 275 const currentSample = inputData[i]; 276 277 // Generate output samples using linear interpolation 278 while (this.resampleAccumulator < 1) { 279 const interpolated = 280 this.lastSample + 281 (currentSample - this.lastSample) * this.resampleAccumulator; 282 outputSamples.push(interpolated); 283 this.resampleAccumulator += this.resampleRatio; 284 } 285 286 this.resampleAccumulator -= 1; 287 this.lastSample = currentSample; 288 } 289 290 return new Float32Array(outputSamples); 291 } 292 293 process(inputs) { 294 const input = inputs[0]; 295 if (input.length > 0) { 296 let channelData = input[0]; // Get first channel (mono) 297 298 // Resample if needed (for Firefox and other browsers that don't 299 // support AudioContext sample rate constraints) 300 if (this.resampleRatio !== 1) { 301 channelData = this.resample(channelData); 302 } 303 304 // Add incoming audio to buffer 305 for (let i = 0; i < channelData.length; i++) { 306 this.buffer.push(channelData[i]); 307 } 308 309 // When buffer reaches threshold, convert and send 310 if (this.buffer.length >= this.bufferSize) { 311 const float32Array = new Float32Array(this.buffer); 312 const int16Array = new Int16Array(float32Array.length); 313 314 // Convert Float32 [-1, 1] to Int16 [-32768, 32767] 315 for (let i = 0; i < float32Array.length; i++) { 316 // Clamp the value to prevent overflow 317 const sample = Math.max(-1, Math.min(1, float32Array[i])); 318 // Scale to PCM16 range 319 int16Array[i] = sample < 0 ? sample * 32768 : sample * 32767; 320 } 321 322 // Send to main thread as transferable ArrayBuffer 323 this.port.postMessage( 324 { 325 audioData: int16Array.buffer 326 }, 327 [int16Array.buffer] 328 ); 329 330 // Clear buffer 331 this.buffer = []; 332 } 333 } 334 335 return true; // Continue processing 336 } 337} 338 339registerProcessor("scribeAudioProcessor", ScribeAudioProcessor); 340 341`),cM=async(e,t)=>{let i,n,r,a,s=()=>{for(let e of i?.getTracks()??[])e.stop();r?.disconnect(),a?.disconnect(),n?.close()};try{let[o]=(i=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.deviceId,echoCancellation:e.echoCancellation??!0,noiseSuppression:e.n
341oiseSuppression??!0,autoGainControl:e.autoGainControl??!0,channelCount:e.channelCount??1,sampleRate:{ideal:16e3}}})).getAudioTracks(),c=o?.getSettings().sampleRate;return n=new AudioContext(c?{sampleRate:c}:{}),await cD(n.audioWorklet),r=n.createMediaStreamSource(i),a=new AudioWorkletNode(n,"scribeAudioProcessor"),16e3!==n.sampleRate&&a.port.postMessage({type:"configure",inputSampleRate:n.sampleRate,outputSampleRate:16e3}),a.port.onmessage=e=>{t(cg(e.data.audioData))},r.connect(a),"suspended"===n.state&&await n.resume(),{mediaStreamTrack:o,cleanup:s}}catch(e){throw s(),e}};new Uint8Array(0);class cA{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);let i=this.listeners.get(e);i&&i.add(t)}off(e,t){let i=this.listeners.get(e);i&&i.delete(t)}emit(e,...t){let i=this.listeners.get(e);i&&i.forEach(e=>{e(...t)})}}(W=eP||(eP={})).SESSION_STARTED="session_started",W.PARTIAL_TRANSCRIPT="partial_transcript",W.COMMITTED_TRANSCRIPT="committed_transcript",W.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS="committed_transcript_with_timestamps",W.AUTH_ERROR="auth_error",W.ERROR="error",W.OPEN="open",W.CLOSE="close",W.QUOTA_EXCEEDED="quota_exceeded",W.COMMIT_THROTTLED="commit_throttled",W.TRANSCRIBER_ERROR="transcriber_error",W.UNACCEPTED_TERMS="unaccepted_terms",W.RATE_LIMITED="rate_limited",W.INPUT_ERROR="input_error",W.QUEUE_OVERFLOW="queue_overflow",W.RESOURCE_EXHAUSTED="resource_exhausted",W.SESSION_TIME_LIMIT_EXCEEDED="session_time_limit_exceeded",W.CHUNK_SIZE_EXCEEDED="chunk_size_exceeded",W.INSUFFICIENT_AUDIO_ACTIVITY="insufficient_audio_activity";class cN{websocket=null;eventEmitter=new cA;currentSampleRate=16e3;_muted=!1;_closed=!1;_audioCleanup;_mediaStreamTrack;constructor(e){this.currentSampleRate=e}get isMuted(){return this._muted}getMediaStreamTrackForMute(e){if(!this._mediaStreamTrack)throw Error(`Cannot ${e} audio without an active microphone MediaStreamTrack. mute() and unmute() are only supported for microphone connections.`);return this._mediaStreamTrack}mute(){let e=this.getMediaStreamTrackForMute("mute");this._muted=!0,e.enabled=!1}unmute(){let e=this.getMediaStreamTrackForMute("unmute");this._muted=!1,e.enabled=!0}setWebSocket(e){this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(eP.OPEN):this.websocket.addEventListener("open",()=>{this.eventEmitter.emit(eP.OPEN)}),this.websocket.addEventListener("message",e=>{try{let t=JSON.parse(e.data);switch(t.message_type){case"session_started":this.eventEmitter.emit(eP.
341SESSION_STARTED,t);break;case"partial_transcript":this.eventEmitter.emit(eP.PARTIAL_TRANSCRIPT,t);break;case"committed_transcript":this.eventEmitter.emit(eP.COMMITTED_TRANSCRIPT,t);break;case"committed_transcript_with_timestamps":this.eventEmitter.emit(eP.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,t);break;case"auth_error":this.eventEmitter.emit(eP.AUTH_ERROR,t),this.eventEmitter.emit(eP.ERROR,t);break;case"quota_exceeded":this.eventEmitter.emit(eP.QUOTA_EXCEEDED,t),this.eventEmitter.emit(eP.ERROR,t);break;case"commit_throttled":this.eventEmitter.emit(eP.COMMIT_THROTTLED,t),this.eventEmitter.emit(eP.ERROR,t);break;case"transcriber_error":this.eventEmitter.emit(eP.TRANSCRIBER_ERROR,t),this.eventEmitter.emit(eP.ERROR,t);break;case"unaccepted_terms":this.eventEmitter.emit(eP.UNACCEPTED_TERMS,t),this.eventEmitter.emit(eP.ERROR,t);break;case"rate_limited":this.eventEmitter.emit(eP.RATE_LIMITED,t),this.eventEmitter.emit(eP.ERROR,t);break;case"input_error":this.eventEmitter.emit(eP.INPUT_ERROR,t),this.eventEmitter.emit(eP.ERROR,t);break;case"queue_overflow":this.eventEmitter.emit(eP.QUEUE_OVERFLOW,t),this.eventEmitter.emit(eP.ERROR,t);break;case"resource_exhausted":this.eventEmitter.emit(eP.RESOURCE_EXHAUSTED,t),this.eventEmitter.emit(eP.ERROR,t);break;
341case"session_time_limit_exceeded":this.eventEmitter.emit(eP.SESSION_TIME_LIMIT_EXCEEDED,t),this.eventEmitter.emit(eP.ERROR,t);break;case"chunk_size_exceeded":this.eventEmitter.emit(eP.CHUNK_SIZE_EXCEEDED,t),this.eventEmitter.emit(eP.ERROR,t);break;case"insufficient_audio_activity":this.eventEmitter.emit(eP.INSUFFICIENT_AUDIO_ACTIVITY,t),this.eventEmitter.emit(eP.ERROR,t);break;case"error":this.eventEmitter.emit(eP.ERROR,t);break;default:console.warn("Unknown message type:",t)}}catch(t){console.error("Failed to parse WebSocket message:",t,e.data),this._emitError(Error(`Failed to parse message: ${t}`))}}),this.websocket.addEventListener("error",e=>{this._closed||(console.error("WebSocket error:",e),this._emitError(Error("WebSocket error")))}),this.websocket.addEventListener("close",e=>{let t=this._closed;if(this._closed=!0,!t&&(console.log(`WebSocket closed: code=${e.code}, reason="${e.reason}", wasClean=${e.wasClean}`),!e.wasClean||1e3!==e.code&&1005!==e.code)){let t=`WebSocket closed unexpectedly: ${e.code} - ${e.reason||"No reason provided"}`;console.error(t),this._emitError(Error(t))}this._audioCleanup&&(this._audioCleanup(),this._audioCleanup=void 0),this.eventEmitter.emit(eP.CLOSE,e)})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}_emitError(e){this.eventEmitter.emit(eP.ERROR,"object"==typeof e&&null!==e&&"message_type"in e&&"error"in e&&"string"==typeof e.message_type&&"string"==typeof e.error?e:{message_type:"error",error:e instanceof Error?e.message:String(e)})}send(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error("WebSocket is not connected");let t={message_type:"input_audio_chunk",audio_base_64:e.audioBase64,commit:e.commit??!1,sample_rate:e.sampleRate??this.currentSampleRate,previous_text:e.previousText};this.websocket.send(JSON.stringify(t))}commit(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error("WebSocket is not connected");let e={message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:this.currentSampleRate};this.websocket.send(JSON.stringify(e))}close(){this._closed=!0,this._audioCleanup&&(this._audioCleanup(),this._audioCleanup=void 0),this.websocket&&this.websocket.close(1e3,"User ended session")}}(H=e_||(e_={})).PCM_8000="pcm_8000",H.PCM_16000="pcm_16000",H.PCM_22050="pcm_22050",H.PCM_24000="pcm_24000",H.PCM_44100="pcm_44100",H.PCM_48000="pcm_48000",H.ULAW_8000="ulaw_8000",(G=eI||(eI={})).MANUAL="manual",G.VAD="vad";class cL{static DEFAULT_BASE_URI="wss://api.elevenlabs.io";static getWebSocketUri(e=cL.DEFAULT_BASE_URI){return`${e}
341/v1/speech-to-text/realtime`}static buildWebSocketUri(e){let t=cL.getWebSocketUri(e.baseUri),i=new URLSearchParams;if(i.append("model_id",e.modelId),i.append("token",e.token),void 0!==e.commitStrategy&&i.append("commit_strategy",e.commitStrategy),void 0!==e.audioFormat&&i.append("audio_format",e.audioFormat),void 0!==e.vadSilenceThresholdSecs){if(e.vadSilenceThresholdSecs<=.3||e.vadSilenceThresholdSecs>3)throw Error("vadSilenceThresholdSecs must be between 0.3 and 3.0");i.append("vad_silence_threshold_secs",e.vadSilenceThresholdSecs.toString())}if(void 0!==e.vadThreshold){if(e.vadThreshold<.1||e.vadThreshold>.9)throw Error("vadThreshold must be between 0.1 and 0.9");i.append("vad_threshold",e.vadThreshold.toString())}if(void 0!==e.minSpeechDurationMs){if(e.minSpeechDurationMs<=50||e.minSpeechDurationMs>2e3)throw Error("minSpeechDurationMs must be between 50 and 2000");i.append("min_speech_duration_ms",e.minSpeechDurationMs.toString())}if(void 0!==e.minSilenceDurationMs){if(e.minSilenceDurationMs<=50||e.minSilenceDurationMs>2e3)throw Error("minSilenceDurationMs must be between 50 and 2000");i.append("min_silence_duration_ms",e.minSilenceDurationMs.toString())}if(void 0!==e.languageCode&&i.append("language_code",e.languageCode),void 0!==e.includeTimestamps&&i.append("include_timestamps",e.includeTimestamps?"true":"false"),void 0!==e.includeLanguageDetection&&i.append("include_language_detection",e.includeLanguageDetection?"true":"false"),void 0!==e.ke
341yterms)for(let t of e.keyterms)i.append("keyterms",t);void 0!==e.noVerbatim&&i.append("no_verbatim",e.noVerbatim?"true":"false");let n=i.toString();return n?`${t}?${n}`:t}static connect(e){if(!e.modelId)throw Error("modelId is required");let t=new cN("microphone"in e&&e.microphone?16e3:e.sampleRate),i=new WebSocket(cL.buildWebSocketUri(e));return"microphone"in e&&e.microphone&&i.addEventListener("open",()=>{cL.streamFromMicrophone(e,t)}),t.setWebSocket(i),t}static async streamFromMicrophone(e,t){try{let i=function(){if(!cO)throw Error("No Scribe microphone implementation registered. Import '@elevenlabs/client/platform/web' or provide a custom implementation via setScribeMicrophoneSetup().");return cO}(),n=await i(e.microphone??{},e=>{t._closed||t.send({audioBase64:e})});t._mediaStreamTrack=n.mediaStreamTrack,t._audioCleanup=n.cleanup,t._closed&&(n.cleanup(),t._audioCleanup=void 0)}catch(e){console.error("Failed to start microphone streaming:",e),t._emitError(e)}}}!function(){if(!cT()||cP||"u"<typeof document)return;cP=!0;let e=()=>{!function(){let e,t;if(!cT()||cw)return;let i=new AudioContext;e=i.createBuffer(1,1,22050),(t=i.createBufferSource()).buffer=e,t.connect(i.destination),t.start(0),i.resume().catch(()=>{}),cw=i,cR&&clearTimeout(cR),cR=setTimeout(()=>{cR=null,cI()},3e4)}()};for(let t of cE)document.addEventListener(t,e,!0)}(),n=()=>new cx,cO=cM,e.i(943306),(0,ex.createContext)(null),new Uint8Array(0),(0,ex.createContext)(null),(0,ex.createContext)(null),(0,ex.createContext)(null),(0,ex.createContext)(null),(0,ex.createContext)(null),(0,ex.createContext)(null),to=Object.freeze({name:"react_sdk",version:"1.10.2"});var cU=e.i(778366);let cj={resource_exhausted:"Service is busy. Please try again in a moment.",quota_exceeded:"Usage quota exceeded. Please try again later.",rate_limited:"Too many requests. Please wait a moment."};function cF(e){let t=e?.trim();if(t)return t.length>1e3?t.slice(-1e3):t}function cB(e){return cj[e]||e||"Speech recognition failed"}function cq(e){let t=e.toLowerCase();return t.includes("permission denied")||t.includes("notallowederror")||t.includes("permissiondismissederror")||t.includes("microphone access denied")}function cV(e){return e instanceof Error&&e.message.trim().length>0?e.message:"object"==typeof e&&null!==e&&"error"in e&&"string"==typeof e.error&&e.error.trim().length>0?e.error:e instanceof CloseEvent&&"string"==typeof e.reason&&e.reason.trim().length>0?e.reason:"Speech connection failed"}function cW(e){let t="function"==typeof WebSocket?WebSocket.OPEN:1,i=e.readyState;if("number"==typeof i&&i===t)return!0;let n=e.state;if("string"==typeof n&&"open"===n||"connected"===n)return!0;let r=e.socket;if((0,eN.isObjectRecord)(r)){let e=r.readyState;if("number"==typeof e&&e===t)return!0}return!1}async function cH(e,t){let i=null,n=new Promise((e,t)=>{i=setTimeout(()=>{t(Error("Microphone connection timed out. Please try again."))},15e3)});try{await Promise.race([(async()=>{await e.connect({token:t,audioFormat:e_.PCM_16000,sampleRate:16e3});let i=e.getConnection();if(!i)throw Error("Speech connection was not created");await function(e,t=15e3){return new Promise((i,n)=>{if(cW(e))return void i();let r=!1,a=setTimeout(()=>{s(),n(Error("Microphone connection timed out. Please try again."))},t),s=()=>{r||(r=!0,a&&(clearTimeout(a),a=null),e.off(eP.OPEN,o),e.off(eP.CLOSE,c),e.off(eP.ERROR,l))},o=()=>{s(),i()},c=e=>{s(),n(Error(cV(e)||"Speech connection closed before microphone was ready"))},l=e=>{s(),n(Error(cV(e)))};e.on(eP.OPEN,o),e.on(eP.CLOSE,c),e.on(eP.ERROR,l),cW(e)&&o()})}(i,15e3)})(),n])}finally{i&&clearTimeout(i)}}async function cG(){let e=(0,eA.getActiveWorkspaceRef)();return(0,eA.runWorkspaceMutation)(async()=>{let t,i=await (0,eA.workspaceFetchFor)(e,"/api/speech-to-text/token",{method:"POST"});if(!i.ok){let e=`Failed to get speech token (${i.status})`;try{let t=await i.json();"object"==typeof t&&null!==t&&"error"in t&&"string"==typeof t.error&&(e=t.error)}catch{}throw Error(e)}try{t=await i.json()}catch{throw Error("Invalid response from speech service")}if(!t||"object"!=typeof t||!("token"in t)||"string"!=typeof t.token||!("sessionId"in t)||"string"!=typeof t.sessionId||0===t.token.length||0===t.sessionId.length)throw Error("Missing token or sessionId in response");return{token:t.token,sessionId:t.sessionId,workspace:e}},e)}async function cz(e,{keepalive:t=!1,preferBeacon:i=!1}={}){let n=JSON.stringify({sessionId:e.sessionId,workspace:(0,cU.serializeWorksp
341aceRef)(e.workspace)});if(i&&"u">typeof navigator&&"function"==typeof navigator.sendBeacon)try{if(navigator.sendBeacon("/api/speech-to-text/end",new Blob([n],{type:"application/json"})))return}catch{}try{let i=new AbortController,r=setTimeout(()=>i.abort(),5e3);try{await (0,eA.runWorkspaceMutation)(async()=>{if(!(await (0,eA.workspaceFetchFor)(e.workspace,"/api/speech-to-text/end",{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:t,signal:i.signal})).ok)throw Error("Failed to end speech session")},e.workspace)}finally{clearTimeout(r)}}catch{}}function cK(e){let t=e instanceof Error?e.message:"Failed to start recording";return cq(t)?ts:cB(t)}async function cJ({scribe:e,controls:t,connectAttemptRef:i,sessionRef:n,endActiveSession:r,getTranscriptContext:a}){let{attemptId:s,audioGate:o,createLiveSender:c}=t,l=()=>i.current===s;o.close();let d=null;for(let t=1;t<=2;t+=1){if(!l())return"superseded";try{let{token:t,sessionId:i,workspace:s}=await cG(),d={sessionId:i,workspace:s};if(!l())return await cz(d),"superseded";if(r(),n.current=d,e.getConnection()&&e.disconnect(),await cH(e,t),!l()){try{e.disconnect()}catch{}return"superseded"}return o.open(c(a())),"resumed"}catch(e){d=e,t<2&&await new Promise(e=>setTimeout(e,400))}}throw d instanceof Error?d:Error("Speech connection failed")}async function c$(){if(!navigator?.permissions)return"unknown";try{return(await navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}}let cQ=/built-in|macbook|internal/i,cX="snow.stt.builtInMicrophoneId";function cY(){try{return window.localStorage.getItem(cX)??void 0}catch{return}}function cZ(e){try{window.localStorage.setItem(cX,e)}catch{}}async function c0(){try{var e;let t=(e=(await navigator.mediaDevices.enumerateDevices()).filter(e=>"audioinput"===e.kind).map(({deviceId:e,label:t})=>({deviceId:e,label:t})),e.find(e=>"default"!==e.deviceId&&cQ.test(e.label))?.deviceId);if(t)return cZ(t),t;return cY()}catch{return cY()}}let c1="snowchatScribeAudioProcessor",c2=` 342class SnowchatScribeAudioProcessor extends AudioWorkletProcessor { 343 constructor() { 344 super(); 345 this.buffer = []; 346 this.bufferSize = 1024; 347 this.port.onmessage = (event) => { 348 const data = event.data; 349 if (!data || data.type !== "flush") { 350 return; 351 } 352 353 this.flushBuffer(data.flushId); 354 }; 355 } 356 357 flushBuffer(flushId) { 358 if (this.buffer.length > 0) { 359 const float32Array = new Float32Array(this.buffer); 360 const int16Array = new Int16Array(float32Array.length); 361 362 for (let index = 0; index < float32Array.length; index += 1) { 363 const sample = Math.max(-1, Math.min(1, float32Array[index])); 364 int16Array[index] = sample < 0 ? sample * 32768 : sample * 32767; 365 } 366 367 this.port.postMessage( 368 { type: "audio", audioData: int16Array.buffer, flushId }, 369 [int16Array.buffer] 370 ); 371 372 this.buffer = []; 373 } 374 375 this.port.postMessage({ type: "flush-complete", flushId }); 376 } 377 378 process(inputs) { 379 const input = inputs[0]; 380 if (input.length === 0) { 381 return true; 382 } 383 384 const channelData = input[0]; 385 this.buffer.push(...channelData); 386 387 if (this.buffer.length < this.bufferSize) { 388 return true; 389 } 390 391 this.flushBuffer(); 392 return true; 393 } 394} 395 396registerProcessor("${c1}", SnowchatScribeAudioProcessor); 397`,c3=null,c6=null,c4=null,c5=0;async function c8(){let e=c6;if(!e||"closed"===e.state){let t=new AudioContext({sampleRate:16e3});e=t,c6=t,c4=t.audioWorklet.addModule(c3||(c3=URL.createObjectURL(new Blob([c2],{type:"text/javascript"})))).catch(e=>{throw c6===t&&(c6=null,c4=null),t.close().catch(()=>{}),e})}return await c4,e}function c9(){if("u">typeof DOMException)return new DOMException("The operation was aborted","AbortError");let e=Error("The operation was aborted");return e.name="AbortError",e}function c7(e){if(e?.aborted)throw c9()}async function le(e){let t=null,i=null,n=null,r=null,a=!1,s=!1,o=1,c=new Map,l=async()=>{if(!r)return;let e=o;o+=1,await new Promise(t=>{let i=setTimeout(()=>{c.delete(e),t()},100);c.set(e,{resolve:t,timeoutId:i}),r?.port.postMessage({type:"flush",flushId:e})})},d=async()=>
397{if(!s){await l(),s=!0,e.signal?.removeEventListener("abort",u),r&&(r.port.onmessage=null);try{n?.disconnect()}catch{}try{r?.disconnect()}catch{}if(t?.getTracks().forEach(e=>e.stop()),t=null,n=null,r=null,a&&(a=!1,0===(c5=Math.max(0,c5-1))&&i&&"running"===i.state)){try{await i.suspend()}catch{}if(c5>0&&"running"!==i.state)try{await i.resume()}catch{}}for(let[e,t]of(i=null,c.entries()))clearTimeout(t.timeoutId),c.delete(e),t.resolve()}},u=()=>{d()};e.signal?.addEventListener("abort",u,{once:!0});try{c7(e.signal);let o=t=>navigator.mediaDevices.getUserMedia({audio:{deviceId:t,echoCancellation:e.microphone?.echoCancellation??!0,noiseSuppression:e.microphone?.noiseSuppression??!0,autoGainControl:e.microphone?.autoGainControl??!0,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),l=async()=>{let t=e.microphone?.deviceId,i=await o(t??await c0());if(t)return i;try{var n;let e=i.getAudioTracks()[0];if(n=e?.label??"",cQ.test(n)){let t=e?.getSettings().deviceId;return t&&cZ(t),i}let t=await c0();if(!t)return i;let r=await o(t);return i.getTracks().forEach(e=>e.stop()),r}catch{return i}},[u,h]=await Promise.allSettled([l(),c8()]);if("fulfilled"===u.status&&(t=u.value),"fulfilled"===h.status&&(i=h.value),s)throw t?.getTracks().forEach(e=>e.stop()),t=null,i=null,c9();if("rejected"===u.status)throw u.reason;if("rejected"===h.status)throw h.reason;if(!t||!i)throw Error("Microphone setup failed");return c5+=1,a=!0,c7(e.signal),n=i.createMediaStreamSource(t),(r=new AudioWorkletNode(i,c1)).port.onmessage=t=>{if("flush-complete"===t.data.type)return void(e=>{if("number"!=typeof e)return;let t=c.get(e);t&&(clearTimeout(t.timeoutId),c.delete(e),t.resolve())})(t.data.flushId);if(s||e.signal?.aborted)return;let i=t.data.audioData;i instanceof ArrayBuffer&&(e.onLevel?.(function(e){let t=new Int16Array(e);if(0===t.length)return 0;let i=0;for(let e=0;e<t.length;e+=1){let n=t[e]??0;i+=n*n}return Math.min(1,Math.sqrt(i/t.length)/8e3)}(i)),e.onChunk(function(e){let t=new Uint8Array(e),i="";for(let e=0;e<t.length;e+=1){let n=t[e];void 0!==n&&(i+=String.fromCharCode(n))}return btoa(i)}(i)))},n.connect(r),"running"!==i.state&&await i.resume(),c7(e.signal),{stop:d}}catch(e){throw await d(),e}}async function lt({attemptId:e,scribe:t,previousText:i,onAudioLevel:n,activeControlsRef:r,connectAttemptRef:a,teardownInProgressRef:s,disconnectingRef:o,sessionRef:c,microphoneStreamRef:l,microphoneSetupAbortRef:d,drainingAttemptRef:u,pendingConnectionRef:h,setPendingConnection:p,setIsAwaitingPermission:m,setIsPermissionBlocked:g,clearPermissionListener:f,setPermissionCleanup:v,emitErrorOnce:b,teardownSession:y,handleRealtimeError:k,markMicReady:T,resetIdleTimer:S}){if(s.current)return;let C=await c$();if(a.current!==e)return;if("denied"===C){h.current=!1,p(!1),g(!0),b("Microphone access is blocked. Click the lock icon in your browser's address bar to enable it.");return}if("prompt"===C){m(!0);let t=function(e){if(!navigator?.permissions)return()=>{};let t=null,i=!1,n=()=>{t&&e(t.state)};return navigator.permissions.query({name:"microphone"}).then(e=>{i||(t=e,e.addEventListener("change",n))}).catch(()=>{}),()=>{i=!0,t&&t.removeEventListener("change",n)}}(t=>{if(a.current===e){if("granted"===t){m(!1),f();return}"denied"===t&&(g(!0),b(ts),f(),y({disconnect:!0,endSession:!0}))}});a.current===e?v(t):t()}let E=()=>a.current===e,w=function({maxBufferedChunks:e,onOverflow:t}){let i=[],n=null,r=!1;return{push(a){if(n)return void n(a);if(i.length>=e){r||(r=!0,t());return}i.push(a)},open(e){let t=i;i=[],n=e;for(let r=0;r<t.length;r+=1){let a=t[r];if(void 0!==a&&(e(a),n!==e)){i=i.concat(t.slice(r+1));return}}r=!1},close(){n=null}}}({maxBufferedChunks:480,onOverflow:()=>{E()&&k("Speech connection failed")}}),R=i=>{let n=!0;return r=>{let a=u.current===e;if(E()&&(!s.current||a)&&!o.current)try{t.sendAudio(r,n&&i?{previousText:i}:void 0),n=!1}catch{w.close(),w.push(r)}}};r.current={attemptId:e,audioGate:w,createLiveSender:R};try{let e=li({audioGate:w,isAttemptCurrent:E,microphoneStreamRef:l,microphoneSetupAbortRef:d,onAudioLevel:n,clearPermissionListener:f,markMicReady:T,resetIdleTimer:S}),r=ln({isAttemptCurrent:E,sessionRef:c}),a=lr({audioGate:w,createLiveSender:R,isAttemptCurrent:E,microphoneLeg:e,permissionState:C,previousText:i,scribe:t,tokenLeg:r});await Promise.all([e,r,a])}catch(i){if(a.current!==e||i instanceof Error&&"AbortError"===i.name)return;let t=cK(i);cq(i instanceof Error?i.message:"")&&g(!0),b(t),await y({disconnect:!0,endSession:!0})}}async function li({audioGate:e,isAttemptCurrent:t,microphoneStreamRef:i,microphoneSetupAbortRef:n,onAudioLevel:r,clearPermissionListener:a,markMicReady:s,resetIdleTimer:o}){let c=new AbortController;n.current=c;let l=await le({signal:c.signal,microphone:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},onChunk:t=>{e.push(t)},onLevel:r});(n.current===c&&(n.current=null),t())?(i.current=l,a(),s(),o()):await l.stop()}async function ln({isAttemptCurrent:e,sessionRef:t}){let{token:i,sessionId:n,workspace:r}=await cG(),a={sessionId:n,workspace:r};return e()?(t.current=a,i):(await cz(a),null)}async function lr({audioGate:e,createLiveSender:t,isAttemptCurrent:i,microphoneLeg:n,permissionState:r,previousText:a,scribe:s,tokenLeg:o}){let c=await o;
397if(null!==c&&("granted"!==r&&await n,i())){if(await cH(s,c),!i()){try{s.disconnect()}catch{}return}e.open(t(a))}}e.s(["useSpeechToText",0,function(e={}){let{onTranscriptChange:t,onCommit:i,onError:n,onStop:r,vadSilenceThresholdSecs:a=.8,vadThreshold:s=.4,minSpeechDurationMs:o=100,minSilenceDurationMs:c=100,languageCode:l="auto",idleTimeoutSecs:d=30}=e;return function({config:e,onCommit:t,onError:i,onStop:n,onTranscriptChange:r}){let[a,s]=(0,ex.useState)(null),[o,c]=(0,ex.useState)(!1),[l,d]=(0,ex.useState)(!1),[u,h]=(0,ex.useState)(!1),[p,m]=(0,ex.useState)(!1),g=(0,ex.useRef)(n),f=(0,ex.useRef)(i),v=(0,ex.useRef)(null),b=(0,ex.useRef)(!1),y=(0,ex.useRef)(!1),k=(0,ex.useRef)(async()=>{}),T=(0,ex.useRef)(0),S=(0,ex.useRef)(null),C=(0,ex.useRef)(null),E=(0,ex.useRef)(null),w=(0,ex.useRef)(null),R=(0,ex.useRef)(null),P=(0,ex.useRef)(null),_=(0,ex.useRef)(null),I=(0,ex.useRef)(!1),x=(0,ex.useRef)(null),O=(0,ex.useRef)(0),D=(0,ex.useRef)(!1),M=(0,ex.useRef)(!1),A=(0,ex.useRef)(null),N=(0,ex.useRef)(0);(0,ex.useEffect)(()=>{g.current=n},[n]),(0,ex.useEffect)(()=>{f.current=i},[i]),(0,ex.useEffect)(()=>{D.current=p},[p]),(0,ex.useEffect)(()=>{M.current=o},[o]);let L=(0,ex.useCallback)(()=>{S.current&&(clearTimeout(S.current),S.current=null)},[]),U=(0,ex.useCallback)(()=>{v.current&&(v.current(),v.current=null)},[]),j=(0,ex.useCallback)(()=>{D.current=!1,M.current=!1,O.current=0,m(!1),d(!1),c(!1)},[]),F=(0,ex.useCallback)(()=>{D.current=!0,M.current=!1,m(!0),d(!1),c(!1)},[]),B=(0,ex.useCallback)(e=>{let t=Date.now();A.current===e&&t-N.current<500||(A.current=e,N.current=t,s(e),f.current?.(e))},[]),q=(0,ex.useCallback)(e=>{let t=E.current;t&&(E.current=null,cz(t,e))},[]),V=(0,ex.useCallback)(async()=>{R.current?.abort(),R.current=null;let e=w.current;w.current=null,e&&await e.stop()},[]),W=(0,ex.useCallback)(async()=>{P.current=T.current;try{await V()}finally{P.current=null}},[V]),H=(0,ex.useCallback)(()=>{L(),e.idleTimeoutSecs>0&&(S.current=setTimeout(()=>{k.current({disconnect:!0,endSession:!0,notifyStop:!0})},1e3*e.idleTimeoutSecs))},[L,e.idleTimeoutSecs]),{clearTranscriptBuffers:G,getCurrentText:z,handleCommittedTranscript:K,handlePartialTranscript:J,sealPartialTranscript:$,setBaseText:Q}=function({disconnectingRef:e,isMicReadyRef:t,teardownInProgressRef:i,onCommit:n,onTranscriptChange:r,markMicReady:a,resetIdleTimer:s}){let o=(0,ex.useRef)(""),c=(0,ex.useRef)(""),l=(0,ex.useRef)(""),d=(0,ex.useCallback)(()=>{o.current="",c.current="",l.current=""},[]),u=(0,ex.useCallback)(e=>{o.current=e?e.endsWith(" ")?e:`${e} `:"",c.current="",l.current=""},[]),h=(0,ex.useCallback)(()=>o.current+c.current+l.current,[]),p=(0,ex.useCallback)(()=>{if(!l.current)return;c.current+=`${l.current} `,l.current="";let e=o.current+c.current.trim();r?.(e)},[r]),m=(0,ex.useCallback)(n=>{if(e.current)return;t.current||i.current||a(),n.text!==l.current&&(l.current=n.text,n.text.trim().length>0&&s());let d=o.current+c.current+n.text;r?.(d)},[e,t,i,a,r,s]);return{clearTranscriptBuffers:d,getCurrentText:h,handleCommittedTranscript:(0,ex.useCallback)(s=>{if(e.current)return;t.current||i.current||a(),l.current="",c.current+=`${s.text} `;let d=o.current+c.current.trim();r?.(d),n?.(d)},[e,t,i,a,n,r]),handlePartialTranscript:m,sealPartialTranscript:p,setBaseText:u}}({disconnectingRef:b,isMicReadyRef:D,teardownInProgressRef:y,onCommit:t,onTranscriptChange:r,markMicReady:F,resetIdleTimer:H}),X=(0,ex.useCallback)(async()=>{let e=C.current;if(e){try{e.commit()}catch{return}await new Promise(e=>{let t=setTimeout(()=>{x.current=null,e()},600);x.current={settle:()=>{clearTimeout(t),x.current=null,e()}}})}},[]),Y=(0,ex.useCallback)(async({disconnect:e=!1,endSession:t=!0,notifyStop:i=!1,keepalive:n=!1,preferBeacon:r=!1,commitTail:a=!1}={})=>{if(!y.current){y.current=!0,L(),U();try{if(await W(),T.current+=1,j(),a&&await X(),e){b.current=!0;try{C.current?.disconnect()}catch{}b.current=!1}t&&q({keepalive:n,preferBeacon:r})}finally{G(),j(),y.current=!1,i&&g.current?.()}}},[L,U,G,W,q,X,j]);(0,ex.useEffect)(()=>{k.current=Y},[Y]);let Z=(0,ex.useCallback)(e=>{if(y.current||I.current)return;let t=cq(e);t&&h(!0),B(t?ts:cB(e)),Y({disconnect:!0,endSession:!0})},[B,Y]),ee=(0,ex.useCallback)(()=>!b.current&&!y.current&&!I.current&&D.current&&_.current?.attemptId===T.current,[]),et=(0,ex.useCallback)(()=>
397{if(!ee())return;let e=C.current,t=_.current;e&&t&&(I.current=!0,$(),(async()=>{try{await cJ({scribe:e,controls:t,connectAttemptRef:T,sessionRef:E,endActiveSession:q,getTranscriptContext:()=>cF(z())})}catch(e){B(cK(e)),await Y({disconnect:!0,endSession:!0,notifyStop:!0})}finally{I.current=!1}})())},[ee,B,q,z,$,Y]),ei="auto"===e.languageCode?void 0:e.languageCode,en=function(e={}){let{onSessionStarted:t,onPartialTranscript:i,onCommittedTranscript:n,onCommittedTranscriptWithTimestamps:r,onError:a,onAuthError:s,onQuotaExceededError:o,onCommitThrottledError:c,onTranscriberError:l,onUnacceptedTermsError:d,onRateLimitedError:u,onInputError:h,onQueueOverflowError:p,onResourceExhaustedError:m,onSessionTimeLimitExceededError:g,onChunkSizeExceededError:f,onInsufficientAudioActivityError:v,onConnect:b,onDisconnect:y,token:k,modelId:T,baseUri:S,commitStrategy:C,vadSilenceThresholdSecs:E,vadThreshold:w,minSpeechDurationMs:R,minSilenceDurationMs:P,languageCode:_,microphone:I,audioFormat:x,sampleRate:O,autoConnect:D=!1,includeTimestamps:M,includeLanguageDetection:A,keyterms:N,noVerbatim:L}=e,U=(0,ex.useRef)(null),[j,F]=(0,ex.useState)("disconnected"),[B,q]=(0,ex.useState)(!1),[V,W]=(0,ex.useState)(""),[H,G]=(0,ex.useState)([]),[z,K]=(0,ex.useState)(null);(0,ex.useEffect)(()=>()=>{U.current?.close()},[]);let J=(0,ex.useCallback)(async(e={})=>{if(U.current)return void console.warn("Already connected");try{let D;F("connecting"),K(null);let j=e.token||k,B=e.modelId||T;if(!j)throw Error("Token is required");if(!B)throw Error("Model ID is required");let V=e.microphone||I,H=e.audioFormat||x,z=e.sampleRate||O,J=e.includeTimestamps??M??!!(e.onCommittedTranscriptWithTimestamps||r),$=e.includeLanguageDetection??A;if(V)D=cL.connect({token:j,modelId:B,baseUri:e.baseUri||S,commitStrategy:e.commitStrategy||C,vadSilenceThresholdSecs:e.vadSilenceThresholdSecs||E,vadThreshold:e.vadThreshold||w,minSpeechDurationMs:e.minSpeechDurationMs||R,minSilenceDurationMs:e.minSilenceDurationMs||P,languageCode:e.languageCode||_,keyterms:e.keyterms||N,noVerbatim:e.noVerbatim??L,microphone:V,includeTimestamps:J,includeLanguageDetection:$});else if(H&&z)D=cL.connect({token:j,modelId:B,baseUri:e.baseUri||S,commitStrategy:e.commitStrategy||C,vadSilenceThresholdSecs:e.vadSilenceThresholdSecs||E,vadThreshold:e.vadThreshold||w,minSpeechDurationMs:e.minSpeechDurationMs||R,minSilenceDurationMs:e.minSilenceDurationMs||P,languageCode:e.languageCode||_,keyterms:e.keyterms||N,noVerbatim:e.noVerbatim??L,includeTimestamps:J,includeLanguageDetection:$,audioFormat:H,sampleRate:z});else throw Error("Either microphone options or (audioFormat + sampleRate) must be provided");U.current=D,D.on(eP.SESSION_STARTED,()=>{F("connected"),t?.()}),D.on(eP.PARTIAL_TRANSCRIPT,e=>{W(e.text),F("transcribing"),i?.(e)}),D.on(eP.COMMITTED_TRANSCRIPT,e=>{let t={id:`${Date.now()}-${Math.random()}`,text:e.text,timestamp:Date.now(),isFinal:!0};G(e=>[...e,t]),W(""),n?.(e)}),D.on(eP.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,e=>{let t={id:`${Date.now()}-${Math.random()}`,text:e.text,timestamp:Date.now(),isFinal:!0,languageCode:e.language_code,words:e.words};G(e=>[...e,t]),W(""),r?.(e)}),D.on(eP.ERROR,e=>{K(e.error),F("error"),a?.(Error(e.error))}),D.on(eP.AUTH_ERROR,e=>{K(e.error),F("error"),s?.(e)}),D.on(eP.QUOTA_EXCEEDED,e=>{K(e.error),F("error"),o?.(e)}),D.on(eP.COMMIT_THROTTLED,e=>{K(e.error),F("error"),c?.(e)}),D.on(eP.TRANSCRIBER_ERROR,e=>{K(e.error),F("error"),l?.(e)}),D.on(eP.UNACCEPTED_TERMS,e=>{K(e.error),F("error"),d?.(e)}),D.on(eP.RATE_LIMITED,e=>{K(e.error),F("error"),u?.(e)}),D.on(eP.INPUT_ERROR,e=>{K(e.error),F("error"),h?.(e)}),D.on(eP.QUEUE_OVERFLOW,e=>{K(e.error),F("error"),p?.(e)}),D.on(eP.RESOURCE_EXHAUSTED,e=>{K(e.error),F("error"),m?.(e)}),D.on(eP.SESSION_TIME_LIMIT_EXCEEDED,e=>{K(e.error),F("error"),g?.(e)}),D.on(eP.CHUNK_SIZE_EXCEEDED,e=>{K(e.error),F("error"),f?.(e)}),D.on(eP.INSUFFICIENT_AUDIO_ACTIVITY,e=>{K(e.error),F("error"),v?.(e)}),D.on(eP.OPEN,()=>{b?.()}),D.on(eP.CLOSE,()=>{F("disconnected"),q(!1),U.current=null,y?.()})}catch(e){throw K(e instanceof Error?e.message:"Failed to connect"),F("error"),e}},[k,T,S,C,E,w,R,P,_,I,x,O,M,A,N,L,t,i,n,r,a,s,o,c,l,d,u,h,p,m,g,f,v,b,y]),$=(0,ex.useCallback)(()=>{U.current?.close(),U.current=null,F("disconnected"),q(!1)},[]),Q=(0,ex.useCallback)(()=>
397{if(!U.current)throw Error("Not connected to Scribe");U.current.mute(),q(!0)},[]),X=(0,ex.useCallback)(()=>{if(!U.current)throw Error("Not connected to Scribe");U.current.unmute(),q(!1)},[]),Y=(0,ex.useCallback)((e,t)=>{if(!U.current)throw Error("Not connected to Scribe");U.current.send({audioBase64:e,...t})},[]),Z=(0,ex.useCallback)(()=>{if(!U.current)throw Error("Not connected to Scribe");U.current.commit()},[]),ee=(0,ex.useCallback)(()=>{G([]),W("")},[]),et=(0,ex.useCallback)(()=>U.current,[]);return(0,ex.useEffect)(()=>{D&&J()},[D,J]),{status:j,isConnected:"connected"===j||"transcribing"===j,isTranscribing:"transcribing"===j,isMuted:B,partialTranscript:V,committedTranscripts:H,error:z,connect:J,disconnect:$,mute:Q,unmute:X,sendAudio:Y,commit:Z,clearTranscripts:ee,getConnection:et}}({modelId:"scribe_v2_realtime",vadSilenceThresholdSecs:e.vadSilenceThresholdSecs,vadThreshold:e.vadThreshold,minSpeechDurationMs:e.minSpeechDurationMs,minSilenceDurationMs:e.minSilenceDurationMs,languageCode:ei,noVerbatim:!0,onPartialTranscript:J,onCommittedTranscript:e=>{K(e),x.current?.settle()},onError:e=>{let t,i=e instanceof Error?e.message:"";((t=i.toLowerCase()).includes("websocket error")||t.includes("websocket closed unexpectedly"))&&ee()?et():Z(i||"Speech recognition failed")},onAuthError:e=>{Z(e.error)},onQuotaExceededError:e=>{Z(e.error)},onRateLimitedError:e=>{Z(e.error)},onResourceExhaustedError:e=>{Z(e.error)},onDisconnect:()=>{b.current||y.current||I.current||(ee()?et():(D.current||M.current||E.current)&&Y({disconnect:!1,endSession:!0,notifyStop:!0}))}});(0,ex.useEffect)(()=>{C.current=en},[en]),(0,ex.useEffect)(()=>{let e=e=>{L(),U(),(async()=>{try{await W()}finally{T.current+=1,b.current=!0;try{C.current?.disconnect()}catch{}b.current=!1}})(),G(),D.current=!1,M.current=!1,e&&(s(null),j()),q({keepalive:!0,preferBeacon:!0})},t=()=>e(!0);return window.addEventListener("pagehide",t),window.addEventListener("beforeunload",t),()=>{window.removeEventListener("pagehide",t),window.removeEventListener("beforeunload",t),e(!1)}},[L,U,G,W,q,j]),(0,ex.useEffect)(()=>{if(!a)return;let e=setTimeout(()=>s(null),3e3);return()=>clearTimeout(e)},[a]);let er=(0,ex.useCallback)(async e=>{if(y.current)return;let t=T.current+1;T.current=t,s(null),h(!1),d(!1),m(!1),D.current=!1,c(!0),M.current=!0,L(),U(),E.current&&q(),Q(e),await lt({attemptId:t,scribe:en,previousText:cF(e),onAudioLevel:e=>{O.current=e},activeControlsRef:_,connectAttemptRef:T,teardownInProgressRef:y,disconnectingRef:b,sessionRef:E,microphoneStreamRef:w,microphoneSetupAbortRef:R,drainingAttemptRef:P,pendingConnectionRef:M,setPendingConnection:c,setIsAwaitingPermission:d,setIsPermissionBlocked:h,clearPermissionListener:U,setPermissionCleanup:e=>{v.current=e},emitErrorOnce:B,teardownSession:Y,handleRealtimeError:Z,markMicReady:F,resetIdleTimer:H})},[L,U,B,q,Z,F,H,en,Q,Y]),ea=(0,ex.useCallback)(e=>{Y({disconnect:!0,endSession:!0,notifyStop:!0,commitTail:e?.commitTail??!0})},[Y]),es=(0,ex.useCallback)(async e=>{p||o?ea():await er(e)},[p,o,er,ea]);return{audioLevelRef:O,dismissBlocked:(0,ex.useCallback)(()=>{h(!1),s(null)},[]),error:a,isAwaitingPermission:l,isConnecting:o&&!p,isPermissionBlocked:u,isRecording:p,startRecording:er,stopRecording:ea,toggleRecording:es}}({config:{vadSilenceThresholdSecs:a,vadThreshold:s,minSpeechDurationMs:o,minSilenceDurationMs:c,languageCode:l,idleTimeoutSecs:d},onTranscriptChange:t,onCommit:i,onError:n,onStop:r})}],701049)}]); 398 399//# chunkId=01a0804f-862a-79d0-9e7a-8ff2b7e3968d
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.