@pulsebeam/peer 0.0.21 → 0.1.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +25 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +728 -2
- package/dist/index.d.ts +728 -2
- package/dist/index.global.js +39 -0
- package/dist/index.js +25 -26
- package/dist/index.js.map +1 -1
- package/dist/peer.d.ts +1 -0
- package/dist/peer.js +5807 -0
- package/dist/peer.umd.cjs +39 -0
- package/package.json +13 -24
@@ -0,0 +1,39 @@
|
|
1
|
+
"use strict";(()=>{var Cn=Object.create;var Se=Object.defineProperty;var Sn=Object.getOwnPropertyDescriptor;var Rn=Object.getOwnPropertyNames;var Tn=Object.getPrototypeOf,vn=Object.prototype.hasOwnProperty;var In=(t,e,r)=>e in t?Se(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var xn=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Re=(t,e)=>{for(var r in e)Se(t,r,{get:e[r],enumerable:!0})},En=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Rn(e))!vn.call(t,i)&&i!==r&&Se(t,i,{get:()=>e[i],enumerable:!(n=Sn(e,i))||n.enumerable});return t};var Ir=(t,e,r)=>(r=t!=null?Cn(Tn(t)):{},En(e||!t||!t.__esModule?Se(r,"default",{value:t,enumerable:!0}):r,t));var g=(t,e,r)=>In(t,typeof e!="symbol"?e+"":e,r);var _t=xn((Pi,Dt)=>{"use strict";var h={};h.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};h.localCName=h.generateIdentifier();h.splitLines=function(t){return t.trim().split(`
|
2
|
+
`).map(e=>e.trim())};h.splitSections=function(t){return t.split(`
|
3
|
+
m=`).map((r,n)=>(n>0?"m="+r:r).trim()+`\r
|
4
|
+
`)};h.getDescription=function(t){let e=h.splitSections(t);return e&&e[0]};h.getMediaSections=function(t){let e=h.splitSections(t);return e.shift(),e};h.matchPrefix=function(t,e){return h.splitLines(t).filter(r=>r.indexOf(e)===0)};h.parseCandidate=function(t){let e;t.indexOf("a=candidate:")===0?e=t.substring(12).split(" "):e=t.substring(10).split(" ");let r={foundation:e[0],component:{1:"rtp",2:"rtcp"}[e[1]]||e[1],protocol:e[2].toLowerCase(),priority:parseInt(e[3],10),ip:e[4],address:e[4],port:parseInt(e[5],10),type:e[7]};for(let n=8;n<e.length;n+=2)switch(e[n]){case"raddr":r.relatedAddress=e[n+1];break;case"rport":r.relatedPort=parseInt(e[n+1],10);break;case"tcptype":r.tcpType=e[n+1];break;case"ufrag":r.ufrag=e[n+1],r.usernameFragment=e[n+1];break;default:r[e[n]]===void 0&&(r[e[n]]=e[n+1]);break}return r};h.writeCandidate=function(t){let e=[];e.push(t.foundation);let r=t.component;r==="rtp"?e.push(1):r==="rtcp"?e.push(2):e.push(r),e.push(t.protocol.toUpperCase()),e.push(t.priority),e.push(t.address||t.ip),e.push(t.port);let n=t.type;return e.push("typ"),e.push(n),n!=="host"&&t.relatedAddress&&t.relatedPort&&(e.push("raddr"),e.push(t.relatedAddress),e.push("rport"),e.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(e.push("tcptype"),e.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(e.push("ufrag"),e.push(t.usernameFragment||t.ufrag)),"candidate:"+e.join(" ")};h.parseIceOptions=function(t){return t.substring(14).split(" ")};h.parseRtpMap=function(t){let e=t.substring(9).split(" "),r={payloadType:parseInt(e.shift(),10)};return e=e[0].split("/"),r.name=e[0],r.clockRate=parseInt(e[1],10),r.channels=e.length===3?parseInt(e[2],10):1,r.numChannels=r.channels,r};h.writeRtpMap=function(t){let e=t.payloadType;t.preferredPayloadType!==void 0&&(e=t.preferredPayloadType);let r=t.channels||t.numChannels||1;return"a=rtpmap:"+e+" "+t.name+"/"+t.clockRate+(r!==1?"/"+r:"")+`\r
|
5
|
+
`};h.parseExtmap=function(t){let e=t.substring(9).split(" ");return{id:parseInt(e[0],10),direction:e[0].indexOf("/")>0?e[0].split("/")[1]:"sendrecv",uri:e[1],attributes:e.slice(2).join(" ")}};h.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
|
6
|
+
`};h.parseFmtp=function(t){let e={},r,n=t.substring(t.indexOf(" ")+1).split(";");for(let i=0;i<n.length;i++)r=n[i].trim().split("="),e[r[0].trim()]=r[1];return e};h.writeFmtp=function(t){let e="",r=t.payloadType;if(t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){let n=[];Object.keys(t.parameters).forEach(i=>{t.parameters[i]!==void 0?n.push(i+"="+t.parameters[i]):n.push(i)}),e+="a=fmtp:"+r+" "+n.join(";")+`\r
|
7
|
+
`}return e};h.parseRtcpFb=function(t){let e=t.substring(t.indexOf(" ")+1).split(" ");return{type:e.shift(),parameter:e.join(" ")}};h.writeRtcpFb=function(t){let e="",r=t.payloadType;return t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(n=>{e+="a=rtcp-fb:"+r+" "+n.type+(n.parameter&&n.parameter.length?" "+n.parameter:"")+`\r
|
8
|
+
`}),e};h.parseSsrcMedia=function(t){let e=t.indexOf(" "),r={ssrc:parseInt(t.substring(7,e),10)},n=t.indexOf(":",e);return n>-1?(r.attribute=t.substring(e+1,n),r.value=t.substring(n+1)):r.attribute=t.substring(e+1),r};h.parseSsrcGroup=function(t){let e=t.substring(13).split(" ");return{semantics:e.shift(),ssrcs:e.map(r=>parseInt(r,10))}};h.getMid=function(t){let e=h.matchPrefix(t,"a=mid:")[0];if(e)return e.substring(6)};h.parseFingerprint=function(t){let e=t.substring(14).split(" ");return{algorithm:e[0].toLowerCase(),value:e[1].toUpperCase()}};h.getDtlsParameters=function(t,e){return{role:"auto",fingerprints:h.matchPrefix(t+e,"a=fingerprint:").map(h.parseFingerprint)}};h.writeDtlsParameters=function(t,e){let r="a=setup:"+e+`\r
|
9
|
+
`;return t.fingerprints.forEach(n=>{r+="a=fingerprint:"+n.algorithm+" "+n.value+`\r
|
10
|
+
`}),r};h.parseCryptoLine=function(t){let e=t.substring(9).split(" ");return{tag:parseInt(e[0],10),cryptoSuite:e[1],keyParams:e[2],sessionParams:e.slice(3)}};h.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?h.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
|
11
|
+
`};h.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;let e=t.substring(7).split("|");return{keyMethod:"inline",keySalt:e[0],lifeTime:e[1],mkiValue:e[2]?e[2].split(":")[0]:void 0,mkiLength:e[2]?e[2].split(":")[1]:void 0}};h.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")};h.getCryptoParameters=function(t,e){return h.matchPrefix(t+e,"a=crypto:").map(h.parseCryptoLine)};h.getIceParameters=function(t,e){let r=h.matchPrefix(t+e,"a=ice-ufrag:")[0],n=h.matchPrefix(t+e,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substring(12),password:n.substring(10)}:null};h.writeIceParameters=function(t){let e="a=ice-ufrag:"+t.usernameFragment+`\r
|
12
|
+
a=ice-pwd:`+t.password+`\r
|
13
|
+
`;return t.iceLite&&(e+=`a=ice-lite\r
|
14
|
+
`),e};h.parseRtpParameters=function(t){let e={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=h.splitLines(t)[0].split(" ");e.profile=n[2];for(let s=3;s<n.length;s++){let o=n[s],a=h.matchPrefix(t,"a=rtpmap:"+o+" ")[0];if(a){let c=h.parseRtpMap(a),l=h.matchPrefix(t,"a=fmtp:"+o+" ");switch(c.parameters=l.length?h.parseFmtp(l[0]):{},c.rtcpFeedback=h.matchPrefix(t,"a=rtcp-fb:"+o+" ").map(h.parseRtcpFb),e.codecs.push(c),c.name.toUpperCase()){case"RED":case"ULPFEC":e.fecMechanisms.push(c.name.toUpperCase());break;default:break}}}h.matchPrefix(t,"a=extmap:").forEach(s=>{e.headerExtensions.push(h.parseExtmap(s))});let i=h.matchPrefix(t,"a=rtcp-fb:* ").map(h.parseRtcpFb);return e.codecs.forEach(s=>{i.forEach(o=>{s.rtcpFeedback.find(c=>c.type===o.type&&c.parameter===o.parameter)||s.rtcpFeedback.push(o)})}),e};h.writeRtpDescription=function(t,e){let r="";r+="m="+t+" ",r+=e.codecs.length>0?"9":"0",r+=" "+(e.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=e.codecs.map(i=>i.preferredPayloadType!==void 0?i.preferredPayloadType:i.payloadType).join(" ")+`\r
|
15
|
+
`,r+=`c=IN IP4 0.0.0.0\r
|
16
|
+
`,r+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
17
|
+
`,e.codecs.forEach(i=>{r+=h.writeRtpMap(i),r+=h.writeFmtp(i),r+=h.writeRtcpFb(i)});let n=0;return e.codecs.forEach(i=>{i.maxptime>n&&(n=i.maxptime)}),n>0&&(r+="a=maxptime:"+n+`\r
|
18
|
+
`),e.headerExtensions&&e.headerExtensions.forEach(i=>{r+=h.writeExtmap(i)}),r};h.parseRtpEncodingParameters=function(t){let e=[],r=h.parseRtpParameters(t),n=r.fecMechanisms.indexOf("RED")!==-1,i=r.fecMechanisms.indexOf("ULPFEC")!==-1,s=h.matchPrefix(t,"a=ssrc:").map(p=>h.parseSsrcMedia(p)).filter(p=>p.attribute==="cname"),o=s.length>0&&s[0].ssrc,a,c=h.matchPrefix(t,"a=ssrc-group:FID").map(p=>p.substring(17).split(" ").map(d=>parseInt(d,10)));c.length>0&&c[0].length>1&&c[0][0]===o&&(a=c[0][1]),r.codecs.forEach(p=>{if(p.name.toUpperCase()==="RTX"&&p.parameters.apt){let f={ssrc:o,codecPayloadType:parseInt(p.parameters.apt,10)};o&&a&&(f.rtx={ssrc:a}),e.push(f),n&&(f=JSON.parse(JSON.stringify(f)),f.fec={ssrc:o,mechanism:i?"red+ulpfec":"red"},e.push(f))}}),e.length===0&&o&&e.push({ssrc:o});let l=h.matchPrefix(t,"b=");return l.length&&(l[0].indexOf("b=TIAS:")===0?l=parseInt(l[0].substring(7),10):l[0].indexOf("b=AS:")===0?l=parseInt(l[0].substring(5),10)*1e3*.95-50*40*8:l=void 0,e.forEach(p=>{p.maxBitrate=l})),e};h.parseRtcpParameters=function(t){let e={},r=h.matchPrefix(t,"a=ssrc:").map(s=>h.parseSsrcMedia(s)).filter(s=>s.attribute==="cname")[0];r&&(e.cname=r.value,e.ssrc=r.ssrc);let n=h.matchPrefix(t,"a=rtcp-rsize");e.reducedSize=n.length>0,e.compound=n.length===0;let i=h.matchPrefix(t,"a=rtcp-mux");return e.mux=i.length>0,e};h.writeRtcpParameters=function(t){let e="";return t.reducedSize&&(e+=`a=rtcp-rsize\r
|
19
|
+
`),t.mux&&(e+=`a=rtcp-mux\r
|
20
|
+
`),t.ssrc!==void 0&&t.cname&&(e+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
|
21
|
+
`),e};h.parseMsid=function(t){let e,r=h.matchPrefix(t,"a=msid:");if(r.length===1)return e=r[0].substring(7).split(" "),{stream:e[0],track:e[1]};let n=h.matchPrefix(t,"a=ssrc:").map(i=>h.parseSsrcMedia(i)).filter(i=>i.attribute==="msid");if(n.length>0)return e=n[0].value.split(" "),{stream:e[0],track:e[1]}};h.parseSctpDescription=function(t){let e=h.parseMLine(t),r=h.matchPrefix(t,"a=max-message-size:"),n;r.length>0&&(n=parseInt(r[0].substring(19),10)),isNaN(n)&&(n=65536);let i=h.matchPrefix(t,"a=sctp-port:");if(i.length>0)return{port:parseInt(i[0].substring(12),10),protocol:e.fmt,maxMessageSize:n};let s=h.matchPrefix(t,"a=sctpmap:");if(s.length>0){let o=s[0].substring(10).split(" ");return{port:parseInt(o[0],10),protocol:o[1],maxMessageSize:n}}};h.writeSctpDescription=function(t,e){let r=[];return t.protocol!=="DTLS/SCTP"?r=["m="+t.kind+" 9 "+t.protocol+" "+e.protocol+`\r
|
22
|
+
`,`c=IN IP4 0.0.0.0\r
|
23
|
+
`,"a=sctp-port:"+e.port+`\r
|
24
|
+
`]:r=["m="+t.kind+" 9 "+t.protocol+" "+e.port+`\r
|
25
|
+
`,`c=IN IP4 0.0.0.0\r
|
26
|
+
`,"a=sctpmap:"+e.port+" "+e.protocol+` 65535\r
|
27
|
+
`],e.maxMessageSize!==void 0&&r.push("a=max-message-size:"+e.maxMessageSize+`\r
|
28
|
+
`),r.join("")};h.generateSessionId=function(){return Math.random().toString().substr(2,22)};h.writeSessionBoilerplate=function(t,e,r){let n,i=e!==void 0?e:2;return t?n=t:n=h.generateSessionId(),`v=0\r
|
29
|
+
o=`+(r||"thisisadapterortc")+" "+n+" "+i+` IN IP4 127.0.0.1\r
|
30
|
+
s=-\r
|
31
|
+
t=0 0\r
|
32
|
+
`};h.getDirection=function(t,e){let r=h.splitLines(t);for(let n=0;n<r.length;n++)switch(r[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[n].substring(2);default:}return e?h.getDirection(e):"sendrecv"};h.getKind=function(t){return h.splitLines(t)[0].split(" ")[0].substring(2)};h.isRejected=function(t){return t.split(" ",2)[1]==="0"};h.parseMLine=function(t){let r=h.splitLines(t)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}};h.parseOLine=function(t){let r=h.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}};h.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;let e=h.splitLines(t);for(let r=0;r<e.length;r++)if(e[r].length<2||e[r].charAt(1)!=="=")return!1;return!0};typeof Dt=="object"&&(Dt.exports=h)});var Er=!0,kr=!0;function ee(t,e,r){let n=t.match(e);return n&&n.length>=r&&parseInt(n[r],10)}function V(t,e,r){if(!t.RTCPeerConnection)return;let n=t.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(o,a){if(o!==e)return i.apply(this,arguments);let c=l=>{let p=r(l);p&&(a.handleEvent?a.handleEvent(p):a(p))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),i.apply(this,[o,c])};let s=n.removeEventListener;n.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(a))return s.apply(this,arguments);let c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function Pr(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(Er=t,t?"adapter.js logging disabled":"adapter.js logging enabled")}function Or(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(kr=!t,"adapter.js deprecation warnings "+(t?"disabled":"enabled"))}function Te(){if(typeof window=="object"){if(Er)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Y(t,e){kr&&console.warn(t+" is deprecated, please use "+e+" instead.")}function Nr(t){let e={browser:null,version:null};if(typeof t>"u"||!t.navigator||!t.navigator.userAgent)return e.browser="Not a browser.",e;let{navigator:r}=t;if(r.userAgentData&&r.userAgentData.brands){let n=r.userAgentData.brands.find(i=>i.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(r.mozGetUserMedia)e.browser="firefox",e.version=ee(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||t.isSecureContext===!1&&t.webkitRTCPeerConnection)e.browser="chrome",e.version=ee(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(t.RTCPeerConnection&&r.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=ee(r.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=t.RTCRtpTransceiver&&"currentDirection"in t.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function xr(t){return Object.prototype.toString.call(t)==="[object Object]"}function ot(t){return xr(t)?Object.keys(t).reduce(function(e,r){let n=xr(t[r]),i=n?ot(t[r]):t[r],s=n&&!Object.keys(i).length;return i===void 0||s?e:Object.assign(e,{[r]:i})},{}):t}function st(t,e,r){!e||r.has(e.id)||(r.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?st(t,t.get(e[n]),r):n.endsWith("Ids")&&e[n].forEach(i=>{st(t,t.get(i),r)})}))}function at(t,e,r){let n=r?"outbound-rtp":"inbound-rtp",i=new Map;if(e===null)return i;let s=[];return t.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&s.push(o)}),s.forEach(o=>{t.forEach(a=>{a.type===n&&a.trackId===o.id&&st(t,a,i)})}),i}var xe={};Re(xe,{fixNegotiationNeeded:()=>dt,shimAddTrackRemoveTrack:()=>ut,shimAddTrackRemoveTrackWithNative:()=>_r,shimGetSendersWithDtmf:()=>pt,shimGetUserMedia:()=>ve,shimMediaStream:()=>ct,shimOnTrack:()=>lt,shimPeerConnection:()=>Ie,shimSenderReceiverGetStats:()=>ft});var Dr=Te;function ve(t,e){let r=t&&t.navigator;if(!r.mediaDevices)return;let n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;let c={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;let p=typeof a[l]=="object"?a[l]:{ideal:a[l]};p.exact!==void 0&&typeof p.exact=="number"&&(p.min=p.max=p.exact);let f=function(d,y){return d?d+y.charAt(0).toUpperCase()+y.slice(1):y==="deviceId"?"sourceId":y};if(p.ideal!==void 0){c.optional=c.optional||[];let d={};typeof p.ideal=="number"?(d[f("min",l)]=p.ideal,c.optional.push(d),d={},d[f("max",l)]=p.ideal,c.optional.push(d)):(d[f("",l)]=p.ideal,c.optional.push(d))}p.exact!==void 0&&typeof p.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[f("",l)]=p.exact):["min","max"].forEach(d=>{p[d]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[f(d,l)]=p[d])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},i=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){let l=function(p,f,d){f in p&&!(d in p)&&(p[d]=p[f],delete p[f])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});let p=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(r.mediaDevices.getSupportedConstraints&&r.mediaDevices.getSupportedConstraints().facingMode&&!p)){delete a.video.facingMode;let f;if(l.exact==="environment"||l.ideal==="environment"?f=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(f=["front"]),f)return r.mediaDevices.enumerateDevices().then(d=>{d=d.filter(b=>b.kind==="videoinput");let y=d.find(b=>f.some(E=>b.label.toLowerCase().includes(E)));return!y&&d.length&&f.includes("back")&&(y=d[d.length-1]),y&&(a.video.deviceId=l.exact?{exact:y.deviceId}:{ideal:y.deviceId}),a.video=n(a.video),Dr("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return Dr("chrome: "+JSON.stringify(a)),c(a)},s=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,l){i(a,p=>{r.webkitGetUserMedia(p,c,f=>{l&&l(s(f))})})};if(r.getUserMedia=o.bind(r),r.mediaDevices.getUserMedia){let a=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(c){return i(c,l=>a(l).then(p=>{if(l.audio&&!p.getAudioTracks().length||l.video&&!p.getVideoTracks().length)throw p.getTracks().forEach(f=>{f.stop()}),new DOMException("","NotFoundError");return p},p=>Promise.reject(s(p))))}}}function ct(t){t.MediaStream=t.MediaStream||t.webkitMediaStream}function lt(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("ontrack"in t.RTCPeerConnection.prototype)){Object.defineProperty(t.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(r){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=r)},enumerable:!0,configurable:!0});let e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",i=>{let s;t.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===i.track.id):s={track:i.track};let o=new Event("track");o.track=i.track,o.receiver=s,o.transceiver={receiver:s},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(i=>{let s;t.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===i.id):s={track:i};let o=new Event("track");o.track=i,o.receiver=s,o.transceiver={receiver:s},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else V(t,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function pt(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("getSenders"in t.RTCPeerConnection.prototype)&&"createDTMFSender"in t.RTCPeerConnection.prototype){let e=function(i,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=i.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:i}};if(!t.RTCPeerConnection.prototype.getSenders){t.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let i=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(a,c){let l=i.apply(this,arguments);return l||(l=e(this,a),this._senders.push(l)),l};let s=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(a){s.apply(this,arguments);let c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}let r=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],r.apply(this,[s]),s.getTracks().forEach(o=>{this._senders.push(e(this,o))})};let n=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(o=>{let a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof t=="object"&&t.RTCPeerConnection&&"getSenders"in t.RTCPeerConnection.prototype&&"createDTMFSender"in t.RTCPeerConnection.prototype&&t.RTCRtpSender&&!("dtmf"in t.RTCRtpSender.prototype)){let e=t.RTCPeerConnection.prototype.getSenders;t.RTCPeerConnection.prototype.getSenders=function(){let n=e.apply(this,[]);return n.forEach(i=>i._pc=this),n},Object.defineProperty(t.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ft(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender&&t.RTCRtpReceiver))return;if(!("getStats"in t.RTCRtpSender.prototype)){let r=t.RTCPeerConnection.prototype.getSenders;r&&(t.RTCPeerConnection.prototype.getSenders=function(){let s=r.apply(this,[]);return s.forEach(o=>o._pc=this),s});let n=t.RTCPeerConnection.prototype.addTrack;n&&(t.RTCPeerConnection.prototype.addTrack=function(){let s=n.apply(this,arguments);return s._pc=this,s}),t.RTCRtpSender.prototype.getStats=function(){let s=this;return this._pc.getStats().then(o=>at(o,s.track,!0))}}if(!("getStats"in t.RTCRtpReceiver.prototype)){let r=t.RTCPeerConnection.prototype.getReceivers;r&&(t.RTCPeerConnection.prototype.getReceivers=function(){let i=r.apply(this,[]);return i.forEach(s=>s._pc=this),i}),V(t,"track",n=>(n.receiver._pc=n.srcElement,n)),t.RTCRtpReceiver.prototype.getStats=function(){let i=this;return this._pc.getStats().then(s=>at(s,i.track,!1))}}if(!("getStats"in t.RTCRtpSender.prototype&&"getStats"in t.RTCRtpReceiver.prototype))return;let e=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof t.MediaStreamTrack){let n=arguments[0],i,s,o;return this.getSenders().forEach(a=>{a.track===n&&(i?o=!0:i=a)}),this.getReceivers().forEach(a=>(a.track===n&&(s?o=!0:s=a),a.track===n)),o||i&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function _r(t){t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};let e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};let r=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(f=>f.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});let a=this.getSenders();r.apply(this,arguments);let c=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};let n=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};let i=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{let c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),i.apply(this,arguments)}}function ut(t,e){if(!t.RTCPeerConnection)return;if(t.RTCPeerConnection.prototype.addTrack&&e.version>=65)return _r(t);let r=t.RTCPeerConnection.prototype.getLocalStreams;t.RTCPeerConnection.prototype.getLocalStreams=function(){let p=r.apply(this);return this._reverseStreams=this._reverseStreams||{},p.map(f=>this._reverseStreams[f.id])};let n=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(p){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},p.getTracks().forEach(f=>{if(this.getSenders().find(y=>y.track===f))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[p.id]){let f=new t.MediaStream(p.getTracks());this._streams[p.id]=f,this._reverseStreams[f.id]=p,p=f}n.apply(this,[p])};let i=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(p){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[p.id]||p]),delete this._reverseStreams[this._streams[p.id]?this._streams[p.id].id:p.id],delete this._streams[p.id]},t.RTCPeerConnection.prototype.addTrack=function(p,f){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let d=[].slice.call(arguments,1);if(d.length!==1||!d[0].getTracks().find(E=>E===p))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===p))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let b=this._streams[f.id];if(b)b.addTrack(p),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let E=new t.MediaStream([p]);this._streams[f.id]=E,this._reverseStreams[E.id]=f,this.addStream(E)}return this.getSenders().find(E=>E.track===p)};function s(l,p){let f=p.sdp;return Object.keys(l._reverseStreams||[]).forEach(d=>{let y=l._reverseStreams[d],b=l._streams[y.id];f=f.replace(new RegExp(b.id,"g"),y.id)}),new RTCSessionDescription({type:p.type,sdp:f})}function o(l,p){let f=p.sdp;return Object.keys(l._reverseStreams||[]).forEach(d=>{let y=l._reverseStreams[d],b=l._streams[y.id];f=f.replace(new RegExp(y.id,"g"),b.id)}),new RTCSessionDescription({type:p.type,sdp:f})}["createOffer","createAnswer"].forEach(function(l){let p=t.RTCPeerConnection.prototype[l],f={[l](){let d=arguments;return arguments.length&&typeof arguments[0]=="function"?p.apply(this,[b=>{let E=s(this,b);d[0].apply(null,[E])},b=>{d[1]&&d[1].apply(null,b)},arguments[2]]):p.apply(this,arguments).then(b=>s(this,b))}};t.RTCPeerConnection.prototype[l]=f[l]});let a=t.RTCPeerConnection.prototype.setLocalDescription;t.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};let c=Object.getOwnPropertyDescriptor(t.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(t.RTCPeerConnection.prototype,"localDescription",{get(){let l=c.get.apply(this);return l.type===""?l:s(this,l)}}),t.RTCPeerConnection.prototype.removeTrack=function(p){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!p._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(p._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let d;Object.keys(this._streams).forEach(y=>{this._streams[y].getTracks().find(E=>p.track===E)&&(d=this._streams[y])}),d&&(d.getTracks().length===1?this.removeStream(this._reverseStreams[d.id]):d.removeTrack(p.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Ie(t,e){!t.RTCPeerConnection&&t.webkitRTCPeerConnection&&(t.RTCPeerConnection=t.webkitRTCPeerConnection),t.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){let n=t.RTCPeerConnection.prototype[r],i={[r](){return arguments[0]=new(r==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};t.RTCPeerConnection.prototype[r]=i[r]})}function dt(t,e){V(t,"negotiationneeded",r=>{let n=r.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return r})}var Pe={};Re(Pe,{shimAddTransceiver:()=>Ct,shimCreateAnswer:()=>Tt,shimCreateOffer:()=>Rt,shimGetDisplayMedia:()=>Ar,shimGetParameters:()=>St,shimGetUserMedia:()=>Ee,shimOnTrack:()=>ht,shimPeerConnection:()=>ke,shimRTCDataChannel:()=>bt,shimReceiverGetStats:()=>gt,shimRemoveStream:()=>yt,shimSenderGetStats:()=>mt});function Ee(t,e){let r=t&&t.navigator,n=t&&t.MediaStreamTrack;if(r.getUserMedia=function(i,s,o){Y("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(i).then(s,o)},!(e.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){let i=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},s=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),i(o.audio,"autoGainControl","mozAutoGainControl"),i(o.audio,"noiseSuppression","mozNoiseSuppression")),s(o)},n&&n.prototype.getSettings){let o=n.prototype.getSettings;n.prototype.getSettings=function(){let a=o.apply(this,arguments);return i(a,"mozAutoGainControl","autoGainControl"),i(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){let o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),i(a,"autoGainControl","mozAutoGainControl"),i(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function Ar(t,e){t.navigator.mediaDevices&&"getDisplayMedia"in t.navigator.mediaDevices||t.navigator.mediaDevices&&(t.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,t.navigator.mediaDevices.getUserMedia(n)})}function ht(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ke(t,e){if(typeof t!="object"||!(t.RTCPeerConnection||t.mozRTCPeerConnection))return;!t.RTCPeerConnection&&t.mozRTCPeerConnection&&(t.RTCPeerConnection=t.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(i){let s=t.RTCPeerConnection.prototype[i],o={[i](){return arguments[0]=new(i==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};t.RTCPeerConnection.prototype[i]=o[i]});let r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){let[s,o,a]=arguments;return n.apply(this,[s||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(l=>{l.type=r[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((p,f)=>{c.set(f,Object.assign({},p,{type:r[p.type]||p.type}))})}return c}).then(o,a)}}function mt(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender)||t.RTCRtpSender&&"getStats"in t.RTCRtpSender.prototype)return;let e=t.RTCPeerConnection.prototype.getSenders;e&&(t.RTCPeerConnection.prototype.getSenders=function(){let i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i});let r=t.RTCPeerConnection.prototype.addTrack;r&&(t.RTCPeerConnection.prototype.addTrack=function(){let i=r.apply(this,arguments);return i._pc=this,i}),t.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function gt(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender)||t.RTCRtpSender&&"getStats"in t.RTCRtpReceiver.prototype)return;let e=t.RTCPeerConnection.prototype.getReceivers;e&&(t.RTCPeerConnection.prototype.getReceivers=function(){let n=e.apply(this,[]);return n.forEach(i=>i._pc=this),n}),V(t,"track",r=>(r.receiver._pc=r.srcElement,r)),t.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function yt(t){!t.RTCPeerConnection||"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(r){Y("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&r.getTracks().includes(n.track)&&this.removeTrack(n)})})}function bt(t){t.DataChannel&&!t.RTCDataChannel&&(t.RTCDataChannel=t.DataChannel)}function Ct(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;let e=t.RTCPeerConnection.prototype.addTransceiver;e&&(t.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];let i=n.length>0;i&&n.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});let s=e.apply(this,arguments);if(i){let{sender:o}=s,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=n,o.sendEncodings=n,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return s})}function St(t){if(!(typeof t=="object"&&t.RTCRtpSender))return;let e=t.RTCRtpSender.prototype.getParameters;e&&(t.RTCRtpSender.prototype.getParameters=function(){let n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function Rt(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;let e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function Tt(t){if(!(typeof t=="object"&&t.RTCPeerConnection))return;let e=t.RTCPeerConnection.prototype.createAnswer;t.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var Oe={};Re(Oe,{shimAudioContext:()=>Nt,shimCallbacksAPI:()=>xt,shimConstraints:()=>Lr,shimCreateOfferLegacy:()=>Ot,shimGetUserMedia:()=>Et,shimLocalStreamsAPI:()=>vt,shimRTCIceServerUrls:()=>kt,shimRemoteStreamsAPI:()=>It,shimTrackEventTransceiver:()=>Pt});function vt(t){if(!(typeof t!="object"||!t.RTCPeerConnection)){if("getLocalStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in t.RTCPeerConnection.prototype)){let e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(i=>e.call(this,i,n)),n.getVideoTracks().forEach(i=>e.call(this,i,n))},t.RTCPeerConnection.prototype.addTrack=function(n,...i){return i&&i.forEach(s=>{this._localStreams?this._localStreams.includes(s)||this._localStreams.push(s):this._localStreams=[s]}),e.apply(this,arguments)}}"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(r){this._localStreams||(this._localStreams=[]);let n=this._localStreams.indexOf(r);if(n===-1)return;this._localStreams.splice(n,1);let i=r.getTracks();this.getSenders().forEach(s=>{i.includes(s.track)&&this.removeTrack(s)})})}}function It(t){if(!(typeof t!="object"||!t.RTCPeerConnection)&&("getRemoteStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in t.RTCPeerConnection.prototype))){Object.defineProperty(t.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(r){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=r),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);let s=new Event("addstream");s.stream=i,this.dispatchEvent(s)})})}});let e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){let n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(s=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(s)>=0)return;n._remoteStreams.push(s);let o=new Event("addstream");o.stream=s,n.dispatchEvent(o)})}),e.apply(n,arguments)}}}function xt(t){if(typeof t!="object"||!t.RTCPeerConnection)return;let e=t.RTCPeerConnection.prototype,r=e.createOffer,n=e.createAnswer,i=e.setLocalDescription,s=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,p){let f=arguments.length>=2?arguments[2]:arguments[0],d=r.apply(this,[f]);return p?(d.then(l,p),Promise.resolve()):d},e.createAnswer=function(l,p){let f=arguments.length>=2?arguments[2]:arguments[0],d=n.apply(this,[f]);return p?(d.then(l,p),Promise.resolve()):d};let a=function(c,l,p){let f=i.apply(this,[c]);return p?(f.then(l,p),Promise.resolve()):f};e.setLocalDescription=a,a=function(c,l,p){let f=s.apply(this,[c]);return p?(f.then(l,p),Promise.resolve()):f},e.setRemoteDescription=a,a=function(c,l,p){let f=o.apply(this,[c]);return p?(f.then(l,p),Promise.resolve()):f},e.addIceCandidate=a}function Et(t){let e=t&&t.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){let r=e.mediaDevices,n=r.getUserMedia.bind(r);e.mediaDevices.getUserMedia=i=>n(Lr(i))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(n,i,s){e.mediaDevices.getUserMedia(n).then(i,s)}.bind(e))}function Lr(t){return t&&t.video!==void 0?Object.assign({},t,{video:ot(t.video)}):t}function kt(t){if(!t.RTCPeerConnection)return;let e=t.RTCPeerConnection;t.RTCPeerConnection=function(n,i){if(n&&n.iceServers){let s=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(Y("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,s.push(a)):s.push(n.iceServers[o])}n.iceServers=s}return new e(n,i)},t.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(t.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Pt(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ot(t){let e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);let i=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):n.offerToReceiveAudio===!0&&!i&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);let s=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Nt(t){typeof t!="object"||t.AudioContext||(t.AudioContext=t.webkitAudioContext)}var At={};Re(At,{removeExtmapAllowMixed:()=>_e,shimAddIceCandidateNullOrEmpty:()=>ie,shimConnectionState:()=>De,shimMaxMessageSize:()=>re,shimParameterlessSetLocalDescription:()=>se,shimRTCIceCandidate:()=>te,shimRTCIceCandidateRelayProtocol:()=>Ne,shimSendThrowTypeError:()=>ne});var Z=Ir(_t());function te(t){if(!t.RTCIceCandidate||t.RTCIceCandidate&&"foundation"in t.RTCIceCandidate.prototype)return;let e=t.RTCIceCandidate;t.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){let i=new e(n),s=Z.default.parseCandidate(n.candidate);for(let o in s)o in i||Object.defineProperty(i,o,{value:s[o]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new e(n)},t.RTCIceCandidate.prototype=e.prototype,V(t,"icecandidate",r=>(r.candidate&&Object.defineProperty(r,"candidate",{value:new t.RTCIceCandidate(r.candidate),writable:"false"}),r))}function Ne(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||V(t,"icecandidate",e=>{if(e.candidate){let r=Z.default.parseCandidate(e.candidate.candidate);r.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[r.priority>>24])}return e})}function re(t,e){if(!t.RTCPeerConnection)return;"sctp"in t.RTCPeerConnection.prototype||Object.defineProperty(t.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});let r=function(a){if(!a||!a.sdp)return!1;let c=Z.default.splitSections(a.sdp);return c.shift(),c.some(l=>{let p=Z.default.parseMLine(l);return p&&p.kind==="application"&&p.protocol.indexOf("SCTP")!==-1})},n=function(a){let c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;let l=parseInt(c[1],10);return l!==l?-1:l},i=function(a){let c=65536;return e.browser==="firefox"&&(e.version<57?a===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},s=function(a,c){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);let p=Z.default.matchPrefix(a.sdp,"a=max-message-size:");return p.length>0?l=parseInt(p[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(l=2147483637),l},o=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){let{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){let c=n(arguments[0]),l=i(c),p=s(arguments[0],c),f;l===0&&p===0?f=Number.POSITIVE_INFINITY:l===0||p===0?f=Math.max(l,p):f=Math.min(l,p);let d={};Object.defineProperty(d,"maxMessageSize",{get(){return f}}),this._sctp=d}return o.apply(this,arguments)}}function ne(t){if(!(t.RTCPeerConnection&&"createDataChannel"in t.RTCPeerConnection.prototype))return;function e(n,i){let s=n.send;n.send=function(){let a=arguments[0],c=a.length||a.size||a.byteLength;if(n.readyState==="open"&&i.sctp&&c>i.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+i.sctp.maxMessageSize+" bytes)");return s.apply(n,arguments)}}let r=t.RTCPeerConnection.prototype.createDataChannel;t.RTCPeerConnection.prototype.createDataChannel=function(){let i=r.apply(this,arguments);return e(i,this),i},V(t,"datachannel",n=>(e(n.channel,n.target),n))}function De(t){if(!t.RTCPeerConnection||"connectionState"in t.RTCPeerConnection.prototype)return;let e=t.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(r){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),r&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=r)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(r=>{let n=e[r];e[r]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=i=>{let s=i.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;let o=new Event("connectionstatechange",i);s.dispatchEvent(o)}return i},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function _e(t,e){if(!t.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;let r=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(i){if(i&&i.sdp&&i.sdp.indexOf(`
|
33
|
+
a=extmap-allow-mixed`)!==-1){let s=i.sdp.split(`
|
34
|
+
`).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
|
35
|
+
`);t.RTCSessionDescription&&i instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:i.type,sdp:s}):i.sdp=s}return r.apply(this,arguments)}}function ie(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;let r=t.RTCPeerConnection.prototype.addIceCandidate;!r||r.length===0||(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function se(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;let r=t.RTCPeerConnection.prototype.setLocalDescription;!r||r.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return r.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?r.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>r.apply(this,[o]))})}var kn=Ir(_t());function Mr({window:t}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){let r=Te,n=Nr(t),i={browserDetails:n,commonShim:At,extractVersion:ee,disableLog:Pr,disableWarnings:Or,sdp:kn};switch(n.browser){case"chrome":if(!xe||!Ie||!e.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(n.version===null)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=xe,ie(t,n),se(t,n),ve(t,n),ct(t,n),Ie(t,n),lt(t,n),ut(t,n),pt(t,n),ft(t,n),dt(t,n),te(t,n),Ne(t,n),De(t,n),re(t,n),ne(t,n),_e(t,n);break;case"firefox":if(!Pe||!ke||!e.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=Pe,ie(t,n),se(t,n),Ee(t,n),ke(t,n),ht(t,n),yt(t,n),mt(t,n),gt(t,n),bt(t,n),Ct(t,n),St(t,n),Rt(t,n),Tt(t,n),te(t,n),De(t,n),re(t,n),ne(t,n);break;case"safari":if(!Oe||!e.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=Oe,ie(t,n),se(t,n),kt(t,n),Ot(t,n),xt(t,n),vt(t,n),It(t,n),Pt(t,n),Et(t,n),Nt(t,n),te(t,n),Ne(t,n),re(t,n),ne(t,n),_e(t,n);break;default:r("Unsupported browser!");break}return i}var Pn=Mr({window:typeof window>"u"?void 0:window}),oe=Pn;function Ae(t){let e=typeof t;if(e=="object"){if(Array.isArray(t))return"array";if(t===null)return"null"}return e}function Ur(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var K="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Le=[];for(let t=0;t<K.length;t++)Le[K[t].charCodeAt(0)]=t;Le[45]=K.indexOf("+");Le[95]=K.indexOf("/");function ae(t){let e=t.length*3/4;t[t.length-2]=="="?e-=2:t[t.length-1]=="="&&(e-=1);let r=new Uint8Array(e),n=0,i=0,s,o=0;for(let a=0;a<t.length;a++){if(s=Le[t.charCodeAt(a)],s===void 0)switch(t[a]){case"=":i=0;case`
|
36
|
+
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=s,i=1;break;case 1:r[n++]=o<<2|(s&48)>>4,o=s,i=2;break;case 2:r[n++]=(o&15)<<4|(s&60)>>2,o=s,i=3;break;case 3:r[n++]=(o&3)<<6|s,i=0;break}}if(i==1)throw Error("invalid base64 string.");return r.subarray(0,n)}function ce(t){let e="",r=0,n,i=0;for(let s=0;s<t.length;s++)switch(n=t[s],r){case 0:e+=K[n>>2],i=(n&3)<<4,r=1;break;case 1:e+=K[i|n>>4],i=(n&15)<<2,r=2;break;case 2:e+=K[i|n>>6],e+=K[n&63],r=0;break}return r&&(e+=K[i],e+="=",r==1&&(e+="=")),e}var W;(function(t){t.symbol=Symbol.for("protobuf-ts/unknown"),t.onRead=(r,n,i,s,o)=>{(e(n)?n[t.symbol]:n[t.symbol]=[]).push({no:i,wireType:s,data:o})},t.onWrite=(r,n,i)=>{for(let{no:s,wireType:o,data:a}of t.list(n))i.tag(s,o).raw(a)},t.list=(r,n)=>{if(e(r)){let i=r[t.symbol];return n?i.filter(s=>s.no==n):i}return[]},t.last=(r,n)=>t.list(r,n).slice(-1)[0];let e=r=>r&&Array.isArray(r[t.symbol])})(W||(W={}));function Lt(t,e){return Object.assign(Object.assign({},t),e)}var x;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(x||(x={}));function Fr(){let t=0,e=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[t,e]}let r=this.buf[this.pos++];if(t|=(r&15)<<28,e=(r&112)>>4,(r&128)==0)return this.assertBounds(),[t,e];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(e|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function Ue(t,e,r){for(let s=0;s<28;s=s+7){let o=t>>>s,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(r.push(c),!a)return}let n=t>>>28&15|(e&7)<<4,i=e>>3!=0;if(r.push((i?n|128:n)&255),!!i){for(let s=3;s<31;s=s+7){let o=e>>>s,a=!!(o>>>7),c=(a?o|128:o)&255;if(r.push(c),!a)return}r.push(e>>>31&1)}}var Me=65536*65536;function Mt(t){let e=t[0]=="-";e&&(t=t.slice(1));let r=1e6,n=0,i=0;function s(o,a){let c=Number(t.slice(o,a));i*=r,n=n*r+c,n>=Me&&(i=i+(n/Me|0),n=n%Me)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),[e,n,i]}function Fe(t,e){if(e>>>0<=2097151)return""+(Me*e+(t>>>0));let r=t&16777215,n=(t>>>24|e<<8)>>>0&16777215,i=e>>16&65535,s=r+n*6777216+i*6710656,o=n+i*8147497,a=i*2,c=1e7;s>=c&&(o+=Math.floor(s/c),s%=c),o>=c&&(a+=Math.floor(o/c),o%=c);function l(p,f){let d=p?String(p):"";return f?"0000000".slice(d.length)+d:d}return l(a,0)+l(o,a)+l(s,1)}function Ut(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let r=0;r<9;r++)e.push(t&127|128),t=t>>7;e.push(1)}}function jr(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let r=5;(t&128)!==0&&r<10;r++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var v;function On(){let t=new DataView(new ArrayBuffer(8));v=globalThis.BigInt!==void 0&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:t}:void 0}On();function Br(t){if(!t)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}var Vr=/^-?[0-9]+$/,Be=4294967296,je=2147483648,Ve=class{constructor(e,r){this.lo=e|0,this.hi=r|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*Be+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}},O=class t extends Ve{static from(e){if(v)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=v.C(e);case"number":if(e===0)return this.ZERO;e=v.C(e);case"bigint":if(!e)return this.ZERO;if(e<v.UMIN)throw new Error("signed value for ulong");if(e>v.UMAX)throw new Error("ulong too large");return v.V.setBigUint64(0,e,!0),new t(v.V.getInt32(0,!0),v.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!Vr.test(e))throw new Error("string is no integer");let[r,n,i]=Mt(e);if(r)throw new Error("signed value for ulong");return new t(n,i);case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");if(e<0)throw new Error("signed value for ulong");return new t(e,e/Be)}throw new Error("unknown value "+typeof e)}toString(){return v?this.toBigInt().toString():Fe(this.lo,this.hi)}toBigInt(){return Br(v),v.V.setInt32(0,this.lo,!0),v.V.setInt32(4,this.hi,!0),v.V.getBigUint64(0,!0)}};O.ZERO=new O(0,0);var P=class t extends Ve{static from(e){if(v)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=v.C(e);case"number":if(e===0)return this.ZERO;e=v.C(e);case"bigint":if(!e)return this.ZERO;if(e<v.MIN)throw new Error("signed long too small");if(e>v.MAX)throw new Error("signed long too large");return v.V.setBigInt64(0,e,!0),new t(v.V.getInt32(0,!0),v.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!Vr.test(e))throw new Error("string is no integer");let[r,n,i]=Mt(e);if(r){if(i>je||i==je&&n!=0)throw new Error("signed long too small")}else if(i>=je)throw new Error("signed long too large");let s=new t(n,i);return r?s.negate():s;case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new t(e,e/Be):new t(-e,-e/Be).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&je)!==0}negate(){let e=~this.hi,r=this.lo;return r?r=~r+1:e+=1,new t(r,e)}toString(){if(v)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+Fe(e.lo,e.hi)}return Fe(this.lo,this.hi)}toBigInt(){return Br(v),v.V.setInt32(0,this.lo,!0),v.V.setInt32(4,this.hi,!0),v.V.getBigInt64(0,!0)}};P.ZERO=new P(0,0);var wr={readUnknownField:!0,readerFactory:t=>new Ft(t)};function Kr(t){return t?Object.assign(Object.assign({},wr),t):wr}var Ft=class{constructor(e,r){this.varint64=Fr,this.uint32=jr,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=r??new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),r=e>>>3,n=e&7;if(r<=0||n<0||n>5)throw new Error("illegal tag: field no "+r+" wire type "+n);return[r,n]}skip(e){let r=this.pos;switch(e){case x.Varint:for(;this.buf[this.pos++]&128;);break;case x.Bit64:this.pos+=4;case x.Bit32:this.pos+=4;break;case x.LengthDelimited:let n=this.uint32();this.pos+=n;break;case x.StartGroup:let i;for(;(i=this.tag()[1])!==x.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(r,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return new P(...this.varint64())}uint64(){return new O(...this.varint64())}sint64(){let[e,r]=this.varint64(),n=-(e&1);return e=(e>>>1|(r&1)<<31)^n,r=r>>>1^n,new P(e,r)}bool(){let[e,r]=this.varint64();return e!==0||r!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new O(this.sfixed32(),this.sfixed32())}sfixed64(){return new P(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(),r=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(r,r+e)}string(){return this.textDecoder.decode(this.bytes())}};function C(t,e){if(!t)throw new Error(e)}function jt(t,e){throw new Error(e??"Unexpected object: "+t)}var Nn=34028234663852886e22,Dn=-34028234663852886e22,_n=4294967295,An=2147483647,Ln=-2147483648;function G(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>An||t<Ln)throw new Error("invalid int 32: "+t)}function q(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>_n||t<0)throw new Error("invalid uint 32: "+t)}function z(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(Number.isFinite(t)&&(t>Nn||t<Dn))throw new Error("invalid float 32: "+t)}var Gr={writeUnknownFields:!0,writerFactory:()=>new Bt};function qr(t){return t?Object.assign(Object.assign({},Gr),t):Gr}var Bt=class{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let r=new Uint8Array(e),n=0;for(let i=0;i<this.chunks.length;i++)r.set(this.chunks[i],n),n+=this.chunks[i].length;return this.chunks=[],r}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),r=this.stack.pop();if(!r)throw new Error("invalid state, fork stack empty");return this.chunks=r.chunks,this.buf=r.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,r){return this.uint32((e<<3|r)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(q(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return G(e),Ut(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let r=this.textEncoder.encode(e);return this.uint32(r.byteLength),this.raw(r)}float(e){z(e);let r=new Uint8Array(4);return new DataView(r.buffer).setFloat32(0,e,!0),this.raw(r)}double(e){let r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,e,!0),this.raw(r)}fixed32(e){q(e);let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e,!0),this.raw(r)}sfixed32(e){G(e);let r=new Uint8Array(4);return new DataView(r.buffer).setInt32(0,e,!0),this.raw(r)}sint32(e){return G(e),e=(e<<1^e>>31)>>>0,Ut(e,this.buf),this}sfixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=P.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}fixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=O.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}int64(e){let r=P.from(e);return Ue(r.lo,r.hi,this.buf),this}sint64(e){let r=P.from(e),n=r.hi>>31,i=r.lo<<1^n,s=(r.hi<<1|r.lo>>>31)^n;return Ue(i,s,this.buf),this}uint64(e){let r=O.from(e);return Ue(r.lo,r.hi,this.buf),this}};var Jr={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},$r={ignoreUnknownFields:!1};function Vt(t){return t?Object.assign(Object.assign({},$r),t):$r}function wt(t){return t?Object.assign(Object.assign({},Jr),t):Jr}function Kt(t,e){var r,n;let i=Object.assign(Object.assign({},t),e);return i.typeRegistry=[...(r=t?.typeRegistry)!==null&&r!==void 0?r:[],...(n=e?.typeRegistry)!==null&&n!==void 0?n:[]],i}var we=Symbol.for("protobuf-ts/message-type");function Q(t){let e=!1,r=[];for(let n=0;n<t.length;n++){let i=t.charAt(n);i=="_"?e=!0:/\d/.test(i)?(r.push(i),e=!0):e?(r.push(i.toUpperCase()),e=!1):n==0?r.push(i.toLowerCase()):r.push(i)}return r.join("")}var u;(function(t){t[t.DOUBLE=1]="DOUBLE",t[t.FLOAT=2]="FLOAT",t[t.INT64=3]="INT64",t[t.UINT64=4]="UINT64",t[t.INT32=5]="INT32",t[t.FIXED64=6]="FIXED64",t[t.FIXED32=7]="FIXED32",t[t.BOOL=8]="BOOL",t[t.STRING=9]="STRING",t[t.BYTES=12]="BYTES",t[t.UINT32=13]="UINT32",t[t.SFIXED32=15]="SFIXED32",t[t.SFIXED64=16]="SFIXED64",t[t.SINT32=17]="SINT32",t[t.SINT64=18]="SINT64"})(u||(u={}));var D;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING",t[t.NUMBER=2]="NUMBER"})(D||(D={}));var le;(function(t){t[t.NO=0]="NO",t[t.PACKED=1]="PACKED",t[t.UNPACKED=2]="UNPACKED"})(le||(le={}));function Xr(t){var e,r,n,i;return t.localName=(e=t.localName)!==null&&e!==void 0?e:Q(t.name),t.jsonName=(r=t.jsonName)!==null&&r!==void 0?r:Q(t.name),t.repeat=(n=t.repeat)!==null&&n!==void 0?n:le.NO,t.opt=(i=t.opt)!==null&&i!==void 0?i:t.repeat||t.oneof?!1:t.kind=="message",t}function Wr(t){if(typeof t!="object"||t===null||!t.hasOwnProperty("oneofKind"))return!1;switch(typeof t.oneofKind){case"string":return t[t.oneofKind]===void 0?!1:Object.keys(t).length==2;case"undefined":return Object.keys(t).length==1;default:return!1}}var Ke=class{constructor(e){var r;this.fields=(r=e.fields)!==null&&r!==void 0?r:[]}prepare(){if(this.data)return;let e=[],r=[],n=[];for(let i of this.fields)if(i.oneof)n.includes(i.oneof)||(n.push(i.oneof),e.push(i.oneof),r.push(i.oneof));else switch(r.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&e.push(i.localName);break;case"message":i.repeat&&e.push(i.localName);break;case"map":e.push(i.localName);break}this.data={req:e,known:r,oneofs:Object.values(n)}}is(e,r,n=!1){if(r<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let i=Object.keys(e),s=this.data;if(i.length<s.req.length||s.req.some(o=>!i.includes(o))||!n&&i.some(o=>!s.known.includes(o)))return!1;if(r<1)return!0;for(let o of s.oneofs){let a=e[o];if(!Wr(a))return!1;if(a.oneofKind===void 0)continue;let c=this.fields.find(l=>l.localName===a.oneofKind);if(!c||!this.field(a[a.oneofKind],c,n,r))return!1}for(let o of this.fields)if(o.oneof===void 0&&!this.field(e[o.localName],o,n,r))return!1;return!0}field(e,r,n,i){let s=r.repeat;switch(r.kind){case"scalar":return e===void 0?r.opt:s?this.scalars(e,r.T,i,r.L):this.scalar(e,r.T,r.L);case"enum":return e===void 0?r.opt:s?this.scalars(e,u.INT32,i):this.scalar(e,u.INT32);case"message":return e===void 0?!0:s?this.messages(e,r.T(),n,i):this.message(e,r.T(),n,i);case"map":if(typeof e!="object"||e===null)return!1;if(i<2)return!0;if(!this.mapKeys(e,r.K,i))return!1;switch(r.V.kind){case"scalar":return this.scalars(Object.values(e),r.V.T,i,r.V.L);case"enum":return this.scalars(Object.values(e),u.INT32,i);case"message":return this.messages(Object.values(e),r.V.T(),n,i)}break}return!0}message(e,r,n,i){return n?r.isAssignable(e,i):r.is(e,i)}messages(e,r,n,i){if(!Array.isArray(e))return!1;if(i<2)return!0;if(n){for(let s=0;s<e.length&&s<i;s++)if(!r.isAssignable(e[s],i-1))return!1}else for(let s=0;s<e.length&&s<i;s++)if(!r.is(e[s],i-1))return!1;return!0}scalar(e,r,n){let i=typeof e;switch(r){case u.UINT64:case u.FIXED64:case u.INT64:case u.SFIXED64:case u.SINT64:switch(n){case D.BIGINT:return i=="bigint";case D.NUMBER:return i=="number"&&!isNaN(e);default:return i=="string"}case u.BOOL:return i=="boolean";case u.STRING:return i=="string";case u.BYTES:return e instanceof Uint8Array;case u.DOUBLE:case u.FLOAT:return i=="number"&&!isNaN(e);default:return i=="number"&&Number.isInteger(e)}}scalars(e,r,n,i){if(!Array.isArray(e))return!1;if(n<2)return!0;if(Array.isArray(e)){for(let s=0;s<e.length&&s<n;s++)if(!this.scalar(e[s],r,i))return!1}return!0}mapKeys(e,r,n){let i=Object.keys(e);switch(r){case u.INT32:case u.FIXED32:case u.SFIXED32:case u.SINT32:case u.UINT32:return this.scalars(i.slice(0,n).map(s=>parseInt(s)),r,n);case u.BOOL:return this.scalars(i.slice(0,n).map(s=>s=="true"?!0:s=="false"?!1:s),r,n);default:return this.scalars(i,r,n,D.STRING)}}};function _(t,e){switch(e){case D.BIGINT:return t.toBigInt();case D.NUMBER:return t.toNumber();default:return t.toString()}}var Ge=class{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};let r=(e=this.info.fields)!==null&&e!==void 0?e:[];for(let n of r)this.fMap[n.name]=n,this.fMap[n.jsonName]=n,this.fMap[n.localName]=n}}assert(e,r,n){if(!e){let i=Ae(n);throw(i=="number"||i=="boolean")&&(i=n.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${r}`)}}read(e,r,n){this.prepare();let i=[];for(let[s,o]of Object.entries(e)){let a=this.fMap[s];if(!a){if(!n.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${s}`);continue}let c=a.localName,l;if(a.oneof){if(o===null&&(a.kind!=="enum"||a.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(a.oneof))throw new Error(`Multiple members of the oneof group "${a.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(a.oneof),l=r[a.oneof]={oneofKind:c}}else l=r;if(a.kind=="map"){if(o===null)continue;this.assert(Ur(o),a.name,o);let p=l[c];for(let[f,d]of Object.entries(o)){this.assert(d!==null,a.name+" map value",null);let y;switch(a.V.kind){case"message":y=a.V.T().internalJsonRead(d,n);break;case"enum":if(y=this.enum(a.V.T(),d,a.name,n.ignoreUnknownFields),y===!1)continue;break;case"scalar":y=this.scalar(d,a.V.T,a.V.L,a.name);break}this.assert(y!==void 0,a.name+" map value",d);let b=f;a.K==u.BOOL&&(b=b=="true"?!0:b=="false"?!1:b),b=this.scalar(b,a.K,D.STRING,a.name).toString(),p[b]=y}}else if(a.repeat){if(o===null)continue;this.assert(Array.isArray(o),a.name,o);let p=l[c];for(let f of o){this.assert(f!==null,a.name,null);let d;switch(a.kind){case"message":d=a.T().internalJsonRead(f,n);break;case"enum":if(d=this.enum(a.T(),f,a.name,n.ignoreUnknownFields),d===!1)continue;break;case"scalar":d=this.scalar(f,a.T,a.L,a.name);break}this.assert(d!==void 0,a.name,o),p.push(d)}}else switch(a.kind){case"message":if(o===null&&a.T().typeName!="google.protobuf.Value"){this.assert(a.oneof===void 0,a.name+" (oneof member)",null);continue}l[c]=a.T().internalJsonRead(o,n,l[c]);break;case"enum":if(o===null)continue;let p=this.enum(a.T(),o,a.name,n.ignoreUnknownFields);if(p===!1)continue;l[c]=p;break;case"scalar":if(o===null)continue;l[c]=this.scalar(o,a.T,a.L,a.name);break}}}enum(e,r,n,i){if(e[0]=="google.protobuf.NullValue"&&C(r===null||r==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),r===null)return 0;switch(typeof r){case"number":return C(Number.isInteger(r),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${r}.`),r;case"string":let s=r;e[2]&&r.substring(0,e[2].length)===e[2]&&(s=r.substring(e[2].length));let o=e[1][s];return typeof o>"u"&&i?!1:(C(typeof o=="number",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${r}".`),o)}C(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof r}".`)}scalar(e,r,n,i){let s;try{switch(r){case u.DOUBLE:case u.FLOAT:if(e===null)return 0;if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""){s="empty string";break}if(typeof e=="string"&&e.trim().length!==e.length){s="extra whitespace";break}if(typeof e!="string"&&typeof e!="number")break;let o=Number(e);if(Number.isNaN(o)){s="not a number";break}if(!Number.isFinite(o)){s="too large or small";break}return r==u.FLOAT&&z(o),o;case u.INT32:case u.FIXED32:case u.SFIXED32:case u.SINT32:case u.UINT32:if(e===null)return 0;let a;if(typeof e=="number"?a=e:e===""?s="empty string":typeof e=="string"&&(e.trim().length!==e.length?s="extra whitespace":a=Number(e)),a===void 0)break;return r==u.UINT32?q(a):G(a),a;case u.INT64:case u.SFIXED64:case u.SINT64:if(e===null)return _(P.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return _(P.from(e),n);case u.FIXED64:case u.UINT64:if(e===null)return _(O.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return _(O.from(e),n);case u.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case u.STRING:if(e===null)return"";if(typeof e!="string"){s="extra whitespace";break}try{encodeURIComponent(e)}catch(c){c="invalid UTF8";break}return e;case u.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return ae(e)}}catch(o){s=o.message}this.assert(!1,i+(s?" - "+s:""),e)}};var qe=class{constructor(e){var r;this.fields=(r=e.fields)!==null&&r!==void 0?r:[]}write(e,r){let n={},i=e;for(let s of this.fields){if(!s.oneof){let l=this.field(s,i[s.localName],r);l!==void 0&&(n[r.useProtoFieldName?s.name:s.jsonName]=l);continue}let o=i[s.oneof];if(o.oneofKind!==s.localName)continue;let a=s.kind=="scalar"||s.kind=="enum"?Object.assign(Object.assign({},r),{emitDefaultValues:!0}):r,c=this.field(s,o[s.localName],a);C(c!==void 0),n[r.useProtoFieldName?s.name:s.jsonName]=c}return n}field(e,r,n){let i;if(e.kind=="map"){C(typeof r=="object"&&r!==null);let s={};switch(e.V.kind){case"scalar":for(let[c,l]of Object.entries(r)){let p=this.scalar(e.V.T,l,e.name,!1,!0);C(p!==void 0),s[c.toString()]=p}break;case"message":let o=e.V.T();for(let[c,l]of Object.entries(r)){let p=this.message(o,l,e.name,n);C(p!==void 0),s[c.toString()]=p}break;case"enum":let a=e.V.T();for(let[c,l]of Object.entries(r)){C(l===void 0||typeof l=="number");let p=this.enum(a,l,e.name,!1,!0,n.enumAsInteger);C(p!==void 0),s[c.toString()]=p}break}(n.emitDefaultValues||Object.keys(s).length>0)&&(i=s)}else if(e.repeat){C(Array.isArray(r));let s=[];switch(e.kind){case"scalar":for(let c=0;c<r.length;c++){let l=this.scalar(e.T,r[c],e.name,e.opt,!0);C(l!==void 0),s.push(l)}break;case"enum":let o=e.T();for(let c=0;c<r.length;c++){C(r[c]===void 0||typeof r[c]=="number");let l=this.enum(o,r[c],e.name,e.opt,!0,n.enumAsInteger);C(l!==void 0),s.push(l)}break;case"message":let a=e.T();for(let c=0;c<r.length;c++){let l=this.message(a,r[c],e.name,n);C(l!==void 0),s.push(l)}break}(n.emitDefaultValues||s.length>0||n.emitDefaultValues)&&(i=s)}else switch(e.kind){case"scalar":i=this.scalar(e.T,r,e.name,e.opt,n.emitDefaultValues);break;case"enum":i=this.enum(e.T(),r,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case"message":i=this.message(e.T(),r,e.name,n);break}return i}enum(e,r,n,i,s,o){if(e[0]=="google.protobuf.NullValue")return!s&&!i?void 0:null;if(r===void 0){C(i);return}if(!(r===0&&!s&&!i))return C(typeof r=="number"),C(Number.isInteger(r)),o||!e[1].hasOwnProperty(r)?r:e[2]?e[2]+e[1][r]:e[1][r]}message(e,r,n,i){return r===void 0?i.emitDefaultValues?null:void 0:e.internalJsonWrite(r,i)}scalar(e,r,n,i,s){if(r===void 0){C(i);return}let o=s||i;switch(e){case u.INT32:case u.SFIXED32:case u.SINT32:return r===0?o?0:void 0:(G(r),r);case u.FIXED32:case u.UINT32:return r===0?o?0:void 0:(q(r),r);case u.FLOAT:z(r);case u.DOUBLE:return r===0?o?0:void 0:(C(typeof r=="number"),Number.isNaN(r)?"NaN":r===Number.POSITIVE_INFINITY?"Infinity":r===Number.NEGATIVE_INFINITY?"-Infinity":r);case u.STRING:return r===""?o?"":void 0:(C(typeof r=="string"),r);case u.BOOL:return r===!1?o?!1:void 0:(C(typeof r=="boolean"),r);case u.UINT64:case u.FIXED64:C(typeof r=="number"||typeof r=="string"||typeof r=="bigint");let a=O.from(r);return a.isZero()&&!o?void 0:a.toString();case u.INT64:case u.SFIXED64:case u.SINT64:C(typeof r=="number"||typeof r=="string"||typeof r=="bigint");let c=P.from(r);return c.isZero()&&!o?void 0:c.toString();case u.BYTES:return C(r instanceof Uint8Array),r.byteLength?ce(r):o?"":void 0}}};function pe(t,e=D.STRING){switch(t){case u.BOOL:return!1;case u.UINT64:case u.FIXED64:return _(O.ZERO,e);case u.INT64:case u.SFIXED64:case u.SINT64:return _(P.ZERO,e);case u.DOUBLE:case u.FLOAT:return 0;case u.BYTES:return new Uint8Array(0);case u.STRING:return"";default:return 0}}var Je=class{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){let r=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(r.map(n=>[n.no,n]))}}read(e,r,n,i){this.prepare();let s=i===void 0?e.len:e.pos+i;for(;e.pos<s;){let[o,a]=e.tag(),c=this.fieldNoToField.get(o);if(!c){let d=n.readUnknownField;if(d=="throw")throw new Error(`Unknown field ${o} (wire type ${a}) for ${this.info.typeName}`);let y=e.skip(a);d!==!1&&(d===!0?W.onRead:d)(this.info.typeName,r,o,a,y);continue}let l=r,p=c.repeat,f=c.localName;switch(c.oneof&&(l=l[c.oneof],l.oneofKind!==f&&(l=r[c.oneof]={oneofKind:f})),c.kind){case"scalar":case"enum":let d=c.kind=="enum"?u.INT32:c.T,y=c.kind=="scalar"?c.L:void 0;if(p){let k=l[f];if(a==x.LengthDelimited&&d!=u.STRING&&d!=u.BYTES){let F=e.uint32()+e.pos;for(;e.pos<F;)k.push(this.scalar(e,d,y))}else k.push(this.scalar(e,d,y))}else l[f]=this.scalar(e,d,y);break;case"message":if(p){let k=l[f],F=c.T().internalBinaryRead(e,e.uint32(),n);k.push(F)}else l[f]=c.T().internalBinaryRead(e,e.uint32(),n,l[f]);break;case"map":let[b,E]=this.mapEntry(c,e,n);l[f][b]=E;break}}}mapEntry(e,r,n){let i=r.uint32(),s=r.pos+i,o,a;for(;r.pos<s;){let[c,l]=r.tag();switch(c){case 1:e.K==u.BOOL?o=r.bool().toString():o=this.scalar(r,e.K,D.STRING);break;case 2:switch(e.V.kind){case"scalar":a=this.scalar(r,e.V.T,e.V.L);break;case"enum":a=r.int32();break;case"message":a=e.V.T().internalBinaryRead(r,r.uint32(),n);break}break;default:throw new Error(`Unknown field ${c} (wire type ${l}) in map entry for ${this.info.typeName}#${e.name}`)}}if(o===void 0){let c=pe(e.K);o=e.K==u.BOOL?c.toString():c}if(a===void 0)switch(e.V.kind){case"scalar":a=pe(e.V.T,e.V.L);break;case"enum":a=0;break;case"message":a=e.V.T().create();break}return[o,a]}scalar(e,r,n){switch(r){case u.INT32:return e.int32();case u.STRING:return e.string();case u.BOOL:return e.bool();case u.DOUBLE:return e.double();case u.FLOAT:return e.float();case u.INT64:return _(e.int64(),n);case u.UINT64:return _(e.uint64(),n);case u.FIXED64:return _(e.fixed64(),n);case u.FIXED32:return e.fixed32();case u.BYTES:return e.bytes();case u.UINT32:return e.uint32();case u.SFIXED32:return e.sfixed32();case u.SFIXED64:return _(e.sfixed64(),n);case u.SINT32:return e.sint32();case u.SINT64:return _(e.sint64(),n)}}};var $e=class{constructor(e){this.info=e}prepare(){if(!this.fields){let e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((r,n)=>r.no-n.no)}}write(e,r,n){this.prepare();for(let s of this.fields){let o,a,c=s.repeat,l=s.localName;if(s.oneof){let p=e[s.oneof];if(p.oneofKind!==l)continue;o=p[l],a=!0}else o=e[l],a=!1;switch(s.kind){case"scalar":case"enum":let p=s.kind=="enum"?u.INT32:s.T;if(c)if(C(Array.isArray(o)),c==le.PACKED)this.packed(r,p,s.no,o);else for(let f of o)this.scalar(r,p,s.no,f,!0);else o===void 0?C(s.opt):this.scalar(r,p,s.no,o,a||s.opt);break;case"message":if(c){C(Array.isArray(o));for(let f of o)this.message(r,n,s.T(),s.no,f)}else this.message(r,n,s.T(),s.no,o);break;case"map":C(typeof o=="object"&&o!==null);for(let[f,d]of Object.entries(o))this.mapEntry(r,n,s,f,d);break}}let i=n.writeUnknownFields;i!==!1&&(i===!0?W.onWrite:i)(this.info.typeName,e,r)}mapEntry(e,r,n,i,s){e.tag(n.no,x.LengthDelimited),e.fork();let o=i;switch(n.K){case u.INT32:case u.FIXED32:case u.UINT32:case u.SFIXED32:case u.SINT32:o=Number.parseInt(i);break;case u.BOOL:C(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(e,n.K,1,o,!0),n.V.kind){case"scalar":this.scalar(e,n.V.T,2,s,!0);break;case"enum":this.scalar(e,u.INT32,2,s,!0);break;case"message":this.message(e,r,n.V.T(),2,s);break}e.join()}message(e,r,n,i,s){s!==void 0&&(n.internalBinaryWrite(s,e.tag(i,x.LengthDelimited).fork(),r),e.join())}scalar(e,r,n,i,s){let[o,a,c]=this.scalarInfo(r,i);(!c||s)&&(e.tag(n,o),e[a](i))}packed(e,r,n,i){if(!i.length)return;C(r!==u.BYTES&&r!==u.STRING),e.tag(n,x.LengthDelimited),e.fork();let[,s]=this.scalarInfo(r);for(let o=0;o<i.length;o++)e[s](i[o]);e.join()}scalarInfo(e,r){let n=x.Varint,i,s=r===void 0,o=r===0;switch(e){case u.INT32:i="int32";break;case u.STRING:o=s||!r.length,n=x.LengthDelimited,i="string";break;case u.BOOL:o=r===!1,i="bool";break;case u.UINT32:i="uint32";break;case u.DOUBLE:n=x.Bit64,i="double";break;case u.FLOAT:n=x.Bit32,i="float";break;case u.INT64:o=s||P.from(r).isZero(),i="int64";break;case u.UINT64:o=s||O.from(r).isZero(),i="uint64";break;case u.FIXED64:o=s||O.from(r).isZero(),n=x.Bit64,i="fixed64";break;case u.BYTES:o=s||!r.byteLength,n=x.LengthDelimited,i="bytes";break;case u.FIXED32:n=x.Bit32,i="fixed32";break;case u.SFIXED32:n=x.Bit32,i="sfixed32";break;case u.SFIXED64:o=s||P.from(r).isZero(),n=x.Bit64,i="sfixed64";break;case u.SINT32:i="sint32";break;case u.SINT64:o=s||P.from(r).isZero(),i="sint64";break}return[n,i,s||o]}};function zr(t){let e=t.messagePrototype?Object.create(t.messagePrototype):Object.defineProperty({},we,{value:t});for(let r of t.fields){let n=r.localName;if(!r.opt)if(r.oneof)e[r.oneof]={oneofKind:void 0};else if(r.repeat)e[n]=[];else switch(r.kind){case"scalar":e[n]=pe(r.T,r.L);break;case"enum":e[n]=0;break;case"map":e[n]={};break}}return e}function Xe(t,e,r){let n,i=r,s;for(let o of t.fields){let a=o.localName;if(o.oneof){let c=i[o.oneof];if(c?.oneofKind==null)continue;if(n=c[a],s=e[o.oneof],s.oneofKind=c.oneofKind,n==null){delete s[a];continue}}else if(n=i[a],s=e,n==null)continue;switch(o.repeat&&(s[a].length=n.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let l=0;l<n.length;l++)s[a][l]=n[l];else s[a]=n;break;case"message":let c=o.T();if(o.repeat)for(let l=0;l<n.length;l++)s[a][l]=c.create(n[l]);else s[a]===void 0?s[a]=c.create(n):c.mergePartial(s[a],n);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(s[a],n);break;case"message":let l=o.V.T();for(let p of Object.keys(n))s[a][p]=l.create(n[p]);break}break}}}function Zr(t,e,r){if(e===r)return!0;if(!e||!r)return!1;for(let n of t.fields){let i=n.localName,s=n.oneof?e[n.oneof][i]:e[i],o=n.oneof?r[n.oneof][i]:r[i];switch(n.kind){case"enum":case"scalar":let a=n.kind=="enum"?u.INT32:n.T;if(!(n.repeat?Hr(a,s,o):Qr(a,s,o)))return!1;break;case"map":if(!(n.V.kind=="message"?Yr(n.V.T(),We(s),We(o)):Hr(n.V.kind=="enum"?u.INT32:n.V.T,We(s),We(o))))return!1;break;case"message":let c=n.T();if(!(n.repeat?Yr(c,s,o):c.equals(s,o)))return!1;break}}return!0}var We=Object.values;function Qr(t,e,r){if(e===r)return!0;if(t!==u.BYTES)return!1;let n=e,i=r;if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(n[s]!=i[s])return!1;return!0}function Hr(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!Qr(t,e[n],r[n]))return!1;return!0}function Yr(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!t.equals(e[n],r[n]))return!1;return!0}var Mn=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),I=class{constructor(e,r,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=r.map(Xr),this.options=n??{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},Mn),{[we]:{value:this}})),this.refTypeCheck=new Ke(this),this.refJsonReader=new Ge(this),this.refJsonWriter=new qe(this),this.refBinReader=new Je(this),this.refBinWriter=new $e(this)}create(e){let r=zr(this);return e!==void 0&&Xe(this,r,e),r}clone(e){let r=this.create();return Xe(this,r,e),r}equals(e,r){return Zr(this,e,r)}is(e,r=this.defaultCheckDepth){return this.refTypeCheck.is(e,r,!1)}isAssignable(e,r=this.defaultCheckDepth){return this.refTypeCheck.is(e,r,!0)}mergePartial(e,r){Xe(this,e,r)}fromBinary(e,r){let n=Kr(r);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,r){return this.internalJsonRead(e,Vt(r))}fromJsonString(e,r){let n=JSON.parse(e);return this.fromJson(n,r)}toJson(e,r){return this.internalJsonWrite(e,wt(r))}toJsonString(e,r){var n;let i=this.toJson(e,r);return JSON.stringify(i,null,(n=r?.prettySpaces)!==null&&n!==void 0?n:0)}toBinary(e,r){let n=qr(r);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,r,n){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let i=n??this.create();return this.refJsonReader.read(e,i,r),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${Ae(e)}.`)}internalJsonWrite(e,r){return this.refJsonWriter.write(e,r)}internalBinaryWrite(e,r,n){return this.refBinWriter.write(e,r,n),r}internalBinaryRead(e,r,n,i){let s=i??this.create();return this.refBinReader.read(e,s,n,r),s}};function en(t,e){var r,n,i;let s=t;return s.service=e,s.localName=(r=s.localName)!==null&&r!==void 0?r:Q(s.name),s.serverStreaming=!!s.serverStreaming,s.clientStreaming=!!s.clientStreaming,s.options=(n=s.options)!==null&&n!==void 0?n:{},s.idempotency=(i=s.idempotency)!==null&&i!==void 0?i:void 0,s}var fe=class{constructor(e,r,n){this.typeName=e,this.methods=r.map(i=>en(i,this)),this.options=n??{}}};var R=class extends Error{constructor(e,r="UNKNOWN",n){super(e),this.name="RpcError",Object.setPrototypeOf(this,new.target.prototype),this.code=r,this.meta=n??{}}toString(){let e=[this.name+": "+this.message];this.code&&(e.push(""),e.push("Code: "+this.code)),this.serviceName&&this.methodName&&e.push("Method: "+this.serviceName+"/"+this.methodName);let r=Object.entries(this.meta);if(r.length){e.push(""),e.push("Meta:");for(let[n,i]of r)e.push(` ${n}: ${i}`)}return e.join(`
|
37
|
+
`)}};function Gt(t,e){if(!e)return t;let r={};ze(t,r),ze(e,r);for(let n of Object.keys(e)){let i=e[n];switch(n){case"jsonOptions":r.jsonOptions=Kt(t.jsonOptions,r.jsonOptions);break;case"binaryOptions":r.binaryOptions=Lt(t.binaryOptions,r.binaryOptions);break;case"meta":r.meta={},ze(t.meta,r.meta),ze(e.meta,r.meta);break;case"interceptors":r.interceptors=t.interceptors?t.interceptors.concat(i):i.concat();break}}return r}function ze(t,e){if(!t)return;let r=e;for(let[n,i]of Object.entries(t))i instanceof Date?r[n]=new Date(i.getTime()):Array.isArray(i)?r[n]=i.concat():r[n]=i}var A;(function(t){t[t.PENDING=0]="PENDING",t[t.REJECTED=1]="REJECTED",t[t.RESOLVED=2]="RESOLVED"})(A||(A={}));var M=class{constructor(e=!0){this._state=A.PENDING,this._promise=new Promise((r,n)=>{this._resolve=r,this._reject=n}),e&&this._promise.catch(r=>{})}get state(){return this._state}get promise(){return this._promise}resolve(e){if(this.state!==A.PENDING)throw new Error(`cannot resolve ${A[this.state].toLowerCase()}`);this._resolve(e),this._state=A.RESOLVED}reject(e){if(this.state!==A.PENDING)throw new Error(`cannot reject ${A[this.state].toLowerCase()}`);this._reject(e),this._state=A.REJECTED}resolvePending(e){this._state===A.PENDING&&this.resolve(e)}rejectPending(e){this._state===A.PENDING&&this.reject(e)}};var ue=class{constructor(){this._lis={nxt:[],msg:[],err:[],cmp:[]},this._closed=!1}onNext(e){return this.addLis(e,this._lis.nxt)}onMessage(e){return this.addLis(e,this._lis.msg)}onError(e){return this.addLis(e,this._lis.err)}onComplete(e){return this.addLis(e,this._lis.cmp)}addLis(e,r){return r.push(e),()=>{let n=r.indexOf(e);n>=0&&r.splice(n,1)}}clearLis(){for(let e of Object.values(this._lis))e.splice(0,e.length)}get closed(){return this._closed!==!1}notifyNext(e,r,n){C((e?1:0)+(r?1:0)+(n?1:0)<=1,"only one emission at a time"),e&&this.notifyMessage(e),r&&this.notifyError(r),n&&this.notifyComplete()}notifyMessage(e){C(!this.closed,"stream is closed"),this.pushIt({value:e,done:!1}),this._lis.msg.forEach(r=>r(e)),this._lis.nxt.forEach(r=>r(e,void 0,!1))}notifyError(e){C(!this.closed,"stream is closed"),this._closed=e,this.pushIt(e),this._lis.err.forEach(r=>r(e)),this._lis.nxt.forEach(r=>r(void 0,e,!1)),this.clearLis()}notifyComplete(){C(!this.closed,"stream is closed"),this._closed=!0,this.pushIt({value:null,done:!0}),this._lis.cmp.forEach(e=>e()),this._lis.nxt.forEach(e=>e(void 0,void 0,!0)),this.clearLis()}[Symbol.asyncIterator](){return this._itState||(this._itState={q:[]}),this._closed===!0?this.pushIt({value:null,done:!0}):this._closed!==!1&&this.pushIt(this._closed),{next:()=>{let e=this._itState;C(e,"bad state"),C(!e.p,"iterator contract broken");let r=e.q.shift();return r?"value"in r?Promise.resolve(r):Promise.reject(r):(e.p=new M,e.p.promise)}}}pushIt(e){let r=this._itState;if(r)if(r.p){let n=r.p;C(n.state==A.PENDING,"iterator contract broken"),"value"in e?n.resolve(e):n.reject(e),delete r.p}else r.q.push(e)}};var Un=function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(p){try{l(n.next(p))}catch(f){o(f)}}function c(p){try{l(n.throw(p))}catch(f){o(f)}}function l(p){p.done?s(p.value):i(p.value).then(a,c)}l((n=n.apply(t,e||[])).next())})},de=class{constructor(e,r,n,i,s,o,a){this.method=e,this.requestHeaders=r,this.request=n,this.headers=i,this.response=s,this.status=o,this.trailers=a}then(e,r){return this.promiseFinished().then(n=>e?Promise.resolve(e(n)):n,n=>r?Promise.resolve(r(n)):Promise.reject(n))}promiseFinished(){return Un(this,void 0,void 0,function*(){let[e,r,n,i]=yield Promise.all([this.headers,this.response,this.status,this.trailers]);return{method:this.method,requestHeaders:this.requestHeaders,request:this.request,headers:e,response:r,status:n,trailers:i}})}};var Fn=function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(p){try{l(n.next(p))}catch(f){o(f)}}function c(p){try{l(n.throw(p))}catch(f){o(f)}}function l(p){p.done?s(p.value):i(p.value).then(a,c)}l((n=n.apply(t,e||[])).next())})},he=class{constructor(e,r,n,i,s,o,a){this.method=e,this.requestHeaders=r,this.request=n,this.headers=i,this.responses=s,this.status=o,this.trailers=a}then(e,r){return this.promiseFinished().then(n=>e?Promise.resolve(e(n)):n,n=>r?Promise.resolve(r(n)):Promise.reject(n))}promiseFinished(){return Fn(this,void 0,void 0,function*(){let[e,r,n]=yield Promise.all([this.headers,this.status,this.trailers]);return{method:this.method,requestHeaders:this.requestHeaders,request:this.request,headers:e,status:r,trailers:n}})}};function me(t,e,r,n,i){var s,o,a,c;if(t=="unary"){let l=(p,f,d)=>e.unary(p,f,d);for(let p of((s=n.interceptors)!==null&&s!==void 0?s:[]).filter(f=>f.interceptUnary).reverse()){let f=l;l=(d,y,b)=>p.interceptUnary(f,d,y,b)}return l(r,i,n)}if(t=="serverStreaming"){let l=(p,f,d)=>e.serverStreaming(p,f,d);for(let p of((o=n.interceptors)!==null&&o!==void 0?o:[]).filter(f=>f.interceptServerStreaming).reverse()){let f=l;l=(d,y,b)=>p.interceptServerStreaming(f,d,y,b)}return l(r,i,n)}if(t=="clientStreaming"){let l=(p,f)=>e.clientStreaming(p,f);for(let p of((a=n.interceptors)!==null&&a!==void 0?a:[]).filter(f=>f.interceptClientStreaming).reverse()){let f=l;l=(d,y)=>p.interceptClientStreaming(f,d,y)}return l(r,n)}if(t=="duplex"){let l=(p,f)=>e.duplex(p,f);for(let p of((c=n.interceptors)!==null&&c!==void 0?c:[]).filter(f=>f.interceptDuplex).reverse()){let f=l;l=(d,y)=>p.interceptDuplex(f,d,y)}return l(r,n)}jt(t)}var dr=(s=>(s[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.OFFER=1]="OFFER",s[s.ANSWER=2]="ANSWER",s[s.PRANSWER=3]="PRANSWER",s[s.ROLLBACK=4]="ROLLBACK",s))(dr||{}),qt=class extends I{constructor(){super("pulsebeam.v1.PrepareReq",[])}},jn=new qt,Jt=class extends I{constructor(){super("pulsebeam.v1.PrepareResp",[{no:1,name:"ice_servers",kind:"message",repeat:1,T:()=>Vn}])}},Bn=new Jt,$t=class extends I{constructor(){super("pulsebeam.v1.IceServer",[{no:1,name:"urls",kind:"scalar",repeat:2,T:9},{no:2,name:"username",kind:"scalar",opt:!0,T:9},{no:3,name:"credential",kind:"scalar",opt:!0,T:9}])}},Vn=new $t,Xt=class extends I{constructor(){super("pulsebeam.v1.SendReq",[{no:1,name:"msg",kind:"message",T:()=>tn}])}},wn=new Xt,Wt=class extends I{constructor(){super("pulsebeam.v1.SendResp",[])}},Kn=new Wt,zt=class extends I{constructor(){super("pulsebeam.v1.RecvReq",[{no:1,name:"src",kind:"message",T:()=>Zt}])}},Gn=new zt,Ht=class extends I{constructor(){super("pulsebeam.v1.RecvResp",[{no:1,name:"msg",kind:"message",T:()=>tn}])}},qn=new Ht,Yt=class extends I{constructor(){super("pulsebeam.v1.PeerInfo",[{no:1,name:"group_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"conn_id",kind:"scalar",T:13}])}},Zt=new Yt,Qt=class extends I{constructor(){super("pulsebeam.v1.Message",[{no:1,name:"header",kind:"message",T:()=>$n},{no:2,name:"payload",kind:"message",T:()=>Jn}])}},tn=new Qt,er=class extends I{constructor(){super("pulsebeam.v1.MessagePayload",[{no:1,name:"signal",kind:"message",oneof:"payloadType",T:()=>Xn},{no:2,name:"join",kind:"message",oneof:"payloadType",T:()=>Hn},{no:3,name:"bye",kind:"message",oneof:"payloadType",T:()=>Yn},{no:4,name:"ack",kind:"message",oneof:"payloadType",T:()=>Zn},{no:5,name:"ping",kind:"message",oneof:"payloadType",T:()=>Qn}])}},Jn=new er,tr=class extends I{constructor(){super("pulsebeam.v1.MessageHeader",[{no:1,name:"src",kind:"message",T:()=>Zt},{no:2,name:"dst",kind:"message",T:()=>Zt},{no:7,name:"seqnum",kind:"scalar",T:13},{no:8,name:"reliable",kind:"scalar",T:8}])}},$n=new tr,rr=class extends I{constructor(){super("pulsebeam.v1.Signal",[{no:1,name:"generation_counter",kind:"scalar",T:13},{no:9,name:"sdp",kind:"message",oneof:"data",T:()=>Wn},{no:10,name:"ice_candidate",kind:"message",oneof:"data",T:()=>rn},{no:11,name:"ice_candidate_batch",kind:"message",oneof:"data",T:()=>zn}])}},Xn=new rr,nr=class extends I{constructor(){super("pulsebeam.v1.Sdp",[{no:1,name:"kind",kind:"enum",T:()=>["pulsebeam.v1.SdpKind",dr,"SDP_KIND_"]},{no:2,name:"sdp",kind:"scalar",T:9}])}},Wn=new nr,ir=class extends I{constructor(){super("pulsebeam.v1.ICECandidateBatch",[{no:1,name:"candidates",kind:"message",repeat:1,T:()=>rn}])}},zn=new ir,sr=class extends I{constructor(){super("pulsebeam.v1.ICECandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"sdp_m_line_index",kind:"scalar",opt:!0,T:13},{no:3,name:"sdp_mid",kind:"scalar",opt:!0,T:9},{no:4,name:"username",kind:"scalar",opt:!0,T:9},{no:5,name:"password",kind:"scalar",opt:!0,T:9}])}},rn=new sr,or=class extends I{constructor(){super("pulsebeam.v1.Join",[])}},Hn=new or,ar=class extends I{constructor(){super("pulsebeam.v1.Bye",[])}},Yn=new ar,cr=class extends I{constructor(){super("pulsebeam.v1.Ack",[{no:1,name:"ack_ranges",kind:"message",repeat:1,T:()=>ei}])}},Zn=new cr,lr=class extends I{constructor(){super("pulsebeam.v1.Ping",[])}},Qn=new lr,pr=class extends I{constructor(){super("pulsebeam.v1.AckRange",[{no:1,name:"seqnum_start",kind:"scalar",T:13},{no:2,name:"seqnum_end",kind:"scalar",T:13}])}},ei=new pr,fr=class extends I{constructor(){super("pulsebeam.v1.DataChannel",[{no:10,name:"heartbeat",kind:"message",oneof:"payload",T:()=>ti}])}},Mo=new fr,ur=class extends I{constructor(){super("pulsebeam.v1.DataChannelHeartbeat",[])}},ti=new ur,He=new fe("pulsebeam.v1.Signaling",[{name:"Prepare",options:{},I:jn,O:Bn},{name:"Send",options:{},I:wn,O:Kn},{name:"Recv",serverStreaming:!0,options:{},I:Gn,O:qn}]);var Ye=class{constructor(e){this._transport=e;g(this,"typeName",He.typeName);g(this,"methods",He.methods);g(this,"options",He.options)}prepare(e,r){let n=this.methods[0],i=this._transport.mergeOptions(r);return me("unary",this._transport,n,i,e)}send(e,r){let n=this.methods[1],i=this._transport.mergeOptions(r);return me("unary",this._transport,n,i,e)}recv(e,r){let n=this.methods[2],i=this._transport.mergeOptions(r);return me("serverStreaming",this._transport,n,i,e)}};function hr(t,e){return new Promise(r=>{let n=setTimeout(()=>r(!0),t);e&&e.addEventListener("abort",()=>{clearTimeout(n),r(!1)})})}function Ze(...t){let e=new AbortController,r=()=>{e.abort();for(let n of t)n.removeEventListener("abort",r)};for(let n of t)n.addEventListener("abort",r);return e.signal}async function ge(t,e){let{maxRetries:r,baseDelay:n,maxDelay:i,jitterFactor:s=.3,isRecoverable:o=()=>!0,abortSignal:a}=e,c=0;for(;(c<=r||r<0)&&!a?.aborted;)try{return await t()}catch(l){if(!o(l)||(c++,r>=0&&c>r))throw l;let p=ri(c,n,i,s);await hr(p,a).catch(()=>{})}if(a?.aborted)return null;throw new Error("Retry failed: max retries exceeded")}function ri(t,e,r,n){let i=Math.min(e*2**(t-1),r),s=Math.random()*n*i;return i+s}var nn=9e5,sn=50,mr=1e3;var ni=hr,ii=t=>{let e;do{let r=new Uint32Array(1);crypto.getRandomValues(r),e=r[0]}while(e>=0&&e<t);return e},si=t=>!0,gr=class{constructor(e){g(this,"map");g(this,"emitted");g(this,"unreliable");g(this,"processing");g(this,"logger");g(this,"onmsg",async e=>{});this.logger=e.sub("queue"),this.map=new Map,this.emitted=new Map,this.unreliable=[],this.processing=!1}enqueue(e){if(!e.header?.reliable)this.unreliable.push(e);else{let r=e.header.seqnum;if(this.map.has(r)||this.emitted.has(r))return;this.map.set(r,[performance.now(),e])}this.processNext()}async processNext(){if(this.processing)return;let e=this.unreliable.pop();if(!e){let r=this.map.entries().next().value;if(!r)return;let[n,i]=r;this.map.delete(n),this.emitted.set(n,i);let[s,o]=i;if(!o.header)return;e=o}this.processing=!0;try{await this.onmsg(e)}catch(r){let n={msg:e};r instanceof Error&&(n.err=r),this.logger.error("error processing message",n)}this.processing=!1,this.processNext()}},Qe=class{constructor(e,r){this.client=e;this.opts=r;g(this,"info");g(this,"streams");g(this,"abort");g(this,"logger");g(this,"asleep");g(this,"randUint32");g(this,"isRecoverable");g(this,"onstream",e=>{});g(this,"onclosed",e=>{});g(this,"handleControlMessage",e=>{switch(e.payloadType.oneofKind){case"ping":this.logger.debug("received ping");break;default:this.logger.warn("received unknown control message",{payload:e});break}});g(this,"handleMessages",e=>{if(this.logger.debug("received",{msg:e}),this.abort.signal.aborted)return;if(!e.header)return e.payload?this.handleControlMessage(e.payload):void 0;let r=e.header.src,n=e.header.dst;if(!r||!n)return;if(n.connId>=16&&n.connId!=this.info.connId){this.logger.warn("received messages from a stale connection, ignoring",{receivedConnID:n.connId});return}let i=null;for(let s of this.streams)if(r.groupId===s.other.groupId&&r.peerId===s.other.peerId&&r.connId===s.other.connId){i=s;break}if(!i){if(r.peerId==this.info.peerId){this.logger.warn("loopback detected, ignoring messages");return}this.logger.debug(`session not found, creating one for ${r.peerId}:${r.connId}`),i=new yr(this,this.info,r,this.logger),this.streams.push(i),this.onstream(i)}i.enqueue(e)});this.asleep=r.asleep||ni,this.randUint32=r.randUint32||ii,this.isRecoverable=r.isRecoverable||si,this.info={groupId:r.groupId,peerId:r.peerId,connId:this.randUint32(16)},this.abort=new AbortController,this.logger=r.logger.sub("transport",{info:this.info}),this.streams=[]}async listen(){let e={abort:this.abort.signal,timeout:nn},r={baseDelay:sn,maxDelay:mr,maxRetries:-1,abortSignal:this.abort.signal,isRecoverable:this.isRecoverable};for(;!this.abort.signal.aborted;)try{await ge(async()=>{let n=this.client.recv({src:this.info},e);n.responses.onMessage(i=>!!i.msg&&this.handleMessages(i.msg)),await n},r)}catch(n){this.logger.error("unrecoverable error, force closing",{err:n}),this.close();return}this.logger.debug("poll loop is closed")}async close(e){this.abort.signal.aborted||(e=e||"transport is closed",await Promise.all(this.streams.map(r=>r.close(e))),this.abort.abort(e),this.logger.debug("transport is now closed",{reason:e}),this.streams=[],this.onclosed(e))}removeStream(e){this.streams=this.streams.filter(r=>r!==e)}async connect(e,r,n){let i={payloadType:{oneofKind:"join",join:{}}},s={src:this.info,dst:{groupId:e,peerId:r,connId:0},seqnum:0,reliable:!1},o=!1,a=Ze(n,this.abort.signal);for(;!a.aborted&&!o;)await this.send(a,{header:s,payload:i}),await this.asleep(mr,a).catch(()=>{}),o=!!this.streams.find(c=>c.other.groupId===e&&c.other.peerId===r)}async send(e,r){let n=Ze(e,this.abort.signal),i={abort:n,timeout:nn},s={baseDelay:sn,maxDelay:mr,maxRetries:-1,abortSignal:n,isRecoverable:this.isRecoverable};try{if(await ge(async()=>await this.client.send({msg:r},i),s)===null){this.logger.warn("aborted, message dropped from sending",{msg:r});return}return}catch(o){this.logger.error("unrecoverable error, force closing",{err:o}),this.close();return}}},yr=class{constructor(e,r,n,i){this.transport=e;this.info=r;this.other=n;g(this,"logger");g(this,"abort");g(this,"recvq");g(this,"lastSeqnum");g(this,"onsignal",async e=>{});g(this,"onclosed",e=>{});this.logger=i.sub("stream",{other:n}),this.abort=new AbortController,this.recvq=new gr(this.logger),this.recvq.onmsg=s=>this.handleMessage(s),this.lastSeqnum=0}createSignal(...e){return Ze(this.abort.signal,...e)}enqueue(e){if(this.abort.signal.aborted){this.logger.warn("received a message in closed state, ignoring new messages.");return}this.recvq.enqueue(e)}async send(e,r,n){n||(n=this.abort.signal);let i={header:{src:this.transport.info,dst:this.other,seqnum:this.lastSeqnum,reliable:r},payload:{...e}};this.lastSeqnum++,await this.transport.send(n,i)}async handleMessage(e){if(!e.payload){this.logger.warn("payload is missing from the stream message",{msg:e});return}switch(e.payload.payloadType.oneofKind){case"bye":this.close("received bye",!0);return;case"signal":this.onsignal(e.payload.payloadType.signal);return;case"join":return;default:this.logger.warn("unhandled payload type",{msg:e});return}}async close(e,r){this.abort.signal.aborted||(e=e||"session is closed",r||await this.send({payloadType:{oneofKind:"bye",bye:{}}},!1).catch(n=>this.logger.warn("failed to send bye",{e:n})),this.abort.abort(e),this.transport.removeStream(this),this.onclosed(e),this.logger.debug("sent bye to the other peer",{reason:e}))}};var oi={DEBUG:console.debug,INFO:console.info,WARN:console.warn,ERROR:console.error},on={DEBUG:t=>console.debug(et(t)),INFO:t=>console.info(et(t)),WARN:t=>console.warn(et(t)),ERROR:t=>console.error(et(t))};function an(t,e,r="root",n=new Set){let i=".";if(!n.has(t)){n.add(t);for(let s in t)if(typeof t[s]=="object"&&t[s]!==null){let o=r+i+s;an(t[s],e,o,n)}else{let o=e[r]||[];o.push(`${s}=${t[s]}`),e[r]=o}}}function et(t){let e={};an(t,e);let r=[];for(let n in e)r.push(`[${n}] ${e[n].join(" ")}`);return r.join(`
|
38
|
+
`)}var tt=class t{constructor(e,r,n){this.name=e;g(this,"obj");g(this,"sink");r||(r={}),n||(n=oi),this.sink=n,this.obj={...r,name:e}}log(e,r,n){let i=n||{};e({ts:Date.now(),message:r,...this.obj,...i})}debug(e,r){this.log(this.sink.DEBUG,e,r)}info(e,r){this.log(this.sink.INFO,e,r)}warn(e,r){this.log(this.sink.WARN,e,r)}error(e,r){this.log(this.sink.ERROR,e,r)}sub(e,r){return r||(r={}),new t(this.name+"."+e,{...this.obj,...r},this.sink)}};var ai=1,cn=5e3,ln="__internal";function ci(t){return{candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,usernameFragment:t.password}}function li(t){switch(t){case 1:return"offer";case 2:return"answer";case 3:return"pranswer";case 4:return"rollback";default:throw new Error(`unexpected kind: ${t}`)}}function pn(t){switch(t){case"offer":return 1;case"answer":return 2;case"pranswer":return 3;case"rollback":return 4;default:throw new Error(`unexpected sdp type: ${t}`)}}var rt=class{constructor(e,r){this.stream=e;g(this,"pc");g(this,"makingOffer");g(this,"impolite");g(this,"pendingCandidates");g(this,"iceBatcher");g(this,"logger");g(this,"abort");g(this,"generationCounter");g(this,"iceRestartCount");g(this,"lastIceRestart");g(this,"timers");g(this,"_closeReason");g(this,"_connectionState");g(this,"internalDataChannel");g(this,"ondatachannel",()=>{});g(this,"onconnectionstatechange",()=>{});g(this,"ontrack",()=>{});g(this,"triggerIceRestart",()=>{if(!this.impolite)return;let e=performance.now()-this.lastIceRestart;if(e<cn){let r=cn-e,n=window.setTimeout(()=>{this.triggerIceRestart(),this.timers=this.timers.filter(i=>i===n)},r);return}if(this.pc.connectionState!=="connected"){if(this.iceRestartCount>=ai){this.close("detected sustained network failure");return}this.logger.debug("triggered ICE restart"),this.pc.restartIce(),this.generationCounter++,this.iceRestartCount++,this.lastIceRestart=performance.now()}});g(this,"sendSignal",e=>{this.stream.send({payloadType:{oneofKind:"signal",signal:{...e,generationCounter:this.generationCounter}}},!0)});g(this,"handleSignal",async e=>{if(e.generationCounter<this.generationCounter){this.logger.warn("detected staled generationCounter signals, ignoring");return}this.addCandidates(e);let r=e.data;if(e.generationCounter>this.generationCounter){if(this.logger.debug("detected new generationCounter",{otherGenerationCounter:e.generationCounter,generationCounter:this.generationCounter,msg:r}),r.oneofKind==="iceCandidate"){this.logger.warn("expecting an offer but got ice candidates during an ICE restart, adding to pending.",{msg:r});return}this.generationCounter=e.generationCounter}if(r.oneofKind!="sdp")return;let n=r.sdp;this.logger.debug("received a SDP signal",{sdpKind:n.kind});let i=n.kind===1&&(this.makingOffer||this.pc.signalingState!=="stable");if(this.impolite&&i){this.logger.debug("ignored offer");return}if(this.logger.debug("creating an answer"),await this.pc.setRemoteDescription({type:li(n.kind),sdp:n.sdp}),n.kind===1){if(await this.pc.setLocalDescription(),!this.pc.localDescription){this.logger.error("unexpected null local description");return}this.sendSignal({data:{oneofKind:"sdp",sdp:{kind:pn(this.pc.localDescription.type),sdp:this.pc.localDescription.sdp}}})}this.checkPendingCandidates()});g(this,"checkPendingCandidates",()=>{if(!["stable","have-local-offer","have-remote-offer"].includes(this.pc.signalingState)||!this.pc.remoteDescription){this.logger.debug("wait for adding pending candidates",{signalingState:this.pc.signalingState,iceConnectionState:this.pc.iceConnectionState,connectionState:this.pc.connectionState,remoteDescription:this.pc.remoteDescription,pendingCandidates:this.pendingCandidates.length});return}for(let r of this.pendingCandidates)!r.candidate||r.candidate===""||(this.pc.addIceCandidate(r).catch(n=>{this.logger.warn("failed to add candidate, skipping.",{candidate:r,e:n})}),this.logger.debug(`added ice: ${r.candidate}`));this.pendingCandidates=[]});this.pc=new RTCPeerConnection(r),this.makingOffer=!1,this.pendingCandidates=[],this.stream.info.connId===this.stream.other.connId?this.impolite=this.stream.info.peerId>this.stream.other.peerId:this.impolite=this.stream.info.connId>this.stream.other.connId,this.abort=new AbortController,this.logger=e.logger.sub("session",{role:this.impolite?"impolite":"polite"}),this.generationCounter=0,this.iceRestartCount=0,this.lastIceRestart=0,this.timers=[],this._connectionState="new",this.iceBatcher=new br(this.logger,100,s=>this.sendLocalIceCandidates(s)),e.onsignal=s=>this.handleSignal(s),e.onclosed=s=>this.close(s),this.pc.oniceconnectionstatechange=async()=>{let s=await this.pc.getStats(),o=[],a=[],c=[];s.forEach(l=>{l.type==="candidate-pair"?o.push(l):l.type==="local-candidate"?a.push(l):l.type==="remote-candidate"&&c.push(l)}),this.logger.debug("iceconnectionstate changed",{connectionstate:this.pc.connectionState,iceconnectionstate:this.pc.iceConnectionState,local:a,remote:c,pair:o,pending:this.pendingCandidates})},this.pc.onsignalingstatechange=()=>{this.checkPendingCandidates()};let n=performance.now();this.pc.onconnectionstatechange=s=>{switch(this.logger.debug("connectionstate changed",{connectionstate:this.pc.connectionState,iceconnectionstate:this.pc.iceConnectionState}),this.setConnectionState(this.pc.connectionState,s),this.pc.connectionState){case"connecting":n=performance.now();break;case"connected":{let o=performance.now()-n;this.logger.debug(`it took ${o}ms to connect`),this.iceRestartCount=0;break}case"disconnected":this.triggerIceRestart();break;case"failed":this.close("connection failed");break;case"closed":break}};let i=!0;this.pc.onnegotiationneeded=async()=>{if(i){if(!this.impolite){this.stream.send({payloadType:{oneofKind:"join",join:{}}},!0);return}i=!1}try{if(this.makingOffer=!0,this.logger.debug("creating an offer"),await this.pc.setLocalDescription(),!this.pc.localDescription)throw new Error("expect localDescription to be not empty");this.sendSignal({data:{oneofKind:"sdp",sdp:{kind:pn(this.pc.localDescription.type),sdp:this.pc.localDescription.sdp}}})}catch(s){s instanceof Error&&this.logger.error("failed in negotiating",{err:s})}finally{this.makingOffer=!1}},this.pc.onicecandidate=({candidate:s})=>{this.iceBatcher.addCandidate(s)},this.pc.ondatachannel=s=>{s.channel.label!==ln&&this.ondatachannel&&this.ondatachannel(s)},this.pc.ontrack=(...s)=>{this.ontrack&&this.ontrack(...s)},this.internalDataChannel=this.pc.createDataChannel(ln),this.internalDataChannel}addTrack(...e){return this.pc.addTrack(...e)}removeTrack(...e){return this.pc.removeTrack(...e)}createDataChannel(...e){return this.pc.createDataChannel(...e)}get connectionState(){return this.pc.connectionState}get closeReason(){return this._closeReason}get other(){return{groupId:this.stream.other.groupId,peerId:this.stream.other.peerId,connId:this.stream.other.connId}}close(e){if(this.abort.signal.aborted)return;this.abort.abort(e);for(let n of this.timers)clearTimeout(n);this.timers=[],this.iceBatcher.close(),this.stream.close(),this._closeReason=e,this.pc.close();let r=new Event("connectionstatechange");this.setConnectionState("closed",r),this.logger.debug("session closed",{connectionState:this.connectionState})}sendLocalIceCandidates(e){let r=[];for(let n of e){let i={candidate:"",sdpMLineIndex:0,sdpMid:""};i.candidate=n.candidate,i.sdpMLineIndex=n.sdpMLineIndex??void 0,i.sdpMid=n.sdpMid??void 0,i.username=n.usernameFragment??void 0,r.push(i)}this.sendSignal({data:{oneofKind:"iceCandidateBatch",iceCandidateBatch:{candidates:r}}})}setConnectionState(e,r){e!==this._connectionState&&this.onconnectionstatechange&&this.onconnectionstatechange(r)}addCandidates(e){let r=[];if(e.data.oneofKind==="iceCandidate")r.push(e.data.iceCandidate);else if(e.data.oneofKind==="iceCandidateBatch")r.push(...e.data.iceCandidateBatch.candidates);else return;this.pendingCandidates.push(...r.map(n=>ci(n))),this.checkPendingCandidates()}},br=class{constructor(e,r,n){g(this,"candidates",[]);g(this,"timeoutId",null);g(this,"delayMs");g(this,"logger");g(this,"onIceCandidates");g(this,"addCandidate",e=>{if(!e||e.candidate===""){this.logger.debug("ice gathering is finished, force flush local candidates"),this.flushCandidates();return}this.logger.debug("onicecandidate",{candidate:e}),this.candidates.push(e),this.timeoutId?(clearTimeout(this.timeoutId),this.timeoutId=setTimeout(this.flushCandidates,this.delayMs)):this.timeoutId=setTimeout(this.flushCandidates,this.delayMs)});g(this,"flushCandidates",()=>{this.candidates.length>0&&(this.onIceCandidates(this.candidates),this.candidates=[]),this.timeoutId=null});g(this,"flush",()=>{this.timeoutId&&clearTimeout(this.timeoutId),this.flushCandidates()});g(this,"close",()=>{this.timeoutId&&clearTimeout(this.timeoutId)});this.logger=e.sub("icebatcher"),this.delayMs=r,this.onIceCandidates=n}};var m;(function(t){t[t.OK=0]="OK",t[t.CANCELLED=1]="CANCELLED",t[t.UNKNOWN=2]="UNKNOWN",t[t.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",t[t.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",t[t.NOT_FOUND=5]="NOT_FOUND",t[t.ALREADY_EXISTS=6]="ALREADY_EXISTS",t[t.PERMISSION_DENIED=7]="PERMISSION_DENIED",t[t.UNAUTHENTICATED=16]="UNAUTHENTICATED",t[t.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",t[t.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",t[t.ABORTED=10]="ABORTED",t[t.OUT_OF_RANGE=11]="OUT_OF_RANGE",t[t.UNIMPLEMENTED=12]="UNIMPLEMENTED",t[t.INTERNAL=13]="INTERNAL",t[t.UNAVAILABLE=14]="UNAVAILABLE",t[t.DATA_LOSS=15]="DATA_LOSS"})(m||(m={}));var pi=function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(p){try{l(n.next(p))}catch(f){o(f)}}function c(p){try{l(n.throw(p))}catch(f){o(f)}}function l(p){p.done?s(p.value):i(p.value).then(a,c)}l((n=n.apply(t,e||[])).next())})};function Cr(t,e,r,n,i){if(n)for(let[s,o]of Object.entries(n))if(typeof o=="string")t.append(s,o);else for(let a of o)t.append(s,a);if(t.set("Content-Type",e==="text"?"application/grpc-web-text":"application/grpc-web+proto"),e=="text"&&t.set("Accept","application/grpc-web-text"),t.set("X-Grpc-Web","1"),i&&t.set("X-User-Agent",i),typeof r=="number"){if(r<=0)throw new R(`timeout ${r} ms exceeded`,m[m.DEADLINE_EXCEEDED]);t.set("grpc-timeout",`${r}m`)}else if(r){let s=r.getTime(),o=Date.now();if(s<=o)throw new R(`deadline ${r} exceeded`,m[m.DEADLINE_EXCEEDED]);t.set("grpc-timeout",`${s-o}m`)}return t}function Sr(t,e){let r=new Uint8Array(5+t.length);r[0]=U.DATA;for(let n=t.length,i=4;i>0;i--)r[i]=n%256,n>>>=8;return r.set(t,5),e==="binary"?r:ce(r)}function nt(t,e,r){if(arguments.length===1){let c=t,l;try{l=c.type}catch{}switch(l){case"error":case"opaque":case"opaqueredirect":throw new R(`fetch response type ${c.type}`,m[m.UNKNOWN])}return nt(hi(c.headers),c.status,c.statusText)}let n=t,i=e>=200&&e<300,s=dn(n),[o,a]=un(n);return(o===void 0||o===m.OK)&&!i&&(o=mi(e),a=r),[o,a,s]}function Rr(t){let e=di(t),[r,n]=un(e),i=dn(e);return[r??m.OK,n,i]}var U;(function(t){t[t.DATA=0]="DATA",t[t.TRAILER=128]="TRAILER"})(U||(U={}));function Tr(t,e,r){return pi(this,void 0,void 0,function*(){let n,i="",s=new Uint8Array(0),o=ui(e);if(fi(t)){let a=t.getReader();n={next:()=>a.read()}}else n=t[Symbol.asyncIterator]();for(;;){let a=yield n.next();if(a.value!==void 0){if(o==="text"){for(let l=0;l<a.value.length;l++)i+=String.fromCharCode(a.value[l]);let c=i.length-i.length%4;if(c===0)continue;s=fn(s,ae(i.substring(0,c))),i=i.substring(c)}else s=fn(s,a.value);for(;s.length>=5&&s[0]===U.DATA;){let c=0;for(let l=1;l<5;l++)c=(c<<8)+s[l];if(s.length-5>=c)r(U.DATA,s.subarray(5,5+c)),s=s.subarray(5+c);else break}}if(a.done){if(s.length===0)break;if(s[0]!==U.TRAILER||s.length<5)throw new R("premature EOF",m[m.DATA_LOSS]);r(U.TRAILER,s.subarray(5));break}}})}var fi=t=>typeof t.getReader=="function";function fn(t,e){let r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function ui(t){switch(t){case"application/grpc-web-text":case"application/grpc-web-text+proto":return"text";case"application/grpc-web":case"application/grpc-web+proto":return"binary";case void 0:case null:throw new R("missing response content type",m[m.INTERNAL]);default:throw new R("unexpected response content type: "+t,m[m.INTERNAL])}}function un(t){let e,r,n=t["grpc-message"];if(n!==void 0){if(Array.isArray(n))return[m.INTERNAL,"invalid grpc-web message"];r=n}let i=t["grpc-status"];if(i!==void 0){if(Array.isArray(i))return[m.INTERNAL,"invalid grpc-web status"];if(e=parseInt(i,10),m[e]===void 0)return[m.INTERNAL,"invalid grpc-web status"]}return[e,r]}function dn(t){let e={};for(let[r,n]of Object.entries(t))switch(r){case"grpc-message":case"grpc-status":case"content-type":break;default:e[r]=n}return e}function di(t){let e={};for(let r of String.fromCharCode.apply(String,t).trim().split(`\r
|
39
|
+
`)){if(r=="")continue;let[n,...i]=r.split(":"),s=i.join(":").trim();n=n.trim();let o=e[n];typeof o=="string"?e[n]=[o,s]:Array.isArray(o)?o.push(s):e[n]=s}return e}function hi(t){let e={};return t.forEach((r,n)=>{let i=e[n];typeof i=="string"?e[n]=[i,r]:Array.isArray(i)?i.push(r):e[n]=r}),e}function mi(t){switch(t){case 200:return m.OK;case 400:return m.INVALID_ARGUMENT;case 401:return m.UNAUTHENTICATED;case 403:return m.PERMISSION_DENIED;case 404:return m.NOT_FOUND;case 409:return m.ABORTED;case 412:return m.FAILED_PRECONDITION;case 429:return m.RESOURCE_EXHAUSTED;case 499:return m.CANCELLED;case 500:return m.UNKNOWN;case 501:return m.UNIMPLEMENTED;case 503:return m.UNAVAILABLE;case 504:return m.DEADLINE_EXCEEDED;default:return m.UNKNOWN}}var ye=class{constructor(e){this.defaultOptions=e}mergeOptions(e){return Gt(this.defaultOptions,e)}makeUrl(e,r){let n=r.baseUrl;return n.endsWith("/")&&(n=n.substring(0,n.length-1)),`${n}/${e.service.typeName}/${e.name}`}clientStreaming(e){let r=new R("Client streaming is not supported by grpc-web",m[m.UNIMPLEMENTED]);throw r.methodName=e.name,r.serviceName=e.service.typeName,r}duplex(e){let r=new R("Duplex streaming is not supported by grpc-web",m[m.UNIMPLEMENTED]);throw r.methodName=e.name,r.serviceName=e.service.typeName,r}serverStreaming(e,r,n){var i,s,o,a;let c=n,l=(i=c.format)!==null&&i!==void 0?i:"text",p=(s=c.fetchInit)!==null&&s!==void 0?s:{},f=this.makeUrl(e,c),d=e.I.toBinary(r,c.binaryOptions),y=new M,b=new ue,E=!0,k,F=new M,B,$=new M;return globalThis.fetch(f,Object.assign(Object.assign({},p),{method:"POST",headers:Cr(new globalThis.Headers,l,c.timeout,c.meta),body:Sr(d,l),signal:(o=n.abort)!==null&&o!==void 0?o:null})).then(T=>{let[S,N,L]=nt(T);if(y.resolve(L),S!=null&&S!==m.OK)throw new R(N??m[S],m[S],L);return S!=null&&(k={code:m[S],detail:N??m[S]}),T}).then(T=>{if(!T.body)throw new R("missing response body",m[m.INTERNAL]);return Tr(T.body,T.headers.get("content-type"),(S,N)=>{switch(S){case U.DATA:b.notifyMessage(e.O.fromBinary(N,c.binaryOptions)),E=!1;break;case U.TRAILER:let L,w;[L,w,B]=Rr(N),k={code:m[L],detail:w??m[L]};break}})}).then(()=>{if(!B&&!E)throw new R("missing trailers",m[m.DATA_LOSS]);if(!k)throw new R("missing status",m[m.INTERNAL]);if(k.code!=="OK")throw new R(k.detail,k.code,B);b.notifyComplete(),F.resolve(k),$.resolve(B||{})}).catch(T=>{let S;T instanceof R?S=T:T instanceof Error&&T.name==="AbortError"?S=new R(T.message,m[m.CANCELLED]):S=new R(T instanceof Error?T.message:""+T,m[m.INTERNAL]),S.methodName=e.name,S.serviceName=e.service.typeName,y.rejectPending(S),b.notifyError(S),F.rejectPending(S),$.rejectPending(S)}),new he(e,(a=c.meta)!==null&&a!==void 0?a:{},r,y.promise,b,F.promise,$.promise)}unary(e,r,n){var i,s,o,a;let c=n,l=(i=c.format)!==null&&i!==void 0?i:"text",p=(s=c.fetchInit)!==null&&s!==void 0?s:{},f=this.makeUrl(e,c),d=e.I.toBinary(r,c.binaryOptions),y=new M,b,E=new M,k,F=new M,B,$=new M;return globalThis.fetch(f,Object.assign(Object.assign({},p),{method:"POST",headers:Cr(new globalThis.Headers,l,c.timeout,c.meta),body:Sr(d,l),signal:(o=n.abort)!==null&&o!==void 0?o:null})).then(T=>{let[S,N,L]=nt(T);if(y.resolve(L),S!=null&&S!==m.OK)throw new R(N??m[S],m[S],L);return S!=null&&(k={code:m[S],detail:N??m[S]}),T}).then(T=>{if(!T.body)throw new R("missing response body",m[m.INTERNAL]);return Tr(T.body,T.headers.get("content-type"),(S,N)=>{switch(S){case U.DATA:if(b)throw new R("unary call received 2nd message",m[m.DATA_LOSS]);b=e.O.fromBinary(N,c.binaryOptions);break;case U.TRAILER:let L,w;[L,w,B]=Rr(N),k={code:m[L],detail:w??m[L]};break}})}).then(()=>{if(!B&&b)throw new R("missing trailers",m[m.DATA_LOSS]);if(!k)throw new R("missing status",m[m.INTERNAL]);if(!b&&k.code==="OK")throw new R("expected error status",m[m.DATA_LOSS]);if(!b)throw new R(k.detail,k.code,B);if(E.resolve(b),k.code!=="OK")throw new R(k.detail,k.code,B);F.resolve(k),$.resolve(B||{})}).catch(T=>{let S;T instanceof R?S=T:T instanceof Error&&T.name==="AbortError"?S=new R(T.message,m[m.CANCELLED]):S=new R(T instanceof Error?T.message:""+T,m[m.INTERNAL]),S.methodName=e.name,S.serviceName=e.service.typeName,y.rejectPending(S),E.rejectPending(S),F.rejectPending(S),$.rejectPending(S)}),new de(e,(a=c.meta)!==null&&a!==void 0?a:{},r,y.promise,E.promise,F.promise,$.promise)}};var H=class extends Error{};H.prototype.name="InvalidTokenError";function gi(t){return decodeURIComponent(atob(t).replace(/(.)/g,(e,r)=>{let n=r.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}function yi(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return gi(e)}catch{return atob(e)}}function hn(t,e){if(typeof t!="string")throw new H("Invalid token specified: must be a string");e||(e={});let r=e.header===!0?0:1,n=t.split(".")[r];if(typeof n!="string")throw new H(`Invalid token specified: missing part #${r+1}`);let i;try{i=yi(n)}catch(s){throw new H(`Invalid token specified: invalid base64 for part #${r+1} (${s.message})`)}try{return JSON.parse(i)}catch(s){throw new H(`Invalid token specified: invalid json for part #${r+1} (${s.message})`)}}var bi="https://cloud.pulsebeam.dev/grpc",vr=class{constructor(e,r,n,i){g(this,"transport");g(this,"logger");g(this,"sessions");g(this,"_state");g(this,"onsession",e=>{});g(this,"onstatechange",()=>{});g(this,"peerId");this.peerId=n.peerId,this.logger=e.sub("peer",{peerId:this.peerId}),this.sessions=[],this._state="new";let s={bundlePolicy:"balanced",iceTransportPolicy:n.forceRelay?"relay":"all",iceCandidatePoolSize:0,iceServers:n.iceServers};this.transport=new Qe(r,{enableDiscovery:!1,groupId:n.groupId,peerId:n.peerId,logger:this.logger,isRecoverable:i}),this.transport.onstream=o=>{let a=new rt(o,s);this.sessions.push(a),this.onsession(a)},this.transport.onclosed=()=>{this.close()}}start(){if(this._state==="closed")throw new Error("peer is already closed");this.transport.listen()}async close(){this.sessions=[],await this.transport.close(),this.setState("closed")}connect(e,r,n){return this.transport.connect(e,r,n)}get state(){return this._state}setState(e){e!==this._state&&(this._state=e,this.onstatechange())}},Ci=[m[m.PERMISSION_DENIED],m[m.INVALID_ARGUMENT],m[m.ABORTED],m[m.NOT_FOUND],m[m.UNAUTHENTICATED]];function mn(t){return t instanceof Error?t instanceof R?!Ci.includes(t.code):!0:!1}async function Ra(t){let e=t.token,r=new ye({baseUrl:t.baseUrl||bi,sendJson:!1,format:"binary",jsonOptions:{emitDefaultValues:!0,enumAsInteger:!0,ignoreUnknownFields:!0},interceptors:[{interceptUnary(l,p,f,d){return d.meta||(d.meta={}),d.meta.Authorization=`Bearer ${e}`,l(p,f,d)}}]}),n=new Ye(r),i=await ge(async()=>await n.prepare({}),{baseDelay:50,maxDelay:1e3,maxRetries:5,isRecoverable:mn});if(i===null)throw new Error("createPeer aborted");let s=[...t.iceServers||[]];for(let l of i.response.iceServers)s.push({urls:l.urls,username:l.username,credential:l.credential});let o=hn(e),a={...t,iceServers:s,groupId:o.gid,peerId:o.pid};return new vr(new tt("pulsebeam",void 0,on),n,a,mn)}var gn=Symbol("clean");var j=[],J=0,it=4,Si=0,yn=t=>{let e=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(n){return r.lc=e.push(n),()=>{for(let s=J+it;s<j.length;)j[s]===n?j.splice(s,it):s+=it;let i=e.indexOf(n);~i&&(e.splice(i,1),--r.lc||r.off())}},notify(n,i){Si++;let s=!j.length;for(let o of e)j.push(o,r.value,n,i);if(s){for(J=0;J<j.length;J+=it)j[J](j[J+1],j[J+2],j[J+3]);j.length=0}},off(){},set(n){let i=r.value;i!==n&&(r.value=n,r.notify(i))},subscribe(n){let i=r.listen(n);return n(r.value),i},value:t};return process.env.NODE_ENV!=="production"&&(r[gn]=()=>{e=[],r.lc=0,r.off()}),r};var be=(t={})=>{let e=yn(t);return e.setKey=function(r,n){let i=e.value;typeof n>"u"&&r in e.value?(e.value={...e.value},delete e.value[r],e.notify(i,r)):e.value[r]!==n&&(e.value={...e.value,[r]:n},e.notify(i,r))},e};var Ce=class Ce{constructor(e){this.peer=e;g(this,"$kv");g(this,"$localStreams");g(this,"$remoteStreams");g(this,"crdtStore");g(this,"replicaId");g(this,"sendChannels");this.crdtStore={},this.$kv=be({}),this.$localStreams=be({}),this.$remoteStreams=be({}),this.sendChannels={},this.replicaId=e.peerId,e.onsession=r=>{let n=`${r.other.groupId}:${r.other.peerId}:${r.other.connId}`;this.sendChannels[n]=r.createDataChannel(Ce.KV_NAMESPACE,{ordered:!0,maxRetransmits:3}),r.ondatachannel=s=>{console.log("debug:ondatachannel",s.channel.label),s.channel.label===Ce.KV_NAMESPACE&&(s.channel.onmessage=o=>{let a=JSON.parse(o.data);console.log("debug:onmessage",{update:a}),this.receiveUpdate(a.key,a.entry)},s.channel.onopen=o=>{console.log("debug:sync",{crdt:this.crdtStore});for(let[a,c]of Object.entries(this.crdtStore))console.log("debug:notifying",{key:a,entry:c}),this.notifyPeer(this.sendChannels[n],{key:a,entry:c})})},r.ontrack=s=>{for(let o of s.streams){let a=`${n}:${o.id}`;this.$remoteStreams.setKey(a,o)}},r.onconnectionstatechange=s=>{r.connectionState==="failed"&&(delete this.sendChannels[n],console.log(`connection failed, removed ${n}`))};let i=Object.entries(this.$localStreams.get());for(let[s,o]of i)for(let a of o.getTracks())r.addTrack(a,o)},this.$kv.listen((r,n,i)=>{let s=r[i];this.set(i,s)})}async addUserMedia(e){let r=await navigator.mediaDevices.getUserMedia(e);this.addMediaStream(r)}async addDisplayMedia(e){let r=await navigator.mediaDevices.getDisplayMedia(e);this.addMediaStream(r)}addMediaStream(e){this.$localStreams.setKey(e.id,e)}start(){this.peer.start()}close(){this.peer.close()}set(e,r){let n=this.crdtStore[e];if(n&&n.value===r)return;let i={value:r,timestamp:Date.now(),replicaId:this.replicaId};this.notifyPeers(e,i)}notifyPeer(e,r){e.send(JSON.stringify(r))}notifyPeers(e,r){let n={key:e,entry:r};for(let i of Object.values(this.sendChannels))this.notifyPeer(i,n)}receiveUpdate(e,r){let n=this.crdtStore[e];if(console.log("debug:received_update",{key:e,remoteEntry:r,currentEntry:n}),!n)this.crdtStore[e]=r,this.$kv.setKey(e,r.value),console.log("debug:received_update accepted (resolution=empty)",r);else if(r.timestamp>n.timestamp)this.crdtStore[e]=r,this.$kv.setKey(e,r.value),console.log("debug:received_update accepted (resolution=older)",r);else if(r.timestamp===n.timestamp&&r.replicaId>this.replicaId)this.crdtStore[e]=r,this.$kv.setKey(e,r.value),console.log("debug:received_update accepted (resolution=replicaId)",r);else{console.log("debug:received_update ignored remote update",{remoteEntry:r,currentEntry:n});return}}};g(Ce,"KV_NAMESPACE","__crdt_kv");var bn=Ce;oe.disableLog(!1);oe.disableWarnings(!1);console.log("UA: ",navigator.userAgent);console.log("webrtc-adapter is enabled",JSON.stringify({shim:oe.browserShim,version:oe.browserDetails},null,2));})();
|