sx-peerjs-http-util 1.0.6 → 1.2.0

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../node_modules/sdp/sdp.js", "../src/index.ts", "../node_modules/peerjs-js-binarypack/lib/binarypack.ts", "../node_modules/peerjs-js-binarypack/lib/bufferbuilder.ts", "../node_modules/webrtc-adapter/src/js/utils.js", "../node_modules/webrtc-adapter/src/js/chrome/chrome_shim.js", "../node_modules/webrtc-adapter/src/js/chrome/getusermedia.js", "../node_modules/webrtc-adapter/src/js/firefox/firefox_shim.js", "../node_modules/webrtc-adapter/src/js/firefox/getusermedia.js", "../node_modules/webrtc-adapter/src/js/firefox/getdisplaymedia.js", "../node_modules/webrtc-adapter/src/js/safari/safari_shim.js", "../node_modules/webrtc-adapter/src/js/common_shim.js", "../node_modules/webrtc-adapter/src/js/adapter_factory.js", "../node_modules/webrtc-adapter/src/js/adapter_core.js", "../node_modules/peerjs/dist/lib/exports.ts", "../node_modules/peerjs/dist/lib/util.ts", "../node_modules/peerjs/dist/lib/dataconnection/BufferedConnection/binaryPackChunker.ts", "../node_modules/peerjs/dist/lib/supports.ts", "../node_modules/peerjs/dist/lib/utils/validateId.ts", "../node_modules/peerjs/dist/lib/utils/randomToken.ts", "../node_modules/peerjs/dist/lib/peer.ts", "../node_modules/peerjs/dist/lib/logger.ts", "../node_modules/peerjs/dist/lib/socket.ts", "../node_modules/peerjs/dist/node_modules/eventemitter3/index.js", "../node_modules/peerjs/dist/lib/enums.ts", "../node_modules/peerjs/dist/lib/version.ts", "../node_modules/peerjs/dist/lib/mediaconnection.ts", "../node_modules/peerjs/dist/lib/negotiator.ts", "../node_modules/peerjs/dist/lib/baseconnection.ts", "../node_modules/peerjs/dist/lib/peerError.ts", "../node_modules/peerjs/dist/lib/api.ts", "../node_modules/peerjs/dist/lib/dataconnection/BufferedConnection/BinaryPack.ts", "../node_modules/peerjs/dist/lib/dataconnection/BufferedConnection/BufferedConnection.ts", "../node_modules/peerjs/dist/lib/dataconnection/DataConnection.ts", "../node_modules/peerjs/dist/lib/dataconnection/BufferedConnection/Raw.ts", "../node_modules/peerjs/dist/lib/dataconnection/BufferedConnection/Json.ts", "../node_modules/peerjs/dist/lib/msgPackPeer.ts", "../node_modules/peerjs/dist/lib/dataconnection/StreamConnection/MsgPack.ts", "../node_modules/peerjs/dist/lib/dataconnection/StreamConnection/StreamConnection.ts"],
4
- "sourcesContent": ["/* eslint-env node */\n'use strict';\n\n// SDP helpers.\nconst SDPUtils = {};\n\n// Generate an alphanumeric identifier for cname or mids.\n// TODO: use UUIDs instead? https://gist.github.com/jed/982883\nSDPUtils.generateIdentifier = function() {\n return Math.random().toString(36).substring(2, 12);\n};\n\n// The RTCP CNAME used by all peerconnections from the same JS.\nSDPUtils.localCName = SDPUtils.generateIdentifier();\n\n// Splits SDP into lines, dealing with both CRLF and LF.\nSDPUtils.splitLines = function(blob) {\n return blob.trim().split('\\n').map(line => line.trim());\n};\n// Splits SDP into sessionpart and mediasections. Ensures CRLF.\nSDPUtils.splitSections = function(blob) {\n const parts = blob.split('\\nm=');\n return parts.map((part, index) => (index > 0 ?\n 'm=' + part : part).trim() + '\\r\\n');\n};\n\n// Returns the session description.\nSDPUtils.getDescription = function(blob) {\n const sections = SDPUtils.splitSections(blob);\n return sections && sections[0];\n};\n\n// Returns the individual media sections.\nSDPUtils.getMediaSections = function(blob) {\n const sections = SDPUtils.splitSections(blob);\n sections.shift();\n return sections;\n};\n\n// Returns lines that start with a certain prefix.\nSDPUtils.matchPrefix = function(blob, prefix) {\n return SDPUtils.splitLines(blob).filter(line => line.indexOf(prefix) === 0);\n};\n\n// Parses an ICE candidate line. Sample input:\n// candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8\n// rport 55996\"\n// Input can be prefixed with a=.\nSDPUtils.parseCandidate = function(line) {\n let parts;\n // Parse both variants.\n if (line.indexOf('a=candidate:') === 0) {\n parts = line.substring(12).split(' ');\n } else {\n parts = line.substring(10).split(' ');\n }\n\n const candidate = {\n foundation: parts[0],\n component: {1: 'rtp', 2: 'rtcp'}[parts[1]] || parts[1],\n protocol: parts[2].toLowerCase(),\n priority: parseInt(parts[3], 10),\n ip: parts[4],\n address: parts[4], // address is an alias for ip.\n port: parseInt(parts[5], 10),\n // skip parts[6] == 'typ'\n type: parts[7],\n };\n\n for (let i = 8; i < parts.length; i += 2) {\n switch (parts[i]) {\n case 'raddr':\n candidate.relatedAddress = parts[i + 1];\n break;\n case 'rport':\n candidate.relatedPort = parseInt(parts[i + 1], 10);\n break;\n case 'tcptype':\n candidate.tcpType = parts[i + 1];\n break;\n case 'ufrag':\n candidate.ufrag = parts[i + 1]; // for backward compatibility.\n candidate.usernameFragment = parts[i + 1];\n break;\n default: // extension handling, in particular ufrag. Don't overwrite.\n if (candidate[parts[i]] === undefined) {\n candidate[parts[i]] = parts[i + 1];\n }\n break;\n }\n }\n return candidate;\n};\n\n// Translates a candidate object into SDP candidate attribute.\n// This does not include the a= prefix!\nSDPUtils.writeCandidate = function(candidate) {\n const sdp = [];\n sdp.push(candidate.foundation);\n\n const component = candidate.component;\n if (component === 'rtp') {\n sdp.push(1);\n } else if (component === 'rtcp') {\n sdp.push(2);\n } else {\n sdp.push(component);\n }\n sdp.push(candidate.protocol.toUpperCase());\n sdp.push(candidate.priority);\n sdp.push(candidate.address || candidate.ip);\n sdp.push(candidate.port);\n\n const type = candidate.type;\n sdp.push('typ');\n sdp.push(type);\n if (type !== 'host' && candidate.relatedAddress &&\n candidate.relatedPort) {\n sdp.push('raddr');\n sdp.push(candidate.relatedAddress);\n sdp.push('rport');\n sdp.push(candidate.relatedPort);\n }\n if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {\n sdp.push('tcptype');\n sdp.push(candidate.tcpType);\n }\n if (candidate.usernameFragment || candidate.ufrag) {\n sdp.push('ufrag');\n sdp.push(candidate.usernameFragment || candidate.ufrag);\n }\n return 'candidate:' + sdp.join(' ');\n};\n\n// Parses an ice-options line, returns an array of option tags.\n// Sample input:\n// a=ice-options:foo bar\nSDPUtils.parseIceOptions = function(line) {\n return line.substring(14).split(' ');\n};\n\n// Parses a rtpmap line, returns RTCRtpCoddecParameters. Sample input:\n// a=rtpmap:111 opus/48000/2\nSDPUtils.parseRtpMap = function(line) {\n let parts = line.substring(9).split(' ');\n const parsed = {\n payloadType: parseInt(parts.shift(), 10), // was: id\n };\n\n parts = parts[0].split('/');\n\n parsed.name = parts[0];\n parsed.clockRate = parseInt(parts[1], 10); // was: clockrate\n parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1;\n // legacy alias, got renamed back to channels in ORTC.\n parsed.numChannels = parsed.channels;\n return parsed;\n};\n\n// Generates a rtpmap line from RTCRtpCodecCapability or\n// RTCRtpCodecParameters.\nSDPUtils.writeRtpMap = function(codec) {\n let pt = codec.payloadType;\n if (codec.preferredPayloadType !== undefined) {\n pt = codec.preferredPayloadType;\n }\n const channels = codec.channels || codec.numChannels || 1;\n return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +\n (channels !== 1 ? '/' + channels : '') + '\\r\\n';\n};\n\n// Parses a extmap line (headerextension from RFC 5285). Sample input:\n// a=extmap:2 urn:ietf:params:rtp-hdrext:toffset\n// a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset\nSDPUtils.parseExtmap = function(line) {\n const parts = line.substring(9).split(' ');\n return {\n id: parseInt(parts[0], 10),\n direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',\n uri: parts[1],\n attributes: parts.slice(2).join(' '),\n };\n};\n\n// Generates an extmap line from RTCRtpHeaderExtensionParameters or\n// RTCRtpHeaderExtension.\nSDPUtils.writeExtmap = function(headerExtension) {\n return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +\n (headerExtension.direction && headerExtension.direction !== 'sendrecv'\n ? '/' + headerExtension.direction\n : '') +\n ' ' + headerExtension.uri +\n (headerExtension.attributes ? ' ' + headerExtension.attributes : '') +\n '\\r\\n';\n};\n\n// Parses a fmtp line, returns dictionary. Sample input:\n// a=fmtp:96 vbr=on;cng=on\n// Also deals with vbr=on; cng=on\n// Non-key-value such as telephone-events `0-15` get parsed as\n// {`0-15`:undefined}\nSDPUtils.parseFmtp = function(line) {\n const parsed = {};\n let kv;\n const parts = line.substring(line.indexOf(' ') + 1).split(';');\n for (let j = 0; j < parts.length; j++) {\n kv = parts[j].trim().split('=');\n parsed[kv[0].trim()] = kv[1];\n }\n return parsed;\n};\n\n// Generates a fmtp line from RTCRtpCodecCapability or RTCRtpCodecParameters.\nSDPUtils.writeFmtp = function(codec) {\n let line = '';\n let pt = codec.payloadType;\n if (codec.preferredPayloadType !== undefined) {\n pt = codec.preferredPayloadType;\n }\n if (codec.parameters && Object.keys(codec.parameters).length) {\n const params = [];\n Object.keys(codec.parameters).forEach(param => {\n if (codec.parameters[param] !== undefined) {\n params.push(param + '=' + codec.parameters[param]);\n } else {\n params.push(param);\n }\n });\n line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\\r\\n';\n }\n return line;\n};\n\n// Parses a rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:\n// a=rtcp-fb:98 nack rpsi\nSDPUtils.parseRtcpFb = function(line) {\n const parts = line.substring(line.indexOf(' ') + 1).split(' ');\n return {\n type: parts.shift(),\n parameter: parts.join(' '),\n };\n};\n\n// Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.\nSDPUtils.writeRtcpFb = function(codec) {\n let lines = '';\n let pt = codec.payloadType;\n if (codec.preferredPayloadType !== undefined) {\n pt = codec.preferredPayloadType;\n }\n if (codec.rtcpFeedback && codec.rtcpFeedback.length) {\n // FIXME: special handling for trr-int?\n codec.rtcpFeedback.forEach(fb => {\n lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +\n (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +\n '\\r\\n';\n });\n }\n return lines;\n};\n\n// Parses a RFC 5576 ssrc media attribute. Sample input:\n// a=ssrc:3735928559 cname:something\nSDPUtils.parseSsrcMedia = function(line) {\n const sp = line.indexOf(' ');\n const parts = {\n ssrc: parseInt(line.substring(7, sp), 10),\n };\n const colon = line.indexOf(':', sp);\n if (colon > -1) {\n parts.attribute = line.substring(sp + 1, colon);\n parts.value = line.substring(colon + 1);\n } else {\n parts.attribute = line.substring(sp + 1);\n }\n return parts;\n};\n\n// Parse a ssrc-group line (see RFC 5576). Sample input:\n// a=ssrc-group:semantics 12 34\nSDPUtils.parseSsrcGroup = function(line) {\n const parts = line.substring(13).split(' ');\n return {\n semantics: parts.shift(),\n ssrcs: parts.map(ssrc => parseInt(ssrc, 10)),\n };\n};\n\n// Extracts the MID (RFC 5888) from a media section.\n// Returns the MID or undefined if no mid line was found.\nSDPUtils.getMid = function(mediaSection) {\n const mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];\n if (mid) {\n return mid.substring(6);\n }\n};\n\n// Parses a fingerprint line for DTLS-SRTP.\nSDPUtils.parseFingerprint = function(line) {\n const parts = line.substring(14).split(' ');\n return {\n algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.\n value: parts[1].toUpperCase(), // the definition is upper-case in RFC 4572.\n };\n};\n\n// Extracts DTLS parameters from SDP media section or sessionpart.\n// FIXME: for consistency with other functions this should only\n// get the fingerprint line as input. See also getIceParameters.\nSDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {\n const lines = SDPUtils.matchPrefix(mediaSection + sessionpart,\n 'a=fingerprint:');\n // Note: a=setup line is ignored since we use the 'auto' role in Edge.\n return {\n role: 'auto',\n fingerprints: lines.map(SDPUtils.parseFingerprint),\n };\n};\n\n// Serializes DTLS parameters to SDP.\nSDPUtils.writeDtlsParameters = function(params, setupType) {\n let sdp = 'a=setup:' + setupType + '\\r\\n';\n params.fingerprints.forEach(fp => {\n sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\\r\\n';\n });\n return sdp;\n};\n\n// Parses a=crypto lines into\n// https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#dictionary-rtcsrtpsdesparameters-members\nSDPUtils.parseCryptoLine = function(line) {\n const parts = line.substring(9).split(' ');\n return {\n tag: parseInt(parts[0], 10),\n cryptoSuite: parts[1],\n keyParams: parts[2],\n sessionParams: parts.slice(3),\n };\n};\n\nSDPUtils.writeCryptoLine = function(parameters) {\n return 'a=crypto:' + parameters.tag + ' ' +\n parameters.cryptoSuite + ' ' +\n (typeof parameters.keyParams === 'object'\n ? SDPUtils.writeCryptoKeyParams(parameters.keyParams)\n : parameters.keyParams) +\n (parameters.sessionParams ? ' ' + parameters.sessionParams.join(' ') : '') +\n '\\r\\n';\n};\n\n// Parses the crypto key parameters into\n// https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#rtcsrtpkeyparam*\nSDPUtils.parseCryptoKeyParams = function(keyParams) {\n if (keyParams.indexOf('inline:') !== 0) {\n return null;\n }\n const parts = keyParams.substring(7).split('|');\n return {\n keyMethod: 'inline',\n keySalt: parts[0],\n lifeTime: parts[1],\n mkiValue: parts[2] ? parts[2].split(':')[0] : undefined,\n mkiLength: parts[2] ? parts[2].split(':')[1] : undefined,\n };\n};\n\nSDPUtils.writeCryptoKeyParams = function(keyParams) {\n return keyParams.keyMethod + ':'\n + keyParams.keySalt +\n (keyParams.lifeTime ? '|' + keyParams.lifeTime : '') +\n (keyParams.mkiValue && keyParams.mkiLength\n ? '|' + keyParams.mkiValue + ':' + keyParams.mkiLength\n : '');\n};\n\n// Extracts all SDES parameters.\nSDPUtils.getCryptoParameters = function(mediaSection, sessionpart) {\n const lines = SDPUtils.matchPrefix(mediaSection + sessionpart,\n 'a=crypto:');\n return lines.map(SDPUtils.parseCryptoLine);\n};\n\n// Parses ICE information from SDP media section or sessionpart.\n// FIXME: for consistency with other functions this should only\n// get the ice-ufrag and ice-pwd lines as input.\nSDPUtils.getIceParameters = function(mediaSection, sessionpart) {\n const ufrag = SDPUtils.matchPrefix(mediaSection + sessionpart,\n 'a=ice-ufrag:')[0];\n const pwd = SDPUtils.matchPrefix(mediaSection + sessionpart,\n 'a=ice-pwd:')[0];\n if (!(ufrag && pwd)) {\n return null;\n }\n return {\n usernameFragment: ufrag.substring(12),\n password: pwd.substring(10),\n };\n};\n\n// Serializes ICE parameters to SDP.\nSDPUtils.writeIceParameters = function(params) {\n let sdp = 'a=ice-ufrag:' + params.usernameFragment + '\\r\\n' +\n 'a=ice-pwd:' + params.password + '\\r\\n';\n if (params.iceLite) {\n sdp += 'a=ice-lite\\r\\n';\n }\n return sdp;\n};\n\n// Parses the SDP media section and returns RTCRtpParameters.\nSDPUtils.parseRtpParameters = function(mediaSection) {\n const description = {\n codecs: [],\n headerExtensions: [],\n fecMechanisms: [],\n rtcp: [],\n };\n const lines = SDPUtils.splitLines(mediaSection);\n const mline = lines[0].split(' ');\n description.profile = mline[2];\n for (let i = 3; i < mline.length; i++) { // find all codecs from mline[3..]\n const pt = mline[i];\n const rtpmapline = SDPUtils.matchPrefix(\n mediaSection, 'a=rtpmap:' + pt + ' ')[0];\n if (rtpmapline) {\n const codec = SDPUtils.parseRtpMap(rtpmapline);\n const fmtps = SDPUtils.matchPrefix(\n mediaSection, 'a=fmtp:' + pt + ' ');\n // Only the first a=fmtp:<pt> is considered.\n codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};\n codec.rtcpFeedback = SDPUtils.matchPrefix(\n mediaSection, 'a=rtcp-fb:' + pt + ' ')\n .map(SDPUtils.parseRtcpFb);\n description.codecs.push(codec);\n // parse FEC mechanisms from rtpmap lines.\n switch (codec.name.toUpperCase()) {\n case 'RED':\n case 'ULPFEC':\n description.fecMechanisms.push(codec.name.toUpperCase());\n break;\n default: // only RED and ULPFEC are recognized as FEC mechanisms.\n break;\n }\n }\n }\n SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(line => {\n description.headerExtensions.push(SDPUtils.parseExtmap(line));\n });\n const wildcardRtcpFb = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-fb:* ')\n .map(SDPUtils.parseRtcpFb);\n description.codecs.forEach(codec => {\n wildcardRtcpFb.forEach(fb=> {\n const duplicate = codec.rtcpFeedback.find(existingFeedback => {\n return existingFeedback.type === fb.type &&\n existingFeedback.parameter === fb.parameter;\n });\n if (!duplicate) {\n codec.rtcpFeedback.push(fb);\n }\n });\n });\n // FIXME: parse rtcp.\n return description;\n};\n\n// Generates parts of the SDP media section describing the capabilities /\n// parameters.\nSDPUtils.writeRtpDescription = function(kind, caps) {\n let sdp = '';\n\n // Build the mline.\n sdp += 'm=' + kind + ' ';\n sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.\n sdp += ' ' + (caps.profile || 'UDP/TLS/RTP/SAVPF') + ' ';\n sdp += caps.codecs.map(codec => {\n if (codec.preferredPayloadType !== undefined) {\n return codec.preferredPayloadType;\n }\n return codec.payloadType;\n }).join(' ') + '\\r\\n';\n\n sdp += 'c=IN IP4 0.0.0.0\\r\\n';\n sdp += 'a=rtcp:9 IN IP4 0.0.0.0\\r\\n';\n\n // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.\n caps.codecs.forEach(codec => {\n sdp += SDPUtils.writeRtpMap(codec);\n sdp += SDPUtils.writeFmtp(codec);\n sdp += SDPUtils.writeRtcpFb(codec);\n });\n let maxptime = 0;\n caps.codecs.forEach(codec => {\n if (codec.maxptime > maxptime) {\n maxptime = codec.maxptime;\n }\n });\n if (maxptime > 0) {\n sdp += 'a=maxptime:' + maxptime + '\\r\\n';\n }\n\n if (caps.headerExtensions) {\n caps.headerExtensions.forEach(extension => {\n sdp += SDPUtils.writeExtmap(extension);\n });\n }\n // FIXME: write fecMechanisms.\n return sdp;\n};\n\n// Parses the SDP media section and returns an array of\n// RTCRtpEncodingParameters.\nSDPUtils.parseRtpEncodingParameters = function(mediaSection) {\n const encodingParameters = [];\n const description = SDPUtils.parseRtpParameters(mediaSection);\n const hasRed = description.fecMechanisms.indexOf('RED') !== -1;\n const hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;\n\n // filter a=ssrc:... cname:, ignore PlanB-msid\n const ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')\n .map(line => SDPUtils.parseSsrcMedia(line))\n .filter(parts => parts.attribute === 'cname');\n const primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;\n let secondarySsrc;\n\n const flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')\n .map(line => {\n const parts = line.substring(17).split(' ');\n return parts.map(part => parseInt(part, 10));\n });\n if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {\n secondarySsrc = flows[0][1];\n }\n\n description.codecs.forEach(codec => {\n if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {\n let encParam = {\n ssrc: primarySsrc,\n codecPayloadType: parseInt(codec.parameters.apt, 10),\n };\n if (primarySsrc && secondarySsrc) {\n encParam.rtx = {ssrc: secondarySsrc};\n }\n encodingParameters.push(encParam);\n if (hasRed) {\n encParam = JSON.parse(JSON.stringify(encParam));\n encParam.fec = {\n ssrc: primarySsrc,\n mechanism: hasUlpfec ? 'red+ulpfec' : 'red',\n };\n encodingParameters.push(encParam);\n }\n }\n });\n if (encodingParameters.length === 0 && primarySsrc) {\n encodingParameters.push({\n ssrc: primarySsrc,\n });\n }\n\n // we support both b=AS and b=TIAS but interpret AS as TIAS.\n let bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');\n if (bandwidth.length) {\n if (bandwidth[0].indexOf('b=TIAS:') === 0) {\n bandwidth = parseInt(bandwidth[0].substring(7), 10);\n } else if (bandwidth[0].indexOf('b=AS:') === 0) {\n // use formula from JSEP to convert b=AS to TIAS value.\n bandwidth = parseInt(bandwidth[0].substring(5), 10) * 1000 * 0.95\n - (50 * 40 * 8);\n } else {\n bandwidth = undefined;\n }\n encodingParameters.forEach(params => {\n params.maxBitrate = bandwidth;\n });\n }\n return encodingParameters;\n};\n\n// parses http://draft.ortc.org/#rtcrtcpparameters*\nSDPUtils.parseRtcpParameters = function(mediaSection) {\n const rtcpParameters = {};\n\n // Gets the first SSRC. Note that with RTX there might be multiple\n // SSRCs.\n const remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')\n .map(line => SDPUtils.parseSsrcMedia(line))\n .filter(obj => obj.attribute === 'cname')[0];\n if (remoteSsrc) {\n rtcpParameters.cname = remoteSsrc.value;\n rtcpParameters.ssrc = remoteSsrc.ssrc;\n }\n\n // Edge uses the compound attribute instead of reducedSize\n // compound is !reducedSize\n const rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');\n rtcpParameters.reducedSize = rsize.length > 0;\n rtcpParameters.compound = rsize.length === 0;\n\n // parses the rtcp-mux attr\u0456bute.\n // Note that Edge does not support unmuxed RTCP.\n const mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');\n rtcpParameters.mux = mux.length > 0;\n\n return rtcpParameters;\n};\n\nSDPUtils.writeRtcpParameters = function(rtcpParameters) {\n let sdp = '';\n if (rtcpParameters.reducedSize) {\n sdp += 'a=rtcp-rsize\\r\\n';\n }\n if (rtcpParameters.mux) {\n sdp += 'a=rtcp-mux\\r\\n';\n }\n if (rtcpParameters.ssrc !== undefined && rtcpParameters.cname) {\n sdp += 'a=ssrc:' + rtcpParameters.ssrc +\n ' cname:' + rtcpParameters.cname + '\\r\\n';\n }\n return sdp;\n};\n\n\n// parses either a=msid: or a=ssrc:... msid lines and returns\n// the id of the MediaStream and MediaStreamTrack.\nSDPUtils.parseMsid = function(mediaSection) {\n let parts;\n const spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');\n if (spec.length === 1) {\n parts = spec[0].substring(7).split(' ');\n return {stream: parts[0], track: parts[1]};\n }\n const planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')\n .map(line => SDPUtils.parseSsrcMedia(line))\n .filter(msidParts => msidParts.attribute === 'msid');\n if (planB.length > 0) {\n parts = planB[0].value.split(' ');\n return {stream: parts[0], track: parts[1]};\n }\n};\n\n// SCTP\n// parses draft-ietf-mmusic-sctp-sdp-26 first and falls back\n// to draft-ietf-mmusic-sctp-sdp-05\nSDPUtils.parseSctpDescription = function(mediaSection) {\n const mline = SDPUtils.parseMLine(mediaSection);\n const maxSizeLine = SDPUtils.matchPrefix(mediaSection, 'a=max-message-size:');\n let maxMessageSize;\n if (maxSizeLine.length > 0) {\n maxMessageSize = parseInt(maxSizeLine[0].substring(19), 10);\n }\n if (isNaN(maxMessageSize)) {\n maxMessageSize = 65536;\n }\n const sctpPort = SDPUtils.matchPrefix(mediaSection, 'a=sctp-port:');\n if (sctpPort.length > 0) {\n return {\n port: parseInt(sctpPort[0].substring(12), 10),\n protocol: mline.fmt,\n maxMessageSize,\n };\n }\n const sctpMapLines = SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:');\n if (sctpMapLines.length > 0) {\n const parts = sctpMapLines[0]\n .substring(10)\n .split(' ');\n return {\n port: parseInt(parts[0], 10),\n protocol: parts[1],\n maxMessageSize,\n };\n }\n};\n\n// SCTP\n// outputs the draft-ietf-mmusic-sctp-sdp-26 version that all browsers\n// support by now receiving in this format, unless we originally parsed\n// as the draft-ietf-mmusic-sctp-sdp-05 format (indicated by the m-line\n// protocol of DTLS/SCTP -- without UDP/ or TCP/)\nSDPUtils.writeSctpDescription = function(media, sctp) {\n let output = [];\n if (media.protocol !== 'DTLS/SCTP') {\n output = [\n 'm=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.protocol + '\\r\\n',\n 'c=IN IP4 0.0.0.0\\r\\n',\n 'a=sctp-port:' + sctp.port + '\\r\\n',\n ];\n } else {\n output = [\n 'm=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.port + '\\r\\n',\n 'c=IN IP4 0.0.0.0\\r\\n',\n 'a=sctpmap:' + sctp.port + ' ' + sctp.protocol + ' 65535\\r\\n',\n ];\n }\n if (sctp.maxMessageSize !== undefined) {\n output.push('a=max-message-size:' + sctp.maxMessageSize + '\\r\\n');\n }\n return output.join('');\n};\n\n// Generate a session ID for SDP.\n// https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1\n// recommends using a cryptographically random +ve 64-bit value\n// but right now this should be acceptable and within the right range\nSDPUtils.generateSessionId = function() {\n return Math.random().toString().substr(2, 22);\n};\n\n// Write boiler plate for start of SDP\n// sessId argument is optional - if not supplied it will\n// be generated randomly\n// sessVersion is optional and defaults to 2\n// sessUser is optional and defaults to 'thisisadapterortc'\nSDPUtils.writeSessionBoilerplate = function(sessId, sessVer, sessUser) {\n let sessionId;\n const version = sessVer !== undefined ? sessVer : 2;\n if (sessId) {\n sessionId = sessId;\n } else {\n sessionId = SDPUtils.generateSessionId();\n }\n const user = sessUser || 'thisisadapterortc';\n // FIXME: sess-id should be an NTP timestamp.\n return 'v=0\\r\\n' +\n 'o=' + user + ' ' + sessionId + ' ' + version +\n ' IN IP4 127.0.0.1\\r\\n' +\n 's=-\\r\\n' +\n 't=0 0\\r\\n';\n};\n\n// Gets the direction from the mediaSection or the sessionpart.\nSDPUtils.getDirection = function(mediaSection, sessionpart) {\n // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.\n const lines = SDPUtils.splitLines(mediaSection);\n for (let i = 0; i < lines.length; i++) {\n switch (lines[i]) {\n case 'a=sendrecv':\n case 'a=sendonly':\n case 'a=recvonly':\n case 'a=inactive':\n return lines[i].substring(2);\n default:\n // FIXME: What should happen here?\n }\n }\n if (sessionpart) {\n return SDPUtils.getDirection(sessionpart);\n }\n return 'sendrecv';\n};\n\nSDPUtils.getKind = function(mediaSection) {\n const lines = SDPUtils.splitLines(mediaSection);\n const mline = lines[0].split(' ');\n return mline[0].substring(2);\n};\n\nSDPUtils.isRejected = function(mediaSection) {\n return mediaSection.split(' ', 2)[1] === '0';\n};\n\nSDPUtils.parseMLine = function(mediaSection) {\n const lines = SDPUtils.splitLines(mediaSection);\n const parts = lines[0].substring(2).split(' ');\n return {\n kind: parts[0],\n port: parseInt(parts[1], 10),\n protocol: parts[2],\n fmt: parts.slice(3).join(' '),\n };\n};\n\nSDPUtils.parseOLine = function(mediaSection) {\n const line = SDPUtils.matchPrefix(mediaSection, 'o=')[0];\n const parts = line.substring(2).split(' ');\n return {\n username: parts[0],\n sessionId: parts[1],\n sessionVersion: parseInt(parts[2], 10),\n netType: parts[3],\n addressType: parts[4],\n address: parts[5],\n };\n};\n\n// a very naive interpretation of a valid SDP.\nSDPUtils.isValidSDP = function(blob) {\n if (typeof blob !== 'string' || blob.length === 0) {\n return false;\n }\n const lines = SDPUtils.splitLines(blob);\n for (let i = 0; i < lines.length; i++) {\n if (lines[i].length < 2 || lines[i].charAt(1) !== '=') {\n return false;\n }\n // TODO: check the modifier a bit more.\n }\n return true;\n};\n\n// Expose public methods.\nif (typeof module === 'object') {\n module.exports = SDPUtils;\n}\n", "import { Peer, DataConnection, MediaConnection } from 'peerjs';\nimport type {\n Request,\n Response,\n SimpleHandler,\n CallOptions,\n CallSession,\n CallState,\n CallStateListener,\n IncomingCallEvent,\n IncomingCallListener\n} from './types';\n\n// \u7248\u672C\u53F7\uFF08\u6784\u5EFA\u65F6\u6CE8\u5165\uFF09\ndeclare const __VERSION__: string;\nexport const VERSION = __VERSION__;\n\n// \u6253\u5370\u7248\u672C\u53F7\u5230\u63A7\u5236\u53F0\nconsole.log(`[sx-peerjs-http-util] v${VERSION}`);\n\n// \u5185\u90E8\u6D88\u606F\u683C\u5F0F\ninterface InternalMessage {\n type: 'request' | 'response';\n id: string;\n request?: Request;\n response?: Response;\n}\n\n/**\n * \u670D\u52A1\u5668\u914D\u7F6E\uFF08PeerJS \u4FE1\u4EE4\u670D\u52A1\u5668\uFF09\n */\nexport interface ServerConfig {\n host?: string;\n port?: number;\n path?: string;\n secure?: boolean;\n}\n\n/**\n * \u751F\u6210 UUID v4\n */\nfunction generateUUID(): string {\n return crypto.randomUUID();\n}\n\n/**\n * CallSessionImpl - \u901A\u8BDD\u4F1A\u8BDD\u7684\u5185\u90E8\u5B9E\u73B0\n */\nclass CallSessionImpl implements CallSession {\n readonly peerId: string;\n readonly hasVideo: boolean;\n\n private mediaConnection: MediaConnection;\n private localStream: MediaStream | null = null;\n private remoteStream: MediaStream | null = null;\n private stateListeners = new Set<CallStateListener>();\n private debugLogFn: (obj: string, event: string, data?: unknown) => void;\n private onCleanup: (session: CallSessionImpl) => void;\n\n private _state: CallState = 'connecting';\n private isMuted = false;\n private isVideoEnabled = true;\n\n constructor(\n peerId: string,\n mediaConnection: MediaConnection,\n hasVideo: boolean,\n debugLog: (obj: string, event: string, data?: unknown) => void,\n onCleanup: (session: CallSessionImpl) => void\n ) {\n this.peerId = peerId;\n this.mediaConnection = mediaConnection;\n this.hasVideo = hasVideo;\n this.debugLogFn = debugLog;\n this.onCleanup = onCleanup;\n }\n\n get isConnected(): boolean {\n return this._state === 'connected';\n }\n\n get state(): CallState {\n return this._state;\n }\n\n setState(state: CallState, reason?: string): void {\n this._state = state;\n this.notifyStateChange(state, reason);\n }\n\n setLocalStream(stream: MediaStream): void {\n this.localStream = stream;\n }\n\n setRemoteStream(stream: MediaStream): void {\n this.remoteStream = stream;\n }\n\n getLocalStream(): MediaStream | null {\n return this.localStream;\n }\n\n getRemoteStream(): MediaStream | null {\n return this.remoteStream;\n }\n\n toggleMute(): boolean {\n if (!this.localStream) return this.isMuted;\n\n const audioTracks = this.localStream.getAudioTracks();\n for (const track of audioTracks) {\n track.enabled = this.isMuted; // \u5207\u6362\u72B6\u6001\n }\n this.isMuted = !this.isMuted;\n this.debugLogFn('CallSession', 'toggleMute', this.isMuted);\n return this.isMuted;\n }\n\n toggleVideo(): boolean {\n if (!this.hasVideo || !this.localStream) return this.isVideoEnabled;\n\n const videoTracks = this.localStream.getVideoTracks();\n for (const track of videoTracks) {\n track.enabled = !this.isVideoEnabled; // \u5207\u6362\u72B6\u6001\n }\n this.isVideoEnabled = !this.isVideoEnabled;\n this.debugLogFn('CallSession', 'toggleVideo', this.isVideoEnabled);\n return this.isVideoEnabled;\n }\n\n hangUp(): void {\n this.debugLogFn('CallSession', 'hangUp', this.peerId);\n this.mediaConnection.close();\n }\n\n close(): void {\n // \u505C\u6B62\u672C\u5730\u6D41\n if (this.localStream) {\n this.localStream.getTracks().forEach(track => track.stop());\n this.localStream = null;\n }\n this.remoteStream = null;\n this._state = 'ended';\n }\n\n onStateChange(listener: CallStateListener): void {\n this.stateListeners.add(listener);\n }\n\n offStateChange(listener: CallStateListener): void {\n this.stateListeners.delete(listener);\n }\n\n private notifyStateChange(state: CallState, reason?: string): void {\n this.debugLogFn('CallSession', 'stateChange', { peer: this.peerId, state, reason });\n this.stateListeners.forEach(listener => {\n try {\n listener(state, reason);\n } catch (err) {\n this.debugLogFn('CallSession', 'listenerError', err);\n }\n });\n\n // \u901A\u8BDD\u7ED3\u675F\u65F6\u6E05\u7406\n if (state === 'ended') {\n this.onCleanup(this);\n }\n }\n}\n\n/**\n * PeerJsWrapper - \u5C01\u88C5 PeerJS \u4E3A\u7C7B\u4F3C HTTP \u7684 API\n *\n * @example\n * ```js\n * const wrapper = new PeerJsWrapper();\n * const data = await wrapper.send(peerId, '/api/hello', { name: 'world' });\n * console.log(data); // \u76F4\u63A5\u8F93\u51FA\u54CD\u5E94\u6570\u636E\n *\n * // \u670D\u52A1\u7AEF\u6CE8\u518C\u5904\u7406\u5668\n * wrapper.registerHandler('/api/hello', (data) => {\n * return { message: 'hello' }; // \u76F4\u63A5\u8FD4\u56DE\u6570\u636E\n * });\n * ```\n */\nexport class PeerJsWrapper {\n /**\n * \u672C\u5730 Peer ID\uFF0C\u6784\u9020\u65F6\u786E\u5B9A\uFF08\u4F20\u5165\u6216\u81EA\u52A8\u751F\u6210\uFF09\n */\n private myPeerId: string;\n\n /**\n * PeerJS \u5B9E\u4F8B\n */\n private peerInstance: Peer | null = null;\n\n /**\n * \u5F53\u524D\u6D3B\u8DC3\u7684\u4F20\u5165\u8FDE\u63A5\u96C6\u5408\n */\n private connections = new Set<DataConnection>();\n\n /**\n * \u5F85\u5904\u7406\u7684\u8BF7\u6C42\u6620\u5C04\u8868\uFF08\u7528\u4E8E\u8BF7\u6C42-\u54CD\u5E94\u5339\u914D\uFF09\n */\n private pendingRequests = new Map<\n string,\n {\n resolve: (data: unknown) => void;\n reject: (error: Error) => void;\n timeout: ReturnType<typeof setTimeout>;\n }\n >();\n\n /**\n * \u8DEF\u5F84\u5904\u7406\u5668\u6620\u5C04\u8868\n */\n private simpleHandlers = new Map<string, SimpleHandler>();\n\n /**\n * \u91CD\u8FDE\u5B9A\u65F6\u5668\n */\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * \u662F\u5426\u5DF2\u9500\u6BC1\n */\n private isDestroyed = false;\n\n /**\n * \u662F\u5426\u5F00\u542F\u8C03\u8BD5\u6A21\u5F0F\n */\n private isDebug: boolean;\n\n /**\n * \u670D\u52A1\u5668\u914D\u7F6E\n */\n private serverConfig?: ServerConfig;\n\n /**\n * \u5F53\u524D\u6D3B\u8DC3\u7684\u901A\u8BDD\n */\n private activeCall: CallSessionImpl | null = null;\n\n /**\n * \u6765\u7535\u76D1\u542C\u5668\u96C6\u5408\n */\n private incomingCallListeners = new Set<IncomingCallListener>();\n\n /**\n * \u521B\u5EFA PeerJsWrapper \u5B9E\u4F8B\n * @param peerId \u53EF\u9009\u7684 Peer ID\uFF0C\u5982\u679C\u4E0D\u63D0\u4F9B\u5219\u81EA\u52A8\u751F\u6210 UUID\n * @param isDebug \u662F\u5426\u5F00\u542F\u8C03\u8BD5\u6A21\u5F0F\uFF0C\u5F00\u542F\u540E\u4F1A\u6253\u5370\u4E8B\u4EF6\u65E5\u5FD7\n * @param server \u53EF\u9009\u7684\u4FE1\u4EE4\u670D\u52A1\u5668\u914D\u7F6E\uFF0C\u4E0D\u63D0\u4F9B\u5219\u4F7F\u7528 PeerJS \u516C\u5171\u670D\u52A1\u5668\n */\n constructor(peerId?: string, isDebug?: boolean, server?: ServerConfig) {\n this.myPeerId = peerId || generateUUID();\n this.isDebug = isDebug ?? false;\n this.serverConfig = server;\n this.connect();\n }\n\n /**\n * \u8C03\u8BD5\u65E5\u5FD7\u8F93\u51FA\n * @param obj \u5BF9\u8C61\u540D\n * @param event \u4E8B\u4EF6\u540D\n * @param data \u4E8B\u4EF6\u6570\u636E\n */\n private debugLog(obj: string, event: string, data?: unknown): void {\n if (this.isDebug) {\n const dataStr = data !== undefined ? (typeof data === 'object' ? JSON.stringify(data) : String(data)) : '';\n console.log(`${obj} ${event} ${dataStr}`);\n }\n }\n\n /**\n * \u8FDE\u63A5\u5230 PeerJS \u670D\u52A1\u5668\n */\n private connect(): void {\n if (this.isDestroyed) return;\n\n this.peerInstance = this.serverConfig\n ? new Peer(this.myPeerId, { ...this.serverConfig })\n : new Peer(this.myPeerId);\n\n this.setupPeerEventHandlers();\n }\n\n /**\n * \u8BBE\u7F6E Peer \u5B9E\u4F8B\u7684\u4E8B\u4EF6\u5904\u7406\u5668\n */\n private setupPeerEventHandlers(): void {\n if (!this.peerInstance) return;\n\n this.peerInstance.on('open', (id) => {\n this.debugLog('Peer', 'open', id);\n // \u6E05\u9664\u91CD\u8FDE\u5B9A\u65F6\u5668\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n });\n\n this.peerInstance.on('disconnected', () => {\n this.debugLog('Peer', 'disconnected');\n this.scheduleReconnect();\n });\n\n this.peerInstance.on('error', (err) => {\n this.debugLog('Peer', 'error', { type: err.type, message: err.message });\n // \u7F51\u7EDC\u76F8\u5173\u9519\u8BEF\u65F6\u5C1D\u8BD5\u91CD\u8FDE\n if (\n err.type === 'network' ||\n err.type === 'server-error' ||\n err.type === 'socket-error' ||\n err.type === 'socket-closed'\n ) {\n this.scheduleReconnect();\n }\n });\n\n this.peerInstance.on('close', () => {\n this.debugLog('Peer', 'close');\n });\n\n // \u5904\u7406\u6765\u7535\n this.peerInstance.on('call', (mediaConnection: MediaConnection) => {\n this.handleIncomingCall(mediaConnection);\n });\n\n // \u8BBE\u7F6E\u4F20\u5165\u8FDE\u63A5\u5904\u7406\u5668\n this.setupIncomingConnectionHandler();\n }\n\n /**\n * \u5B89\u6392\u91CD\u8FDE\n */\n private scheduleReconnect(): void {\n if (this.isDestroyed) return;\n if (this.reconnectTimer) return; // \u5DF2\u6709\u91CD\u8FDE\u4EFB\u52A1\u5728\u7B49\u5F85\n\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n this.reconnect();\n }, 1000);\n }\n\n /**\n * \u6267\u884C\u91CD\u8FDE\n */\n private reconnect(): void {\n if (this.isDestroyed) return;\n\n this.debugLog('PeerJsWrapper', 'reconnect');\n\n // \u9500\u6BC1\u65E7\u5B9E\u4F8B\n if (this.peerInstance) {\n try {\n this.peerInstance.destroy();\n } catch {\n // \u5FFD\u7565\u9500\u6BC1\u65F6\u7684\u9519\u8BEF\n }\n this.peerInstance = null;\n }\n\n // \u91CD\u65B0\u8FDE\u63A5\n this.connect();\n }\n\n /**\n * \u83B7\u53D6\u5F53\u524D Peer ID\n * @returns string \u5F53\u524D Peer ID\n */\n getPeerId(): string {\n return this.myPeerId;\n }\n\n /**\n * \u7B49\u5F85 Peer \u8FDE\u63A5\u5C31\u7EEA\uFF08\u8FDE\u63A5\u5230\u4FE1\u4EE4\u670D\u52A1\u5668\uFF09\n * @returns Promise<void> \u5F53\u8FDE\u63A5\u6210\u529F\u65F6 resolve\n */\n whenReady(): Promise<void> {\n return this.waitForReady();\n }\n\n /**\n * \u7B49\u5F85 Peer \u8FDE\u63A5\u5C31\u7EEA\n */\n private waitForReady(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!this.peerInstance) {\n reject(new Error('Peer instance not initialized'));\n return;\n }\n\n if (this.peerInstance.open) {\n resolve();\n return;\n }\n\n const onOpen = () => {\n this.peerInstance?.off('open', onOpen);\n this.peerInstance?.off('error', onError);\n resolve();\n };\n\n const onError = (err: Error) => {\n this.peerInstance?.off('open', onOpen);\n this.peerInstance?.off('error', onError);\n reject(err);\n };\n\n this.peerInstance.on('open', onOpen);\n this.peerInstance.on('error', onError);\n });\n }\n\n /**\n * \u53D1\u9001\u8BF7\u6C42\u5230\u6307\u5B9A Peer\n * @param peerId \u5BF9\u7AEF\u8BBE\u5907 ID\n * @param path \u8BF7\u6C42\u8DEF\u5F84\n * @param data \u8BF7\u6C42\u6570\u636E\n * @returns Promise<unknown> \u8FD4\u56DE\u54CD\u5E94\u6570\u636E\uFF08\u81EA\u52A8\u62C6\u7BB1\uFF0C\u53EA\u8FD4\u56DE data \u90E8\u5206\uFF09\n */\n send(peerId: string, path: string, data?: unknown): Promise<unknown> {\n return new Promise((resolve, reject) => {\n this.debugLog('PeerJsWrapper', 'send', { peerId, path, data });\n\n // \u7B49\u5F85 peer \u5B9E\u4F8B\u51C6\u5907\u597D\n this.waitForReady()\n .then(() => {\n if (!this.peerInstance) {\n reject(new Error('Peer instance not available'));\n return;\n }\n\n // \u6BCF\u6B21\u53D1\u9001\u6D88\u606F\u65F6\uFF0C\u90FD\u8FDE\u63A5\u4E00\u4E2A\u65B0\u7684 conn\n const conn = this.peerInstance.connect(peerId, {\n reliable: true,\n });\n\n const timeout = setTimeout(() => {\n conn.close();\n this.pendingRequests.delete(requestId);\n reject(new Error(`Request timeout: ${peerId}${path}`));\n }, 30000);\n\n const requestId = `${this.myPeerId}-${Date.now()}-${Math.random()}`;\n this.pendingRequests.set(requestId, { resolve, reject, timeout });\n\n conn.on('open', () => {\n this.debugLog('Conn', 'open', peerId);\n const request: Request = { path, data };\n const message: InternalMessage = {\n type: 'request',\n id: requestId,\n request,\n };\n conn.send(message);\n });\n\n conn.on('data', (responseData: unknown) => {\n this.debugLog('Conn', 'data', { peer: peerId, data: responseData });\n const message = responseData as InternalMessage;\n if (message.type === 'response' && message.id === requestId) {\n const pending = this.pendingRequests.get(requestId);\n if (pending) {\n clearTimeout(pending.timeout);\n this.pendingRequests.delete(requestId);\n\n const response = message.response!;\n // \u6821\u9A8C\u72B6\u6001\u7801\uFF0C\u975E 2xx \u5219 reject\n if (response.status < 200 || response.status >= 300) {\n pending.reject(\n new Error(`Request failed: ${response.status} ${JSON.stringify(response.data)}`)\n );\n } else {\n // \u81EA\u52A8\u62C6\u7BB1\uFF1A\u53EA\u8FD4\u56DE data \u90E8\u5206\n pending.resolve(response.data);\n }\n }\n conn.close();\n }\n });\n\n conn.on('error', (err) => {\n this.debugLog('Conn', 'error', { peer: peerId, error: err });\n const pending = this.pendingRequests.get(requestId);\n if (pending) {\n clearTimeout(pending.timeout);\n this.pendingRequests.delete(requestId);\n pending.reject(err as Error);\n }\n });\n\n conn.on('close', () => {\n this.debugLog('Conn', 'close', peerId);\n const pending = this.pendingRequests.get(requestId);\n if (pending) {\n clearTimeout(pending.timeout);\n this.pendingRequests.delete(requestId);\n pending.reject(new Error('Connection closed'));\n }\n });\n })\n .catch((err) => {\n reject(err);\n });\n });\n }\n\n /**\n * \u8BBE\u7F6E\u4F20\u5165\u8FDE\u63A5\u5904\u7406\u5668\n */\n private setupIncomingConnectionHandler(): void {\n if (!this.peerInstance) return;\n\n this.peerInstance.on('connection', (conn: DataConnection) => {\n this.debugLog('Peer', 'connection', conn.peer);\n this.connections.add(conn);\n\n conn.on('open', () => {\n this.debugLog('Conn', 'open', conn.peer);\n });\n\n conn.on('data', async (data: unknown) => {\n this.debugLog('Conn', 'data', { peer: conn.peer, data });\n const message = data as InternalMessage;\n\n if (message.type === 'request' && message.request) {\n try {\n const response = await this.handleRequest(conn.peer, message.request);\n\n const responseMessage: InternalMessage = {\n type: 'response',\n id: message.id,\n response,\n };\n\n conn.send(responseMessage);\n } catch (error) {\n const errorResponse: InternalMessage = {\n type: 'response',\n id: message.id,\n response: {\n status: 500,\n data: { error: error instanceof Error ? error.message : 'Unknown error' },\n },\n };\n\n conn.send(errorResponse);\n }\n }\n });\n\n conn.on('close', () => {\n this.debugLog('Conn', 'close', conn.peer);\n this.connections.delete(conn);\n });\n\n conn.on('error', (err) => {\n this.debugLog('Conn', 'error', { peer: conn.peer, error: err });\n this.connections.delete(conn);\n });\n });\n }\n\n // ============== \u8BED\u97F3/\u89C6\u9891\u901A\u8BDD\u76F8\u5173\u65B9\u6CD5 ==============\n\n /**\n * \u53D1\u8D77\u8BED\u97F3/\u89C6\u9891\u901A\u8BDD\n * @param peerId \u5BF9\u7AEF\u8BBE\u5907 ID\n * @param options \u901A\u8BDD\u9009\u9879\n * @returns Promise<CallSession> \u901A\u8BDD\u4F1A\u8BDD\u5BF9\u8C61\n */\n call(peerId: string, options?: CallOptions): Promise<CallSession> {\n return new Promise((resolve, reject) => {\n this.debugLog('PeerJsWrapper', 'call', { peerId, options });\n\n // \u68C0\u67E5\u662F\u5426\u5DF2\u6709\u6D3B\u8DC3\u901A\u8BDD\n if (this.activeCall) {\n reject(new Error('Already in a call'));\n return;\n }\n\n // \u7B49\u5F85 peer \u5B9E\u4F8B\u51C6\u5907\u597D\n this.waitForReady()\n .then(async () => {\n if (!this.peerInstance) {\n reject(new Error('Peer instance not available'));\n return;\n }\n\n const hasVideo = options?.video ?? false;\n\n // \u83B7\u53D6\u672C\u5730\u5A92\u4F53\u6D41\n let localStream: MediaStream;\n try {\n localStream = await navigator.mediaDevices.getUserMedia({\n audio: true,\n video: hasVideo\n });\n } catch (err) {\n reject(new Error(`Failed to get media: ${err instanceof Error ? err.message : err}`));\n return;\n }\n\n // \u521B\u5EFA MediaConnection\n const mediaConnection = this.peerInstance.call(peerId, localStream, {\n metadata: {\n video: hasVideo,\n custom: options?.metadata\n }\n });\n\n // \u521B\u5EFA\u901A\u8BDD\u4F1A\u8BDD\n const session = new CallSessionImpl(\n peerId,\n mediaConnection,\n hasVideo,\n this.debugLog.bind(this),\n this.cleanupCall.bind(this)\n );\n session.setLocalStream(localStream);\n\n // \u8BBE\u7F6E MediaConnection \u4E8B\u4EF6\u5904\u7406\n this.setupMediaConnectionHandlers(session, mediaConnection);\n\n // \u4FDD\u5B58\u4E3A\u6D3B\u8DC3\u901A\u8BDD\n this.activeCall = session;\n\n // \u8BBE\u7F6E\u8D85\u65F6\uFF0830\u79D2\u65E0\u5E94\u7B54\uFF09\n const timeout = setTimeout(() => {\n if (!session.isConnected) {\n session.hangUp();\n reject(new Error('Call timeout - no answer'));\n }\n }, 30000);\n\n // \u76D1\u542C\u8FDE\u63A5\u72B6\u6001\n const onConnected = () => {\n clearTimeout(timeout);\n session.offStateChange(onConnected);\n session.offStateChange(onEnded);\n resolve(session);\n };\n\n const onEnded = (state: CallState, reason?: string) => {\n clearTimeout(timeout);\n session.offStateChange(onConnected);\n session.offStateChange(onEnded);\n if (state === 'ended') {\n reject(new Error(reason || 'Call ended before connected'));\n }\n };\n\n session.onStateChange(onConnected);\n session.onStateChange(onEnded);\n })\n .catch(reject);\n });\n }\n\n /**\n * \u6CE8\u518C\u6765\u7535\u76D1\u542C\u5668\n * @param listener \u6765\u7535\u56DE\u8C03\u51FD\u6570\n */\n onIncomingCall(listener: IncomingCallListener): void {\n this.incomingCallListeners.add(listener);\n }\n\n /**\n * \u79FB\u9664\u6765\u7535\u76D1\u542C\u5668\n * @param listener \u6765\u7535\u56DE\u8C03\u51FD\u6570\n */\n offIncomingCall(listener: IncomingCallListener): void {\n this.incomingCallListeners.delete(listener);\n }\n\n /**\n * \u83B7\u53D6\u5F53\u524D\u6D3B\u8DC3\u7684\u901A\u8BDD\n * @returns CallSession | null \u5F53\u524D\u901A\u8BDD\u4F1A\u8BDD\uFF0C\u65E0\u901A\u8BDD\u65F6\u8FD4\u56DE null\n */\n getActiveCall(): CallSession | null {\n return this.activeCall;\n }\n\n /**\n * \u8BBE\u7F6E MediaConnection \u4E8B\u4EF6\u5904\u7406\u5668\n */\n private setupMediaConnectionHandlers(\n session: CallSessionImpl,\n mediaConnection: MediaConnection\n ): void {\n mediaConnection.on('stream', (remoteStream: MediaStream) => {\n this.debugLog('MediaConnection', 'stream', { peer: mediaConnection.peer });\n session.setRemoteStream(remoteStream);\n session.setState('connected');\n });\n\n mediaConnection.on('close', () => {\n this.debugLog('MediaConnection', 'close', mediaConnection.peer);\n session.close();\n session.setState('ended', 'Connection closed');\n });\n\n mediaConnection.on('error', (err) => {\n this.debugLog('MediaConnection', 'error', { peer: mediaConnection.peer, error: err });\n session.close();\n session.setState('ended', err.message || 'Media error');\n });\n }\n\n /**\n * \u6E05\u7406\u901A\u8BDD\u8D44\u6E90\n */\n private cleanupCall(session: CallSessionImpl): void {\n if (this.activeCall === session) {\n this.activeCall = null;\n }\n }\n\n /**\n * \u5904\u7406\u6765\u7535\n */\n private handleIncomingCall(mediaConnection: MediaConnection): void {\n this.debugLog('Peer', 'call', { from: mediaConnection.peer, metadata: mediaConnection.metadata });\n\n const metadata = mediaConnection.metadata as { video?: boolean; custom?: unknown } | undefined;\n const hasVideo = metadata?.video ?? false;\n\n // \u521B\u5EFA\u6765\u7535\u4E8B\u4EF6\u5BF9\u8C61\n const event: IncomingCallEvent = {\n from: mediaConnection.peer,\n hasVideo,\n metadata: metadata?.custom,\n\n answer: async () => {\n // \u68C0\u67E5\u662F\u5426\u5DF2\u6709\u6D3B\u8DC3\u901A\u8BDD\n if (this.activeCall) {\n mediaConnection.close();\n throw new Error('Already in a call');\n }\n\n // \u83B7\u53D6\u672C\u5730\u5A92\u4F53\u6D41\n let localStream: MediaStream;\n try {\n localStream = await navigator.mediaDevices.getUserMedia({\n audio: true,\n video: hasVideo\n });\n } catch (err) {\n mediaConnection.close();\n throw new Error(`Failed to get media: ${err instanceof Error ? err.message : err}`);\n }\n\n // \u521B\u5EFA\u901A\u8BDD\u4F1A\u8BDD\uFF08\u5148\u521B\u5EFA\uFF0C\u518D\u8BBE\u7F6E\u4E8B\u4EF6\u5904\u7406\u5668\uFF09\n const session = new CallSessionImpl(\n mediaConnection.peer,\n mediaConnection,\n hasVideo,\n this.debugLog.bind(this),\n this.cleanupCall.bind(this)\n );\n session.setLocalStream(localStream);\n\n // \u8BBE\u7F6E\u4E8B\u4EF6\u5904\u7406\uFF08\u5FC5\u987B\u5728 answer \u4E4B\u524D\u8BBE\u7F6E\uFF0C\u5426\u5219\u53EF\u80FD\u4E22\u5931 stream \u4E8B\u4EF6\uFF09\n this.setupMediaConnectionHandlers(session, mediaConnection);\n\n // \u4FDD\u5B58\u4E3A\u6D3B\u8DC3\u901A\u8BDD\n this.activeCall = session;\n\n // \u63A5\u542C\uFF08\u653E\u5728\u6700\u540E\uFF0C\u56E0\u4E3A answer \u540E\u53EF\u80FD\u7ACB\u5373\u89E6\u53D1 stream \u4E8B\u4EF6\uFF09\n mediaConnection.answer(localStream);\n\n return session;\n },\n\n reject: () => {\n mediaConnection.close();\n this.debugLog('Call', 'rejected', mediaConnection.peer);\n }\n };\n\n // \u901A\u77E5\u6240\u6709\u76D1\u542C\u5668\n this.incomingCallListeners.forEach(listener => {\n try {\n listener(event);\n } catch (err) {\n this.debugLog('IncomingCallListener', 'error', err);\n }\n });\n }\n\n /**\n * \u6CE8\u518C\u7B80\u5316\u5904\u7406\u5668\uFF08\u76F4\u63A5\u8FD4\u56DE\u6570\u636E\uFF0C\u81EA\u52A8\u88C5\u7BB1\uFF09\n * @param path \u8BF7\u6C42\u8DEF\u5F84\n * @param handler \u5904\u7406\u5668\u51FD\u6570\uFF0C\u63A5\u6536\u8BF7\u6C42\u6570\u636E\uFF0C\u76F4\u63A5\u8FD4\u56DE\u54CD\u5E94\u6570\u636E\n */\n registerHandler(path: string, handler: SimpleHandler): void {\n this.simpleHandlers.set(path, handler);\n }\n\n /**\n * \u6CE8\u9500\u7B80\u5316\u5904\u7406\u5668\n * @param path \u8BF7\u6C42\u8DEF\u5F84\n */\n unregisterHandler(path: string): void {\n this.simpleHandlers.delete(path);\n }\n\n /**\n * \u5185\u90E8\u8BF7\u6C42\u5904\u7406\u65B9\u6CD5\n * @param from \u53D1\u9001\u8005\u7684 Peer ID\n * @param request \u8BF7\u6C42\u6570\u636E\n */\n private async handleRequest(from: string, request: Request): Promise<Response> {\n const simpleHandler = this.simpleHandlers.get(request.path);\n if (simpleHandler) {\n const data = await simpleHandler(from, request.data);\n // \u81EA\u52A8\u88C5\u7BB1\uFF1A\u5C06\u8FD4\u56DE\u7684\u6570\u636E\u5305\u88C5\u6210 Response\n return { status: 200, data };\n }\n\n // \u6CA1\u6709\u627E\u5230\u5339\u914D\u7684\u5904\u7406\u5668\n return {\n status: 404,\n data: { error: `Path not found: ${request.path}` },\n };\n }\n\n /**\n * \u5173\u95ED\u6240\u6709\u8FDE\u63A5\u5E76\u9500\u6BC1 Peer \u5B9E\u4F8B\n */\n destroy(): void {\n this.isDestroyed = true;\n\n // \u6E05\u9664\u91CD\u8FDE\u5B9A\u65F6\u5668\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n // \u6302\u65AD\u6D3B\u8DC3\u901A\u8BDD\n if (this.activeCall) {\n this.activeCall.hangUp();\n this.activeCall = null;\n }\n\n // \u6E05\u9664\u6765\u7535\u76D1\u542C\u5668\n this.incomingCallListeners.clear();\n\n for (const conn of this.connections.values()) {\n conn.close();\n }\n this.connections.clear();\n\n for (const pending of this.pendingRequests.values()) {\n clearTimeout(pending.timeout);\n pending.reject(new Error('Peer destroyed'));\n }\n this.pendingRequests.clear();\n this.simpleHandlers.clear();\n\n if (this.peerInstance) {\n this.peerInstance.destroy();\n this.peerInstance = null;\n }\n }\n}\n\n// \u5BFC\u51FA\u7C7B\u578B\nexport type {\n Request,\n Response,\n SimpleHandler,\n CallOptions,\n CallSession,\n CallState,\n CallStateListener,\n IncomingCallEvent,\n IncomingCallListener\n};\n", "import { BufferBuilder } from \"./bufferbuilder\";\n\nexport type Packable =\n\t| null\n\t| undefined\n\t| string\n\t| number\n\t| boolean\n\t| Date\n\t| ArrayBuffer\n\t| Blob\n\t| Array<Packable>\n\t| { [key: string]: Packable }\n\t| ({ BYTES_PER_ELEMENT: number } & ArrayBufferView);\nexport type Unpackable =\n\t| null\n\t| undefined\n\t| string\n\t| number\n\t| boolean\n\t| ArrayBuffer\n\t| Array<Unpackable>\n\t| { [key: string]: Unpackable };\n\nexport function unpack<T extends Unpackable>(data: ArrayBuffer) {\n\tconst unpacker = new Unpacker(data);\n\treturn unpacker.unpack() as T;\n}\n\nexport function pack(data: Packable) {\n\tconst packer = new Packer();\n\tconst res = packer.pack(data);\n\tif (res instanceof Promise) {\n\t\treturn res.then(() => packer.getBuffer());\n\t}\n\treturn packer.getBuffer();\n}\n\nclass Unpacker {\n\tprivate index: number;\n\tprivate readonly dataBuffer: ArrayBuffer;\n\tprivate readonly dataView: Uint8Array;\n\tprivate readonly length: number;\n\n\tconstructor(data: ArrayBuffer) {\n\t\tthis.index = 0;\n\t\tthis.dataBuffer = data;\n\t\tthis.dataView = new Uint8Array(this.dataBuffer);\n\t\tthis.length = this.dataBuffer.byteLength;\n\t}\n\n\tunpack(): Unpackable {\n\t\tconst type = this.unpack_uint8();\n\t\tif (type < 0x80) {\n\t\t\treturn type;\n\t\t} else if ((type ^ 0xe0) < 0x20) {\n\t\t\treturn (type ^ 0xe0) - 0x20;\n\t\t}\n\n\t\tlet size;\n\t\tif ((size = type ^ 0xa0) <= 0x0f) {\n\t\t\treturn this.unpack_raw(size);\n\t\t} else if ((size = type ^ 0xb0) <= 0x0f) {\n\t\t\treturn this.unpack_string(size);\n\t\t} else if ((size = type ^ 0x90) <= 0x0f) {\n\t\t\treturn this.unpack_array(size);\n\t\t} else if ((size = type ^ 0x80) <= 0x0f) {\n\t\t\treturn this.unpack_map(size);\n\t\t}\n\n\t\tswitch (type) {\n\t\t\tcase 0xc0:\n\t\t\t\treturn null;\n\t\t\tcase 0xc1:\n\t\t\t\treturn undefined;\n\t\t\tcase 0xc2:\n\t\t\t\treturn false;\n\t\t\tcase 0xc3:\n\t\t\t\treturn true;\n\t\t\tcase 0xca:\n\t\t\t\treturn this.unpack_float();\n\t\t\tcase 0xcb:\n\t\t\t\treturn this.unpack_double();\n\t\t\tcase 0xcc:\n\t\t\t\treturn this.unpack_uint8();\n\t\t\tcase 0xcd:\n\t\t\t\treturn this.unpack_uint16();\n\t\t\tcase 0xce:\n\t\t\t\treturn this.unpack_uint32();\n\t\t\tcase 0xcf:\n\t\t\t\treturn this.unpack_uint64();\n\t\t\tcase 0xd0:\n\t\t\t\treturn this.unpack_int8();\n\t\t\tcase 0xd1:\n\t\t\t\treturn this.unpack_int16();\n\t\t\tcase 0xd2:\n\t\t\t\treturn this.unpack_int32();\n\t\t\tcase 0xd3:\n\t\t\t\treturn this.unpack_int64();\n\t\t\tcase 0xd4:\n\t\t\t\treturn undefined;\n\t\t\tcase 0xd5:\n\t\t\t\treturn undefined;\n\t\t\tcase 0xd6:\n\t\t\t\treturn undefined;\n\t\t\tcase 0xd7:\n\t\t\t\treturn undefined;\n\t\t\tcase 0xd8:\n\t\t\t\tsize = this.unpack_uint16();\n\t\t\t\treturn this.unpack_string(size);\n\t\t\tcase 0xd9:\n\t\t\t\tsize = this.unpack_uint32();\n\t\t\t\treturn this.unpack_string(size);\n\t\t\tcase 0xda:\n\t\t\t\tsize = this.unpack_uint16();\n\t\t\t\treturn this.unpack_raw(size);\n\t\t\tcase 0xdb:\n\t\t\t\tsize = this.unpack_uint32();\n\t\t\t\treturn this.unpack_raw(size);\n\t\t\tcase 0xdc:\n\t\t\t\tsize = this.unpack_uint16();\n\t\t\t\treturn this.unpack_array(size);\n\t\t\tcase 0xdd:\n\t\t\t\tsize = this.unpack_uint32();\n\t\t\t\treturn this.unpack_array(size);\n\t\t\tcase 0xde:\n\t\t\t\tsize = this.unpack_uint16();\n\t\t\t\treturn this.unpack_map(size);\n\t\t\tcase 0xdf:\n\t\t\t\tsize = this.unpack_uint32();\n\t\t\t\treturn this.unpack_map(size);\n\t\t}\n\t}\n\n\tunpack_uint8() {\n\t\tconst byte = this.dataView[this.index] & 0xff;\n\t\tthis.index++;\n\t\treturn byte;\n\t}\n\n\tunpack_uint16() {\n\t\tconst bytes = this.read(2);\n\t\tconst uint16 = (bytes[0] & 0xff) * 256 + (bytes[1] & 0xff);\n\t\tthis.index += 2;\n\t\treturn uint16;\n\t}\n\n\tunpack_uint32() {\n\t\tconst bytes = this.read(4);\n\t\tconst uint32 =\n\t\t\t((bytes[0] * 256 + bytes[1]) * 256 + bytes[2]) * 256 + bytes[3];\n\t\tthis.index += 4;\n\t\treturn uint32;\n\t}\n\n\tunpack_uint64() {\n\t\tconst bytes = this.read(8);\n\t\tconst uint64 =\n\t\t\t((((((bytes[0] * 256 + bytes[1]) * 256 + bytes[2]) * 256 + bytes[3]) *\n\t\t\t\t256 +\n\t\t\t\tbytes[4]) *\n\t\t\t\t256 +\n\t\t\t\tbytes[5]) *\n\t\t\t\t256 +\n\t\t\t\tbytes[6]) *\n\t\t\t\t256 +\n\t\t\tbytes[7];\n\t\tthis.index += 8;\n\t\treturn uint64;\n\t}\n\n\tunpack_int8() {\n\t\tconst uint8 = this.unpack_uint8();\n\t\treturn uint8 < 0x80 ? uint8 : uint8 - (1 << 8);\n\t}\n\n\tunpack_int16() {\n\t\tconst uint16 = this.unpack_uint16();\n\t\treturn uint16 < 0x8000 ? uint16 : uint16 - (1 << 16);\n\t}\n\n\tunpack_int32() {\n\t\tconst uint32 = this.unpack_uint32();\n\t\treturn uint32 < 2 ** 31 ? uint32 : uint32 - 2 ** 32;\n\t}\n\n\tunpack_int64() {\n\t\tconst uint64 = this.unpack_uint64();\n\t\treturn uint64 < 2 ** 63 ? uint64 : uint64 - 2 ** 64;\n\t}\n\n\tunpack_raw(size: number) {\n\t\tif (this.length < this.index + size) {\n\t\t\tthrow new Error(\n\t\t\t\t`BinaryPackFailure: index is out of range ${this.index} ${size} ${this.length}`,\n\t\t\t);\n\t\t}\n\t\tconst buf = this.dataBuffer.slice(this.index, this.index + size);\n\t\tthis.index += size;\n\n\t\treturn buf;\n\t}\n\n\tunpack_string(size: number) {\n\t\tconst bytes = this.read(size);\n\t\tlet i = 0;\n\t\tlet str = \"\";\n\t\tlet c;\n\t\tlet code;\n\n\t\twhile (i < size) {\n\t\t\tc = bytes[i];\n\t\t\t// The length of a UTF-8 sequence is specified in the first byte:\n\t\t\t// 0xxxxxxx means length 1,\n\t\t\t// 110xxxxx means length 2,\n\t\t\t// 1110xxxx means length 3,\n\t\t\t// 11110xxx means length 4.\n\t\t\t// 10xxxxxx is for non-initial bytes.\n\t\t\tif (c < 0xa0) {\n\t\t\t\t// One-byte sequence: bits 0xxxxxxx\n\t\t\t\tcode = c;\n\t\t\t\ti++;\n\t\t\t} else if ((c ^ 0xc0) < 0x20) {\n\t\t\t\t// Two-byte sequence: bits 110xxxxx 10xxxxxx\n\t\t\t\tcode = ((c & 0x1f) << 6) | (bytes[i + 1] & 0x3f);\n\t\t\t\ti += 2;\n\t\t\t} else if ((c ^ 0xe0) < 0x10) {\n\t\t\t\t// Three-byte sequence: bits 1110xxxx 10xxxxxx 10xxxxxx\n\t\t\t\tcode =\n\t\t\t\t\t((c & 0x0f) << 12) |\n\t\t\t\t\t((bytes[i + 1] & 0x3f) << 6) |\n\t\t\t\t\t(bytes[i + 2] & 0x3f);\n\t\t\t\ti += 3;\n\t\t\t} else {\n\t\t\t\t// Four-byte sequence: bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n\t\t\t\tcode =\n\t\t\t\t\t((c & 0x07) << 18) |\n\t\t\t\t\t((bytes[i + 1] & 0x3f) << 12) |\n\t\t\t\t\t((bytes[i + 2] & 0x3f) << 6) |\n\t\t\t\t\t(bytes[i + 3] & 0x3f);\n\t\t\t\ti += 4;\n\t\t\t}\n\t\t\tstr += String.fromCodePoint(code);\n\t\t}\n\n\t\tthis.index += size;\n\t\treturn str;\n\t}\n\n\tunpack_array(size: number) {\n\t\tconst objects = new Array<Unpackable>(size);\n\t\tfor (let i = 0; i < size; i++) {\n\t\t\tobjects[i] = this.unpack();\n\t\t}\n\t\treturn objects;\n\t}\n\n\tunpack_map(size: number) {\n\t\tconst map: { [key: string]: Unpackable } = {};\n\t\tfor (let i = 0; i < size; i++) {\n\t\t\tconst key = this.unpack() as string;\n\t\t\tmap[key] = this.unpack();\n\t\t}\n\t\treturn map;\n\t}\n\n\tunpack_float() {\n\t\tconst uint32 = this.unpack_uint32();\n\t\tconst sign = uint32 >> 31;\n\t\tconst exp = ((uint32 >> 23) & 0xff) - 127;\n\t\tconst fraction = (uint32 & 0x7fffff) | 0x800000;\n\t\treturn (sign === 0 ? 1 : -1) * fraction * 2 ** (exp - 23);\n\t}\n\n\tunpack_double() {\n\t\tconst h32 = this.unpack_uint32();\n\t\tconst l32 = this.unpack_uint32();\n\t\tconst sign = h32 >> 31;\n\t\tconst exp = ((h32 >> 20) & 0x7ff) - 1023;\n\t\tconst hfrac = (h32 & 0xfffff) | 0x100000;\n\t\tconst frac = hfrac * 2 ** (exp - 20) + l32 * 2 ** (exp - 52);\n\t\treturn (sign === 0 ? 1 : -1) * frac;\n\t}\n\n\tread(length: number) {\n\t\tconst j = this.index;\n\t\tif (j + length <= this.length) {\n\t\t\treturn this.dataView.subarray(j, j + length);\n\t\t} else {\n\t\t\tthrow new Error(\"BinaryPackFailure: read index out of range\");\n\t\t}\n\t}\n}\n\nexport class Packer {\n\tprivate _bufferBuilder = new BufferBuilder();\n\tprivate _textEncoder = new TextEncoder();\n\n\tgetBuffer() {\n\t\treturn this._bufferBuilder.toArrayBuffer();\n\t}\n\n\tpack(value: Packable) {\n\t\tif (typeof value === \"string\") {\n\t\t\tthis.pack_string(value);\n\t\t} else if (typeof value === \"number\") {\n\t\t\tif (Math.floor(value) === value) {\n\t\t\t\tthis.pack_integer(value);\n\t\t\t} else {\n\t\t\t\tthis.pack_double(value);\n\t\t\t}\n\t\t} else if (typeof value === \"boolean\") {\n\t\t\tif (value === true) {\n\t\t\t\tthis._bufferBuilder.append(0xc3);\n\t\t\t} else if (value === false) {\n\t\t\t\tthis._bufferBuilder.append(0xc2);\n\t\t\t}\n\t\t} else if (value === undefined) {\n\t\t\tthis._bufferBuilder.append(0xc0);\n\t\t} else if (typeof value === \"object\") {\n\t\t\tif (value === null) {\n\t\t\t\tthis._bufferBuilder.append(0xc0);\n\t\t\t} else {\n\t\t\t\tconst constructor = value.constructor;\n\t\t\t\tif (value instanceof Array) {\n\t\t\t\t\tconst res = this.pack_array(value);\n\t\t\t\t\tif (res instanceof Promise) {\n\t\t\t\t\t\treturn res.then(() => this._bufferBuilder.flush());\n\t\t\t\t\t}\n\t\t\t\t} else if (value instanceof ArrayBuffer) {\n\t\t\t\t\tthis.pack_bin(new Uint8Array(value));\n\t\t\t\t} else if (\"BYTES_PER_ELEMENT\" in value) {\n\t\t\t\t\tconst v = value as unknown as DataView;\n\t\t\t\t\tthis.pack_bin(new Uint8Array(v.buffer, v.byteOffset, v.byteLength));\n\t\t\t\t} else if (value instanceof Date) {\n\t\t\t\t\tthis.pack_string(value.toString());\n\t\t\t\t} else if (value instanceof Blob) {\n\t\t\t\t\treturn value.arrayBuffer().then((buffer) => {\n\t\t\t\t\t\tthis.pack_bin(new Uint8Array(buffer));\n\t\t\t\t\t\tthis._bufferBuilder.flush();\n\t\t\t\t\t});\n\t\t\t\t\t// this.pack_bin(new Uint8Array(await value.arrayBuffer()));\n\t\t\t\t} else if (\n\t\t\t\t\tconstructor == Object ||\n\t\t\t\t\tconstructor.toString().startsWith(\"class\")\n\t\t\t\t) {\n\t\t\t\t\tconst res = this.pack_object(value);\n\t\t\t\t\tif (res instanceof Promise) {\n\t\t\t\t\t\treturn res.then(() => this._bufferBuilder.flush());\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(`Type \"${constructor.toString()}\" not yet supported`);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new Error(`Type \"${typeof value}\" not yet supported`);\n\t\t}\n\t\tthis._bufferBuilder.flush();\n\t}\n\n\tpack_bin(blob: Uint8Array) {\n\t\tconst length = blob.length;\n\n\t\tif (length <= 0x0f) {\n\t\t\tthis.pack_uint8(0xa0 + length);\n\t\t} else if (length <= 0xffff) {\n\t\t\tthis._bufferBuilder.append(0xda);\n\t\t\tthis.pack_uint16(length);\n\t\t} else if (length <= 0xffffffff) {\n\t\t\tthis._bufferBuilder.append(0xdb);\n\t\t\tthis.pack_uint32(length);\n\t\t} else {\n\t\t\tthrow new Error(\"Invalid length\");\n\t\t}\n\t\tthis._bufferBuilder.append_buffer(blob);\n\t}\n\n\tpack_string(str: string) {\n\t\tconst encoded = this._textEncoder.encode(str);\n\t\tconst length = encoded.length;\n\n\t\tif (length <= 0x0f) {\n\t\t\tthis.pack_uint8(0xb0 + length);\n\t\t} else if (length <= 0xffff) {\n\t\t\tthis._bufferBuilder.append(0xd8);\n\t\t\tthis.pack_uint16(length);\n\t\t} else if (length <= 0xffffffff) {\n\t\t\tthis._bufferBuilder.append(0xd9);\n\t\t\tthis.pack_uint32(length);\n\t\t} else {\n\t\t\tthrow new Error(\"Invalid length\");\n\t\t}\n\t\tthis._bufferBuilder.append_buffer(encoded);\n\t}\n\n\tpack_array(ary: Packable[]) {\n\t\tconst length = ary.length;\n\t\tif (length <= 0x0f) {\n\t\t\tthis.pack_uint8(0x90 + length);\n\t\t} else if (length <= 0xffff) {\n\t\t\tthis._bufferBuilder.append(0xdc);\n\t\t\tthis.pack_uint16(length);\n\t\t} else if (length <= 0xffffffff) {\n\t\t\tthis._bufferBuilder.append(0xdd);\n\t\t\tthis.pack_uint32(length);\n\t\t} else {\n\t\t\tthrow new Error(\"Invalid length\");\n\t\t}\n\n\t\tconst packNext = (index: number): Promise<void> | void => {\n\t\t\tif (index < length) {\n\t\t\t\tconst res = this.pack(ary[index]);\n\t\t\t\tif (res instanceof Promise) {\n\t\t\t\t\treturn res.then(() => packNext(index + 1));\n\t\t\t\t}\n\t\t\t\treturn packNext(index + 1);\n\t\t\t}\n\t\t};\n\n\t\treturn packNext(0);\n\t}\n\n\tpack_integer(num: number) {\n\t\tif (num >= -0x20 && num <= 0x7f) {\n\t\t\tthis._bufferBuilder.append(num & 0xff);\n\t\t} else if (num >= 0x00 && num <= 0xff) {\n\t\t\tthis._bufferBuilder.append(0xcc);\n\t\t\tthis.pack_uint8(num);\n\t\t} else if (num >= -0x80 && num <= 0x7f) {\n\t\t\tthis._bufferBuilder.append(0xd0);\n\t\t\tthis.pack_int8(num);\n\t\t} else if (num >= 0x0000 && num <= 0xffff) {\n\t\t\tthis._bufferBuilder.append(0xcd);\n\t\t\tthis.pack_uint16(num);\n\t\t} else if (num >= -0x8000 && num <= 0x7fff) {\n\t\t\tthis._bufferBuilder.append(0xd1);\n\t\t\tthis.pack_int16(num);\n\t\t} else if (num >= 0x00000000 && num <= 0xffffffff) {\n\t\t\tthis._bufferBuilder.append(0xce);\n\t\t\tthis.pack_uint32(num);\n\t\t} else if (num >= -0x80000000 && num <= 0x7fffffff) {\n\t\t\tthis._bufferBuilder.append(0xd2);\n\t\t\tthis.pack_int32(num);\n\t\t} else if (num >= -0x8000000000000000 && num <= 0x7fffffffffffffff) {\n\t\t\tthis._bufferBuilder.append(0xd3);\n\t\t\tthis.pack_int64(num);\n\t\t} else if (num >= 0x0000000000000000 && num <= 0xffffffffffffffff) {\n\t\t\tthis._bufferBuilder.append(0xcf);\n\t\t\tthis.pack_uint64(num);\n\t\t} else {\n\t\t\tthrow new Error(\"Invalid integer\");\n\t\t}\n\t}\n\n\tpack_double(num: number) {\n\t\tlet sign = 0;\n\t\tif (num < 0) {\n\t\t\tsign = 1;\n\t\t\tnum = -num;\n\t\t}\n\t\tconst exp = Math.floor(Math.log(num) / Math.LN2);\n\t\tconst frac0 = num / 2 ** exp - 1;\n\t\tconst frac1 = Math.floor(frac0 * 2 ** 52);\n\t\tconst b32 = 2 ** 32;\n\t\tconst h32 =\n\t\t\t(sign << 31) | ((exp + 1023) << 20) | ((frac1 / b32) & 0x0fffff);\n\t\tconst l32 = frac1 % b32;\n\t\tthis._bufferBuilder.append(0xcb);\n\t\tthis.pack_int32(h32);\n\t\tthis.pack_int32(l32);\n\t}\n\n\tpack_object(obj: { [key: string]: Packable }) {\n\t\tconst keys = Object.keys(obj);\n\t\tconst length = keys.length;\n\t\tif (length <= 0x0f) {\n\t\t\tthis.pack_uint8(0x80 + length);\n\t\t} else if (length <= 0xffff) {\n\t\t\tthis._bufferBuilder.append(0xde);\n\t\t\tthis.pack_uint16(length);\n\t\t} else if (length <= 0xffffffff) {\n\t\t\tthis._bufferBuilder.append(0xdf);\n\t\t\tthis.pack_uint32(length);\n\t\t} else {\n\t\t\tthrow new Error(\"Invalid length\");\n\t\t}\n\n\t\tconst packNext = (index: number): Promise<void> | void => {\n\t\t\tif (index < keys.length) {\n\t\t\t\tconst prop = keys[index];\n\t\t\t\t// eslint-disable-next-line no-prototype-builtins\n\t\t\t\tif (obj.hasOwnProperty(prop)) {\n\t\t\t\t\tthis.pack(prop);\n\t\t\t\t\tconst res = this.pack(obj[prop]);\n\t\t\t\t\tif (res instanceof Promise) {\n\t\t\t\t\t\treturn res.then(() => packNext(index + 1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn packNext(index + 1);\n\t\t\t}\n\t\t};\n\n\t\treturn packNext(0);\n\t}\n\n\tpack_uint8(num: number) {\n\t\tthis._bufferBuilder.append(num);\n\t}\n\n\tpack_uint16(num: number) {\n\t\tthis._bufferBuilder.append(num >> 8);\n\t\tthis._bufferBuilder.append(num & 0xff);\n\t}\n\n\tpack_uint32(num: number) {\n\t\tconst n = num & 0xffffffff;\n\t\tthis._bufferBuilder.append((n & 0xff000000) >>> 24);\n\t\tthis._bufferBuilder.append((n & 0x00ff0000) >>> 16);\n\t\tthis._bufferBuilder.append((n & 0x0000ff00) >>> 8);\n\t\tthis._bufferBuilder.append(n & 0x000000ff);\n\t}\n\n\tpack_uint64(num: number) {\n\t\tconst high = num / 2 ** 32;\n\t\tconst low = num % 2 ** 32;\n\t\tthis._bufferBuilder.append((high & 0xff000000) >>> 24);\n\t\tthis._bufferBuilder.append((high & 0x00ff0000) >>> 16);\n\t\tthis._bufferBuilder.append((high & 0x0000ff00) >>> 8);\n\t\tthis._bufferBuilder.append(high & 0x000000ff);\n\t\tthis._bufferBuilder.append((low & 0xff000000) >>> 24);\n\t\tthis._bufferBuilder.append((low & 0x00ff0000) >>> 16);\n\t\tthis._bufferBuilder.append((low & 0x0000ff00) >>> 8);\n\t\tthis._bufferBuilder.append(low & 0x000000ff);\n\t}\n\n\tpack_int8(num: number) {\n\t\tthis._bufferBuilder.append(num & 0xff);\n\t}\n\n\tpack_int16(num: number) {\n\t\tthis._bufferBuilder.append((num & 0xff00) >> 8);\n\t\tthis._bufferBuilder.append(num & 0xff);\n\t}\n\n\tpack_int32(num: number) {\n\t\tthis._bufferBuilder.append((num >>> 24) & 0xff);\n\t\tthis._bufferBuilder.append((num & 0x00ff0000) >>> 16);\n\t\tthis._bufferBuilder.append((num & 0x0000ff00) >>> 8);\n\t\tthis._bufferBuilder.append(num & 0x000000ff);\n\t}\n\n\tpack_int64(num: number) {\n\t\tconst high = Math.floor(num / 2 ** 32);\n\t\tconst low = num % 2 ** 32;\n\t\tthis._bufferBuilder.append((high & 0xff000000) >>> 24);\n\t\tthis._bufferBuilder.append((high & 0x00ff0000) >>> 16);\n\t\tthis._bufferBuilder.append((high & 0x0000ff00) >>> 8);\n\t\tthis._bufferBuilder.append(high & 0x000000ff);\n\t\tthis._bufferBuilder.append((low & 0xff000000) >>> 24);\n\t\tthis._bufferBuilder.append((low & 0x00ff0000) >>> 16);\n\t\tthis._bufferBuilder.append((low & 0x0000ff00) >>> 8);\n\t\tthis._bufferBuilder.append(low & 0x000000ff);\n\t}\n}\n", "class BufferBuilder {\n\tprivate _pieces: number[];\n\tprivate readonly _parts: ArrayBufferView[];\n\n\tconstructor() {\n\t\tthis._pieces = [];\n\t\tthis._parts = [];\n\t}\n\n\tappend_buffer(data: ArrayBufferView) {\n\t\tthis.flush();\n\t\tthis._parts.push(data);\n\t}\n\n\tappend(data: number) {\n\t\tthis._pieces.push(data);\n\t}\n\n\tflush() {\n\t\tif (this._pieces.length > 0) {\n\t\t\tconst buf = new Uint8Array(this._pieces);\n\t\t\tthis._parts.push(buf);\n\t\t\tthis._pieces = [];\n\t\t}\n\t}\n\n\tprivate encoder = new TextEncoder();\n\n\tpublic toArrayBuffer() {\n\t\tconst buffer = [];\n\t\tfor (const part of this._parts) {\n\t\t\tbuffer.push(part);\n\t\t}\n\t\treturn concatArrayBuffers(buffer).buffer;\n\t}\n}\n\nexport { BufferBuilder };\n\nfunction concatArrayBuffers(bufs: ArrayBufferView[]) {\n\tlet size = 0;\n\tfor (const buf of bufs) {\n\t\tsize += buf.byteLength;\n\t}\n\tconst result = new Uint8Array(size);\n\tlet offset = 0;\n\tfor (const buf of bufs) {\n\t\tconst view = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n\t\tresult.set(view, offset);\n\t\toffset += buf.byteLength;\n\t}\n\treturn result;\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\n\nlet logDisabled_ = true;\nlet deprecationWarnings_ = true;\n\n/**\n * Extract browser version out of the provided user agent string.\n *\n * @param {!string} uastring userAgent string.\n * @param {!string} expr Regular expression used as match criteria.\n * @param {!number} pos position in the version string to be returned.\n * @return {!number} browser version.\n */\nexport function extractVersion(uastring, expr, pos) {\n const match = uastring.match(expr);\n return match && match.length >= pos && parseFloat(match[pos], 10);\n}\n\n// Wraps the peerconnection event eventNameToWrap in a function\n// which returns the modified event object (or false to prevent\n// the event).\nexport function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) {\n if (!window.RTCPeerConnection) {\n return;\n }\n const proto = window.RTCPeerConnection.prototype;\n const nativeAddEventListener = proto.addEventListener;\n proto.addEventListener = function(nativeEventName, cb) {\n if (nativeEventName !== eventNameToWrap) {\n return nativeAddEventListener.apply(this, arguments);\n }\n const wrappedCallback = (e) => {\n const modifiedEvent = wrapper(e);\n if (modifiedEvent) {\n if (cb.handleEvent) {\n cb.handleEvent(modifiedEvent);\n } else {\n cb(modifiedEvent);\n }\n }\n };\n this._eventMap = this._eventMap || {};\n if (!this._eventMap[eventNameToWrap]) {\n this._eventMap[eventNameToWrap] = new Map();\n }\n this._eventMap[eventNameToWrap].set(cb, wrappedCallback);\n return nativeAddEventListener.apply(this, [nativeEventName,\n wrappedCallback]);\n };\n\n const nativeRemoveEventListener = proto.removeEventListener;\n proto.removeEventListener = function(nativeEventName, cb) {\n if (nativeEventName !== eventNameToWrap || !this._eventMap\n || !this._eventMap[eventNameToWrap]) {\n return nativeRemoveEventListener.apply(this, arguments);\n }\n if (!this._eventMap[eventNameToWrap].has(cb)) {\n return nativeRemoveEventListener.apply(this, arguments);\n }\n const unwrappedCb = this._eventMap[eventNameToWrap].get(cb);\n this._eventMap[eventNameToWrap].delete(cb);\n if (this._eventMap[eventNameToWrap].size === 0) {\n delete this._eventMap[eventNameToWrap];\n }\n if (Object.keys(this._eventMap).length === 0) {\n delete this._eventMap;\n }\n return nativeRemoveEventListener.apply(this, [nativeEventName,\n unwrappedCb]);\n };\n\n Object.defineProperty(proto, 'on' + eventNameToWrap, {\n get() {\n return this['_on' + eventNameToWrap];\n },\n set(cb) {\n if (this['_on' + eventNameToWrap]) {\n this.removeEventListener(eventNameToWrap,\n this['_on' + eventNameToWrap]);\n delete this['_on' + eventNameToWrap];\n }\n if (cb) {\n this.addEventListener(eventNameToWrap,\n this['_on' + eventNameToWrap] = cb);\n }\n },\n enumerable: true,\n configurable: true\n });\n}\n\nexport function disableLog(bool) {\n if (typeof bool !== 'boolean') {\n return new Error('Argument type: ' + typeof bool +\n '. Please use a boolean.');\n }\n logDisabled_ = bool;\n return (bool) ? 'adapter.js logging disabled' :\n 'adapter.js logging enabled';\n}\n\n/**\n * Disable or enable deprecation warnings\n * @param {!boolean} bool set to true to disable warnings.\n */\nexport function disableWarnings(bool) {\n if (typeof bool !== 'boolean') {\n return new Error('Argument type: ' + typeof bool +\n '. Please use a boolean.');\n }\n deprecationWarnings_ = !bool;\n return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');\n}\n\nexport function log() {\n if (typeof window === 'object') {\n if (logDisabled_) {\n return;\n }\n if (typeof console !== 'undefined' && typeof console.log === 'function') {\n console.log.apply(console, arguments);\n }\n }\n}\n\n/**\n * Shows a deprecation warning suggesting the modern and spec-compatible API.\n */\nexport function deprecated(oldMethod, newMethod) {\n if (!deprecationWarnings_) {\n return;\n }\n console.warn(oldMethod + ' is deprecated, please use ' + newMethod +\n ' instead.');\n}\n\n/**\n * Browser detector.\n *\n * @return {object} result containing browser and version\n * properties.\n */\nexport function detectBrowser(window) {\n // Returned result object.\n const result = {browser: null, version: null};\n\n // Fail early if it's not a browser\n if (typeof window === 'undefined' || !window.navigator ||\n !window.navigator.userAgent) {\n result.browser = 'Not a browser.';\n return result;\n }\n\n const {navigator} = window;\n\n // Prefer navigator.userAgentData.\n if (navigator.userAgentData && navigator.userAgentData.brands) {\n const chromium = navigator.userAgentData.brands.find((brand) => {\n return brand.brand === 'Chromium';\n });\n if (chromium) {\n return {browser: 'chrome', version: parseInt(chromium.version, 10)};\n }\n }\n\n if (navigator.mozGetUserMedia) { // Firefox.\n result.browser = 'firefox';\n result.version = parseInt(extractVersion(navigator.userAgent,\n /Firefox\\/(\\d+)\\./, 1));\n } else if (navigator.webkitGetUserMedia ||\n (window.isSecureContext === false && window.webkitRTCPeerConnection)) {\n // Chrome, Chromium, Webview, Opera.\n // Version matches Chrome/WebRTC version.\n // Chrome 74 removed webkitGetUserMedia on http as well so we need the\n // more complicated fallback to webkitRTCPeerConnection.\n result.browser = 'chrome';\n result.version = parseInt(extractVersion(navigator.userAgent,\n /Chrom(e|ium)\\/(\\d+)\\./, 2));\n } else if (window.RTCPeerConnection &&\n navigator.userAgent.match(/AppleWebKit\\/(\\d+)\\./)) { // Safari.\n result.browser = 'safari';\n result.version = parseInt(extractVersion(navigator.userAgent,\n /AppleWebKit\\/(\\d+)\\./, 1));\n result.supportsUnifiedPlan = window.RTCRtpTransceiver &&\n 'currentDirection' in window.RTCRtpTransceiver.prototype;\n // Only for internal usage.\n result._safariVersion = extractVersion(navigator.userAgent,\n /Version\\/(\\d+(\\.?\\d+))/, 1);\n } else { // Default fallthrough: not supported.\n result.browser = 'Not a supported browser.';\n return result;\n }\n\n return result;\n}\n\n/**\n * Checks if something is an object.\n *\n * @param {*} val The something you want to check.\n * @return true if val is an object, false otherwise.\n */\nfunction isObject(val) {\n return Object.prototype.toString.call(val) === '[object Object]';\n}\n\n/**\n * Remove all empty objects and undefined values\n * from a nested object -- an enhanced and vanilla version\n * of Lodash's `compact`.\n */\nexport function compactObject(data) {\n if (!isObject(data)) {\n return data;\n }\n\n return Object.keys(data).reduce(function(accumulator, key) {\n const isObj = isObject(data[key]);\n const value = isObj ? compactObject(data[key]) : data[key];\n const isEmptyObject = isObj && !Object.keys(value).length;\n if (value === undefined || isEmptyObject) {\n return accumulator;\n }\n return Object.assign(accumulator, {[key]: value});\n }, {});\n}\n\n/* iterates the stats graph recursively. */\nexport function walkStats(stats, base, resultSet) {\n if (!base || resultSet.has(base.id)) {\n return;\n }\n resultSet.set(base.id, base);\n Object.keys(base).forEach(name => {\n if (name.endsWith('Id')) {\n walkStats(stats, stats.get(base[name]), resultSet);\n } else if (name.endsWith('Ids')) {\n base[name].forEach(id => {\n walkStats(stats, stats.get(id), resultSet);\n });\n }\n });\n}\n\n/* filter getStats for a sender/receiver track. */\nexport function filterStats(result, track, outbound) {\n const streamStatsType = outbound ? 'outbound-rtp' : 'inbound-rtp';\n const filteredResult = new Map();\n if (track === null) {\n return filteredResult;\n }\n const trackStats = [];\n result.forEach(value => {\n if (value.type === 'track' &&\n value.trackIdentifier === track.id) {\n trackStats.push(value);\n }\n });\n trackStats.forEach(trackStat => {\n result.forEach(stats => {\n if (stats.type === streamStatsType && stats.trackId === trackStat.id) {\n walkStats(result, stats, filteredResult);\n }\n });\n });\n return filteredResult;\n}\n\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\nimport * as utils from '../utils.js';\n\nexport {shimGetUserMedia} from './getusermedia';\n\nexport function shimMediaStream(window) {\n window.MediaStream = window.MediaStream || window.webkitMediaStream;\n}\n\nexport function shimOnTrack(window) {\n if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in\n window.RTCPeerConnection.prototype)) {\n Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {\n get() {\n return this._ontrack;\n },\n set(f) {\n if (this._ontrack) {\n this.removeEventListener('track', this._ontrack);\n }\n this.addEventListener('track', this._ontrack = f);\n },\n enumerable: true,\n configurable: true\n });\n const origSetRemoteDescription =\n window.RTCPeerConnection.prototype.setRemoteDescription;\n window.RTCPeerConnection.prototype.setRemoteDescription =\n function setRemoteDescription() {\n if (!this._ontrackpoly) {\n this._ontrackpoly = (e) => {\n // onaddstream does not fire when a track is added to an existing\n // stream. But stream.onaddtrack is implemented so we use that.\n e.stream.addEventListener('addtrack', te => {\n let receiver;\n if (window.RTCPeerConnection.prototype.getReceivers) {\n receiver = this.getReceivers()\n .find(r => r.track && r.track.id === te.track.id);\n } else {\n receiver = {track: te.track};\n }\n\n const event = new Event('track');\n event.track = te.track;\n event.receiver = receiver;\n event.transceiver = {receiver};\n event.streams = [e.stream];\n this.dispatchEvent(event);\n });\n e.stream.getTracks().forEach(track => {\n let receiver;\n if (window.RTCPeerConnection.prototype.getReceivers) {\n receiver = this.getReceivers()\n .find(r => r.track && r.track.id === track.id);\n } else {\n receiver = {track};\n }\n const event = new Event('track');\n event.track = track;\n event.receiver = receiver;\n event.transceiver = {receiver};\n event.streams = [e.stream];\n this.dispatchEvent(event);\n });\n };\n this.addEventListener('addstream', this._ontrackpoly);\n }\n return origSetRemoteDescription.apply(this, arguments);\n };\n } else {\n // even if RTCRtpTransceiver is in window, it is only used and\n // emitted in unified-plan. Unfortunately this means we need\n // to unconditionally wrap the event.\n utils.wrapPeerConnectionEvent(window, 'track', e => {\n if (!e.transceiver) {\n Object.defineProperty(e, 'transceiver',\n {value: {receiver: e.receiver}});\n }\n return e;\n });\n }\n}\n\nexport function shimGetSendersWithDtmf(window) {\n // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.\n if (typeof window === 'object' && window.RTCPeerConnection &&\n !('getSenders' in window.RTCPeerConnection.prototype) &&\n 'createDTMFSender' in window.RTCPeerConnection.prototype) {\n const shimSenderWithDtmf = function(pc, track) {\n return {\n track,\n get dtmf() {\n if (this._dtmf === undefined) {\n if (track.kind === 'audio') {\n this._dtmf = pc.createDTMFSender(track);\n } else {\n this._dtmf = null;\n }\n }\n return this._dtmf;\n },\n _pc: pc\n };\n };\n\n // augment addTrack when getSenders is not available.\n if (!window.RTCPeerConnection.prototype.getSenders) {\n window.RTCPeerConnection.prototype.getSenders = function getSenders() {\n this._senders = this._senders || [];\n return this._senders.slice(); // return a copy of the internal state.\n };\n const origAddTrack = window.RTCPeerConnection.prototype.addTrack;\n window.RTCPeerConnection.prototype.addTrack =\n function addTrack(track, stream) {\n let sender = origAddTrack.apply(this, arguments);\n if (!sender) {\n sender = shimSenderWithDtmf(this, track);\n this._senders.push(sender);\n }\n return sender;\n };\n\n const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;\n window.RTCPeerConnection.prototype.removeTrack =\n function removeTrack(sender) {\n origRemoveTrack.apply(this, arguments);\n const idx = this._senders.indexOf(sender);\n if (idx !== -1) {\n this._senders.splice(idx, 1);\n }\n };\n }\n const origAddStream = window.RTCPeerConnection.prototype.addStream;\n window.RTCPeerConnection.prototype.addStream = function addStream(stream) {\n this._senders = this._senders || [];\n origAddStream.apply(this, [stream]);\n stream.getTracks().forEach(track => {\n this._senders.push(shimSenderWithDtmf(this, track));\n });\n };\n\n const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;\n window.RTCPeerConnection.prototype.removeStream =\n function removeStream(stream) {\n this._senders = this._senders || [];\n origRemoveStream.apply(this, [stream]);\n\n stream.getTracks().forEach(track => {\n const sender = this._senders.find(s => s.track === track);\n if (sender) { // remove sender\n this._senders.splice(this._senders.indexOf(sender), 1);\n }\n });\n };\n } else if (typeof window === 'object' && window.RTCPeerConnection &&\n 'getSenders' in window.RTCPeerConnection.prototype &&\n 'createDTMFSender' in window.RTCPeerConnection.prototype &&\n window.RTCRtpSender &&\n !('dtmf' in window.RTCRtpSender.prototype)) {\n const origGetSenders = window.RTCPeerConnection.prototype.getSenders;\n window.RTCPeerConnection.prototype.getSenders = function getSenders() {\n const senders = origGetSenders.apply(this, []);\n senders.forEach(sender => sender._pc = this);\n return senders;\n };\n\n Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {\n get() {\n if (this._dtmf === undefined) {\n if (this.track.kind === 'audio') {\n this._dtmf = this._pc.createDTMFSender(this.track);\n } else {\n this._dtmf = null;\n }\n }\n return this._dtmf;\n }\n });\n }\n}\n\nexport function shimSenderReceiverGetStats(window) {\n if (!(typeof window === 'object' && window.RTCPeerConnection &&\n window.RTCRtpSender && window.RTCRtpReceiver)) {\n return;\n }\n\n // shim sender stats.\n if (!('getStats' in window.RTCRtpSender.prototype)) {\n const origGetSenders = window.RTCPeerConnection.prototype.getSenders;\n if (origGetSenders) {\n window.RTCPeerConnection.prototype.getSenders = function getSenders() {\n const senders = origGetSenders.apply(this, []);\n senders.forEach(sender => sender._pc = this);\n return senders;\n };\n }\n\n const origAddTrack = window.RTCPeerConnection.prototype.addTrack;\n if (origAddTrack) {\n window.RTCPeerConnection.prototype.addTrack = function addTrack() {\n const sender = origAddTrack.apply(this, arguments);\n sender._pc = this;\n return sender;\n };\n }\n window.RTCRtpSender.prototype.getStats = function getStats() {\n const sender = this;\n return this._pc.getStats().then(result =>\n /* Note: this will include stats of all senders that\n * send a track with the same id as sender.track as\n * it is not possible to identify the RTCRtpSender.\n */\n utils.filterStats(result, sender.track, true));\n };\n }\n\n // shim receiver stats.\n if (!('getStats' in window.RTCRtpReceiver.prototype)) {\n const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;\n if (origGetReceivers) {\n window.RTCPeerConnection.prototype.getReceivers =\n function getReceivers() {\n const receivers = origGetReceivers.apply(this, []);\n receivers.forEach(receiver => receiver._pc = this);\n return receivers;\n };\n }\n utils.wrapPeerConnectionEvent(window, 'track', e => {\n e.receiver._pc = e.srcElement;\n return e;\n });\n window.RTCRtpReceiver.prototype.getStats = function getStats() {\n const receiver = this;\n return this._pc.getStats().then(result =>\n utils.filterStats(result, receiver.track, false));\n };\n }\n\n if (!('getStats' in window.RTCRtpSender.prototype &&\n 'getStats' in window.RTCRtpReceiver.prototype)) {\n return;\n }\n\n // shim RTCPeerConnection.getStats(track).\n const origGetStats = window.RTCPeerConnection.prototype.getStats;\n window.RTCPeerConnection.prototype.getStats = function getStats() {\n if (arguments.length > 0 &&\n arguments[0] instanceof window.MediaStreamTrack) {\n const track = arguments[0];\n let sender;\n let receiver;\n let err;\n this.getSenders().forEach(s => {\n if (s.track === track) {\n if (sender) {\n err = true;\n } else {\n sender = s;\n }\n }\n });\n this.getReceivers().forEach(r => {\n if (r.track === track) {\n if (receiver) {\n err = true;\n } else {\n receiver = r;\n }\n }\n return r.track === track;\n });\n if (err || (sender && receiver)) {\n return Promise.reject(new DOMException(\n 'There are more than one sender or receiver for the track.',\n 'InvalidAccessError'));\n } else if (sender) {\n return sender.getStats();\n } else if (receiver) {\n return receiver.getStats();\n }\n return Promise.reject(new DOMException(\n 'There is no sender or receiver for the track.',\n 'InvalidAccessError'));\n }\n return origGetStats.apply(this, arguments);\n };\n}\n\nexport function shimAddTrackRemoveTrackWithNative(window) {\n // shim addTrack/removeTrack with native variants in order to make\n // the interactions with legacy getLocalStreams behave as in other browsers.\n // Keeps a mapping stream.id => [stream, rtpsenders...]\n window.RTCPeerConnection.prototype.getLocalStreams =\n function getLocalStreams() {\n this._shimmedLocalStreams = this._shimmedLocalStreams || {};\n return Object.keys(this._shimmedLocalStreams)\n .map(streamId => this._shimmedLocalStreams[streamId][0]);\n };\n\n const origAddTrack = window.RTCPeerConnection.prototype.addTrack;\n window.RTCPeerConnection.prototype.addTrack =\n function addTrack(track, stream) {\n if (!stream) {\n return origAddTrack.apply(this, arguments);\n }\n this._shimmedLocalStreams = this._shimmedLocalStreams || {};\n\n const sender = origAddTrack.apply(this, arguments);\n if (!this._shimmedLocalStreams[stream.id]) {\n this._shimmedLocalStreams[stream.id] = [stream, sender];\n } else if (this._shimmedLocalStreams[stream.id].indexOf(sender) === -1) {\n this._shimmedLocalStreams[stream.id].push(sender);\n }\n return sender;\n };\n\n const origAddStream = window.RTCPeerConnection.prototype.addStream;\n window.RTCPeerConnection.prototype.addStream = function addStream(stream) {\n this._shimmedLocalStreams = this._shimmedLocalStreams || {};\n\n stream.getTracks().forEach(track => {\n const alreadyExists = this.getSenders().find(s => s.track === track);\n if (alreadyExists) {\n throw new DOMException('Track already exists.',\n 'InvalidAccessError');\n }\n });\n const existingSenders = this.getSenders();\n origAddStream.apply(this, arguments);\n const newSenders = this.getSenders()\n .filter(newSender => existingSenders.indexOf(newSender) === -1);\n this._shimmedLocalStreams[stream.id] = [stream].concat(newSenders);\n };\n\n const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;\n window.RTCPeerConnection.prototype.removeStream =\n function removeStream(stream) {\n this._shimmedLocalStreams = this._shimmedLocalStreams || {};\n delete this._shimmedLocalStreams[stream.id];\n return origRemoveStream.apply(this, arguments);\n };\n\n const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;\n window.RTCPeerConnection.prototype.removeTrack =\n function removeTrack(sender) {\n this._shimmedLocalStreams = this._shimmedLocalStreams || {};\n if (sender) {\n Object.keys(this._shimmedLocalStreams).forEach(streamId => {\n const idx = this._shimmedLocalStreams[streamId].indexOf(sender);\n if (idx !== -1) {\n this._shimmedLocalStreams[streamId].splice(idx, 1);\n }\n if (this._shimmedLocalStreams[streamId].length === 1) {\n delete this._shimmedLocalStreams[streamId];\n }\n });\n }\n return origRemoveTrack.apply(this, arguments);\n };\n}\n\nexport function shimAddTrackRemoveTrack(window, browserDetails) {\n if (!window.RTCPeerConnection) {\n return;\n }\n // shim addTrack and removeTrack.\n if (window.RTCPeerConnection.prototype.addTrack &&\n browserDetails.version >= 65) {\n return shimAddTrackRemoveTrackWithNative(window);\n }\n\n // also shim pc.getLocalStreams when addTrack is shimmed\n // to return the original streams.\n const origGetLocalStreams = window.RTCPeerConnection.prototype\n .getLocalStreams;\n window.RTCPeerConnection.prototype.getLocalStreams =\n function getLocalStreams() {\n const nativeStreams = origGetLocalStreams.apply(this);\n this._reverseStreams = this._reverseStreams || {};\n return nativeStreams.map(stream => this._reverseStreams[stream.id]);\n };\n\n const origAddStream = window.RTCPeerConnection.prototype.addStream;\n window.RTCPeerConnection.prototype.addStream = function addStream(stream) {\n this._streams = this._streams || {};\n this._reverseStreams = this._reverseStreams || {};\n\n stream.getTracks().forEach(track => {\n const alreadyExists = this.getSenders().find(s => s.track === track);\n if (alreadyExists) {\n throw new DOMException('Track already exists.',\n 'InvalidAccessError');\n }\n });\n // Add identity mapping for consistency with addTrack.\n // Unless this is being used with a stream from addTrack.\n if (!this._reverseStreams[stream.id]) {\n const newStream = new window.MediaStream(stream.getTracks());\n this._streams[stream.id] = newStream;\n this._reverseStreams[newStream.id] = stream;\n stream = newStream;\n }\n origAddStream.apply(this, [stream]);\n };\n\n const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;\n window.RTCPeerConnection.prototype.removeStream =\n function removeStream(stream) {\n this._streams = this._streams || {};\n this._reverseStreams = this._reverseStreams || {};\n\n origRemoveStream.apply(this, [(this._streams[stream.id] || stream)]);\n delete this._reverseStreams[(this._streams[stream.id] ?\n this._streams[stream.id].id : stream.id)];\n delete this._streams[stream.id];\n };\n\n window.RTCPeerConnection.prototype.addTrack =\n function addTrack(track, stream) {\n if (this.signalingState === 'closed') {\n throw new DOMException(\n 'The RTCPeerConnection\\'s signalingState is \\'closed\\'.',\n 'InvalidStateError');\n }\n const streams = [].slice.call(arguments, 1);\n if (streams.length !== 1 ||\n !streams[0].getTracks().find(t => t === track)) {\n // this is not fully correct but all we can manage without\n // [[associated MediaStreams]] internal slot.\n throw new DOMException(\n 'The adapter.js addTrack polyfill only supports a single ' +\n ' stream which is associated with the specified track.',\n 'NotSupportedError');\n }\n\n const alreadyExists = this.getSenders().find(s => s.track === track);\n if (alreadyExists) {\n throw new DOMException('Track already exists.',\n 'InvalidAccessError');\n }\n\n this._streams = this._streams || {};\n this._reverseStreams = this._reverseStreams || {};\n const oldStream = this._streams[stream.id];\n if (oldStream) {\n // this is using odd Chrome behaviour, use with caution:\n // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815\n // Note: we rely on the high-level addTrack/dtmf shim to\n // create the sender with a dtmf sender.\n oldStream.addTrack(track);\n\n // Trigger ONN async.\n Promise.resolve().then(() => {\n this.dispatchEvent(new Event('negotiationneeded'));\n });\n } else {\n const newStream = new window.MediaStream([track]);\n this._streams[stream.id] = newStream;\n this._reverseStreams[newStream.id] = stream;\n this.addStream(newStream);\n }\n return this.getSenders().find(s => s.track === track);\n };\n\n // replace the internal stream id with the external one and\n // vice versa.\n function replaceInternalStreamId(pc, description) {\n let sdp = description.sdp;\n Object.keys(pc._reverseStreams || []).forEach(internalId => {\n const externalStream = pc._reverseStreams[internalId];\n const internalStream = pc._streams[externalStream.id];\n sdp = sdp.replace(new RegExp(internalStream.id, 'g'),\n externalStream.id);\n });\n return new RTCSessionDescription({\n type: description.type,\n sdp\n });\n }\n function replaceExternalStreamId(pc, description) {\n let sdp = description.sdp;\n Object.keys(pc._reverseStreams || []).forEach(internalId => {\n const externalStream = pc._reverseStreams[internalId];\n const internalStream = pc._streams[externalStream.id];\n sdp = sdp.replace(new RegExp(externalStream.id, 'g'),\n internalStream.id);\n });\n return new RTCSessionDescription({\n type: description.type,\n sdp\n });\n }\n ['createOffer', 'createAnswer'].forEach(function(method) {\n const nativeMethod = window.RTCPeerConnection.prototype[method];\n const methodObj = {[method]() {\n const args = arguments;\n const isLegacyCall = arguments.length &&\n typeof arguments[0] === 'function';\n if (isLegacyCall) {\n return nativeMethod.apply(this, [\n (description) => {\n const desc = replaceInternalStreamId(this, description);\n args[0].apply(null, [desc]);\n },\n (err) => {\n if (args[1]) {\n args[1].apply(null, err);\n }\n }, arguments[2]\n ]);\n }\n return nativeMethod.apply(this, arguments)\n .then(description => replaceInternalStreamId(this, description));\n }};\n window.RTCPeerConnection.prototype[method] = methodObj[method];\n });\n\n const origSetLocalDescription =\n window.RTCPeerConnection.prototype.setLocalDescription;\n window.RTCPeerConnection.prototype.setLocalDescription =\n function setLocalDescription() {\n if (!arguments.length || !arguments[0].type) {\n return origSetLocalDescription.apply(this, arguments);\n }\n arguments[0] = replaceExternalStreamId(this, arguments[0]);\n return origSetLocalDescription.apply(this, arguments);\n };\n\n // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier\n\n const origLocalDescription = Object.getOwnPropertyDescriptor(\n window.RTCPeerConnection.prototype, 'localDescription');\n Object.defineProperty(window.RTCPeerConnection.prototype,\n 'localDescription', {\n get() {\n const description = origLocalDescription.get.apply(this);\n if (description.type === '') {\n return description;\n }\n return replaceInternalStreamId(this, description);\n }\n });\n\n window.RTCPeerConnection.prototype.removeTrack =\n function removeTrack(sender) {\n if (this.signalingState === 'closed') {\n throw new DOMException(\n 'The RTCPeerConnection\\'s signalingState is \\'closed\\'.',\n 'InvalidStateError');\n }\n // We can not yet check for sender instanceof RTCRtpSender\n // since we shim RTPSender. So we check if sender._pc is set.\n if (!sender._pc) {\n throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' +\n 'does not implement interface RTCRtpSender.', 'TypeError');\n }\n const isLocal = sender._pc === this;\n if (!isLocal) {\n throw new DOMException('Sender was not created by this connection.',\n 'InvalidAccessError');\n }\n\n // Search for the native stream the senders track belongs to.\n this._streams = this._streams || {};\n let stream;\n Object.keys(this._streams).forEach(streamid => {\n const hasTrack = this._streams[streamid].getTracks()\n .find(track => sender.track === track);\n if (hasTrack) {\n stream = this._streams[streamid];\n }\n });\n\n if (stream) {\n if (stream.getTracks().length === 1) {\n // if this is the last track of the stream, remove the stream. This\n // takes care of any shimmed _senders.\n this.removeStream(this._reverseStreams[stream.id]);\n } else {\n // relying on the same odd chrome behaviour as above.\n stream.removeTrack(sender.track);\n }\n this.dispatchEvent(new Event('negotiationneeded'));\n }\n };\n}\n\nexport function shimPeerConnection(window, browserDetails) {\n if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) {\n // very basic support for old versions.\n window.RTCPeerConnection = window.webkitRTCPeerConnection;\n }\n if (!window.RTCPeerConnection) {\n return;\n }\n\n // shim implicit creation of RTCSessionDescription/RTCIceCandidate\n if (browserDetails.version < 53) {\n ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']\n .forEach(function(method) {\n const nativeMethod = window.RTCPeerConnection.prototype[method];\n const methodObj = {[method]() {\n arguments[0] = new ((method === 'addIceCandidate') ?\n window.RTCIceCandidate :\n window.RTCSessionDescription)(arguments[0]);\n return nativeMethod.apply(this, arguments);\n }};\n window.RTCPeerConnection.prototype[method] = methodObj[method];\n });\n }\n}\n\n// Attempt to fix ONN in plan-b mode.\nexport function fixNegotiationNeeded(window, browserDetails) {\n utils.wrapPeerConnectionEvent(window, 'negotiationneeded', e => {\n const pc = e.target;\n if (browserDetails.version < 72 || (pc.getConfiguration &&\n pc.getConfiguration().sdpSemantics === 'plan-b')) {\n if (pc.signalingState !== 'stable') {\n return;\n }\n }\n return e;\n });\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\nimport * as utils from '../utils.js';\nconst logging = utils.log;\n\nexport function shimGetUserMedia(window, browserDetails) {\n const navigator = window && window.navigator;\n\n if (!navigator.mediaDevices) {\n return;\n }\n\n const constraintsToChrome_ = function(c) {\n if (typeof c !== 'object' || c.mandatory || c.optional) {\n return c;\n }\n const cc = {};\n Object.keys(c).forEach(key => {\n if (key === 'require' || key === 'advanced' || key === 'mediaSource') {\n return;\n }\n const r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};\n if (r.exact !== undefined && typeof r.exact === 'number') {\n r.min = r.max = r.exact;\n }\n const oldname_ = function(prefix, name) {\n if (prefix) {\n return prefix + name.charAt(0).toUpperCase() + name.slice(1);\n }\n return (name === 'deviceId') ? 'sourceId' : name;\n };\n if (r.ideal !== undefined) {\n cc.optional = cc.optional || [];\n let oc = {};\n if (typeof r.ideal === 'number') {\n oc[oldname_('min', key)] = r.ideal;\n cc.optional.push(oc);\n oc = {};\n oc[oldname_('max', key)] = r.ideal;\n cc.optional.push(oc);\n } else {\n oc[oldname_('', key)] = r.ideal;\n cc.optional.push(oc);\n }\n }\n if (r.exact !== undefined && typeof r.exact !== 'number') {\n cc.mandatory = cc.mandatory || {};\n cc.mandatory[oldname_('', key)] = r.exact;\n } else {\n ['min', 'max'].forEach(mix => {\n if (r[mix] !== undefined) {\n cc.mandatory = cc.mandatory || {};\n cc.mandatory[oldname_(mix, key)] = r[mix];\n }\n });\n }\n });\n if (c.advanced) {\n cc.optional = (cc.optional || []).concat(c.advanced);\n }\n return cc;\n };\n\n const shimConstraints_ = function(constraints, func) {\n if (browserDetails.version >= 61) {\n return func(constraints);\n }\n constraints = JSON.parse(JSON.stringify(constraints));\n if (constraints && typeof constraints.audio === 'object') {\n const remap = function(obj, a, b) {\n if (a in obj && !(b in obj)) {\n obj[b] = obj[a];\n delete obj[a];\n }\n };\n constraints = JSON.parse(JSON.stringify(constraints));\n remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');\n remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');\n constraints.audio = constraintsToChrome_(constraints.audio);\n }\n if (constraints && typeof constraints.video === 'object') {\n // Shim facingMode for mobile & surface pro.\n let face = constraints.video.facingMode;\n face = face && ((typeof face === 'object') ? face : {ideal: face});\n const getSupportedFacingModeLies = browserDetails.version < 66;\n\n if ((face && (face.exact === 'user' || face.exact === 'environment' ||\n face.ideal === 'user' || face.ideal === 'environment')) &&\n !(navigator.mediaDevices.getSupportedConstraints &&\n navigator.mediaDevices.getSupportedConstraints().facingMode &&\n !getSupportedFacingModeLies)) {\n delete constraints.video.facingMode;\n let matches;\n if (face.exact === 'environment' || face.ideal === 'environment') {\n matches = ['back', 'rear'];\n } else if (face.exact === 'user' || face.ideal === 'user') {\n matches = ['front'];\n }\n if (matches) {\n // Look for matches in label, or use last cam for back (typical).\n return navigator.mediaDevices.enumerateDevices()\n .then(devices => {\n devices = devices.filter(d => d.kind === 'videoinput');\n let dev = devices.find(d => matches.some(match =>\n d.label.toLowerCase().includes(match)));\n if (!dev && devices.length && matches.includes('back')) {\n dev = devices[devices.length - 1]; // more likely the back cam\n }\n if (dev) {\n constraints.video.deviceId = face.exact\n ? {exact: dev.deviceId}\n : {ideal: dev.deviceId};\n }\n constraints.video = constraintsToChrome_(constraints.video);\n logging('chrome: ' + JSON.stringify(constraints));\n return func(constraints);\n });\n }\n }\n constraints.video = constraintsToChrome_(constraints.video);\n }\n logging('chrome: ' + JSON.stringify(constraints));\n return func(constraints);\n };\n\n const shimError_ = function(e) {\n if (browserDetails.version >= 64) {\n return e;\n }\n return {\n name: {\n PermissionDeniedError: 'NotAllowedError',\n PermissionDismissedError: 'NotAllowedError',\n InvalidStateError: 'NotAllowedError',\n DevicesNotFoundError: 'NotFoundError',\n ConstraintNotSatisfiedError: 'OverconstrainedError',\n TrackStartError: 'NotReadableError',\n MediaDeviceFailedDueToShutdown: 'NotAllowedError',\n MediaDeviceKillSwitchOn: 'NotAllowedError',\n TabCaptureError: 'AbortError',\n ScreenCaptureError: 'AbortError',\n DeviceCaptureError: 'AbortError'\n }[e.name] || e.name,\n message: e.message,\n constraint: e.constraint || e.constraintName,\n toString() {\n return this.name + (this.message && ': ') + this.message;\n }\n };\n };\n\n const getUserMedia_ = function(constraints, onSuccess, onError) {\n shimConstraints_(constraints, c => {\n navigator.webkitGetUserMedia(c, onSuccess, e => {\n if (onError) {\n onError(shimError_(e));\n }\n });\n });\n };\n navigator.getUserMedia = getUserMedia_.bind(navigator);\n\n // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia\n // function which returns a Promise, it does not accept spec-style\n // constraints.\n if (navigator.mediaDevices.getUserMedia) {\n const origGetUserMedia = navigator.mediaDevices.getUserMedia.\n bind(navigator.mediaDevices);\n navigator.mediaDevices.getUserMedia = function(cs) {\n return shimConstraints_(cs, c => origGetUserMedia(c).then(stream => {\n if (c.audio && !stream.getAudioTracks().length ||\n c.video && !stream.getVideoTracks().length) {\n stream.getTracks().forEach(track => {\n track.stop();\n });\n throw new DOMException('', 'NotFoundError');\n }\n return stream;\n }, e => Promise.reject(shimError_(e))));\n };\n }\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\n\nimport * as utils from '../utils';\nexport {shimGetUserMedia} from './getusermedia';\nexport {shimGetDisplayMedia} from './getdisplaymedia';\n\nexport function shimOnTrack(window) {\n if (typeof window === 'object' && window.RTCTrackEvent &&\n ('receiver' in window.RTCTrackEvent.prototype) &&\n !('transceiver' in window.RTCTrackEvent.prototype)) {\n Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {\n get() {\n return {receiver: this.receiver};\n }\n });\n }\n}\n\nexport function shimPeerConnection(window, browserDetails) {\n if (typeof window !== 'object' ||\n !(window.RTCPeerConnection || window.mozRTCPeerConnection)) {\n return; // probably media.peerconnection.enabled=false in about:config\n }\n if (!window.RTCPeerConnection && window.mozRTCPeerConnection) {\n // very basic support for old versions.\n window.RTCPeerConnection = window.mozRTCPeerConnection;\n }\n\n if (browserDetails.version < 53) {\n // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.\n ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']\n .forEach(function(method) {\n const nativeMethod = window.RTCPeerConnection.prototype[method];\n const methodObj = {[method]() {\n arguments[0] = new ((method === 'addIceCandidate') ?\n window.RTCIceCandidate :\n window.RTCSessionDescription)(arguments[0]);\n return nativeMethod.apply(this, arguments);\n }};\n window.RTCPeerConnection.prototype[method] = methodObj[method];\n });\n }\n\n const modernStatsTypes = {\n inboundrtp: 'inbound-rtp',\n outboundrtp: 'outbound-rtp',\n candidatepair: 'candidate-pair',\n localcandidate: 'local-candidate',\n remotecandidate: 'remote-candidate'\n };\n\n const nativeGetStats = window.RTCPeerConnection.prototype.getStats;\n window.RTCPeerConnection.prototype.getStats = function getStats() {\n const [selector, onSucc, onErr] = arguments;\n return nativeGetStats.apply(this, [selector || null])\n .then(stats => {\n if (browserDetails.version < 53 && !onSucc) {\n // Shim only promise getStats with spec-hyphens in type names\n // Leave callback version alone; misc old uses of forEach before Map\n try {\n stats.forEach(stat => {\n stat.type = modernStatsTypes[stat.type] || stat.type;\n });\n } catch (e) {\n if (e.name !== 'TypeError') {\n throw e;\n }\n // Avoid TypeError: \"type\" is read-only, in old versions. 34-43ish\n stats.forEach((stat, i) => {\n stats.set(i, Object.assign({}, stat, {\n type: modernStatsTypes[stat.type] || stat.type\n }));\n });\n }\n }\n return stats;\n })\n .then(onSucc, onErr);\n };\n}\n\nexport function shimSenderGetStats(window) {\n if (!(typeof window === 'object' && window.RTCPeerConnection &&\n window.RTCRtpSender)) {\n return;\n }\n if (window.RTCRtpSender && 'getStats' in window.RTCRtpSender.prototype) {\n return;\n }\n const origGetSenders = window.RTCPeerConnection.prototype.getSenders;\n if (origGetSenders) {\n window.RTCPeerConnection.prototype.getSenders = function getSenders() {\n const senders = origGetSenders.apply(this, []);\n senders.forEach(sender => sender._pc = this);\n return senders;\n };\n }\n\n const origAddTrack = window.RTCPeerConnection.prototype.addTrack;\n if (origAddTrack) {\n window.RTCPeerConnection.prototype.addTrack = function addTrack() {\n const sender = origAddTrack.apply(this, arguments);\n sender._pc = this;\n return sender;\n };\n }\n window.RTCRtpSender.prototype.getStats = function getStats() {\n return this.track ? this._pc.getStats(this.track) :\n Promise.resolve(new Map());\n };\n}\n\nexport function shimReceiverGetStats(window) {\n if (!(typeof window === 'object' && window.RTCPeerConnection &&\n window.RTCRtpSender)) {\n return;\n }\n if (window.RTCRtpSender && 'getStats' in window.RTCRtpReceiver.prototype) {\n return;\n }\n const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;\n if (origGetReceivers) {\n window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {\n const receivers = origGetReceivers.apply(this, []);\n receivers.forEach(receiver => receiver._pc = this);\n return receivers;\n };\n }\n utils.wrapPeerConnectionEvent(window, 'track', e => {\n e.receiver._pc = e.srcElement;\n return e;\n });\n window.RTCRtpReceiver.prototype.getStats = function getStats() {\n return this._pc.getStats(this.track);\n };\n}\n\nexport function shimRemoveStream(window) {\n if (!window.RTCPeerConnection ||\n 'removeStream' in window.RTCPeerConnection.prototype) {\n return;\n }\n window.RTCPeerConnection.prototype.removeStream =\n function removeStream(stream) {\n utils.deprecated('removeStream', 'removeTrack');\n this.getSenders().forEach(sender => {\n if (sender.track && stream.getTracks().includes(sender.track)) {\n this.removeTrack(sender);\n }\n });\n };\n}\n\nexport function shimRTCDataChannel(window) {\n // rename DataChannel to RTCDataChannel (native fix in FF60):\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1173851\n if (window.DataChannel && !window.RTCDataChannel) {\n window.RTCDataChannel = window.DataChannel;\n }\n}\n\nexport function shimAddTransceiver(window) {\n // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647\n // Firefox ignores the init sendEncodings options passed to addTransceiver\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918\n if (!(typeof window === 'object' && window.RTCPeerConnection)) {\n return;\n }\n const origAddTransceiver = window.RTCPeerConnection.prototype.addTransceiver;\n if (origAddTransceiver) {\n window.RTCPeerConnection.prototype.addTransceiver =\n function addTransceiver() {\n this.setParametersPromises = [];\n // WebIDL input coercion and validation\n let sendEncodings = arguments[1] && arguments[1].sendEncodings;\n if (sendEncodings === undefined) {\n sendEncodings = [];\n }\n sendEncodings = [...sendEncodings];\n const shouldPerformCheck = sendEncodings.length > 0;\n if (shouldPerformCheck) {\n // If sendEncodings params are provided, validate grammar\n sendEncodings.forEach((encodingParam) => {\n if ('rid' in encodingParam) {\n const ridRegex = /^[a-z0-9]{0,16}$/i;\n if (!ridRegex.test(encodingParam.rid)) {\n throw new TypeError('Invalid RID value provided.');\n }\n }\n if ('scaleResolutionDownBy' in encodingParam) {\n if (!(parseFloat(encodingParam.scaleResolutionDownBy) >= 1.0)) {\n throw new RangeError('scale_resolution_down_by must be >= 1.0');\n }\n }\n if ('maxFramerate' in encodingParam) {\n if (!(parseFloat(encodingParam.maxFramerate) >= 0)) {\n throw new RangeError('max_framerate must be >= 0.0');\n }\n }\n });\n }\n const transceiver = origAddTransceiver.apply(this, arguments);\n if (shouldPerformCheck) {\n // Check if the init options were applied. If not we do this in an\n // asynchronous way and save the promise reference in a global object.\n // This is an ugly hack, but at the same time is way more robust than\n // checking the sender parameters before and after the createOffer\n // Also note that after the createoffer we are not 100% sure that\n // the params were asynchronously applied so we might miss the\n // opportunity to recreate offer.\n const {sender} = transceiver;\n const params = sender.getParameters();\n if (!('encodings' in params) ||\n // Avoid being fooled by patched getParameters() below.\n (params.encodings.length === 1 &&\n Object.keys(params.encodings[0]).length === 0)) {\n params.encodings = sendEncodings;\n sender.sendEncodings = sendEncodings;\n this.setParametersPromises.push(sender.setParameters(params)\n .then(() => {\n delete sender.sendEncodings;\n }).catch(() => {\n delete sender.sendEncodings;\n })\n );\n }\n }\n return transceiver;\n };\n }\n}\n\nexport function shimGetParameters(window) {\n if (!(typeof window === 'object' && window.RTCRtpSender)) {\n return;\n }\n const origGetParameters = window.RTCRtpSender.prototype.getParameters;\n if (origGetParameters) {\n window.RTCRtpSender.prototype.getParameters =\n function getParameters() {\n const params = origGetParameters.apply(this, arguments);\n if (!('encodings' in params)) {\n params.encodings = [].concat(this.sendEncodings || [{}]);\n }\n return params;\n };\n }\n}\n\nexport function shimCreateOffer(window) {\n // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647\n // Firefox ignores the init sendEncodings options passed to addTransceiver\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918\n if (!(typeof window === 'object' && window.RTCPeerConnection)) {\n return;\n }\n const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;\n window.RTCPeerConnection.prototype.createOffer = function createOffer() {\n if (this.setParametersPromises && this.setParametersPromises.length) {\n return Promise.all(this.setParametersPromises)\n .then(() => {\n return origCreateOffer.apply(this, arguments);\n })\n .finally(() => {\n this.setParametersPromises = [];\n });\n }\n return origCreateOffer.apply(this, arguments);\n };\n}\n\nexport function shimCreateAnswer(window) {\n // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647\n // Firefox ignores the init sendEncodings options passed to addTransceiver\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918\n if (!(typeof window === 'object' && window.RTCPeerConnection)) {\n return;\n }\n const origCreateAnswer = window.RTCPeerConnection.prototype.createAnswer;\n window.RTCPeerConnection.prototype.createAnswer = function createAnswer() {\n if (this.setParametersPromises && this.setParametersPromises.length) {\n return Promise.all(this.setParametersPromises)\n .then(() => {\n return origCreateAnswer.apply(this, arguments);\n })\n .finally(() => {\n this.setParametersPromises = [];\n });\n }\n return origCreateAnswer.apply(this, arguments);\n };\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\n\nimport * as utils from '../utils';\n\nexport function shimGetUserMedia(window, browserDetails) {\n const navigator = window && window.navigator;\n const MediaStreamTrack = window && window.MediaStreamTrack;\n\n navigator.getUserMedia = function(constraints, onSuccess, onError) {\n // Replace Firefox 44+'s deprecation warning with unprefixed version.\n utils.deprecated('navigator.getUserMedia',\n 'navigator.mediaDevices.getUserMedia');\n navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);\n };\n\n if (!(browserDetails.version > 55 &&\n 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {\n const remap = function(obj, a, b) {\n if (a in obj && !(b in obj)) {\n obj[b] = obj[a];\n delete obj[a];\n }\n };\n\n const nativeGetUserMedia = navigator.mediaDevices.getUserMedia.\n bind(navigator.mediaDevices);\n navigator.mediaDevices.getUserMedia = function(c) {\n if (typeof c === 'object' && typeof c.audio === 'object') {\n c = JSON.parse(JSON.stringify(c));\n remap(c.audio, 'autoGainControl', 'mozAutoGainControl');\n remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');\n }\n return nativeGetUserMedia(c);\n };\n\n if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {\n const nativeGetSettings = MediaStreamTrack.prototype.getSettings;\n MediaStreamTrack.prototype.getSettings = function() {\n const obj = nativeGetSettings.apply(this, arguments);\n remap(obj, 'mozAutoGainControl', 'autoGainControl');\n remap(obj, 'mozNoiseSuppression', 'noiseSuppression');\n return obj;\n };\n }\n\n if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {\n const nativeApplyConstraints =\n MediaStreamTrack.prototype.applyConstraints;\n MediaStreamTrack.prototype.applyConstraints = function(c) {\n if (this.kind === 'audio' && typeof c === 'object') {\n c = JSON.parse(JSON.stringify(c));\n remap(c, 'autoGainControl', 'mozAutoGainControl');\n remap(c, 'noiseSuppression', 'mozNoiseSuppression');\n }\n return nativeApplyConstraints.apply(this, [c]);\n };\n }\n }\n}\n", "/*\n * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\n\nexport function shimGetDisplayMedia(window, preferredMediaSource) {\n if (window.navigator.mediaDevices &&\n 'getDisplayMedia' in window.navigator.mediaDevices) {\n return;\n }\n if (!(window.navigator.mediaDevices)) {\n return;\n }\n window.navigator.mediaDevices.getDisplayMedia =\n function getDisplayMedia(constraints) {\n if (!(constraints && constraints.video)) {\n const err = new DOMException('getDisplayMedia without video ' +\n 'constraints is undefined');\n err.name = 'NotFoundError';\n // from https://heycam.github.io/webidl/#idl-DOMException-error-names\n err.code = 8;\n return Promise.reject(err);\n }\n if (constraints.video === true) {\n constraints.video = {mediaSource: preferredMediaSource};\n } else {\n constraints.video.mediaSource = preferredMediaSource;\n }\n return window.navigator.mediaDevices.getUserMedia(constraints);\n };\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n'use strict';\nimport * as utils from '../utils';\n\nexport function shimLocalStreamsAPI(window) {\n if (typeof window !== 'object' || !window.RTCPeerConnection) {\n return;\n }\n if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {\n window.RTCPeerConnection.prototype.getLocalStreams =\n function getLocalStreams() {\n if (!this._localStreams) {\n this._localStreams = [];\n }\n return this._localStreams;\n };\n }\n if (!('addStream' in window.RTCPeerConnection.prototype)) {\n const _addTrack = window.RTCPeerConnection.prototype.addTrack;\n window.RTCPeerConnection.prototype.addStream = function addStream(stream) {\n if (!this._localStreams) {\n this._localStreams = [];\n }\n if (!this._localStreams.includes(stream)) {\n this._localStreams.push(stream);\n }\n // Try to emulate Chrome's behaviour of adding in audio-video order.\n // Safari orders by track id.\n stream.getAudioTracks().forEach(track => _addTrack.call(this, track,\n stream));\n stream.getVideoTracks().forEach(track => _addTrack.call(this, track,\n stream));\n };\n\n window.RTCPeerConnection.prototype.addTrack =\n function addTrack(track, ...streams) {\n if (streams) {\n streams.forEach((stream) => {\n if (!this._localStreams) {\n this._localStreams = [stream];\n } else if (!this._localStreams.includes(stream)) {\n this._localStreams.push(stream);\n }\n });\n }\n return _addTrack.apply(this, arguments);\n };\n }\n if (!('removeStream' in window.RTCPeerConnection.prototype)) {\n window.RTCPeerConnection.prototype.removeStream =\n function removeStream(stream) {\n if (!this._localStreams) {\n this._localStreams = [];\n }\n const index = this._localStreams.indexOf(stream);\n if (index === -1) {\n return;\n }\n this._localStreams.splice(index, 1);\n const tracks = stream.getTracks();\n this.getSenders().forEach(sender => {\n if (tracks.includes(sender.track)) {\n this.removeTrack(sender);\n }\n });\n };\n }\n}\n\nexport function shimRemoteStreamsAPI(window) {\n if (typeof window !== 'object' || !window.RTCPeerConnection) {\n return;\n }\n if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {\n window.RTCPeerConnection.prototype.getRemoteStreams =\n function getRemoteStreams() {\n return this._remoteStreams ? this._remoteStreams : [];\n };\n }\n if (!('onaddstream' in window.RTCPeerConnection.prototype)) {\n Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {\n get() {\n return this._onaddstream;\n },\n set(f) {\n if (this._onaddstream) {\n this.removeEventListener('addstream', this._onaddstream);\n this.removeEventListener('track', this._onaddstreampoly);\n }\n this.addEventListener('addstream', this._onaddstream = f);\n this.addEventListener('track', this._onaddstreampoly = (e) => {\n e.streams.forEach(stream => {\n if (!this._remoteStreams) {\n this._remoteStreams = [];\n }\n if (this._remoteStreams.includes(stream)) {\n return;\n }\n this._remoteStreams.push(stream);\n const event = new Event('addstream');\n event.stream = stream;\n this.dispatchEvent(event);\n });\n });\n }\n });\n const origSetRemoteDescription =\n window.RTCPeerConnection.prototype.setRemoteDescription;\n window.RTCPeerConnection.prototype.setRemoteDescription =\n function setRemoteDescription() {\n const pc = this;\n if (!this._onaddstreampoly) {\n this.addEventListener('track', this._onaddstreampoly = function(e) {\n e.streams.forEach(stream => {\n if (!pc._remoteStreams) {\n pc._remoteStreams = [];\n }\n if (pc._remoteStreams.indexOf(stream) >= 0) {\n return;\n }\n pc._remoteStreams.push(stream);\n const event = new Event('addstream');\n event.stream = stream;\n pc.dispatchEvent(event);\n });\n });\n }\n return origSetRemoteDescription.apply(pc, arguments);\n };\n }\n}\n\nexport function shimCallbacksAPI(window) {\n if (typeof window !== 'object' || !window.RTCPeerConnection) {\n return;\n }\n const prototype = window.RTCPeerConnection.prototype;\n const origCreateOffer = prototype.createOffer;\n const origCreateAnswer = prototype.createAnswer;\n const setLocalDescription = prototype.setLocalDescription;\n const setRemoteDescription = prototype.setRemoteDescription;\n const addIceCandidate = prototype.addIceCandidate;\n\n prototype.createOffer =\n function createOffer(successCallback, failureCallback) {\n const options = (arguments.length >= 2) ? arguments[2] : arguments[0];\n const promise = origCreateOffer.apply(this, [options]);\n if (!failureCallback) {\n return promise;\n }\n promise.then(successCallback, failureCallback);\n return Promise.resolve();\n };\n\n prototype.createAnswer =\n function createAnswer(successCallback, failureCallback) {\n const options = (arguments.length >= 2) ? arguments[2] : arguments[0];\n const promise = origCreateAnswer.apply(this, [options]);\n if (!failureCallback) {\n return promise;\n }\n promise.then(successCallback, failureCallback);\n return Promise.resolve();\n };\n\n let withCallback = function(description, successCallback, failureCallback) {\n const promise = setLocalDescription.apply(this, [description]);\n if (!failureCallback) {\n return promise;\n }\n promise.then(successCallback, failureCallback);\n return Promise.resolve();\n };\n prototype.setLocalDescription = withCallback;\n\n withCallback = function(description, successCallback, failureCallback) {\n const promise = setRemoteDescription.apply(this, [description]);\n if (!failureCallback) {\n return promise;\n }\n promise.then(successCallback, failureCallback);\n return Promise.resolve();\n };\n prototype.setRemoteDescription = withCallback;\n\n withCallback = function(candidate, successCallback, failureCallback) {\n const promise = addIceCandidate.apply(this, [candidate]);\n if (!failureCallback) {\n return promise;\n }\n promise.then(successCallback, failureCallback);\n return Promise.resolve();\n };\n prototype.addIceCandidate = withCallback;\n}\n\nexport function shimGetUserMedia(window) {\n const navigator = window && window.navigator;\n\n if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {\n // shim not needed in Safari 12.1\n const mediaDevices = navigator.mediaDevices;\n const _getUserMedia = mediaDevices.getUserMedia.bind(mediaDevices);\n navigator.mediaDevices.getUserMedia = (constraints) => {\n return _getUserMedia(shimConstraints(constraints));\n };\n }\n\n if (!navigator.getUserMedia && navigator.mediaDevices &&\n navigator.mediaDevices.getUserMedia) {\n navigator.getUserMedia = function getUserMedia(constraints, cb, errcb) {\n navigator.mediaDevices.getUserMedia(constraints)\n .then(cb, errcb);\n }.bind(navigator);\n }\n}\n\nexport function shimConstraints(constraints) {\n if (constraints && constraints.video !== undefined) {\n return Object.assign({},\n constraints,\n {video: utils.compactObject(constraints.video)}\n );\n }\n\n return constraints;\n}\n\nexport function shimRTCIceServerUrls(window) {\n if (!window.RTCPeerConnection) {\n return;\n }\n // migrate from non-spec RTCIceServer.url to RTCIceServer.urls\n const OrigPeerConnection = window.RTCPeerConnection;\n window.RTCPeerConnection =\n function RTCPeerConnection(pcConfig, pcConstraints) {\n if (pcConfig && pcConfig.iceServers) {\n const newIceServers = [];\n for (let i = 0; i < pcConfig.iceServers.length; i++) {\n let server = pcConfig.iceServers[i];\n if (server.urls === undefined && server.url) {\n utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');\n server = JSON.parse(JSON.stringify(server));\n server.urls = server.url;\n delete server.url;\n newIceServers.push(server);\n } else {\n newIceServers.push(pcConfig.iceServers[i]);\n }\n }\n pcConfig.iceServers = newIceServers;\n }\n return new OrigPeerConnection(pcConfig, pcConstraints);\n };\n window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;\n // wrap static methods. Currently just generateCertificate.\n if ('generateCertificate' in OrigPeerConnection) {\n Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {\n get() {\n return OrigPeerConnection.generateCertificate;\n }\n });\n }\n}\n\nexport function shimTrackEventTransceiver(window) {\n // Add event.transceiver member over deprecated event.receiver\n if (typeof window === 'object' && window.RTCTrackEvent &&\n 'receiver' in window.RTCTrackEvent.prototype &&\n !('transceiver' in window.RTCTrackEvent.prototype)) {\n Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {\n get() {\n return {receiver: this.receiver};\n }\n });\n }\n}\n\nexport function shimCreateOfferLegacy(window) {\n const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;\n window.RTCPeerConnection.prototype.createOffer =\n function createOffer(offerOptions) {\n if (offerOptions) {\n if (typeof offerOptions.offerToReceiveAudio !== 'undefined') {\n // support bit values\n offerOptions.offerToReceiveAudio =\n !!offerOptions.offerToReceiveAudio;\n }\n const audioTransceiver = this.getTransceivers().find(transceiver =>\n transceiver.receiver.track.kind === 'audio');\n if (offerOptions.offerToReceiveAudio === false && audioTransceiver) {\n if (audioTransceiver.direction === 'sendrecv') {\n if (audioTransceiver.setDirection) {\n audioTransceiver.setDirection('sendonly');\n } else {\n audioTransceiver.direction = 'sendonly';\n }\n } else if (audioTransceiver.direction === 'recvonly') {\n if (audioTransceiver.setDirection) {\n audioTransceiver.setDirection('inactive');\n } else {\n audioTransceiver.direction = 'inactive';\n }\n }\n } else if (offerOptions.offerToReceiveAudio === true &&\n !audioTransceiver) {\n this.addTransceiver('audio', {direction: 'recvonly'});\n }\n\n if (typeof offerOptions.offerToReceiveVideo !== 'undefined') {\n // support bit values\n offerOptions.offerToReceiveVideo =\n !!offerOptions.offerToReceiveVideo;\n }\n const videoTransceiver = this.getTransceivers().find(transceiver =>\n transceiver.receiver.track.kind === 'video');\n if (offerOptions.offerToReceiveVideo === false && videoTransceiver) {\n if (videoTransceiver.direction === 'sendrecv') {\n if (videoTransceiver.setDirection) {\n videoTransceiver.setDirection('sendonly');\n } else {\n videoTransceiver.direction = 'sendonly';\n }\n } else if (videoTransceiver.direction === 'recvonly') {\n if (videoTransceiver.setDirection) {\n videoTransceiver.setDirection('inactive');\n } else {\n videoTransceiver.direction = 'inactive';\n }\n }\n } else if (offerOptions.offerToReceiveVideo === true &&\n !videoTransceiver) {\n this.addTransceiver('video', {direction: 'recvonly'});\n }\n }\n return origCreateOffer.apply(this, arguments);\n };\n}\n\nexport function shimAudioContext(window) {\n if (typeof window !== 'object' || window.AudioContext) {\n return;\n }\n window.AudioContext = window.webkitAudioContext;\n}\n\n", "/*\n * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\n\nimport SDPUtils from 'sdp';\nimport * as utils from './utils';\n\nexport function shimRTCIceCandidate(window) {\n // foundation is arbitrarily chosen as an indicator for full support for\n // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface\n if (!window.RTCIceCandidate || (window.RTCIceCandidate && 'foundation' in\n window.RTCIceCandidate.prototype)) {\n return;\n }\n\n const NativeRTCIceCandidate = window.RTCIceCandidate;\n window.RTCIceCandidate = function RTCIceCandidate(args) {\n // Remove the a= which shouldn't be part of the candidate string.\n if (typeof args === 'object' && args.candidate &&\n args.candidate.indexOf('a=') === 0) {\n args = JSON.parse(JSON.stringify(args));\n args.candidate = args.candidate.substring(2);\n }\n\n if (args.candidate && args.candidate.length) {\n // Augment the native candidate with the parsed fields.\n const nativeCandidate = new NativeRTCIceCandidate(args);\n const parsedCandidate = SDPUtils.parseCandidate(args.candidate);\n for (const key in parsedCandidate) {\n if (!(key in nativeCandidate)) {\n Object.defineProperty(nativeCandidate, key,\n {value: parsedCandidate[key]});\n }\n }\n\n // Override serializer to not serialize the extra attributes.\n nativeCandidate.toJSON = function toJSON() {\n return {\n candidate: nativeCandidate.candidate,\n sdpMid: nativeCandidate.sdpMid,\n sdpMLineIndex: nativeCandidate.sdpMLineIndex,\n usernameFragment: nativeCandidate.usernameFragment,\n };\n };\n return nativeCandidate;\n }\n return new NativeRTCIceCandidate(args);\n };\n window.RTCIceCandidate.prototype = NativeRTCIceCandidate.prototype;\n\n // Hook up the augmented candidate in onicecandidate and\n // addEventListener('icecandidate', ...)\n utils.wrapPeerConnectionEvent(window, 'icecandidate', e => {\n if (e.candidate) {\n Object.defineProperty(e, 'candidate', {\n value: new window.RTCIceCandidate(e.candidate),\n writable: 'false'\n });\n }\n return e;\n });\n}\n\nexport function shimRTCIceCandidateRelayProtocol(window) {\n if (!window.RTCIceCandidate || (window.RTCIceCandidate && 'relayProtocol' in\n window.RTCIceCandidate.prototype)) {\n return;\n }\n\n // Hook up the augmented candidate in onicecandidate and\n // addEventListener('icecandidate', ...)\n utils.wrapPeerConnectionEvent(window, 'icecandidate', e => {\n if (e.candidate) {\n const parsedCandidate = SDPUtils.parseCandidate(e.candidate.candidate);\n if (parsedCandidate.type === 'relay') {\n // This is a libwebrtc-specific mapping of local type preference\n // to relayProtocol.\n e.candidate.relayProtocol = {\n 0: 'tls',\n 1: 'tcp',\n 2: 'udp',\n }[parsedCandidate.priority >> 24];\n }\n }\n return e;\n });\n}\n\nexport function shimMaxMessageSize(window, browserDetails) {\n if (!window.RTCPeerConnection) {\n return;\n }\n\n if (!('sctp' in window.RTCPeerConnection.prototype)) {\n Object.defineProperty(window.RTCPeerConnection.prototype, 'sctp', {\n get() {\n return typeof this._sctp === 'undefined' ? null : this._sctp;\n }\n });\n }\n\n const sctpInDescription = function(description) {\n if (!description || !description.sdp) {\n return false;\n }\n const sections = SDPUtils.splitSections(description.sdp);\n sections.shift();\n return sections.some(mediaSection => {\n const mLine = SDPUtils.parseMLine(mediaSection);\n return mLine && mLine.kind === 'application'\n && mLine.protocol.indexOf('SCTP') !== -1;\n });\n };\n\n const getRemoteFirefoxVersion = function(description) {\n // TODO: Is there a better solution for detecting Firefox?\n const match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\\d+)/);\n if (match === null || match.length < 2) {\n return -1;\n }\n const version = parseInt(match[1], 10);\n // Test for NaN (yes, this is ugly)\n return version !== version ? -1 : version;\n };\n\n const getCanSendMaxMessageSize = function(remoteIsFirefox) {\n // Every implementation we know can send at least 64 KiB.\n // Note: Although Chrome is technically able to send up to 256 KiB, the\n // data does not reach the other peer reliably.\n // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8419\n let canSendMaxMessageSize = 65536;\n if (browserDetails.browser === 'firefox') {\n if (browserDetails.version < 57) {\n if (remoteIsFirefox === -1) {\n // FF < 57 will send in 16 KiB chunks using the deprecated PPID\n // fragmentation.\n canSendMaxMessageSize = 16384;\n } else {\n // However, other FF (and RAWRTC) can reassemble PPID-fragmented\n // messages. Thus, supporting ~2 GiB when sending.\n canSendMaxMessageSize = 2147483637;\n }\n } else if (browserDetails.version < 60) {\n // Currently, all FF >= 57 will reset the remote maximum message size\n // to the default value when a data channel is created at a later\n // stage. :(\n // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831\n canSendMaxMessageSize =\n browserDetails.version === 57 ? 65535 : 65536;\n } else {\n // FF >= 60 supports sending ~2 GiB\n canSendMaxMessageSize = 2147483637;\n }\n }\n return canSendMaxMessageSize;\n };\n\n const getMaxMessageSize = function(description, remoteIsFirefox) {\n // Note: 65536 bytes is the default value from the SDP spec. Also,\n // every implementation we know supports receiving 65536 bytes.\n let maxMessageSize = 65536;\n\n // FF 57 has a slightly incorrect default remote max message size, so\n // we need to adjust it here to avoid a failure when sending.\n // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1425697\n if (browserDetails.browser === 'firefox'\n && browserDetails.version === 57) {\n maxMessageSize = 65535;\n }\n\n const match = SDPUtils.matchPrefix(description.sdp,\n 'a=max-message-size:');\n if (match.length > 0) {\n maxMessageSize = parseInt(match[0].substring(19), 10);\n } else if (browserDetails.browser === 'firefox' &&\n remoteIsFirefox !== -1) {\n // If the maximum message size is not present in the remote SDP and\n // both local and remote are Firefox, the remote peer can receive\n // ~2 GiB.\n maxMessageSize = 2147483637;\n }\n return maxMessageSize;\n };\n\n const origSetRemoteDescription =\n window.RTCPeerConnection.prototype.setRemoteDescription;\n window.RTCPeerConnection.prototype.setRemoteDescription =\n function setRemoteDescription() {\n this._sctp = null;\n // Chrome decided to not expose .sctp in plan-b mode.\n // As usual, adapter.js has to do an 'ugly worakaround'\n // to cover up the mess.\n if (browserDetails.browser === 'chrome' && browserDetails.version >= 76) {\n const {sdpSemantics} = this.getConfiguration();\n if (sdpSemantics === 'plan-b') {\n Object.defineProperty(this, 'sctp', {\n get() {\n return typeof this._sctp === 'undefined' ? null : this._sctp;\n },\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n if (sctpInDescription(arguments[0])) {\n // Check if the remote is FF.\n const isFirefox = getRemoteFirefoxVersion(arguments[0]);\n\n // Get the maximum message size the local peer is capable of sending\n const canSendMMS = getCanSendMaxMessageSize(isFirefox);\n\n // Get the maximum message size of the remote peer.\n const remoteMMS = getMaxMessageSize(arguments[0], isFirefox);\n\n // Determine final maximum message size\n let maxMessageSize;\n if (canSendMMS === 0 && remoteMMS === 0) {\n maxMessageSize = Number.POSITIVE_INFINITY;\n } else if (canSendMMS === 0 || remoteMMS === 0) {\n maxMessageSize = Math.max(canSendMMS, remoteMMS);\n } else {\n maxMessageSize = Math.min(canSendMMS, remoteMMS);\n }\n\n // Create a dummy RTCSctpTransport object and the 'maxMessageSize'\n // attribute.\n const sctp = {};\n Object.defineProperty(sctp, 'maxMessageSize', {\n get() {\n return maxMessageSize;\n }\n });\n this._sctp = sctp;\n }\n\n return origSetRemoteDescription.apply(this, arguments);\n };\n}\n\nexport function shimSendThrowTypeError(window) {\n if (!(window.RTCPeerConnection &&\n 'createDataChannel' in window.RTCPeerConnection.prototype)) {\n return;\n }\n\n // Note: Although Firefox >= 57 has a native implementation, the maximum\n // message size can be reset for all data channels at a later stage.\n // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831\n\n function wrapDcSend(dc, pc) {\n const origDataChannelSend = dc.send;\n dc.send = function send() {\n const data = arguments[0];\n const length = data.length || data.size || data.byteLength;\n if (dc.readyState === 'open' &&\n pc.sctp && length > pc.sctp.maxMessageSize) {\n throw new TypeError('Message too large (can send a maximum of ' +\n pc.sctp.maxMessageSize + ' bytes)');\n }\n return origDataChannelSend.apply(dc, arguments);\n };\n }\n const origCreateDataChannel =\n window.RTCPeerConnection.prototype.createDataChannel;\n window.RTCPeerConnection.prototype.createDataChannel =\n function createDataChannel() {\n const dataChannel = origCreateDataChannel.apply(this, arguments);\n wrapDcSend(dataChannel, this);\n return dataChannel;\n };\n utils.wrapPeerConnectionEvent(window, 'datachannel', e => {\n wrapDcSend(e.channel, e.target);\n return e;\n });\n}\n\n\n/* shims RTCConnectionState by pretending it is the same as iceConnectionState.\n * See https://bugs.chromium.org/p/webrtc/issues/detail?id=6145#c12\n * for why this is a valid hack in Chrome. In Firefox it is slightly incorrect\n * since DTLS failures would be hidden. See\n * https://bugzilla.mozilla.org/show_bug.cgi?id=1265827\n * for the Firefox tracking bug.\n */\nexport function shimConnectionState(window) {\n if (!window.RTCPeerConnection ||\n 'connectionState' in window.RTCPeerConnection.prototype) {\n return;\n }\n const proto = window.RTCPeerConnection.prototype;\n Object.defineProperty(proto, 'connectionState', {\n get() {\n return {\n completed: 'connected',\n checking: 'connecting'\n }[this.iceConnectionState] || this.iceConnectionState;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(proto, 'onconnectionstatechange', {\n get() {\n return this._onconnectionstatechange || null;\n },\n set(cb) {\n if (this._onconnectionstatechange) {\n this.removeEventListener('connectionstatechange',\n this._onconnectionstatechange);\n delete this._onconnectionstatechange;\n }\n if (cb) {\n this.addEventListener('connectionstatechange',\n this._onconnectionstatechange = cb);\n }\n },\n enumerable: true,\n configurable: true\n });\n\n ['setLocalDescription', 'setRemoteDescription'].forEach((method) => {\n const origMethod = proto[method];\n proto[method] = function() {\n if (!this._connectionstatechangepoly) {\n this._connectionstatechangepoly = e => {\n const pc = e.target;\n if (pc._lastConnectionState !== pc.connectionState) {\n pc._lastConnectionState = pc.connectionState;\n const newEvent = new Event('connectionstatechange', e);\n pc.dispatchEvent(newEvent);\n }\n return e;\n };\n this.addEventListener('iceconnectionstatechange',\n this._connectionstatechangepoly);\n }\n return origMethod.apply(this, arguments);\n };\n });\n}\n\nexport function removeExtmapAllowMixed(window, browserDetails) {\n /* remove a=extmap-allow-mixed for webrtc.org < M71 */\n if (!window.RTCPeerConnection) {\n return;\n }\n if (browserDetails.browser === 'chrome' && browserDetails.version >= 71) {\n return;\n }\n if (browserDetails.browser === 'safari' &&\n browserDetails._safariVersion >= 13.1) {\n return;\n }\n const nativeSRD = window.RTCPeerConnection.prototype.setRemoteDescription;\n window.RTCPeerConnection.prototype.setRemoteDescription =\n function setRemoteDescription(desc) {\n if (desc && desc.sdp && desc.sdp.indexOf('\\na=extmap-allow-mixed') !== -1) {\n const sdp = desc.sdp.split('\\n').filter((line) => {\n return line.trim() !== 'a=extmap-allow-mixed';\n }).join('\\n');\n // Safari enforces read-only-ness of RTCSessionDescription fields.\n if (window.RTCSessionDescription &&\n desc instanceof window.RTCSessionDescription) {\n arguments[0] = new window.RTCSessionDescription({\n type: desc.type,\n sdp,\n });\n } else {\n desc.sdp = sdp;\n }\n }\n return nativeSRD.apply(this, arguments);\n };\n}\n\nexport function shimAddIceCandidateNullOrEmpty(window, browserDetails) {\n // Support for addIceCandidate(null or undefined)\n // as well as addIceCandidate({candidate: \"\", ...})\n // https://bugs.chromium.org/p/chromium/issues/detail?id=978582\n // Note: must be called before other polyfills which change the signature.\n if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) {\n return;\n }\n const nativeAddIceCandidate =\n window.RTCPeerConnection.prototype.addIceCandidate;\n if (!nativeAddIceCandidate || nativeAddIceCandidate.length === 0) {\n return;\n }\n window.RTCPeerConnection.prototype.addIceCandidate =\n function addIceCandidate() {\n if (!arguments[0]) {\n if (arguments[1]) {\n arguments[1].apply(null);\n }\n return Promise.resolve();\n }\n // Firefox 68+ emits and processes {candidate: \"\", ...}, ignore\n // in older versions.\n // Native support for ignoring exists for Chrome M77+.\n // Safari ignores as well, exact version unknown but works in the same\n // version that also ignores addIceCandidate(null).\n if (((browserDetails.browser === 'chrome' && browserDetails.version < 78)\n || (browserDetails.browser === 'firefox'\n && browserDetails.version < 68)\n || (browserDetails.browser === 'safari'))\n && arguments[0] && arguments[0].candidate === '') {\n return Promise.resolve();\n }\n return nativeAddIceCandidate.apply(this, arguments);\n };\n}\n\n// Note: Make sure to call this ahead of APIs that modify\n// setLocalDescription.length\nexport function shimParameterlessSetLocalDescription(window, browserDetails) {\n if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) {\n return;\n }\n const nativeSetLocalDescription =\n window.RTCPeerConnection.prototype.setLocalDescription;\n if (!nativeSetLocalDescription || nativeSetLocalDescription.length === 0) {\n return;\n }\n window.RTCPeerConnection.prototype.setLocalDescription =\n function setLocalDescription() {\n let desc = arguments[0] || {};\n if (typeof desc !== 'object' || (desc.type && desc.sdp)) {\n return nativeSetLocalDescription.apply(this, arguments);\n }\n // The remaining steps should technically happen when SLD comes off the\n // RTCPeerConnection's operations chain (not ahead of going on it), but\n // this is too difficult to shim. Instead, this shim only covers the\n // common case where the operations chain is empty. This is imperfect, but\n // should cover many cases. Rationale: Even if we can't reduce the glare\n // window to zero on imperfect implementations, there's value in tapping\n // into the perfect negotiation pattern that several browsers support.\n desc = {type: desc.type, sdp: desc.sdp};\n if (!desc.type) {\n switch (this.signalingState) {\n case 'stable':\n case 'have-local-offer':\n case 'have-remote-pranswer':\n desc.type = 'offer';\n break;\n default:\n desc.type = 'answer';\n break;\n }\n }\n if (desc.sdp || (desc.type !== 'offer' && desc.type !== 'answer')) {\n return nativeSetLocalDescription.apply(this, [desc]);\n }\n const func = desc.type === 'offer' ? this.createOffer : this.createAnswer;\n return func.apply(this)\n .then(d => nativeSetLocalDescription.apply(this, [d]));\n };\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\nimport * as utils from './utils';\n\n// Browser shims.\nimport * as chromeShim from './chrome/chrome_shim';\nimport * as firefoxShim from './firefox/firefox_shim';\nimport * as safariShim from './safari/safari_shim';\nimport * as commonShim from './common_shim';\nimport * as sdp from 'sdp';\n\n// Shimming starts here.\nexport function adapterFactory({window} = {}, options = {\n shimChrome: true,\n shimFirefox: true,\n shimSafari: true,\n}) {\n // Utils.\n const logging = utils.log;\n const browserDetails = utils.detectBrowser(window);\n\n const adapter = {\n browserDetails,\n commonShim,\n extractVersion: utils.extractVersion,\n disableLog: utils.disableLog,\n disableWarnings: utils.disableWarnings,\n // Expose sdp as a convenience. For production apps include directly.\n sdp,\n };\n\n // Shim browser if found.\n switch (browserDetails.browser) {\n case 'chrome':\n if (!chromeShim || !chromeShim.shimPeerConnection ||\n !options.shimChrome) {\n logging('Chrome shim is not included in this adapter release.');\n return adapter;\n }\n if (browserDetails.version === null) {\n logging('Chrome shim can not determine version, not shimming.');\n return adapter;\n }\n logging('adapter.js shimming chrome.');\n // Export to the adapter global object visible in the browser.\n adapter.browserShim = chromeShim;\n\n // Must be called before shimPeerConnection.\n commonShim.shimAddIceCandidateNullOrEmpty(window, browserDetails);\n commonShim.shimParameterlessSetLocalDescription(window, browserDetails);\n\n chromeShim.shimGetUserMedia(window, browserDetails);\n chromeShim.shimMediaStream(window, browserDetails);\n chromeShim.shimPeerConnection(window, browserDetails);\n chromeShim.shimOnTrack(window, browserDetails);\n chromeShim.shimAddTrackRemoveTrack(window, browserDetails);\n chromeShim.shimGetSendersWithDtmf(window, browserDetails);\n chromeShim.shimSenderReceiverGetStats(window, browserDetails);\n chromeShim.fixNegotiationNeeded(window, browserDetails);\n\n commonShim.shimRTCIceCandidate(window, browserDetails);\n commonShim.shimRTCIceCandidateRelayProtocol(window, browserDetails);\n commonShim.shimConnectionState(window, browserDetails);\n commonShim.shimMaxMessageSize(window, browserDetails);\n commonShim.shimSendThrowTypeError(window, browserDetails);\n commonShim.removeExtmapAllowMixed(window, browserDetails);\n break;\n case 'firefox':\n if (!firefoxShim || !firefoxShim.shimPeerConnection ||\n !options.shimFirefox) {\n logging('Firefox shim is not included in this adapter release.');\n return adapter;\n }\n logging('adapter.js shimming firefox.');\n // Export to the adapter global object visible in the browser.\n adapter.browserShim = firefoxShim;\n\n // Must be called before shimPeerConnection.\n commonShim.shimAddIceCandidateNullOrEmpty(window, browserDetails);\n commonShim.shimParameterlessSetLocalDescription(window, browserDetails);\n\n firefoxShim.shimGetUserMedia(window, browserDetails);\n firefoxShim.shimPeerConnection(window, browserDetails);\n firefoxShim.shimOnTrack(window, browserDetails);\n firefoxShim.shimRemoveStream(window, browserDetails);\n firefoxShim.shimSenderGetStats(window, browserDetails);\n firefoxShim.shimReceiverGetStats(window, browserDetails);\n firefoxShim.shimRTCDataChannel(window, browserDetails);\n firefoxShim.shimAddTransceiver(window, browserDetails);\n firefoxShim.shimGetParameters(window, browserDetails);\n firefoxShim.shimCreateOffer(window, browserDetails);\n firefoxShim.shimCreateAnswer(window, browserDetails);\n\n commonShim.shimRTCIceCandidate(window, browserDetails);\n commonShim.shimConnectionState(window, browserDetails);\n commonShim.shimMaxMessageSize(window, browserDetails);\n commonShim.shimSendThrowTypeError(window, browserDetails);\n break;\n case 'safari':\n if (!safariShim || !options.shimSafari) {\n logging('Safari shim is not included in this adapter release.');\n return adapter;\n }\n logging('adapter.js shimming safari.');\n // Export to the adapter global object visible in the browser.\n adapter.browserShim = safariShim;\n\n // Must be called before shimCallbackAPI.\n commonShim.shimAddIceCandidateNullOrEmpty(window, browserDetails);\n commonShim.shimParameterlessSetLocalDescription(window, browserDetails);\n\n safariShim.shimRTCIceServerUrls(window, browserDetails);\n safariShim.shimCreateOfferLegacy(window, browserDetails);\n safariShim.shimCallbacksAPI(window, browserDetails);\n safariShim.shimLocalStreamsAPI(window, browserDetails);\n safariShim.shimRemoteStreamsAPI(window, browserDetails);\n safariShim.shimTrackEventTransceiver(window, browserDetails);\n safariShim.shimGetUserMedia(window, browserDetails);\n safariShim.shimAudioContext(window, browserDetails);\n\n commonShim.shimRTCIceCandidate(window, browserDetails);\n commonShim.shimRTCIceCandidateRelayProtocol(window, browserDetails);\n commonShim.shimMaxMessageSize(window, browserDetails);\n commonShim.shimSendThrowTypeError(window, browserDetails);\n commonShim.removeExtmapAllowMixed(window, browserDetails);\n break;\n default:\n logging('Unsupported browser!');\n break;\n }\n\n return adapter;\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n\n'use strict';\n\nimport {adapterFactory} from './adapter_factory.js';\n\nconst adapter =\n adapterFactory({window: typeof window === 'undefined' ? undefined : window});\nexport default adapter;\n", "export { util, type Util } from \"./util\";\nimport { Peer } from \"./peer\";\nimport { MsgPackPeer } from \"./msgPackPeer\";\n\nexport type { PeerEvents, PeerOptions } from \"./peer\";\n\nexport type {\n\tPeerJSOption,\n\tPeerConnectOption,\n\tAnswerOption,\n\tCallOption,\n} from \"./optionInterfaces\";\nexport type { UtilSupportsObj } from \"./util\";\nexport type { DataConnection } from \"./dataconnection/DataConnection\";\nexport type { MediaConnection } from \"./mediaconnection\";\nexport type { LogLevel } from \"./logger\";\nexport * from \"./enums\";\n\nexport { BufferedConnection } from \"./dataconnection/BufferedConnection/BufferedConnection\";\nexport { StreamConnection } from \"./dataconnection/StreamConnection/StreamConnection\";\nexport { MsgPack } from \"./dataconnection/StreamConnection/MsgPack\";\nexport type { SerializerMapping } from \"./peer\";\n\nexport { Peer, MsgPackPeer };\n\nexport { PeerError } from \"./peerError\";\nexport default Peer;\n", "import { BinaryPackChunker } from \"./dataconnection/BufferedConnection/binaryPackChunker\";\nimport * as BinaryPack from \"peerjs-js-binarypack\";\nimport { Supports } from \"./supports\";\nimport { validateId } from \"./utils/validateId\";\nimport { randomToken } from \"./utils/randomToken\";\n\nexport interface UtilSupportsObj {\n\t/**\n\t * The current browser.\n\t * This property can be useful in determining whether two peers can connect.\n\t *\n\t * ```ts\n\t * if (util.browser === 'firefox') {\n\t * // OK to peer with Firefox peers.\n\t * }\n\t * ```\n\t *\n\t * `util.browser` can currently have the values\n\t * `'firefox', 'chrome', 'safari', 'edge', 'Not a supported browser.', 'Not a browser.' (unknown WebRTC-compatible agent).\n\t */\n\tbrowser: boolean;\n\twebRTC: boolean;\n\t/**\n\t * True if the current browser supports media streams and PeerConnection.\n\t */\n\taudioVideo: boolean;\n\t/**\n\t * True if the current browser supports DataChannel and PeerConnection.\n\t */\n\tdata: boolean;\n\tbinaryBlob: boolean;\n\t/**\n\t * True if the current browser supports reliable DataChannels.\n\t */\n\treliable: boolean;\n}\n\nconst DEFAULT_CONFIG = {\n\ticeServers: [\n\t\t{ urls: \"stun:stun.l.google.com:19302\" },\n\t\t{\n\t\t\turls: [\n\t\t\t\t\"turn:eu-0.turn.peerjs.com:3478\",\n\t\t\t\t\"turn:us-0.turn.peerjs.com:3478\",\n\t\t\t],\n\t\t\tusername: \"peerjs\",\n\t\t\tcredential: \"peerjsp\",\n\t\t},\n\t],\n\tsdpSemantics: \"unified-plan\",\n};\n\nexport class Util extends BinaryPackChunker {\n\tnoop(): void {}\n\n\treadonly CLOUD_HOST = \"0.peerjs.com\";\n\treadonly CLOUD_PORT = 443;\n\n\t// Browsers that need chunking:\n\treadonly chunkedBrowsers = { Chrome: 1, chrome: 1 };\n\n\t// Returns browser-agnostic default config\n\treadonly defaultConfig = DEFAULT_CONFIG;\n\n\treadonly browser = Supports.getBrowser();\n\treadonly browserVersion = Supports.getVersion();\n\n\tpack = BinaryPack.pack;\n\tunpack = BinaryPack.unpack;\n\n\t/**\n\t * A hash of WebRTC features mapped to booleans that correspond to whether the feature is supported by the current browser.\n\t *\n\t * :::caution\n\t * Only the properties documented here are guaranteed to be present on `util.supports`\n\t * :::\n\t */\n\treadonly supports = (function () {\n\t\tconst supported: UtilSupportsObj = {\n\t\t\tbrowser: Supports.isBrowserSupported(),\n\t\t\twebRTC: Supports.isWebRTCSupported(),\n\t\t\taudioVideo: false,\n\t\t\tdata: false,\n\t\t\tbinaryBlob: false,\n\t\t\treliable: false,\n\t\t};\n\n\t\tif (!supported.webRTC) return supported;\n\n\t\tlet pc: RTCPeerConnection;\n\n\t\ttry {\n\t\t\tpc = new RTCPeerConnection(DEFAULT_CONFIG);\n\n\t\t\tsupported.audioVideo = true;\n\n\t\t\tlet dc: RTCDataChannel;\n\n\t\t\ttry {\n\t\t\t\tdc = pc.createDataChannel(\"_PEERJSTEST\", { ordered: true });\n\t\t\t\tsupported.data = true;\n\t\t\t\tsupported.reliable = !!dc.ordered;\n\n\t\t\t\t// Binary test\n\t\t\t\ttry {\n\t\t\t\t\tdc.binaryType = \"blob\";\n\t\t\t\t\tsupported.binaryBlob = !Supports.isIOS;\n\t\t\t\t} catch (e) {}\n\t\t\t} catch (e) {\n\t\t\t} finally {\n\t\t\t\tif (dc) {\n\t\t\t\t\tdc.close();\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t} finally {\n\t\t\tif (pc) {\n\t\t\t\tpc.close();\n\t\t\t}\n\t\t}\n\n\t\treturn supported;\n\t})();\n\n\t// Ensure alphanumeric ids\n\tvalidateId = validateId;\n\trandomToken = randomToken;\n\n\tblobToArrayBuffer(\n\t\tblob: Blob,\n\t\tcb: (arg: ArrayBuffer | null) => void,\n\t): FileReader {\n\t\tconst fr = new FileReader();\n\n\t\tfr.onload = function (evt) {\n\t\t\tif (evt.target) {\n\t\t\t\tcb(evt.target.result as ArrayBuffer);\n\t\t\t}\n\t\t};\n\n\t\tfr.readAsArrayBuffer(blob);\n\n\t\treturn fr;\n\t}\n\n\tbinaryStringToArrayBuffer(binary: string): ArrayBuffer | SharedArrayBuffer {\n\t\tconst byteArray = new Uint8Array(binary.length);\n\n\t\tfor (let i = 0; i < binary.length; i++) {\n\t\t\tbyteArray[i] = binary.charCodeAt(i) & 0xff;\n\t\t}\n\n\t\treturn byteArray.buffer;\n\t}\n\tisSecure(): boolean {\n\t\treturn location.protocol === \"https:\";\n\t}\n}\n\n/**\n * Provides a variety of helpful utilities.\n *\n * :::caution\n * Only the utilities documented here are guaranteed to be present on `util`.\n * Undocumented utilities can be removed without warning.\n * We don't consider these to be breaking changes.\n * :::\n */\nexport const util = new Util();\n", "export class BinaryPackChunker {\n\treadonly chunkedMTU = 16300; // The original 60000 bytes setting does not work when sending data from Firefox to Chrome, which is \"cut off\" after 16384 bytes and delivered individually.\n\n\t// Binary stuff\n\n\tprivate _dataCount: number = 1;\n\n\tchunk = (\n\t\tblob: ArrayBuffer,\n\t): { __peerData: number; n: number; total: number; data: Uint8Array }[] => {\n\t\tconst chunks = [];\n\t\tconst size = blob.byteLength;\n\t\tconst total = Math.ceil(size / this.chunkedMTU);\n\n\t\tlet index = 0;\n\t\tlet start = 0;\n\n\t\twhile (start < size) {\n\t\t\tconst end = Math.min(size, start + this.chunkedMTU);\n\t\t\tconst b = blob.slice(start, end);\n\n\t\t\tconst chunk = {\n\t\t\t\t__peerData: this._dataCount,\n\t\t\t\tn: index,\n\t\t\t\tdata: b,\n\t\t\t\ttotal,\n\t\t\t};\n\n\t\t\tchunks.push(chunk);\n\n\t\t\tstart = end;\n\t\t\tindex++;\n\t\t}\n\n\t\tthis._dataCount++;\n\n\t\treturn chunks;\n\t};\n}\n\nexport function concatArrayBuffers(bufs: Uint8Array[]) {\n\tlet size = 0;\n\tfor (const buf of bufs) {\n\t\tsize += buf.byteLength;\n\t}\n\tconst result = new Uint8Array(size);\n\tlet offset = 0;\n\tfor (const buf of bufs) {\n\t\tresult.set(buf, offset);\n\t\toffset += buf.byteLength;\n\t}\n\treturn result;\n}\n", "import webRTCAdapter_import from \"webrtc-adapter\";\n\nconst webRTCAdapter: typeof webRTCAdapter_import =\n\t//@ts-ignore\n\twebRTCAdapter_import.default || webRTCAdapter_import;\n\nexport const Supports = new (class {\n\treadonly isIOS =\n\t\ttypeof navigator !== \"undefined\"\n\t\t\t? [\"iPad\", \"iPhone\", \"iPod\"].includes(navigator.platform)\n\t\t\t: false;\n\treadonly supportedBrowsers = [\"firefox\", \"chrome\", \"safari\"];\n\n\treadonly minFirefoxVersion = 59;\n\treadonly minChromeVersion = 72;\n\treadonly minSafariVersion = 605;\n\n\tisWebRTCSupported(): boolean {\n\t\treturn typeof RTCPeerConnection !== \"undefined\";\n\t}\n\n\tisBrowserSupported(): boolean {\n\t\tconst browser = this.getBrowser();\n\t\tconst version = this.getVersion();\n\n\t\tconst validBrowser = this.supportedBrowsers.includes(browser);\n\n\t\tif (!validBrowser) return false;\n\n\t\tif (browser === \"chrome\") return version >= this.minChromeVersion;\n\t\tif (browser === \"firefox\") return version >= this.minFirefoxVersion;\n\t\tif (browser === \"safari\")\n\t\t\treturn !this.isIOS && version >= this.minSafariVersion;\n\n\t\treturn false;\n\t}\n\n\tgetBrowser(): string {\n\t\treturn webRTCAdapter.browserDetails.browser;\n\t}\n\n\tgetVersion(): number {\n\t\treturn webRTCAdapter.browserDetails.version || 0;\n\t}\n\n\tisUnifiedPlanSupported(): boolean {\n\t\tconst browser = this.getBrowser();\n\t\tconst version = webRTCAdapter.browserDetails.version || 0;\n\n\t\tif (browser === \"chrome\" && version < this.minChromeVersion) return false;\n\t\tif (browser === \"firefox\" && version >= this.minFirefoxVersion) return true;\n\t\tif (\n\t\t\t!window.RTCRtpTransceiver ||\n\t\t\t!(\"currentDirection\" in RTCRtpTransceiver.prototype)\n\t\t)\n\t\t\treturn false;\n\n\t\tlet tempPc: RTCPeerConnection;\n\t\tlet supported = false;\n\n\t\ttry {\n\t\t\ttempPc = new RTCPeerConnection();\n\t\t\ttempPc.addTransceiver(\"audio\");\n\t\t\tsupported = true;\n\t\t} catch (e) {\n\t\t} finally {\n\t\t\tif (tempPc) {\n\t\t\t\ttempPc.close();\n\t\t\t}\n\t\t}\n\n\t\treturn supported;\n\t}\n\n\ttoString(): string {\n\t\treturn `Supports:\n browser:${this.getBrowser()}\n version:${this.getVersion()}\n isIOS:${this.isIOS}\n isWebRTCSupported:${this.isWebRTCSupported()}\n isBrowserSupported:${this.isBrowserSupported()}\n isUnifiedPlanSupported:${this.isUnifiedPlanSupported()}`;\n\t}\n})();\n", "export const validateId = (id: string): boolean => {\n\t// Allow empty ids\n\treturn !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(id);\n};\n", "export const randomToken = () => Math.random().toString(36).slice(2);\n", "import { util } from \"./util\";\nimport logger, { LogLevel } from \"./logger\";\nimport { Socket } from \"./socket\";\nimport { MediaConnection } from \"./mediaconnection\";\nimport type { DataConnection } from \"./dataconnection/DataConnection\";\nimport {\n\tConnectionType,\n\tPeerErrorType,\n\tServerMessageType,\n\tSocketEventType,\n} from \"./enums\";\nimport type { ServerMessage } from \"./servermessage\";\nimport { API } from \"./api\";\nimport type {\n\tCallOption,\n\tPeerConnectOption,\n\tPeerJSOption,\n} from \"./optionInterfaces\";\nimport { BinaryPack } from \"./dataconnection/BufferedConnection/BinaryPack\";\nimport { Raw } from \"./dataconnection/BufferedConnection/Raw\";\nimport { Json } from \"./dataconnection/BufferedConnection/Json\";\n\nimport { EventEmitterWithError, PeerError } from \"./peerError\";\n\nclass PeerOptions implements PeerJSOption {\n\t/**\n\t * Prints log messages depending on the debug level passed in.\n\t */\n\tdebug?: LogLevel;\n\t/**\n\t * Server host. Defaults to `0.peerjs.com`.\n\t * Also accepts `'/'` to signify relative hostname.\n\t */\n\thost?: string;\n\t/**\n\t * Server port. Defaults to `443`.\n\t */\n\tport?: number;\n\t/**\n\t * The path where your self-hosted PeerServer is running. Defaults to `'/'`\n\t */\n\tpath?: string;\n\t/**\n\t * API key for the PeerServer.\n\t * This is not used anymore.\n\t * @deprecated\n\t */\n\tkey?: string;\n\ttoken?: string;\n\t/**\n\t * Configuration hash passed to RTCPeerConnection.\n\t * This hash contains any custom ICE/TURN server configuration.\n\t *\n\t * Defaults to {@apilink util.defaultConfig}\n\t */\n\tconfig?: any;\n\t/**\n\t * Set to true `true` if you're using TLS.\n\t * :::danger\n\t * If possible *always use TLS*\n\t * :::\n\t */\n\tsecure?: boolean;\n\tpingInterval?: number;\n\treferrerPolicy?: ReferrerPolicy;\n\tlogFunction?: (logLevel: LogLevel, ...rest: any[]) => void;\n\tserializers?: SerializerMapping;\n}\n\nexport { type PeerOptions };\n\nexport interface SerializerMapping {\n\t[key: string]: new (\n\t\tpeerId: string,\n\t\tprovider: Peer,\n\t\toptions: any,\n\t) => DataConnection;\n}\n\nexport interface PeerEvents {\n\t/**\n\t * Emitted when a connection to the PeerServer is established.\n\t *\n\t * You may use the peer before this is emitted, but messages to the server will be queued. <code>id</code> is the brokering ID of the peer (which was either provided in the constructor or assigned by the server).<span class='tip'>You should not wait for this event before connecting to other peers if connection speed is important.</span>\n\t */\n\topen: (id: string) => void;\n\t/**\n\t * Emitted when a new data connection is established from a remote peer.\n\t */\n\tconnection: (dataConnection: DataConnection) => void;\n\t/**\n\t * Emitted when a remote peer attempts to call you.\n\t */\n\tcall: (mediaConnection: MediaConnection) => void;\n\t/**\n\t * Emitted when the peer is destroyed and can no longer accept or create any new connections.\n\t */\n\tclose: () => void;\n\t/**\n\t * Emitted when the peer is disconnected from the signalling server\n\t */\n\tdisconnected: (currentId: string) => void;\n\t/**\n\t * Errors on the peer are almost always fatal and will destroy the peer.\n\t *\n\t * Errors from the underlying socket and PeerConnections are forwarded here.\n\t */\n\terror: (error: PeerError<`${PeerErrorType}`>) => void;\n}\n/**\n * A peer who can initiate connections with other peers.\n */\nexport class Peer extends EventEmitterWithError<PeerErrorType, PeerEvents> {\n\tprivate static readonly DEFAULT_KEY = \"peerjs\";\n\n\tprotected readonly _serializers: SerializerMapping = {\n\t\traw: Raw,\n\t\tjson: Json,\n\t\tbinary: BinaryPack,\n\t\t\"binary-utf8\": BinaryPack,\n\n\t\tdefault: BinaryPack,\n\t};\n\tprivate readonly _options: PeerOptions;\n\tprivate readonly _api: API;\n\tprivate readonly _socket: Socket;\n\n\tprivate _id: string | null = null;\n\tprivate _lastServerId: string | null = null;\n\n\t// States.\n\tprivate _destroyed = false; // Connections have been killed\n\tprivate _disconnected = false; // Connection to PeerServer killed but P2P connections still active\n\tprivate _open = false; // Sockets and such are not yet open.\n\tprivate readonly _connections: Map<\n\t\tstring,\n\t\t(DataConnection | MediaConnection)[]\n\t> = new Map(); // All connections for this peer.\n\tprivate readonly _lostMessages: Map<string, ServerMessage[]> = new Map(); // src => [list of messages]\n\t/**\n\t * The brokering ID of this peer\n\t *\n\t * If no ID was specified in {@apilink Peer | the constructor},\n\t * this will be `undefined` until the {@apilink PeerEvents | `open`} event is emitted.\n\t */\n\tget id() {\n\t\treturn this._id;\n\t}\n\n\tget options() {\n\t\treturn this._options;\n\t}\n\n\tget open() {\n\t\treturn this._open;\n\t}\n\n\t/**\n\t * @internal\n\t */\n\tget socket() {\n\t\treturn this._socket;\n\t}\n\n\t/**\n\t * A hash of all connections associated with this peer, keyed by the remote peer's ID.\n\t * @deprecated\n\t * Return type will change from Object to Map<string,[]>\n\t */\n\tget connections(): Object {\n\t\tconst plainConnections = Object.create(null);\n\n\t\tfor (const [k, v] of this._connections) {\n\t\t\tplainConnections[k] = v;\n\t\t}\n\n\t\treturn plainConnections;\n\t}\n\n\t/**\n\t * true if this peer and all of its connections can no longer be used.\n\t */\n\tget destroyed() {\n\t\treturn this._destroyed;\n\t}\n\t/**\n\t * false if there is an active connection to the PeerServer.\n\t */\n\tget disconnected() {\n\t\treturn this._disconnected;\n\t}\n\n\t/**\n\t * A peer can connect to other peers and listen for connections.\n\t */\n\tconstructor();\n\n\t/**\n\t * A peer can connect to other peers and listen for connections.\n\t * @param options for specifying details about PeerServer\n\t */\n\tconstructor(options: PeerOptions);\n\n\t/**\n\t * A peer can connect to other peers and listen for connections.\n\t * @param id Other peers can connect to this peer using the provided ID.\n\t * If no ID is given, one will be generated by the brokering server.\n\t * The ID must start and end with an alphanumeric character (lower or upper case character or a digit). In the middle of the ID spaces, dashes (-) and underscores (_) are allowed. Use {@apilink PeerOptions.metadata } to send identifying information.\n\t * @param options for specifying details about PeerServer\n\t */\n\tconstructor(id: string, options?: PeerOptions);\n\n\tconstructor(id?: string | PeerOptions, options?: PeerOptions) {\n\t\tsuper();\n\n\t\tlet userId: string | undefined;\n\n\t\t// Deal with overloading\n\t\tif (id && id.constructor == Object) {\n\t\t\toptions = id as PeerOptions;\n\t\t} else if (id) {\n\t\t\tuserId = id.toString();\n\t\t}\n\n\t\t// Configurize options\n\t\toptions = {\n\t\t\tdebug: 0, // 1: Errors, 2: Warnings, 3: All logs\n\t\t\thost: util.CLOUD_HOST,\n\t\t\tport: util.CLOUD_PORT,\n\t\t\tpath: \"/\",\n\t\t\tkey: Peer.DEFAULT_KEY,\n\t\t\ttoken: util.randomToken(),\n\t\t\tconfig: util.defaultConfig,\n\t\t\treferrerPolicy: \"strict-origin-when-cross-origin\",\n\t\t\tserializers: {},\n\t\t\t...options,\n\t\t};\n\t\tthis._options = options;\n\t\tthis._serializers = { ...this._serializers, ...this.options.serializers };\n\n\t\t// Detect relative URL host.\n\t\tif (this._options.host === \"/\") {\n\t\t\tthis._options.host = window.location.hostname;\n\t\t}\n\n\t\t// Set path correctly.\n\t\tif (this._options.path) {\n\t\t\tif (this._options.path[0] !== \"/\") {\n\t\t\t\tthis._options.path = \"/\" + this._options.path;\n\t\t\t}\n\t\t\tif (this._options.path[this._options.path.length - 1] !== \"/\") {\n\t\t\t\tthis._options.path += \"/\";\n\t\t\t}\n\t\t}\n\n\t\t// Set whether we use SSL to same as current host\n\t\tif (\n\t\t\tthis._options.secure === undefined &&\n\t\t\tthis._options.host !== util.CLOUD_HOST\n\t\t) {\n\t\t\tthis._options.secure = util.isSecure();\n\t\t} else if (this._options.host == util.CLOUD_HOST) {\n\t\t\tthis._options.secure = true;\n\t\t}\n\t\t// Set a custom log function if present\n\t\tif (this._options.logFunction) {\n\t\t\tlogger.setLogFunction(this._options.logFunction);\n\t\t}\n\n\t\tlogger.logLevel = this._options.debug || 0;\n\n\t\tthis._api = new API(options);\n\t\tthis._socket = this._createServerConnection();\n\n\t\t// Sanity checks\n\t\t// Ensure WebRTC supported\n\t\tif (!util.supports.audioVideo && !util.supports.data) {\n\t\t\tthis._delayedAbort(\n\t\t\t\tPeerErrorType.BrowserIncompatible,\n\t\t\t\t\"The current browser does not support WebRTC\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// Ensure alphanumeric id\n\t\tif (!!userId && !util.validateId(userId)) {\n\t\t\tthis._delayedAbort(PeerErrorType.InvalidID, `ID \"${userId}\" is invalid`);\n\t\t\treturn;\n\t\t}\n\n\t\tif (userId) {\n\t\t\tthis._initialize(userId);\n\t\t} else {\n\t\t\tthis._api\n\t\t\t\t.retrieveId()\n\t\t\t\t.then((id) => this._initialize(id))\n\t\t\t\t.catch((error) => this._abort(PeerErrorType.ServerError, error));\n\t\t}\n\t}\n\n\tprivate _createServerConnection(): Socket {\n\t\tconst socket = new Socket(\n\t\t\tthis._options.secure,\n\t\t\tthis._options.host!,\n\t\t\tthis._options.port!,\n\t\t\tthis._options.path!,\n\t\t\tthis._options.key!,\n\t\t\tthis._options.pingInterval,\n\t\t);\n\n\t\tsocket.on(SocketEventType.Message, (data: ServerMessage) => {\n\t\t\tthis._handleMessage(data);\n\t\t});\n\n\t\tsocket.on(SocketEventType.Error, (error: string) => {\n\t\t\tthis._abort(PeerErrorType.SocketError, error);\n\t\t});\n\n\t\tsocket.on(SocketEventType.Disconnected, () => {\n\t\t\tif (this.disconnected) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.emitError(PeerErrorType.Network, \"Lost connection to server.\");\n\t\t\tthis.disconnect();\n\t\t});\n\n\t\tsocket.on(SocketEventType.Close, () => {\n\t\t\tif (this.disconnected) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._abort(\n\t\t\t\tPeerErrorType.SocketClosed,\n\t\t\t\t\"Underlying socket is already closed.\",\n\t\t\t);\n\t\t});\n\n\t\treturn socket;\n\t}\n\n\t/** Initialize a connection with the server. */\n\tprivate _initialize(id: string): void {\n\t\tthis._id = id;\n\t\tthis.socket.start(id, this._options.token!);\n\t}\n\n\t/** Handles messages from the server. */\n\tprivate _handleMessage(message: ServerMessage): void {\n\t\tconst type = message.type;\n\t\tconst payload = message.payload;\n\t\tconst peerId = message.src;\n\n\t\tswitch (type) {\n\t\t\tcase ServerMessageType.Open: // The connection to the server is open.\n\t\t\t\tthis._lastServerId = this.id;\n\t\t\t\tthis._open = true;\n\t\t\t\tthis.emit(\"open\", this.id);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Error: // Server error.\n\t\t\t\tthis._abort(PeerErrorType.ServerError, payload.msg);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.IdTaken: // The selected ID is taken.\n\t\t\t\tthis._abort(PeerErrorType.UnavailableID, `ID \"${this.id}\" is taken`);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.InvalidKey: // The given API key cannot be found.\n\t\t\t\tthis._abort(\n\t\t\t\t\tPeerErrorType.InvalidKey,\n\t\t\t\t\t`API KEY \"${this._options.key}\" is invalid`,\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Leave: // Another peer has closed its connection to this peer.\n\t\t\t\tlogger.log(`Received leave message from ${peerId}`);\n\t\t\t\tthis._cleanupPeer(peerId);\n\t\t\t\tthis._connections.delete(peerId);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Expire: // The offer sent to a peer has expired without response.\n\t\t\t\tthis.emitError(\n\t\t\t\t\tPeerErrorType.PeerUnavailable,\n\t\t\t\t\t`Could not connect to peer ${peerId}`,\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Offer: {\n\t\t\t\t// we should consider switching this to CALL/CONNECT, but this is the least breaking option.\n\t\t\t\tconst connectionId = payload.connectionId;\n\t\t\t\tlet connection = this.getConnection(peerId, connectionId);\n\n\t\t\t\tif (connection) {\n\t\t\t\t\tconnection.close();\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t`Offer received for existing Connection ID:${connectionId}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Create a new connection.\n\t\t\t\tif (payload.type === ConnectionType.Media) {\n\t\t\t\t\tconst mediaConnection = new MediaConnection(peerId, this, {\n\t\t\t\t\t\tconnectionId: connectionId,\n\t\t\t\t\t\t_payload: payload,\n\t\t\t\t\t\tmetadata: payload.metadata,\n\t\t\t\t\t});\n\t\t\t\t\tconnection = mediaConnection;\n\t\t\t\t\tthis._addConnection(peerId, connection);\n\t\t\t\t\tthis.emit(\"call\", mediaConnection);\n\t\t\t\t} else if (payload.type === ConnectionType.Data) {\n\t\t\t\t\tconst dataConnection = new this._serializers[payload.serialization](\n\t\t\t\t\t\tpeerId,\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconnectionId: connectionId,\n\t\t\t\t\t\t\t_payload: payload,\n\t\t\t\t\t\t\tmetadata: payload.metadata,\n\t\t\t\t\t\t\tlabel: payload.label,\n\t\t\t\t\t\t\tserialization: payload.serialization,\n\t\t\t\t\t\t\treliable: payload.reliable,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\tconnection = dataConnection;\n\n\t\t\t\t\tthis._addConnection(peerId, connection);\n\t\t\t\t\tthis.emit(\"connection\", dataConnection);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn(`Received malformed connection type:${payload.type}`);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Find messages.\n\t\t\t\tconst messages = this._getMessages(connectionId);\n\t\t\t\tfor (const message of messages) {\n\t\t\t\t\tconnection.handleMessage(message);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tif (!payload) {\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t`You received a malformed message from ${peerId} of type ${type}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst connectionId = payload.connectionId;\n\t\t\t\tconst connection = this.getConnection(peerId, connectionId);\n\n\t\t\t\tif (connection && connection.peerConnection) {\n\t\t\t\t\t// Pass it on.\n\t\t\t\t\tconnection.handleMessage(message);\n\t\t\t\t} else if (connectionId) {\n\t\t\t\t\t// Store for possible later use\n\t\t\t\t\tthis._storeMessage(connectionId, message);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn(\"You received an unrecognized message:\", message);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Stores messages without a set up connection, to be claimed later. */\n\tprivate _storeMessage(connectionId: string, message: ServerMessage): void {\n\t\tif (!this._lostMessages.has(connectionId)) {\n\t\t\tthis._lostMessages.set(connectionId, []);\n\t\t}\n\n\t\tthis._lostMessages.get(connectionId).push(message);\n\t}\n\n\t/**\n\t * Retrieve messages from lost message store\n\t * @internal\n\t */\n\t//TODO Change it to private\n\tpublic _getMessages(connectionId: string): ServerMessage[] {\n\t\tconst messages = this._lostMessages.get(connectionId);\n\n\t\tif (messages) {\n\t\t\tthis._lostMessages.delete(connectionId);\n\t\t\treturn messages;\n\t\t}\n\n\t\treturn [];\n\t}\n\n\t/**\n\t * Connects to the remote peer specified by id and returns a data connection.\n\t * @param peer The brokering ID of the remote peer (their {@apilink Peer.id}).\n\t * @param options for specifying details about Peer Connection\n\t */\n\tconnect(peer: string, options: PeerConnectOption = {}): DataConnection {\n\t\toptions = {\n\t\t\tserialization: \"default\",\n\t\t\t...options,\n\t\t};\n\t\tif (this.disconnected) {\n\t\t\tlogger.warn(\n\t\t\t\t\"You cannot connect to a new Peer because you called \" +\n\t\t\t\t\t\".disconnect() on this Peer and ended your connection with the \" +\n\t\t\t\t\t\"server. You can create a new Peer to reconnect, or call reconnect \" +\n\t\t\t\t\t\"on this peer if you believe its ID to still be available.\",\n\t\t\t);\n\t\t\tthis.emitError(\n\t\t\t\tPeerErrorType.Disconnected,\n\t\t\t\t\"Cannot connect to new Peer after disconnecting from server.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst dataConnection = new this._serializers[options.serialization](\n\t\t\tpeer,\n\t\t\tthis,\n\t\t\toptions,\n\t\t);\n\t\tthis._addConnection(peer, dataConnection);\n\t\treturn dataConnection;\n\t}\n\n\t/**\n\t * Calls the remote peer specified by id and returns a media connection.\n\t * @param peer The brokering ID of the remote peer (their peer.id).\n\t * @param stream The caller's media stream\n\t * @param options Metadata associated with the connection, passed in by whoever initiated the connection.\n\t */\n\tcall(\n\t\tpeer: string,\n\t\tstream: MediaStream,\n\t\toptions: CallOption = {},\n\t): MediaConnection {\n\t\tif (this.disconnected) {\n\t\t\tlogger.warn(\n\t\t\t\t\"You cannot connect to a new Peer because you called \" +\n\t\t\t\t\t\".disconnect() on this Peer and ended your connection with the \" +\n\t\t\t\t\t\"server. You can create a new Peer to reconnect.\",\n\t\t\t);\n\t\t\tthis.emitError(\n\t\t\t\tPeerErrorType.Disconnected,\n\t\t\t\t\"Cannot connect to new Peer after disconnecting from server.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!stream) {\n\t\t\tlogger.error(\n\t\t\t\t\"To call a peer, you must provide a stream from your browser's `getUserMedia`.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst mediaConnection = new MediaConnection(peer, this, {\n\t\t\t...options,\n\t\t\t_stream: stream,\n\t\t});\n\t\tthis._addConnection(peer, mediaConnection);\n\t\treturn mediaConnection;\n\t}\n\n\t/** Add a data/media connection to this peer. */\n\tprivate _addConnection(\n\t\tpeerId: string,\n\t\tconnection: MediaConnection | DataConnection,\n\t): void {\n\t\tlogger.log(\n\t\t\t`add connection ${connection.type}:${connection.connectionId} to peerId:${peerId}`,\n\t\t);\n\n\t\tif (!this._connections.has(peerId)) {\n\t\t\tthis._connections.set(peerId, []);\n\t\t}\n\t\tthis._connections.get(peerId).push(connection);\n\t}\n\n\t//TODO should be private\n\t_removeConnection(connection: DataConnection | MediaConnection): void {\n\t\tconst connections = this._connections.get(connection.peer);\n\n\t\tif (connections) {\n\t\t\tconst index = connections.indexOf(connection);\n\n\t\t\tif (index !== -1) {\n\t\t\t\tconnections.splice(index, 1);\n\t\t\t}\n\t\t}\n\n\t\t//remove from lost messages\n\t\tthis._lostMessages.delete(connection.connectionId);\n\t}\n\n\t/** Retrieve a data/media connection for this peer. */\n\tgetConnection(\n\t\tpeerId: string,\n\t\tconnectionId: string,\n\t): null | DataConnection | MediaConnection {\n\t\tconst connections = this._connections.get(peerId);\n\t\tif (!connections) {\n\t\t\treturn null;\n\t\t}\n\n\t\tfor (const connection of connections) {\n\t\t\tif (connection.connectionId === connectionId) {\n\t\t\t\treturn connection;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tprivate _delayedAbort(type: PeerErrorType, message: string | Error): void {\n\t\tsetTimeout(() => {\n\t\t\tthis._abort(type, message);\n\t\t}, 0);\n\t}\n\n\t/**\n\t * Emits an error message and destroys the Peer.\n\t * The Peer is not destroyed if it's in a disconnected state, in which case\n\t * it retains its disconnected state and its existing connections.\n\t */\n\tprivate _abort(type: PeerErrorType, message: string | Error): void {\n\t\tlogger.error(\"Aborting!\");\n\n\t\tthis.emitError(type, message);\n\n\t\tif (!this._lastServerId) {\n\t\t\tthis.destroy();\n\t\t} else {\n\t\t\tthis.disconnect();\n\t\t}\n\t}\n\n\t/**\n\t * Destroys the Peer: closes all active connections as well as the connection\n\t * to the server.\n\t *\n\t * :::caution\n\t * This cannot be undone; the respective peer object will no longer be able\n\t * to create or receive any connections, its ID will be forfeited on the server,\n\t * and all of its data and media connections will be closed.\n\t * :::\n\t */\n\tdestroy(): void {\n\t\tif (this.destroyed) {\n\t\t\treturn;\n\t\t}\n\n\t\tlogger.log(`Destroy peer with ID:${this.id}`);\n\n\t\tthis.disconnect();\n\t\tthis._cleanup();\n\n\t\tthis._destroyed = true;\n\n\t\tthis.emit(\"close\");\n\t}\n\n\t/** Disconnects every connection on this peer. */\n\tprivate _cleanup(): void {\n\t\tfor (const peerId of this._connections.keys()) {\n\t\t\tthis._cleanupPeer(peerId);\n\t\t\tthis._connections.delete(peerId);\n\t\t}\n\n\t\tthis.socket.removeAllListeners();\n\t}\n\n\t/** Closes all connections to this peer. */\n\tprivate _cleanupPeer(peerId: string): void {\n\t\tconst connections = this._connections.get(peerId);\n\n\t\tif (!connections) return;\n\n\t\tfor (const connection of connections) {\n\t\t\tconnection.close();\n\t\t}\n\t}\n\n\t/**\n\t * Disconnects the Peer's connection to the PeerServer. Does not close any\n\t * active connections.\n\t * Warning: The peer can no longer create or accept connections after being\n\t * disconnected. It also cannot reconnect to the server.\n\t */\n\tdisconnect(): void {\n\t\tif (this.disconnected) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst currentId = this.id;\n\n\t\tlogger.log(`Disconnect peer with ID:${currentId}`);\n\n\t\tthis._disconnected = true;\n\t\tthis._open = false;\n\n\t\tthis.socket.close();\n\n\t\tthis._lastServerId = currentId;\n\t\tthis._id = null;\n\n\t\tthis.emit(\"disconnected\", currentId);\n\t}\n\n\t/** Attempts to reconnect with the same ID.\n\t *\n\t * Only {@apilink Peer.disconnect | disconnected peers} can be reconnected.\n\t * Destroyed peers cannot be reconnected.\n\t * If the connection fails (as an example, if the peer's old ID is now taken),\n\t * the peer's existing connections will not close, but any associated errors events will fire.\n\t */\n\treconnect(): void {\n\t\tif (this.disconnected && !this.destroyed) {\n\t\t\tlogger.log(\n\t\t\t\t`Attempting reconnection to server with ID ${this._lastServerId}`,\n\t\t\t);\n\t\t\tthis._disconnected = false;\n\t\t\tthis._initialize(this._lastServerId!);\n\t\t} else if (this.destroyed) {\n\t\t\tthrow new Error(\n\t\t\t\t\"This peer cannot reconnect to the server. It has already been destroyed.\",\n\t\t\t);\n\t\t} else if (!this.disconnected && !this.open) {\n\t\t\t// Do nothing. We're still connecting the first time.\n\t\t\tlogger.error(\n\t\t\t\t\"In a hurry? We're still trying to make the initial connection!\",\n\t\t\t);\n\t\t} else {\n\t\t\tthrow new Error(\n\t\t\t\t`Peer ${this.id} cannot reconnect because it is not disconnected from the server!`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Get a list of available peer IDs. If you're running your own server, you'll\n\t * want to set allow_discovery: true in the PeerServer options. If you're using\n\t * the cloud server, email team@peerjs.com to get the functionality enabled for\n\t * your key.\n\t */\n\tlistAllPeers(cb = (_: any[]) => {}): void {\n\t\tthis._api\n\t\t\t.listAllPeers()\n\t\t\t.then((peers) => cb(peers))\n\t\t\t.catch((error) => this._abort(PeerErrorType.ServerError, error));\n\t}\n}\n", "const LOG_PREFIX = \"PeerJS: \";\n\n/*\nPrints log messages depending on the debug level passed in. Defaults to 0.\n0 Prints no logs.\n1 Prints only errors.\n2 Prints errors and warnings.\n3 Prints all logs.\n*/\nexport enum LogLevel {\n\t/**\n\t * Prints no logs.\n\t */\n\tDisabled,\n\t/**\n\t * Prints only errors.\n\t */\n\tErrors,\n\t/**\n\t * Prints errors and warnings.\n\t */\n\tWarnings,\n\t/**\n\t * Prints all logs.\n\t */\n\tAll,\n}\n\nclass Logger {\n\tprivate _logLevel = LogLevel.Disabled;\n\n\tget logLevel(): LogLevel {\n\t\treturn this._logLevel;\n\t}\n\n\tset logLevel(logLevel: LogLevel) {\n\t\tthis._logLevel = logLevel;\n\t}\n\n\tlog(...args: any[]) {\n\t\tif (this._logLevel >= LogLevel.All) {\n\t\t\tthis._print(LogLevel.All, ...args);\n\t\t}\n\t}\n\n\twarn(...args: any[]) {\n\t\tif (this._logLevel >= LogLevel.Warnings) {\n\t\t\tthis._print(LogLevel.Warnings, ...args);\n\t\t}\n\t}\n\n\terror(...args: any[]) {\n\t\tif (this._logLevel >= LogLevel.Errors) {\n\t\t\tthis._print(LogLevel.Errors, ...args);\n\t\t}\n\t}\n\n\tsetLogFunction(fn: (logLevel: LogLevel, ..._: any[]) => void): void {\n\t\tthis._print = fn;\n\t}\n\n\tprivate _print(logLevel: LogLevel, ...rest: any[]): void {\n\t\tconst copy = [LOG_PREFIX, ...rest];\n\n\t\tfor (const i in copy) {\n\t\t\tif (copy[i] instanceof Error) {\n\t\t\t\tcopy[i] = \"(\" + copy[i].name + \") \" + copy[i].message;\n\t\t\t}\n\t\t}\n\n\t\tif (logLevel >= LogLevel.All) {\n\t\t\tconsole.log(...copy);\n\t\t} else if (logLevel >= LogLevel.Warnings) {\n\t\t\tconsole.warn(\"WARNING\", ...copy);\n\t\t} else if (logLevel >= LogLevel.Errors) {\n\t\t\tconsole.error(\"ERROR\", ...copy);\n\t\t}\n\t}\n}\n\nexport default new Logger();\n", "import { EventEmitter } from \"eventemitter3\";\nimport logger from \"./logger\";\nimport { ServerMessageType, SocketEventType } from \"./enums\";\nimport { version } from \"./version\";\n\n/**\n * An abstraction on top of WebSockets to provide fastest\n * possible connection for peers.\n */\nexport class Socket extends EventEmitter {\n\tprivate _disconnected: boolean = true;\n\tprivate _id?: string;\n\tprivate _messagesQueue: Array<object> = [];\n\tprivate _socket?: WebSocket;\n\tprivate _wsPingTimer?: any;\n\tprivate readonly _baseUrl: string;\n\n\tconstructor(\n\t\tsecure: any,\n\t\thost: string,\n\t\tport: number,\n\t\tpath: string,\n\t\tkey: string,\n\t\tprivate readonly pingInterval: number = 5000,\n\t) {\n\t\tsuper();\n\n\t\tconst wsProtocol = secure ? \"wss://\" : \"ws://\";\n\n\t\tthis._baseUrl = wsProtocol + host + \":\" + port + path + \"peerjs?key=\" + key;\n\t}\n\n\tstart(id: string, token: string): void {\n\t\tthis._id = id;\n\n\t\tconst wsUrl = `${this._baseUrl}&id=${id}&token=${token}`;\n\n\t\tif (!!this._socket || !this._disconnected) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._socket = new WebSocket(wsUrl + \"&version=\" + version);\n\t\tthis._disconnected = false;\n\n\t\tthis._socket.onmessage = (event) => {\n\t\t\tlet data;\n\n\t\t\ttry {\n\t\t\t\tdata = JSON.parse(event.data);\n\t\t\t\tlogger.log(\"Server message received:\", data);\n\t\t\t} catch (e) {\n\t\t\t\tlogger.log(\"Invalid server message\", event.data);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.emit(SocketEventType.Message, data);\n\t\t};\n\n\t\tthis._socket.onclose = (event) => {\n\t\t\tif (this._disconnected) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogger.log(\"Socket closed.\", event);\n\n\t\t\tthis._cleanup();\n\t\t\tthis._disconnected = true;\n\n\t\t\tthis.emit(SocketEventType.Disconnected);\n\t\t};\n\n\t\t// Take care of the queue of connections if necessary and make sure Peer knows\n\t\t// socket is open.\n\t\tthis._socket.onopen = () => {\n\t\t\tif (this._disconnected) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._sendQueuedMessages();\n\n\t\t\tlogger.log(\"Socket open\");\n\n\t\t\tthis._scheduleHeartbeat();\n\t\t};\n\t}\n\n\tprivate _scheduleHeartbeat(): void {\n\t\tthis._wsPingTimer = setTimeout(() => {\n\t\t\tthis._sendHeartbeat();\n\t\t}, this.pingInterval);\n\t}\n\n\tprivate _sendHeartbeat(): void {\n\t\tif (!this._wsOpen()) {\n\t\t\tlogger.log(`Cannot send heartbeat, because socket closed`);\n\t\t\treturn;\n\t\t}\n\n\t\tconst message = JSON.stringify({ type: ServerMessageType.Heartbeat });\n\n\t\tthis._socket!.send(message);\n\n\t\tthis._scheduleHeartbeat();\n\t}\n\n\t/** Is the websocket currently open? */\n\tprivate _wsOpen(): boolean {\n\t\treturn !!this._socket && this._socket.readyState === 1;\n\t}\n\n\t/** Send queued messages. */\n\tprivate _sendQueuedMessages(): void {\n\t\t//Create copy of queue and clear it,\n\t\t//because send method push the message back to queue if smth will go wrong\n\t\tconst copiedQueue = [...this._messagesQueue];\n\t\tthis._messagesQueue = [];\n\n\t\tfor (const message of copiedQueue) {\n\t\t\tthis.send(message);\n\t\t}\n\t}\n\n\t/** Exposed send for DC & Peer. */\n\tsend(data: any): void {\n\t\tif (this._disconnected) {\n\t\t\treturn;\n\t\t}\n\n\t\t// If we didn't get an ID yet, we can't yet send anything so we should queue\n\t\t// up these messages.\n\t\tif (!this._id) {\n\t\t\tthis._messagesQueue.push(data);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!data.type) {\n\t\t\tthis.emit(SocketEventType.Error, \"Invalid message\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this._wsOpen()) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst message = JSON.stringify(data);\n\n\t\tthis._socket!.send(message);\n\t}\n\n\tclose(): void {\n\t\tif (this._disconnected) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._cleanup();\n\n\t\tthis._disconnected = true;\n\t}\n\n\tprivate _cleanup(): void {\n\t\tif (this._socket) {\n\t\t\tthis._socket.onopen =\n\t\t\t\tthis._socket.onmessage =\n\t\t\t\tthis._socket.onclose =\n\t\t\t\t\tnull;\n\t\t\tthis._socket.close();\n\t\t\tthis._socket = undefined;\n\t\t}\n\n\t\tclearTimeout(this._wsPingTimer!);\n\t}\n}\n", "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n", "export enum ConnectionType {\n\tData = \"data\",\n\tMedia = \"media\",\n}\n\nexport enum PeerErrorType {\n\t/**\n\t * The client's browser does not support some or all WebRTC features that you are trying to use.\n\t */\n\tBrowserIncompatible = \"browser-incompatible\",\n\t/**\n\t * You've already disconnected this peer from the server and can no longer make any new connections on it.\n\t */\n\tDisconnected = \"disconnected\",\n\t/**\n\t * The ID passed into the Peer constructor contains illegal characters.\n\t */\n\tInvalidID = \"invalid-id\",\n\t/**\n\t * The API key passed into the Peer constructor contains illegal characters or is not in the system (cloud server only).\n\t */\n\tInvalidKey = \"invalid-key\",\n\t/**\n\t * Lost or cannot establish a connection to the signalling server.\n\t */\n\tNetwork = \"network\",\n\t/**\n\t * The peer you're trying to connect to does not exist.\n\t */\n\tPeerUnavailable = \"peer-unavailable\",\n\t/**\n\t * PeerJS is being used securely, but the cloud server does not support SSL. Use a custom PeerServer.\n\t */\n\tSslUnavailable = \"ssl-unavailable\",\n\t/**\n\t * Unable to reach the server.\n\t */\n\tServerError = \"server-error\",\n\t/**\n\t * An error from the underlying socket.\n\t */\n\tSocketError = \"socket-error\",\n\t/**\n\t * The underlying socket closed unexpectedly.\n\t */\n\tSocketClosed = \"socket-closed\",\n\t/**\n\t * The ID passed into the Peer constructor is already taken.\n\t *\n\t * :::caution\n\t * This error is not fatal if your peer has open peer-to-peer connections.\n\t * This can happen if you attempt to {@apilink Peer.reconnect} a peer that has been disconnected from the server,\n\t * but its old ID has now been taken.\n\t * :::\n\t */\n\tUnavailableID = \"unavailable-id\",\n\t/**\n\t * Native WebRTC errors.\n\t */\n\tWebRTC = \"webrtc\",\n}\n\nexport enum BaseConnectionErrorType {\n\tNegotiationFailed = \"negotiation-failed\",\n\tConnectionClosed = \"connection-closed\",\n}\n\nexport enum DataConnectionErrorType {\n\tNotOpenYet = \"not-open-yet\",\n\tMessageToBig = \"message-too-big\",\n}\n\nexport enum SerializationType {\n\tBinary = \"binary\",\n\tBinaryUTF8 = \"binary-utf8\",\n\tJSON = \"json\",\n\tNone = \"raw\",\n}\n\nexport enum SocketEventType {\n\tMessage = \"message\",\n\tDisconnected = \"disconnected\",\n\tError = \"error\",\n\tClose = \"close\",\n}\n\nexport enum ServerMessageType {\n\tHeartbeat = \"HEARTBEAT\",\n\tCandidate = \"CANDIDATE\",\n\tOffer = \"OFFER\",\n\tAnswer = \"ANSWER\",\n\tOpen = \"OPEN\", // The connection to the server is open.\n\tError = \"ERROR\", // Server error.\n\tIdTaken = \"ID-TAKEN\", // The selected ID is taken.\n\tInvalidKey = \"INVALID-KEY\", // The given API key cannot be found.\n\tLeave = \"LEAVE\", // Another peer has closed its connection to this peer.\n\tExpire = \"EXPIRE\", // The offer sent to a peer has expired without response.\n}\n", "export const version = \"1.5.5\";\n", "import { util } from \"./util\";\nimport logger from \"./logger\";\nimport { Negotiator } from \"./negotiator\";\nimport { ConnectionType, ServerMessageType } from \"./enums\";\nimport type { Peer } from \"./peer\";\nimport { BaseConnection, type BaseConnectionEvents } from \"./baseconnection\";\nimport type { ServerMessage } from \"./servermessage\";\nimport type { AnswerOption } from \"./optionInterfaces\";\n\nexport interface MediaConnectionEvents extends BaseConnectionEvents<never> {\n\t/**\n\t * Emitted when a connection to the PeerServer is established.\n\t *\n\t * ```ts\n\t * mediaConnection.on('stream', (stream) => { ... });\n\t * ```\n\t */\n\tstream: (stream: MediaStream) => void;\n\t/**\n\t * Emitted when the auxiliary data channel is established.\n\t * After this event, hanging up will close the connection cleanly on the remote peer.\n\t * @beta\n\t */\n\twillCloseOnRemote: () => void;\n}\n\n/**\n * Wraps WebRTC's media streams.\n * To get one, use {@apilink Peer.call} or listen for the {@apilink PeerEvents | `call`} event.\n */\nexport class MediaConnection extends BaseConnection<MediaConnectionEvents> {\n\tprivate static readonly ID_PREFIX = \"mc_\";\n\treadonly label: string;\n\n\tprivate _negotiator: Negotiator<MediaConnectionEvents, this>;\n\tprivate _localStream: MediaStream;\n\tprivate _remoteStream: MediaStream;\n\n\t/**\n\t * For media connections, this is always 'media'.\n\t */\n\tget type() {\n\t\treturn ConnectionType.Media;\n\t}\n\n\tget localStream(): MediaStream {\n\t\treturn this._localStream;\n\t}\n\n\tget remoteStream(): MediaStream {\n\t\treturn this._remoteStream;\n\t}\n\n\tconstructor(peerId: string, provider: Peer, options: any) {\n\t\tsuper(peerId, provider, options);\n\n\t\tthis._localStream = this.options._stream;\n\t\tthis.connectionId =\n\t\t\tthis.options.connectionId ||\n\t\t\tMediaConnection.ID_PREFIX + util.randomToken();\n\n\t\tthis._negotiator = new Negotiator(this);\n\n\t\tif (this._localStream) {\n\t\t\tthis._negotiator.startConnection({\n\t\t\t\t_stream: this._localStream,\n\t\t\t\toriginator: true,\n\t\t\t});\n\t\t}\n\t}\n\n\t/** Called by the Negotiator when the DataChannel is ready. */\n\toverride _initializeDataChannel(dc: RTCDataChannel): void {\n\t\tthis.dataChannel = dc;\n\n\t\tthis.dataChannel.onopen = () => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc connection success`);\n\t\t\tthis.emit(\"willCloseOnRemote\");\n\t\t};\n\n\t\tthis.dataChannel.onclose = () => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc closed for:`, this.peer);\n\t\t\tthis.close();\n\t\t};\n\t}\n\taddStream(remoteStream) {\n\t\tlogger.log(\"Receiving stream\", remoteStream);\n\n\t\tthis._remoteStream = remoteStream;\n\t\tsuper.emit(\"stream\", remoteStream); // Should we call this `open`?\n\t}\n\n\t/**\n\t * @internal\n\t */\n\thandleMessage(message: ServerMessage): void {\n\t\tconst type = message.type;\n\t\tconst payload = message.payload;\n\n\t\tswitch (message.type) {\n\t\t\tcase ServerMessageType.Answer:\n\t\t\t\t// Forward to negotiator\n\t\t\t\tvoid this._negotiator.handleSDP(type, payload.sdp);\n\t\t\t\tthis._open = true;\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Candidate:\n\t\t\t\tvoid this._negotiator.handleCandidate(payload.candidate);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(`Unrecognized message type:${type} from peer:${this.peer}`);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/**\n * When receiving a {@apilink PeerEvents | `call`} event on a peer, you can call\n * `answer` on the media connection provided by the callback to accept the call\n * and optionally send your own media stream.\n\n *\n * @param stream A WebRTC media stream.\n * @param options\n * @returns\n */\n\tanswer(stream?: MediaStream, options: AnswerOption = {}): void {\n\t\tif (this._localStream) {\n\t\t\tlogger.warn(\n\t\t\t\t\"Local stream already exists on this MediaConnection. Are you answering a call twice?\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis._localStream = stream;\n\n\t\tif (options && options.sdpTransform) {\n\t\t\tthis.options.sdpTransform = options.sdpTransform;\n\t\t}\n\n\t\tthis._negotiator.startConnection({\n\t\t\t...this.options._payload,\n\t\t\t_stream: stream,\n\t\t});\n\t\t// Retrieve lost messages stored because PeerConnection not set up.\n\t\tconst messages = this.provider._getMessages(this.connectionId);\n\n\t\tfor (const message of messages) {\n\t\t\tthis.handleMessage(message);\n\t\t}\n\n\t\tthis._open = true;\n\t}\n\n\t/**\n\t * Exposed functionality for users.\n\t */\n\n\t/**\n\t * Closes the media connection.\n\t */\n\tclose(): void {\n\t\tif (this._negotiator) {\n\t\t\tthis._negotiator.cleanup();\n\t\t\tthis._negotiator = null;\n\t\t}\n\n\t\tthis._localStream = null;\n\t\tthis._remoteStream = null;\n\n\t\tif (this.provider) {\n\t\t\tthis.provider._removeConnection(this);\n\n\t\t\tthis.provider = null;\n\t\t}\n\n\t\tif (this.options && this.options._stream) {\n\t\t\tthis.options._stream = null;\n\t\t}\n\n\t\tif (!this.open) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._open = false;\n\n\t\tsuper.emit(\"close\");\n\t}\n}\n", "import logger from \"./logger\";\nimport type { MediaConnection } from \"./mediaconnection\";\nimport type { DataConnection } from \"./dataconnection/DataConnection\";\nimport {\n\tBaseConnectionErrorType,\n\tConnectionType,\n\tPeerErrorType,\n\tServerMessageType,\n} from \"./enums\";\nimport type { BaseConnection, BaseConnectionEvents } from \"./baseconnection\";\nimport type { ValidEventTypes } from \"eventemitter3\";\n\n/**\n * Manages all negotiations between Peers.\n */\nexport class Negotiator<\n\tEvents extends ValidEventTypes,\n\tConnectionType extends BaseConnection<Events | BaseConnectionEvents>,\n> {\n\tconstructor(readonly connection: ConnectionType) {}\n\n\t/** Returns a PeerConnection object set up correctly (for data, media). */\n\tstartConnection(options: any) {\n\t\tconst peerConnection = this._startPeerConnection();\n\n\t\t// Set the connection's PC.\n\t\tthis.connection.peerConnection = peerConnection;\n\n\t\tif (this.connection.type === ConnectionType.Media && options._stream) {\n\t\t\tthis._addTracksToConnection(options._stream, peerConnection);\n\t\t}\n\n\t\t// What do we need to do now?\n\t\tif (options.originator) {\n\t\t\tconst dataConnection = this.connection;\n\n\t\t\tconst config: RTCDataChannelInit = { ordered: !!options.reliable };\n\n\t\t\tconst dataChannel = peerConnection.createDataChannel(\n\t\t\t\tdataConnection.label,\n\t\t\t\tconfig,\n\t\t\t);\n\t\t\tdataConnection._initializeDataChannel(dataChannel);\n\n\t\t\tvoid this._makeOffer();\n\t\t} else {\n\t\t\tvoid this.handleSDP(\"OFFER\", options.sdp);\n\t\t}\n\t}\n\n\t/** Start a PC. */\n\tprivate _startPeerConnection(): RTCPeerConnection {\n\t\tlogger.log(\"Creating RTCPeerConnection.\");\n\n\t\tconst peerConnection = new RTCPeerConnection(\n\t\t\tthis.connection.provider.options.config,\n\t\t);\n\n\t\tthis._setupListeners(peerConnection);\n\n\t\treturn peerConnection;\n\t}\n\n\t/** Set up various WebRTC listeners. */\n\tprivate _setupListeners(peerConnection: RTCPeerConnection) {\n\t\tconst peerId = this.connection.peer;\n\t\tconst connectionId = this.connection.connectionId;\n\t\tconst connectionType = this.connection.type;\n\t\tconst provider = this.connection.provider;\n\n\t\t// ICE CANDIDATES.\n\t\tlogger.log(\"Listening for ICE candidates.\");\n\n\t\tpeerConnection.onicecandidate = (evt) => {\n\t\t\tif (!evt.candidate || !evt.candidate.candidate) return;\n\n\t\t\tlogger.log(`Received ICE candidates for ${peerId}:`, evt.candidate);\n\n\t\t\tprovider.socket.send({\n\t\t\t\ttype: ServerMessageType.Candidate,\n\t\t\t\tpayload: {\n\t\t\t\t\tcandidate: evt.candidate,\n\t\t\t\t\ttype: connectionType,\n\t\t\t\t\tconnectionId: connectionId,\n\t\t\t\t},\n\t\t\t\tdst: peerId,\n\t\t\t});\n\t\t};\n\n\t\tpeerConnection.oniceconnectionstatechange = () => {\n\t\t\tswitch (peerConnection.iceConnectionState) {\n\t\t\t\tcase \"failed\":\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t\"iceConnectionState is failed, closing connections to \" + peerId,\n\t\t\t\t\t);\n\t\t\t\t\tthis.connection.emitError(\n\t\t\t\t\t\tBaseConnectionErrorType.NegotiationFailed,\n\t\t\t\t\t\t\"Negotiation of connection to \" + peerId + \" failed.\",\n\t\t\t\t\t);\n\t\t\t\t\tthis.connection.close();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"closed\":\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t\"iceConnectionState is closed, closing connections to \" + peerId,\n\t\t\t\t\t);\n\t\t\t\t\tthis.connection.emitError(\n\t\t\t\t\t\tBaseConnectionErrorType.ConnectionClosed,\n\t\t\t\t\t\t\"Connection to \" + peerId + \" closed.\",\n\t\t\t\t\t);\n\t\t\t\t\tthis.connection.close();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"disconnected\":\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t\"iceConnectionState changed to disconnected on the connection with \" +\n\t\t\t\t\t\t\tpeerId,\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"completed\":\n\t\t\t\t\tpeerConnection.onicecandidate = () => {};\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tthis.connection.emit(\n\t\t\t\t\"iceStateChanged\",\n\t\t\t\tpeerConnection.iceConnectionState,\n\t\t\t);\n\t\t};\n\n\t\t// DATACONNECTION.\n\t\tlogger.log(\"Listening for data channel\");\n\t\t// Fired between offer and answer, so options should already be saved\n\t\t// in the options hash.\n\t\tpeerConnection.ondatachannel = (evt) => {\n\t\t\tlogger.log(\"Received data channel\");\n\n\t\t\tconst dataChannel = evt.channel;\n\t\t\tconst connection = <DataConnection>(\n\t\t\t\tprovider.getConnection(peerId, connectionId)\n\t\t\t);\n\n\t\t\tconnection._initializeDataChannel(dataChannel);\n\t\t};\n\n\t\t// MEDIACONNECTION.\n\t\tlogger.log(\"Listening for remote stream\");\n\n\t\tpeerConnection.ontrack = (evt) => {\n\t\t\tlogger.log(\"Received remote stream\");\n\n\t\t\tconst stream = evt.streams[0];\n\t\t\tconst connection = provider.getConnection(peerId, connectionId);\n\n\t\t\tif (connection.type === ConnectionType.Media) {\n\t\t\t\tconst mediaConnection = <MediaConnection>connection;\n\n\t\t\t\tthis._addStreamToMediaConnection(stream, mediaConnection);\n\t\t\t}\n\t\t};\n\t}\n\n\tcleanup(): void {\n\t\tlogger.log(\"Cleaning up PeerConnection to \" + this.connection.peer);\n\n\t\tconst peerConnection = this.connection.peerConnection;\n\n\t\tif (!peerConnection) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.connection.peerConnection = null;\n\n\t\t//unsubscribe from all PeerConnection's events\n\t\tpeerConnection.onicecandidate =\n\t\t\tpeerConnection.oniceconnectionstatechange =\n\t\t\tpeerConnection.ondatachannel =\n\t\t\tpeerConnection.ontrack =\n\t\t\t\t() => {};\n\n\t\tconst peerConnectionNotClosed = peerConnection.signalingState !== \"closed\";\n\t\tlet dataChannelNotClosed = false;\n\n\t\tconst dataChannel = this.connection.dataChannel;\n\n\t\tif (dataChannel) {\n\t\t\tdataChannelNotClosed =\n\t\t\t\t!!dataChannel.readyState && dataChannel.readyState !== \"closed\";\n\t\t}\n\n\t\tif (peerConnectionNotClosed || dataChannelNotClosed) {\n\t\t\tpeerConnection.close();\n\t\t}\n\t}\n\n\tprivate async _makeOffer(): Promise<void> {\n\t\tconst peerConnection = this.connection.peerConnection;\n\t\tconst provider = this.connection.provider;\n\n\t\ttry {\n\t\t\tconst offer = await peerConnection.createOffer(\n\t\t\t\tthis.connection.options.constraints,\n\t\t\t);\n\n\t\t\tlogger.log(\"Created offer.\");\n\n\t\t\tif (\n\t\t\t\tthis.connection.options.sdpTransform &&\n\t\t\t\ttypeof this.connection.options.sdpTransform === \"function\"\n\t\t\t) {\n\t\t\t\toffer.sdp =\n\t\t\t\t\tthis.connection.options.sdpTransform(offer.sdp) || offer.sdp;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait peerConnection.setLocalDescription(offer);\n\n\t\t\t\tlogger.log(\n\t\t\t\t\t\"Set localDescription:\",\n\t\t\t\t\toffer,\n\t\t\t\t\t`for:${this.connection.peer}`,\n\t\t\t\t);\n\n\t\t\t\tlet payload: any = {\n\t\t\t\t\tsdp: offer,\n\t\t\t\t\ttype: this.connection.type,\n\t\t\t\t\tconnectionId: this.connection.connectionId,\n\t\t\t\t\tmetadata: this.connection.metadata,\n\t\t\t\t};\n\n\t\t\t\tif (this.connection.type === ConnectionType.Data) {\n\t\t\t\t\tconst dataConnection = <DataConnection>(<unknown>this.connection);\n\n\t\t\t\t\tpayload = {\n\t\t\t\t\t\t...payload,\n\t\t\t\t\t\tlabel: dataConnection.label,\n\t\t\t\t\t\treliable: dataConnection.reliable,\n\t\t\t\t\t\tserialization: dataConnection.serialization,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tprovider.socket.send({\n\t\t\t\t\ttype: ServerMessageType.Offer,\n\t\t\t\t\tpayload,\n\t\t\t\t\tdst: this.connection.peer,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\t// TODO: investigate why _makeOffer is being called from the answer\n\t\t\t\tif (\n\t\t\t\t\terr !=\n\t\t\t\t\t\"OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer\"\n\t\t\t\t) {\n\t\t\t\t\tprovider.emitError(PeerErrorType.WebRTC, err);\n\t\t\t\t\tlogger.log(\"Failed to setLocalDescription, \", err);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err_1) {\n\t\t\tprovider.emitError(PeerErrorType.WebRTC, err_1);\n\t\t\tlogger.log(\"Failed to createOffer, \", err_1);\n\t\t}\n\t}\n\n\tprivate async _makeAnswer(): Promise<void> {\n\t\tconst peerConnection = this.connection.peerConnection;\n\t\tconst provider = this.connection.provider;\n\n\t\ttry {\n\t\t\tconst answer = await peerConnection.createAnswer();\n\t\t\tlogger.log(\"Created answer.\");\n\n\t\t\tif (\n\t\t\t\tthis.connection.options.sdpTransform &&\n\t\t\t\ttypeof this.connection.options.sdpTransform === \"function\"\n\t\t\t) {\n\t\t\t\tanswer.sdp =\n\t\t\t\t\tthis.connection.options.sdpTransform(answer.sdp) || answer.sdp;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait peerConnection.setLocalDescription(answer);\n\n\t\t\t\tlogger.log(\n\t\t\t\t\t`Set localDescription:`,\n\t\t\t\t\tanswer,\n\t\t\t\t\t`for:${this.connection.peer}`,\n\t\t\t\t);\n\n\t\t\t\tprovider.socket.send({\n\t\t\t\t\ttype: ServerMessageType.Answer,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tsdp: answer,\n\t\t\t\t\t\ttype: this.connection.type,\n\t\t\t\t\t\tconnectionId: this.connection.connectionId,\n\t\t\t\t\t},\n\t\t\t\t\tdst: this.connection.peer,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tprovider.emitError(PeerErrorType.WebRTC, err);\n\t\t\t\tlogger.log(\"Failed to setLocalDescription, \", err);\n\t\t\t}\n\t\t} catch (err_1) {\n\t\t\tprovider.emitError(PeerErrorType.WebRTC, err_1);\n\t\t\tlogger.log(\"Failed to create answer, \", err_1);\n\t\t}\n\t}\n\n\t/** Handle an SDP. */\n\tasync handleSDP(type: string, sdp: any): Promise<void> {\n\t\tsdp = new RTCSessionDescription(sdp);\n\t\tconst peerConnection = this.connection.peerConnection;\n\t\tconst provider = this.connection.provider;\n\n\t\tlogger.log(\"Setting remote description\", sdp);\n\n\t\tconst self = this;\n\n\t\ttry {\n\t\t\tawait peerConnection.setRemoteDescription(sdp);\n\t\t\tlogger.log(`Set remoteDescription:${type} for:${this.connection.peer}`);\n\t\t\tif (type === \"OFFER\") {\n\t\t\t\tawait self._makeAnswer();\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tprovider.emitError(PeerErrorType.WebRTC, err);\n\t\t\tlogger.log(\"Failed to setRemoteDescription, \", err);\n\t\t}\n\t}\n\n\t/** Handle a candidate. */\n\tasync handleCandidate(ice: RTCIceCandidate) {\n\t\tlogger.log(`handleCandidate:`, ice);\n\n\t\ttry {\n\t\t\tawait this.connection.peerConnection.addIceCandidate(ice);\n\t\t\tlogger.log(`Added ICE candidate for:${this.connection.peer}`);\n\t\t} catch (err) {\n\t\t\tthis.connection.provider.emitError(PeerErrorType.WebRTC, err);\n\t\t\tlogger.log(\"Failed to handleCandidate, \", err);\n\t\t}\n\t}\n\n\tprivate _addTracksToConnection(\n\t\tstream: MediaStream,\n\t\tpeerConnection: RTCPeerConnection,\n\t): void {\n\t\tlogger.log(`add tracks from stream ${stream.id} to peer connection`);\n\n\t\tif (!peerConnection.addTrack) {\n\t\t\treturn logger.error(\n\t\t\t\t`Your browser does't support RTCPeerConnection#addTrack. Ignored.`,\n\t\t\t);\n\t\t}\n\n\t\tstream.getTracks().forEach((track) => {\n\t\t\tpeerConnection.addTrack(track, stream);\n\t\t});\n\t}\n\n\tprivate _addStreamToMediaConnection(\n\t\tstream: MediaStream,\n\t\tmediaConnection: MediaConnection,\n\t): void {\n\t\tlogger.log(\n\t\t\t`add stream ${stream.id} to media connection ${mediaConnection.connectionId}`,\n\t\t);\n\n\t\tmediaConnection.addStream(stream);\n\t}\n}\n", "import type { Peer } from \"./peer\";\nimport type { ServerMessage } from \"./servermessage\";\nimport type { ConnectionType } from \"./enums\";\nimport { BaseConnectionErrorType } from \"./enums\";\nimport {\n\tEventEmitterWithError,\n\ttype EventsWithError,\n\tPeerError,\n} from \"./peerError\";\nimport type { ValidEventTypes } from \"eventemitter3\";\n\nexport interface BaseConnectionEvents<\n\tErrorType extends string = BaseConnectionErrorType,\n> extends EventsWithError<ErrorType> {\n\t/**\n\t * Emitted when either you or the remote peer closes the connection.\n\t *\n\t * ```ts\n\t * connection.on('close', () => { ... });\n\t * ```\n\t */\n\tclose: () => void;\n\t/**\n\t * ```ts\n\t * connection.on('error', (error) => { ... });\n\t * ```\n\t */\n\terror: (error: PeerError<`${ErrorType}`>) => void;\n\ticeStateChanged: (state: RTCIceConnectionState) => void;\n}\n\nexport abstract class BaseConnection<\n\tSubClassEvents extends ValidEventTypes,\n\tErrorType extends string = never,\n> extends EventEmitterWithError<\n\tErrorType | BaseConnectionErrorType,\n\tSubClassEvents & BaseConnectionEvents<BaseConnectionErrorType | ErrorType>\n> {\n\tprotected _open = false;\n\n\t/**\n\t * Any type of metadata associated with the connection,\n\t * passed in by whoever initiated the connection.\n\t */\n\treadonly metadata: any;\n\tconnectionId: string;\n\n\tpeerConnection: RTCPeerConnection;\n\tdataChannel: RTCDataChannel;\n\n\tabstract get type(): ConnectionType;\n\n\t/**\n\t * The optional label passed in or assigned by PeerJS when the connection was initiated.\n\t */\n\tlabel: string;\n\n\t/**\n\t * Whether the media connection is active (e.g. your call has been answered).\n\t * You can check this if you want to set a maximum wait time for a one-sided call.\n\t */\n\tget open() {\n\t\treturn this._open;\n\t}\n\n\tprotected constructor(\n\t\t/**\n\t\t * The ID of the peer on the other end of this connection.\n\t\t */\n\t\treadonly peer: string,\n\t\tpublic provider: Peer,\n\t\treadonly options: any,\n\t) {\n\t\tsuper();\n\n\t\tthis.metadata = options.metadata;\n\t}\n\n\tabstract close(): void;\n\n\t/**\n\t * @internal\n\t */\n\tabstract handleMessage(message: ServerMessage): void;\n\n\t/**\n\t * Called by the Negotiator when the DataChannel is ready.\n\t * @internal\n\t * */\n\tabstract _initializeDataChannel(dc: RTCDataChannel): void;\n}\n", "import { EventEmitter } from \"eventemitter3\";\nimport logger from \"./logger\";\n\nexport interface EventsWithError<ErrorType extends string> {\n\terror: (error: PeerError<`${ErrorType}`>) => void;\n}\n\nexport class EventEmitterWithError<\n\tErrorType extends string,\n\tEvents extends EventsWithError<ErrorType>,\n> extends EventEmitter<Events, never> {\n\t/**\n\t * Emits a typed error message.\n\t *\n\t * @internal\n\t */\n\temitError(type: ErrorType, err: string | Error): void {\n\t\tlogger.error(\"Error:\", err);\n\n\t\t// @ts-ignore\n\t\tthis.emit(\"error\", new PeerError<`${ErrorType}`>(`${type}`, err));\n\t}\n}\n/**\n * A PeerError is emitted whenever an error occurs.\n * It always has a `.type`, which can be used to identify the error.\n */\nexport class PeerError<T extends string> extends Error {\n\t/**\n\t * @internal\n\t */\n\tconstructor(type: T, err: Error | string) {\n\t\tif (typeof err === \"string\") {\n\t\t\tsuper(err);\n\t\t} else {\n\t\t\tsuper();\n\t\t\tObject.assign(this, err);\n\t\t}\n\n\t\tthis.type = type;\n\t}\n\n\tpublic type: T;\n}\n", "import { util } from \"./util\";\nimport logger from \"./logger\";\nimport type { PeerJSOption } from \"./optionInterfaces\";\nimport { version } from \"./version\";\n\nexport class API {\n\tconstructor(private readonly _options: PeerJSOption) {}\n\n\tprivate _buildRequest(method: string): Promise<Response> {\n\t\tconst protocol = this._options.secure ? \"https\" : \"http\";\n\t\tconst { host, port, path, key } = this._options;\n\t\tconst url = new URL(`${protocol}://${host}:${port}${path}${key}/${method}`);\n\t\t// TODO: Why timestamp, why random?\n\t\turl.searchParams.set(\"ts\", `${Date.now()}${Math.random()}`);\n\t\turl.searchParams.set(\"version\", version);\n\t\treturn fetch(url.href, {\n\t\t\treferrerPolicy: this._options.referrerPolicy,\n\t\t});\n\t}\n\n\t/** Get a unique ID from the server via XHR and initialize with it. */\n\tasync retrieveId(): Promise<string> {\n\t\ttry {\n\t\t\tconst response = await this._buildRequest(\"id\");\n\n\t\t\tif (response.status !== 200) {\n\t\t\t\tthrow new Error(`Error. Status:${response.status}`);\n\t\t\t}\n\n\t\t\treturn response.text();\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error retrieving ID\", error);\n\n\t\t\tlet pathError = \"\";\n\n\t\t\tif (\n\t\t\t\tthis._options.path === \"/\" &&\n\t\t\t\tthis._options.host !== util.CLOUD_HOST\n\t\t\t) {\n\t\t\t\tpathError =\n\t\t\t\t\t\" If you passed in a `path` to your self-hosted PeerServer, \" +\n\t\t\t\t\t\"you'll also need to pass in that same path when creating a new \" +\n\t\t\t\t\t\"Peer.\";\n\t\t\t}\n\n\t\t\tthrow new Error(\"Could not get an ID from the server.\" + pathError);\n\t\t}\n\t}\n\n\t/** @deprecated */\n\tasync listAllPeers(): Promise<any[]> {\n\t\ttry {\n\t\t\tconst response = await this._buildRequest(\"peers\");\n\n\t\t\tif (response.status !== 200) {\n\t\t\t\tif (response.status === 401) {\n\t\t\t\t\tlet helpfulError = \"\";\n\n\t\t\t\t\tif (this._options.host === util.CLOUD_HOST) {\n\t\t\t\t\t\thelpfulError =\n\t\t\t\t\t\t\t\"It looks like you're using the cloud server. You can email \" +\n\t\t\t\t\t\t\t\"team@peerjs.com to enable peer listing for your API key.\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\thelpfulError =\n\t\t\t\t\t\t\t\"You need to enable `allow_discovery` on your self-hosted \" +\n\t\t\t\t\t\t\t\"PeerServer to use this feature.\";\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"It doesn't look like you have permission to list peers IDs. \" +\n\t\t\t\t\t\t\thelpfulError,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tthrow new Error(`Error. Status:${response.status}`);\n\t\t\t}\n\n\t\t\treturn response.json();\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error retrieving list peers\", error);\n\n\t\t\tthrow new Error(\"Could not get list peers from the server.\" + error);\n\t\t}\n\t}\n}\n", "import { BinaryPackChunker, concatArrayBuffers } from \"./binaryPackChunker\";\nimport logger from \"../../logger\";\nimport type { Peer } from \"../../peer\";\nimport { BufferedConnection } from \"./BufferedConnection\";\nimport { SerializationType } from \"../../enums\";\nimport { pack, type Packable, unpack } from \"peerjs-js-binarypack\";\n\nexport class BinaryPack extends BufferedConnection {\n\tprivate readonly chunker = new BinaryPackChunker();\n\treadonly serialization = SerializationType.Binary;\n\n\tprivate _chunkedData: {\n\t\t[id: number]: {\n\t\t\tdata: Uint8Array[];\n\t\t\tcount: number;\n\t\t\ttotal: number;\n\t\t};\n\t} = {};\n\n\tpublic override close(options?: { flush?: boolean }) {\n\t\tsuper.close(options);\n\t\tthis._chunkedData = {};\n\t}\n\n\tconstructor(peerId: string, provider: Peer, options: any) {\n\t\tsuper(peerId, provider, options);\n\t}\n\n\t// Handles a DataChannel message.\n\tprotected override _handleDataMessage({ data }: { data: Uint8Array }): void {\n\t\tconst deserializedData = unpack(data);\n\n\t\t// PeerJS specific message\n\t\tconst peerData = deserializedData[\"__peerData\"];\n\t\tif (peerData) {\n\t\t\tif (peerData.type === \"close\") {\n\t\t\t\tthis.close();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Chunked data -- piece things back together.\n\t\t\t// @ts-ignore\n\t\t\tthis._handleChunk(deserializedData);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.emit(\"data\", deserializedData);\n\t}\n\n\tprivate _handleChunk(data: {\n\t\t__peerData: number;\n\t\tn: number;\n\t\ttotal: number;\n\t\tdata: ArrayBuffer;\n\t}): void {\n\t\tconst id = data.__peerData;\n\t\tconst chunkInfo = this._chunkedData[id] || {\n\t\t\tdata: [],\n\t\t\tcount: 0,\n\t\t\ttotal: data.total,\n\t\t};\n\n\t\tchunkInfo.data[data.n] = new Uint8Array(data.data);\n\t\tchunkInfo.count++;\n\t\tthis._chunkedData[id] = chunkInfo;\n\n\t\tif (chunkInfo.total === chunkInfo.count) {\n\t\t\t// Clean up before making the recursive call to `_handleDataMessage`.\n\t\t\tdelete this._chunkedData[id];\n\n\t\t\t// We've received all the chunks--time to construct the complete data.\n\t\t\t// const data = new Blob(chunkInfo.data);\n\t\t\tconst data = concatArrayBuffers(chunkInfo.data);\n\t\t\tthis._handleDataMessage({ data });\n\t\t}\n\t}\n\n\tprotected override _send(data: Packable, chunked: boolean) {\n\t\tconst blob = pack(data);\n\t\tif (blob instanceof Promise) {\n\t\t\treturn this._send_blob(blob);\n\t\t}\n\n\t\tif (!chunked && blob.byteLength > this.chunker.chunkedMTU) {\n\t\t\tthis._sendChunks(blob);\n\t\t\treturn;\n\t\t}\n\n\t\tthis._bufferedSend(blob);\n\t}\n\tprivate async _send_blob(blobPromise: Promise<ArrayBufferLike>) {\n\t\tconst blob = await blobPromise;\n\t\tif (blob.byteLength > this.chunker.chunkedMTU) {\n\t\t\tthis._sendChunks(blob);\n\t\t\treturn;\n\t\t}\n\n\t\tthis._bufferedSend(blob);\n\t}\n\n\tprivate _sendChunks(blob: ArrayBuffer) {\n\t\tconst blobs = this.chunker.chunk(blob);\n\t\tlogger.log(`DC#${this.connectionId} Try to send ${blobs.length} chunks...`);\n\n\t\tfor (const blob of blobs) {\n\t\t\tthis.send(blob, true);\n\t\t}\n\t}\n}\n", "import logger from \"../../logger\";\nimport { DataConnection } from \"../DataConnection\";\n\nexport abstract class BufferedConnection extends DataConnection {\n\tprivate _buffer: any[] = [];\n\tprivate _bufferSize = 0;\n\tprivate _buffering = false;\n\n\tpublic get bufferSize(): number {\n\t\treturn this._bufferSize;\n\t}\n\n\tpublic override _initializeDataChannel(dc: RTCDataChannel) {\n\t\tsuper._initializeDataChannel(dc);\n\t\tthis.dataChannel.binaryType = \"arraybuffer\";\n\t\tthis.dataChannel.addEventListener(\"message\", (e) =>\n\t\t\tthis._handleDataMessage(e),\n\t\t);\n\t}\n\n\tprotected abstract _handleDataMessage(e: MessageEvent): void;\n\n\tprotected _bufferedSend(msg: ArrayBuffer): void {\n\t\tif (this._buffering || !this._trySend(msg)) {\n\t\t\tthis._buffer.push(msg);\n\t\t\tthis._bufferSize = this._buffer.length;\n\t\t}\n\t}\n\n\t// Returns true if the send succeeds.\n\tprivate _trySend(msg: ArrayBuffer): boolean {\n\t\tif (!this.open) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (this.dataChannel.bufferedAmount > DataConnection.MAX_BUFFERED_AMOUNT) {\n\t\t\tthis._buffering = true;\n\t\t\tsetTimeout(() => {\n\t\t\t\tthis._buffering = false;\n\t\t\t\tthis._tryBuffer();\n\t\t\t}, 50);\n\n\t\t\treturn false;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.dataChannel.send(msg);\n\t\t} catch (e) {\n\t\t\tlogger.error(`DC#:${this.connectionId} Error when sending:`, e);\n\t\t\tthis._buffering = true;\n\n\t\t\tthis.close();\n\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t// Try to send the first message in the buffer.\n\tprivate _tryBuffer(): void {\n\t\tif (!this.open) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._buffer.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst msg = this._buffer[0];\n\n\t\tif (this._trySend(msg)) {\n\t\t\tthis._buffer.shift();\n\t\t\tthis._bufferSize = this._buffer.length;\n\t\t\tthis._tryBuffer();\n\t\t}\n\t}\n\n\tpublic override close(options?: { flush?: boolean }) {\n\t\tif (options?.flush) {\n\t\t\tthis.send({\n\t\t\t\t__peerData: {\n\t\t\t\t\ttype: \"close\",\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tthis._buffer = [];\n\t\tthis._bufferSize = 0;\n\t\tsuper.close();\n\t}\n}\n", "import logger from \"../logger\";\nimport { Negotiator } from \"../negotiator\";\nimport {\n\tBaseConnectionErrorType,\n\tConnectionType,\n\tDataConnectionErrorType,\n\tServerMessageType,\n} from \"../enums\";\nimport type { Peer } from \"../peer\";\nimport { BaseConnection, type BaseConnectionEvents } from \"../baseconnection\";\nimport type { ServerMessage } from \"../servermessage\";\nimport type { EventsWithError } from \"../peerError\";\nimport { randomToken } from \"../utils/randomToken\";\n\nexport interface DataConnectionEvents\n\textends EventsWithError<DataConnectionErrorType | BaseConnectionErrorType>,\n\t\tBaseConnectionEvents<DataConnectionErrorType | BaseConnectionErrorType> {\n\t/**\n\t * Emitted when data is received from the remote peer.\n\t */\n\tdata: (data: unknown) => void;\n\t/**\n\t * Emitted when the connection is established and ready-to-use.\n\t */\n\topen: () => void;\n}\n\n/**\n * Wraps a DataChannel between two Peers.\n */\nexport abstract class DataConnection extends BaseConnection<\n\tDataConnectionEvents,\n\tDataConnectionErrorType\n> {\n\tprotected static readonly ID_PREFIX = \"dc_\";\n\tprotected static readonly MAX_BUFFERED_AMOUNT = 8 * 1024 * 1024;\n\n\tprivate _negotiator: Negotiator<DataConnectionEvents, this>;\n\tabstract readonly serialization: string;\n\treadonly reliable: boolean;\n\n\tpublic get type() {\n\t\treturn ConnectionType.Data;\n\t}\n\n\tconstructor(peerId: string, provider: Peer, options: any) {\n\t\tsuper(peerId, provider, options);\n\n\t\tthis.connectionId =\n\t\t\tthis.options.connectionId || DataConnection.ID_PREFIX + randomToken();\n\n\t\tthis.label = this.options.label || this.connectionId;\n\t\tthis.reliable = !!this.options.reliable;\n\n\t\tthis._negotiator = new Negotiator(this);\n\n\t\tthis._negotiator.startConnection(\n\t\t\tthis.options._payload || {\n\t\t\t\toriginator: true,\n\t\t\t\treliable: this.reliable,\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Called by the Negotiator when the DataChannel is ready. */\n\toverride _initializeDataChannel(dc: RTCDataChannel): void {\n\t\tthis.dataChannel = dc;\n\n\t\tthis.dataChannel.onopen = () => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc connection success`);\n\t\t\tthis._open = true;\n\t\t\tthis.emit(\"open\");\n\t\t};\n\n\t\tthis.dataChannel.onmessage = (e) => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc onmessage:`, e.data);\n\t\t\t// this._handleDataMessage(e);\n\t\t};\n\n\t\tthis.dataChannel.onclose = () => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc closed for:`, this.peer);\n\t\t\tthis.close();\n\t\t};\n\t}\n\n\t/**\n\t * Exposed functionality for users.\n\t */\n\n\t/** Allows user to close connection. */\n\tclose(options?: { flush?: boolean }): void {\n\t\tif (options?.flush) {\n\t\t\tthis.send({\n\t\t\t\t__peerData: {\n\t\t\t\t\ttype: \"close\",\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (this._negotiator) {\n\t\t\tthis._negotiator.cleanup();\n\t\t\tthis._negotiator = null;\n\t\t}\n\n\t\tif (this.provider) {\n\t\t\tthis.provider._removeConnection(this);\n\n\t\t\tthis.provider = null;\n\t\t}\n\n\t\tif (this.dataChannel) {\n\t\t\tthis.dataChannel.onopen = null;\n\t\t\tthis.dataChannel.onmessage = null;\n\t\t\tthis.dataChannel.onclose = null;\n\t\t\tthis.dataChannel = null;\n\t\t}\n\n\t\tif (!this.open) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._open = false;\n\n\t\tsuper.emit(\"close\");\n\t}\n\n\tprotected abstract _send(data: any, chunked: boolean): void | Promise<void>;\n\n\t/** Allows user to send data. */\n\tpublic send(data: any, chunked = false) {\n\t\tif (!this.open) {\n\t\t\tthis.emitError(\n\t\t\t\tDataConnectionErrorType.NotOpenYet,\n\t\t\t\t\"Connection is not open. You should listen for the `open` event before sending messages.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\treturn this._send(data, chunked);\n\t}\n\n\tasync handleMessage(message: ServerMessage) {\n\t\tconst payload = message.payload;\n\n\t\tswitch (message.type) {\n\t\t\tcase ServerMessageType.Answer:\n\t\t\t\tawait this._negotiator.handleSDP(message.type, payload.sdp);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Candidate:\n\t\t\t\tawait this._negotiator.handleCandidate(payload.candidate);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(\n\t\t\t\t\t\"Unrecognized message type:\",\n\t\t\t\t\tmessage.type,\n\t\t\t\t\t\"from peer:\",\n\t\t\t\t\tthis.peer,\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n", "import { BufferedConnection } from \"./BufferedConnection\";\nimport { SerializationType } from \"../../enums\";\n\nexport class Raw extends BufferedConnection {\n\treadonly serialization = SerializationType.None;\n\n\tprotected _handleDataMessage({ data }) {\n\t\tsuper.emit(\"data\", data);\n\t}\n\n\toverride _send(data, _chunked) {\n\t\tthis._bufferedSend(data);\n\t}\n}\n", "import { BufferedConnection } from \"./BufferedConnection\";\nimport { DataConnectionErrorType, SerializationType } from \"../../enums\";\nimport { util } from \"../../util\";\n\nexport class Json extends BufferedConnection {\n\treadonly serialization = SerializationType.JSON;\n\tprivate readonly encoder = new TextEncoder();\n\tprivate readonly decoder = new TextDecoder();\n\n\tstringify: (data: any) => string = JSON.stringify;\n\tparse: (data: string) => any = JSON.parse;\n\n\t// Handles a DataChannel message.\n\tprotected override _handleDataMessage({ data }: { data: Uint8Array }): void {\n\t\tconst deserializedData = this.parse(this.decoder.decode(data));\n\n\t\t// PeerJS specific message\n\t\tconst peerData = deserializedData[\"__peerData\"];\n\t\tif (peerData && peerData.type === \"close\") {\n\t\t\tthis.close();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.emit(\"data\", deserializedData);\n\t}\n\n\toverride _send(data, _chunked) {\n\t\tconst encodedData = this.encoder.encode(this.stringify(data));\n\t\tif (encodedData.byteLength >= util.chunkedMTU) {\n\t\t\tthis.emitError(\n\t\t\t\tDataConnectionErrorType.MessageToBig,\n\t\t\t\t\"Message too big for JSON channel\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis._bufferedSend(encodedData);\n\t}\n}\n", "import { Peer, type SerializerMapping } from \"./peer\";\nimport { MsgPack } from \"./exports\";\n\n/**\n * @experimental\n */\nexport class MsgPackPeer extends Peer {\n\toverride _serializers: SerializerMapping = {\n\t\tMsgPack,\n\t\tdefault: MsgPack,\n\t};\n}\n", "import { decodeMultiStream, Encoder } from \"@msgpack/msgpack\";\nimport { StreamConnection } from \"./StreamConnection.js\";\nimport type { Peer } from \"../../peer.js\";\n\nexport class MsgPack extends StreamConnection {\n\treadonly serialization = \"MsgPack\";\n\tprivate _encoder = new Encoder();\n\n\tconstructor(peerId: string, provider: Peer, options: any) {\n\t\tsuper(peerId, provider, options);\n\n\t\t(async () => {\n\t\t\tfor await (const msg of decodeMultiStream(this._rawReadStream)) {\n\t\t\t\t// @ts-ignore\n\t\t\t\tif (msg.__peerData?.type === \"close\") {\n\t\t\t\t\tthis.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.emit(\"data\", msg);\n\t\t\t}\n\t\t})();\n\t}\n\n\tprotected override _send(data) {\n\t\treturn this.writer.write(this._encoder.encode(data));\n\t}\n}\n", "import logger from \"../../logger.js\";\nimport type { Peer } from \"../../peer.js\";\nimport { DataConnection } from \"../DataConnection.js\";\n\nexport abstract class StreamConnection extends DataConnection {\n\tprivate _CHUNK_SIZE = 1024 * 8 * 4;\n\tprivate _splitStream = new TransformStream<Uint8Array>({\n\t\ttransform: (chunk, controller) => {\n\t\t\tfor (let split = 0; split < chunk.length; split += this._CHUNK_SIZE) {\n\t\t\t\tcontroller.enqueue(chunk.subarray(split, split + this._CHUNK_SIZE));\n\t\t\t}\n\t\t},\n\t});\n\tprivate _rawSendStream = new WritableStream<ArrayBuffer>({\n\t\twrite: async (chunk, controller) => {\n\t\t\tconst openEvent = new Promise((resolve) =>\n\t\t\t\tthis.dataChannel.addEventListener(\"bufferedamountlow\", resolve, {\n\t\t\t\t\tonce: true,\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\t// if we can send the chunk now, send it\n\t\t\t// if not, we wait until at least half of the sending buffer is free again\n\t\t\tawait (this.dataChannel.bufferedAmount <=\n\t\t\t\tDataConnection.MAX_BUFFERED_AMOUNT - chunk.byteLength || openEvent);\n\n\t\t\t// TODO: what can go wrong here?\n\t\t\ttry {\n\t\t\t\tthis.dataChannel.send(chunk);\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error(`DC#:${this.connectionId} Error when sending:`, e);\n\t\t\t\tcontroller.error(e);\n\t\t\t\tthis.close();\n\t\t\t}\n\t\t},\n\t});\n\tprotected writer = this._splitStream.writable.getWriter();\n\n\tprotected _rawReadStream = new ReadableStream<ArrayBuffer>({\n\t\tstart: (controller) => {\n\t\t\tthis.once(\"open\", () => {\n\t\t\t\tthis.dataChannel.addEventListener(\"message\", (e) => {\n\t\t\t\t\tcontroller.enqueue(e.data);\n\t\t\t\t});\n\t\t\t});\n\t\t},\n\t});\n\n\tprotected constructor(peerId: string, provider: Peer, options: any) {\n\t\tsuper(peerId, provider, { ...options, reliable: true });\n\n\t\tvoid this._splitStream.readable.pipeTo(this._rawSendStream);\n\t}\n\n\tpublic override _initializeDataChannel(dc) {\n\t\tsuper._initializeDataChannel(dc);\n\t\tthis.dataChannel.binaryType = \"arraybuffer\";\n\t\tthis.dataChannel.bufferedAmountLowThreshold =\n\t\t\tDataConnection.MAX_BUFFERED_AMOUNT / 2;\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAIA,UAAMA,YAAW,CAAC;AAIlB,MAAAA,UAAS,qBAAqB,WAAW;AACvC,eAAO,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,UAAU,GAAG,EAAE;AAAA,MACnD;AAGA,MAAAA,UAAS,aAAaA,UAAS,mBAAmB;AAGlD,MAAAA,UAAS,aAAa,SAAS,MAAM;AACnC,eAAO,KAAK,KAAK,EAAE,MAAM,IAAI,EAAE,IAAI,UAAQ,KAAK,KAAK,CAAC;AAAA,MACxD;AAEA,MAAAA,UAAS,gBAAgB,S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,MAAM,QAAQ,IAAI;AAEnD,eAAO,EAAE,QAAQ,KAAK,KAAK;AAAA,MAC7B;AAGA,aAAO;AAAA,QACL,QAAQ;AAAA,QACR,MAAM,EAAE,OAAO,mBAAmB,QAAQ,IAAI,GAAG;AAAA,MACnD;AAAA,IACF;AAAA;AAAA;AAAA;AAAA,IAKA,UAAgB;AACd,WAAK,cAAc;AAGnB,UAAI,KAAK,gBAAgB;AACvB,qBAAa,KAAK,cAAc;AAChC,aAAK,iBAAiB;AAAA,MACxB;AAGA,UAAI,KAAK,YAAY;AACnB,aAAK,WAAW,OAAO;AACvB,aAAK,aAAa;AAAA,MACpB;AAGA,WAAK,sBAAsB,MAAM;AAEjC,iBAAW,QAAQ,KAAK,YAAY,OAAO,GAAG;AAC5C,aAAK,MAAM;AAAA,MACb;AACA,WAAK,YAAY,MAAM;AAEvB,iBAAW,WAAW,KAAK,gBAAgB,OAAO,GAAG;AACnD,qBAAa,QAAQ,OAAO;AAC5B,gBAAQ,OAAO,IAAI,MAAM,gBAAgB,CAAC;AAAA,MAC5C;AACA,WAAK,gBAAgB,MAAM;AAC3B,WAAK,eAAe,MAAM;AAE1B,UAAI,KAAK,cAAc;AACrB,aAAK,aAAa,QAAQ;AAC1B,aAAK,eAAe;AAAA,MACtB;AAAA,IACF;AAAA,EACF;",
3
+ "sources": ["../node_modules/sdp/sdp.js", "../src/index.ts", "../node_modules/peerjs-js-binarypack/lib/binarypack.ts", "../node_modules/peerjs-js-binarypack/lib/bufferbuilder.ts", "../node_modules/webrtc-adapter/src/js/utils.js", "../node_modules/webrtc-adapter/src/js/chrome/chrome_shim.js", "../node_modules/webrtc-adapter/src/js/chrome/getusermedia.js", "../node_modules/webrtc-adapter/src/js/firefox/firefox_shim.js", "../node_modules/webrtc-adapter/src/js/firefox/getusermedia.js", "../node_modules/webrtc-adapter/src/js/firefox/getdisplaymedia.js", "../node_modules/webrtc-adapter/src/js/safari/safari_shim.js", "../node_modules/webrtc-adapter/src/js/common_shim.js", "../node_modules/webrtc-adapter/src/js/adapter_factory.js", "../node_modules/webrtc-adapter/src/js/adapter_core.js", "../node_modules/peerjs/dist/lib/exports.ts", "../node_modules/peerjs/dist/lib/util.ts", "../node_modules/peerjs/dist/lib/dataconnection/BufferedConnection/binaryPackChunker.ts", "../node_modules/peerjs/dist/lib/supports.ts", "../node_modules/peerjs/dist/lib/utils/validateId.ts", "../node_modules/peerjs/dist/lib/utils/randomToken.ts", "../node_modules/peerjs/dist/lib/peer.ts", "../node_modules/peerjs/dist/lib/logger.ts", "../node_modules/peerjs/dist/lib/socket.ts", "../node_modules/peerjs/dist/node_modules/eventemitter3/index.js", "../node_modules/peerjs/dist/lib/enums.ts", "../node_modules/peerjs/dist/lib/version.ts", "../node_modules/peerjs/dist/lib/mediaconnection.ts", "../node_modules/peerjs/dist/lib/negotiator.ts", "../node_modules/peerjs/dist/lib/baseconnection.ts", "../node_modules/peerjs/dist/lib/peerError.ts", "../node_modules/peerjs/dist/lib/api.ts", "../node_modules/peerjs/dist/lib/dataconnection/BufferedConnection/BinaryPack.ts", "../node_modules/peerjs/dist/lib/dataconnection/BufferedConnection/BufferedConnection.ts", "../node_modules/peerjs/dist/lib/dataconnection/DataConnection.ts", "../node_modules/peerjs/dist/lib/dataconnection/BufferedConnection/Raw.ts", "../node_modules/peerjs/dist/lib/dataconnection/BufferedConnection/Json.ts", "../node_modules/peerjs/dist/lib/msgPackPeer.ts", "../node_modules/peerjs/dist/lib/dataconnection/StreamConnection/MsgPack.ts", "../node_modules/peerjs/dist/lib/dataconnection/StreamConnection/StreamConnection.ts", "../src/CallSession.ts", "../src/constants.ts", "../src/RoutingDB.ts", "../src/Router.ts", "../src/MessageHandler.ts", "../src/PeerJsWrapper.ts"],
4
+ "sourcesContent": ["/* eslint-env node */\n'use strict';\n\n// SDP helpers.\nconst SDPUtils = {};\n\n// Generate an alphanumeric identifier for cname or mids.\n// TODO: use UUIDs instead? https://gist.github.com/jed/982883\nSDPUtils.generateIdentifier = function() {\n return Math.random().toString(36).substring(2, 12);\n};\n\n// The RTCP CNAME used by all peerconnections from the same JS.\nSDPUtils.localCName = SDPUtils.generateIdentifier();\n\n// Splits SDP into lines, dealing with both CRLF and LF.\nSDPUtils.splitLines = function(blob) {\n return blob.trim().split('\\n').map(line => line.trim());\n};\n// Splits SDP into sessionpart and mediasections. Ensures CRLF.\nSDPUtils.splitSections = function(blob) {\n const parts = blob.split('\\nm=');\n return parts.map((part, index) => (index > 0 ?\n 'm=' + part : part).trim() + '\\r\\n');\n};\n\n// Returns the session description.\nSDPUtils.getDescription = function(blob) {\n const sections = SDPUtils.splitSections(blob);\n return sections && sections[0];\n};\n\n// Returns the individual media sections.\nSDPUtils.getMediaSections = function(blob) {\n const sections = SDPUtils.splitSections(blob);\n sections.shift();\n return sections;\n};\n\n// Returns lines that start with a certain prefix.\nSDPUtils.matchPrefix = function(blob, prefix) {\n return SDPUtils.splitLines(blob).filter(line => line.indexOf(prefix) === 0);\n};\n\n// Parses an ICE candidate line. Sample input:\n// candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8\n// rport 55996\"\n// Input can be prefixed with a=.\nSDPUtils.parseCandidate = function(line) {\n let parts;\n // Parse both variants.\n if (line.indexOf('a=candidate:') === 0) {\n parts = line.substring(12).split(' ');\n } else {\n parts = line.substring(10).split(' ');\n }\n\n const candidate = {\n foundation: parts[0],\n component: {1: 'rtp', 2: 'rtcp'}[parts[1]] || parts[1],\n protocol: parts[2].toLowerCase(),\n priority: parseInt(parts[3], 10),\n ip: parts[4],\n address: parts[4], // address is an alias for ip.\n port: parseInt(parts[5], 10),\n // skip parts[6] == 'typ'\n type: parts[7],\n };\n\n for (let i = 8; i < parts.length; i += 2) {\n switch (parts[i]) {\n case 'raddr':\n candidate.relatedAddress = parts[i + 1];\n break;\n case 'rport':\n candidate.relatedPort = parseInt(parts[i + 1], 10);\n break;\n case 'tcptype':\n candidate.tcpType = parts[i + 1];\n break;\n case 'ufrag':\n candidate.ufrag = parts[i + 1]; // for backward compatibility.\n candidate.usernameFragment = parts[i + 1];\n break;\n default: // extension handling, in particular ufrag. Don't overwrite.\n if (candidate[parts[i]] === undefined) {\n candidate[parts[i]] = parts[i + 1];\n }\n break;\n }\n }\n return candidate;\n};\n\n// Translates a candidate object into SDP candidate attribute.\n// This does not include the a= prefix!\nSDPUtils.writeCandidate = function(candidate) {\n const sdp = [];\n sdp.push(candidate.foundation);\n\n const component = candidate.component;\n if (component === 'rtp') {\n sdp.push(1);\n } else if (component === 'rtcp') {\n sdp.push(2);\n } else {\n sdp.push(component);\n }\n sdp.push(candidate.protocol.toUpperCase());\n sdp.push(candidate.priority);\n sdp.push(candidate.address || candidate.ip);\n sdp.push(candidate.port);\n\n const type = candidate.type;\n sdp.push('typ');\n sdp.push(type);\n if (type !== 'host' && candidate.relatedAddress &&\n candidate.relatedPort) {\n sdp.push('raddr');\n sdp.push(candidate.relatedAddress);\n sdp.push('rport');\n sdp.push(candidate.relatedPort);\n }\n if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {\n sdp.push('tcptype');\n sdp.push(candidate.tcpType);\n }\n if (candidate.usernameFragment || candidate.ufrag) {\n sdp.push('ufrag');\n sdp.push(candidate.usernameFragment || candidate.ufrag);\n }\n return 'candidate:' + sdp.join(' ');\n};\n\n// Parses an ice-options line, returns an array of option tags.\n// Sample input:\n// a=ice-options:foo bar\nSDPUtils.parseIceOptions = function(line) {\n return line.substring(14).split(' ');\n};\n\n// Parses a rtpmap line, returns RTCRtpCoddecParameters. Sample input:\n// a=rtpmap:111 opus/48000/2\nSDPUtils.parseRtpMap = function(line) {\n let parts = line.substring(9).split(' ');\n const parsed = {\n payloadType: parseInt(parts.shift(), 10), // was: id\n };\n\n parts = parts[0].split('/');\n\n parsed.name = parts[0];\n parsed.clockRate = parseInt(parts[1], 10); // was: clockrate\n parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1;\n // legacy alias, got renamed back to channels in ORTC.\n parsed.numChannels = parsed.channels;\n return parsed;\n};\n\n// Generates a rtpmap line from RTCRtpCodecCapability or\n// RTCRtpCodecParameters.\nSDPUtils.writeRtpMap = function(codec) {\n let pt = codec.payloadType;\n if (codec.preferredPayloadType !== undefined) {\n pt = codec.preferredPayloadType;\n }\n const channels = codec.channels || codec.numChannels || 1;\n return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +\n (channels !== 1 ? '/' + channels : '') + '\\r\\n';\n};\n\n// Parses a extmap line (headerextension from RFC 5285). Sample input:\n// a=extmap:2 urn:ietf:params:rtp-hdrext:toffset\n// a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset\nSDPUtils.parseExtmap = function(line) {\n const parts = line.substring(9).split(' ');\n return {\n id: parseInt(parts[0], 10),\n direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',\n uri: parts[1],\n attributes: parts.slice(2).join(' '),\n };\n};\n\n// Generates an extmap line from RTCRtpHeaderExtensionParameters or\n// RTCRtpHeaderExtension.\nSDPUtils.writeExtmap = function(headerExtension) {\n return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +\n (headerExtension.direction && headerExtension.direction !== 'sendrecv'\n ? '/' + headerExtension.direction\n : '') +\n ' ' + headerExtension.uri +\n (headerExtension.attributes ? ' ' + headerExtension.attributes : '') +\n '\\r\\n';\n};\n\n// Parses a fmtp line, returns dictionary. Sample input:\n// a=fmtp:96 vbr=on;cng=on\n// Also deals with vbr=on; cng=on\n// Non-key-value such as telephone-events `0-15` get parsed as\n// {`0-15`:undefined}\nSDPUtils.parseFmtp = function(line) {\n const parsed = {};\n let kv;\n const parts = line.substring(line.indexOf(' ') + 1).split(';');\n for (let j = 0; j < parts.length; j++) {\n kv = parts[j].trim().split('=');\n parsed[kv[0].trim()] = kv[1];\n }\n return parsed;\n};\n\n// Generates a fmtp line from RTCRtpCodecCapability or RTCRtpCodecParameters.\nSDPUtils.writeFmtp = function(codec) {\n let line = '';\n let pt = codec.payloadType;\n if (codec.preferredPayloadType !== undefined) {\n pt = codec.preferredPayloadType;\n }\n if (codec.parameters && Object.keys(codec.parameters).length) {\n const params = [];\n Object.keys(codec.parameters).forEach(param => {\n if (codec.parameters[param] !== undefined) {\n params.push(param + '=' + codec.parameters[param]);\n } else {\n params.push(param);\n }\n });\n line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\\r\\n';\n }\n return line;\n};\n\n// Parses a rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:\n// a=rtcp-fb:98 nack rpsi\nSDPUtils.parseRtcpFb = function(line) {\n const parts = line.substring(line.indexOf(' ') + 1).split(' ');\n return {\n type: parts.shift(),\n parameter: parts.join(' '),\n };\n};\n\n// Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.\nSDPUtils.writeRtcpFb = function(codec) {\n let lines = '';\n let pt = codec.payloadType;\n if (codec.preferredPayloadType !== undefined) {\n pt = codec.preferredPayloadType;\n }\n if (codec.rtcpFeedback && codec.rtcpFeedback.length) {\n // FIXME: special handling for trr-int?\n codec.rtcpFeedback.forEach(fb => {\n lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +\n (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +\n '\\r\\n';\n });\n }\n return lines;\n};\n\n// Parses a RFC 5576 ssrc media attribute. Sample input:\n// a=ssrc:3735928559 cname:something\nSDPUtils.parseSsrcMedia = function(line) {\n const sp = line.indexOf(' ');\n const parts = {\n ssrc: parseInt(line.substring(7, sp), 10),\n };\n const colon = line.indexOf(':', sp);\n if (colon > -1) {\n parts.attribute = line.substring(sp + 1, colon);\n parts.value = line.substring(colon + 1);\n } else {\n parts.attribute = line.substring(sp + 1);\n }\n return parts;\n};\n\n// Parse a ssrc-group line (see RFC 5576). Sample input:\n// a=ssrc-group:semantics 12 34\nSDPUtils.parseSsrcGroup = function(line) {\n const parts = line.substring(13).split(' ');\n return {\n semantics: parts.shift(),\n ssrcs: parts.map(ssrc => parseInt(ssrc, 10)),\n };\n};\n\n// Extracts the MID (RFC 5888) from a media section.\n// Returns the MID or undefined if no mid line was found.\nSDPUtils.getMid = function(mediaSection) {\n const mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];\n if (mid) {\n return mid.substring(6);\n }\n};\n\n// Parses a fingerprint line for DTLS-SRTP.\nSDPUtils.parseFingerprint = function(line) {\n const parts = line.substring(14).split(' ');\n return {\n algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.\n value: parts[1].toUpperCase(), // the definition is upper-case in RFC 4572.\n };\n};\n\n// Extracts DTLS parameters from SDP media section or sessionpart.\n// FIXME: for consistency with other functions this should only\n// get the fingerprint line as input. See also getIceParameters.\nSDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {\n const lines = SDPUtils.matchPrefix(mediaSection + sessionpart,\n 'a=fingerprint:');\n // Note: a=setup line is ignored since we use the 'auto' role in Edge.\n return {\n role: 'auto',\n fingerprints: lines.map(SDPUtils.parseFingerprint),\n };\n};\n\n// Serializes DTLS parameters to SDP.\nSDPUtils.writeDtlsParameters = function(params, setupType) {\n let sdp = 'a=setup:' + setupType + '\\r\\n';\n params.fingerprints.forEach(fp => {\n sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\\r\\n';\n });\n return sdp;\n};\n\n// Parses a=crypto lines into\n// https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#dictionary-rtcsrtpsdesparameters-members\nSDPUtils.parseCryptoLine = function(line) {\n const parts = line.substring(9).split(' ');\n return {\n tag: parseInt(parts[0], 10),\n cryptoSuite: parts[1],\n keyParams: parts[2],\n sessionParams: parts.slice(3),\n };\n};\n\nSDPUtils.writeCryptoLine = function(parameters) {\n return 'a=crypto:' + parameters.tag + ' ' +\n parameters.cryptoSuite + ' ' +\n (typeof parameters.keyParams === 'object'\n ? SDPUtils.writeCryptoKeyParams(parameters.keyParams)\n : parameters.keyParams) +\n (parameters.sessionParams ? ' ' + parameters.sessionParams.join(' ') : '') +\n '\\r\\n';\n};\n\n// Parses the crypto key parameters into\n// https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#rtcsrtpkeyparam*\nSDPUtils.parseCryptoKeyParams = function(keyParams) {\n if (keyParams.indexOf('inline:') !== 0) {\n return null;\n }\n const parts = keyParams.substring(7).split('|');\n return {\n keyMethod: 'inline',\n keySalt: parts[0],\n lifeTime: parts[1],\n mkiValue: parts[2] ? parts[2].split(':')[0] : undefined,\n mkiLength: parts[2] ? parts[2].split(':')[1] : undefined,\n };\n};\n\nSDPUtils.writeCryptoKeyParams = function(keyParams) {\n return keyParams.keyMethod + ':'\n + keyParams.keySalt +\n (keyParams.lifeTime ? '|' + keyParams.lifeTime : '') +\n (keyParams.mkiValue && keyParams.mkiLength\n ? '|' + keyParams.mkiValue + ':' + keyParams.mkiLength\n : '');\n};\n\n// Extracts all SDES parameters.\nSDPUtils.getCryptoParameters = function(mediaSection, sessionpart) {\n const lines = SDPUtils.matchPrefix(mediaSection + sessionpart,\n 'a=crypto:');\n return lines.map(SDPUtils.parseCryptoLine);\n};\n\n// Parses ICE information from SDP media section or sessionpart.\n// FIXME: for consistency with other functions this should only\n// get the ice-ufrag and ice-pwd lines as input.\nSDPUtils.getIceParameters = function(mediaSection, sessionpart) {\n const ufrag = SDPUtils.matchPrefix(mediaSection + sessionpart,\n 'a=ice-ufrag:')[0];\n const pwd = SDPUtils.matchPrefix(mediaSection + sessionpart,\n 'a=ice-pwd:')[0];\n if (!(ufrag && pwd)) {\n return null;\n }\n return {\n usernameFragment: ufrag.substring(12),\n password: pwd.substring(10),\n };\n};\n\n// Serializes ICE parameters to SDP.\nSDPUtils.writeIceParameters = function(params) {\n let sdp = 'a=ice-ufrag:' + params.usernameFragment + '\\r\\n' +\n 'a=ice-pwd:' + params.password + '\\r\\n';\n if (params.iceLite) {\n sdp += 'a=ice-lite\\r\\n';\n }\n return sdp;\n};\n\n// Parses the SDP media section and returns RTCRtpParameters.\nSDPUtils.parseRtpParameters = function(mediaSection) {\n const description = {\n codecs: [],\n headerExtensions: [],\n fecMechanisms: [],\n rtcp: [],\n };\n const lines = SDPUtils.splitLines(mediaSection);\n const mline = lines[0].split(' ');\n description.profile = mline[2];\n for (let i = 3; i < mline.length; i++) { // find all codecs from mline[3..]\n const pt = mline[i];\n const rtpmapline = SDPUtils.matchPrefix(\n mediaSection, 'a=rtpmap:' + pt + ' ')[0];\n if (rtpmapline) {\n const codec = SDPUtils.parseRtpMap(rtpmapline);\n const fmtps = SDPUtils.matchPrefix(\n mediaSection, 'a=fmtp:' + pt + ' ');\n // Only the first a=fmtp:<pt> is considered.\n codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};\n codec.rtcpFeedback = SDPUtils.matchPrefix(\n mediaSection, 'a=rtcp-fb:' + pt + ' ')\n .map(SDPUtils.parseRtcpFb);\n description.codecs.push(codec);\n // parse FEC mechanisms from rtpmap lines.\n switch (codec.name.toUpperCase()) {\n case 'RED':\n case 'ULPFEC':\n description.fecMechanisms.push(codec.name.toUpperCase());\n break;\n default: // only RED and ULPFEC are recognized as FEC mechanisms.\n break;\n }\n }\n }\n SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(line => {\n description.headerExtensions.push(SDPUtils.parseExtmap(line));\n });\n const wildcardRtcpFb = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-fb:* ')\n .map(SDPUtils.parseRtcpFb);\n description.codecs.forEach(codec => {\n wildcardRtcpFb.forEach(fb=> {\n const duplicate = codec.rtcpFeedback.find(existingFeedback => {\n return existingFeedback.type === fb.type &&\n existingFeedback.parameter === fb.parameter;\n });\n if (!duplicate) {\n codec.rtcpFeedback.push(fb);\n }\n });\n });\n // FIXME: parse rtcp.\n return description;\n};\n\n// Generates parts of the SDP media section describing the capabilities /\n// parameters.\nSDPUtils.writeRtpDescription = function(kind, caps) {\n let sdp = '';\n\n // Build the mline.\n sdp += 'm=' + kind + ' ';\n sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.\n sdp += ' ' + (caps.profile || 'UDP/TLS/RTP/SAVPF') + ' ';\n sdp += caps.codecs.map(codec => {\n if (codec.preferredPayloadType !== undefined) {\n return codec.preferredPayloadType;\n }\n return codec.payloadType;\n }).join(' ') + '\\r\\n';\n\n sdp += 'c=IN IP4 0.0.0.0\\r\\n';\n sdp += 'a=rtcp:9 IN IP4 0.0.0.0\\r\\n';\n\n // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.\n caps.codecs.forEach(codec => {\n sdp += SDPUtils.writeRtpMap(codec);\n sdp += SDPUtils.writeFmtp(codec);\n sdp += SDPUtils.writeRtcpFb(codec);\n });\n let maxptime = 0;\n caps.codecs.forEach(codec => {\n if (codec.maxptime > maxptime) {\n maxptime = codec.maxptime;\n }\n });\n if (maxptime > 0) {\n sdp += 'a=maxptime:' + maxptime + '\\r\\n';\n }\n\n if (caps.headerExtensions) {\n caps.headerExtensions.forEach(extension => {\n sdp += SDPUtils.writeExtmap(extension);\n });\n }\n // FIXME: write fecMechanisms.\n return sdp;\n};\n\n// Parses the SDP media section and returns an array of\n// RTCRtpEncodingParameters.\nSDPUtils.parseRtpEncodingParameters = function(mediaSection) {\n const encodingParameters = [];\n const description = SDPUtils.parseRtpParameters(mediaSection);\n const hasRed = description.fecMechanisms.indexOf('RED') !== -1;\n const hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;\n\n // filter a=ssrc:... cname:, ignore PlanB-msid\n const ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')\n .map(line => SDPUtils.parseSsrcMedia(line))\n .filter(parts => parts.attribute === 'cname');\n const primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;\n let secondarySsrc;\n\n const flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')\n .map(line => {\n const parts = line.substring(17).split(' ');\n return parts.map(part => parseInt(part, 10));\n });\n if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {\n secondarySsrc = flows[0][1];\n }\n\n description.codecs.forEach(codec => {\n if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {\n let encParam = {\n ssrc: primarySsrc,\n codecPayloadType: parseInt(codec.parameters.apt, 10),\n };\n if (primarySsrc && secondarySsrc) {\n encParam.rtx = {ssrc: secondarySsrc};\n }\n encodingParameters.push(encParam);\n if (hasRed) {\n encParam = JSON.parse(JSON.stringify(encParam));\n encParam.fec = {\n ssrc: primarySsrc,\n mechanism: hasUlpfec ? 'red+ulpfec' : 'red',\n };\n encodingParameters.push(encParam);\n }\n }\n });\n if (encodingParameters.length === 0 && primarySsrc) {\n encodingParameters.push({\n ssrc: primarySsrc,\n });\n }\n\n // we support both b=AS and b=TIAS but interpret AS as TIAS.\n let bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');\n if (bandwidth.length) {\n if (bandwidth[0].indexOf('b=TIAS:') === 0) {\n bandwidth = parseInt(bandwidth[0].substring(7), 10);\n } else if (bandwidth[0].indexOf('b=AS:') === 0) {\n // use formula from JSEP to convert b=AS to TIAS value.\n bandwidth = parseInt(bandwidth[0].substring(5), 10) * 1000 * 0.95\n - (50 * 40 * 8);\n } else {\n bandwidth = undefined;\n }\n encodingParameters.forEach(params => {\n params.maxBitrate = bandwidth;\n });\n }\n return encodingParameters;\n};\n\n// parses http://draft.ortc.org/#rtcrtcpparameters*\nSDPUtils.parseRtcpParameters = function(mediaSection) {\n const rtcpParameters = {};\n\n // Gets the first SSRC. Note that with RTX there might be multiple\n // SSRCs.\n const remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')\n .map(line => SDPUtils.parseSsrcMedia(line))\n .filter(obj => obj.attribute === 'cname')[0];\n if (remoteSsrc) {\n rtcpParameters.cname = remoteSsrc.value;\n rtcpParameters.ssrc = remoteSsrc.ssrc;\n }\n\n // Edge uses the compound attribute instead of reducedSize\n // compound is !reducedSize\n const rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');\n rtcpParameters.reducedSize = rsize.length > 0;\n rtcpParameters.compound = rsize.length === 0;\n\n // parses the rtcp-mux attr\u0456bute.\n // Note that Edge does not support unmuxed RTCP.\n const mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');\n rtcpParameters.mux = mux.length > 0;\n\n return rtcpParameters;\n};\n\nSDPUtils.writeRtcpParameters = function(rtcpParameters) {\n let sdp = '';\n if (rtcpParameters.reducedSize) {\n sdp += 'a=rtcp-rsize\\r\\n';\n }\n if (rtcpParameters.mux) {\n sdp += 'a=rtcp-mux\\r\\n';\n }\n if (rtcpParameters.ssrc !== undefined && rtcpParameters.cname) {\n sdp += 'a=ssrc:' + rtcpParameters.ssrc +\n ' cname:' + rtcpParameters.cname + '\\r\\n';\n }\n return sdp;\n};\n\n\n// parses either a=msid: or a=ssrc:... msid lines and returns\n// the id of the MediaStream and MediaStreamTrack.\nSDPUtils.parseMsid = function(mediaSection) {\n let parts;\n const spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');\n if (spec.length === 1) {\n parts = spec[0].substring(7).split(' ');\n return {stream: parts[0], track: parts[1]};\n }\n const planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')\n .map(line => SDPUtils.parseSsrcMedia(line))\n .filter(msidParts => msidParts.attribute === 'msid');\n if (planB.length > 0) {\n parts = planB[0].value.split(' ');\n return {stream: parts[0], track: parts[1]};\n }\n};\n\n// SCTP\n// parses draft-ietf-mmusic-sctp-sdp-26 first and falls back\n// to draft-ietf-mmusic-sctp-sdp-05\nSDPUtils.parseSctpDescription = function(mediaSection) {\n const mline = SDPUtils.parseMLine(mediaSection);\n const maxSizeLine = SDPUtils.matchPrefix(mediaSection, 'a=max-message-size:');\n let maxMessageSize;\n if (maxSizeLine.length > 0) {\n maxMessageSize = parseInt(maxSizeLine[0].substring(19), 10);\n }\n if (isNaN(maxMessageSize)) {\n maxMessageSize = 65536;\n }\n const sctpPort = SDPUtils.matchPrefix(mediaSection, 'a=sctp-port:');\n if (sctpPort.length > 0) {\n return {\n port: parseInt(sctpPort[0].substring(12), 10),\n protocol: mline.fmt,\n maxMessageSize,\n };\n }\n const sctpMapLines = SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:');\n if (sctpMapLines.length > 0) {\n const parts = sctpMapLines[0]\n .substring(10)\n .split(' ');\n return {\n port: parseInt(parts[0], 10),\n protocol: parts[1],\n maxMessageSize,\n };\n }\n};\n\n// SCTP\n// outputs the draft-ietf-mmusic-sctp-sdp-26 version that all browsers\n// support by now receiving in this format, unless we originally parsed\n// as the draft-ietf-mmusic-sctp-sdp-05 format (indicated by the m-line\n// protocol of DTLS/SCTP -- without UDP/ or TCP/)\nSDPUtils.writeSctpDescription = function(media, sctp) {\n let output = [];\n if (media.protocol !== 'DTLS/SCTP') {\n output = [\n 'm=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.protocol + '\\r\\n',\n 'c=IN IP4 0.0.0.0\\r\\n',\n 'a=sctp-port:' + sctp.port + '\\r\\n',\n ];\n } else {\n output = [\n 'm=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.port + '\\r\\n',\n 'c=IN IP4 0.0.0.0\\r\\n',\n 'a=sctpmap:' + sctp.port + ' ' + sctp.protocol + ' 65535\\r\\n',\n ];\n }\n if (sctp.maxMessageSize !== undefined) {\n output.push('a=max-message-size:' + sctp.maxMessageSize + '\\r\\n');\n }\n return output.join('');\n};\n\n// Generate a session ID for SDP.\n// https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1\n// recommends using a cryptographically random +ve 64-bit value\n// but right now this should be acceptable and within the right range\nSDPUtils.generateSessionId = function() {\n return Math.random().toString().substr(2, 22);\n};\n\n// Write boiler plate for start of SDP\n// sessId argument is optional - if not supplied it will\n// be generated randomly\n// sessVersion is optional and defaults to 2\n// sessUser is optional and defaults to 'thisisadapterortc'\nSDPUtils.writeSessionBoilerplate = function(sessId, sessVer, sessUser) {\n let sessionId;\n const version = sessVer !== undefined ? sessVer : 2;\n if (sessId) {\n sessionId = sessId;\n } else {\n sessionId = SDPUtils.generateSessionId();\n }\n const user = sessUser || 'thisisadapterortc';\n // FIXME: sess-id should be an NTP timestamp.\n return 'v=0\\r\\n' +\n 'o=' + user + ' ' + sessionId + ' ' + version +\n ' IN IP4 127.0.0.1\\r\\n' +\n 's=-\\r\\n' +\n 't=0 0\\r\\n';\n};\n\n// Gets the direction from the mediaSection or the sessionpart.\nSDPUtils.getDirection = function(mediaSection, sessionpart) {\n // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.\n const lines = SDPUtils.splitLines(mediaSection);\n for (let i = 0; i < lines.length; i++) {\n switch (lines[i]) {\n case 'a=sendrecv':\n case 'a=sendonly':\n case 'a=recvonly':\n case 'a=inactive':\n return lines[i].substring(2);\n default:\n // FIXME: What should happen here?\n }\n }\n if (sessionpart) {\n return SDPUtils.getDirection(sessionpart);\n }\n return 'sendrecv';\n};\n\nSDPUtils.getKind = function(mediaSection) {\n const lines = SDPUtils.splitLines(mediaSection);\n const mline = lines[0].split(' ');\n return mline[0].substring(2);\n};\n\nSDPUtils.isRejected = function(mediaSection) {\n return mediaSection.split(' ', 2)[1] === '0';\n};\n\nSDPUtils.parseMLine = function(mediaSection) {\n const lines = SDPUtils.splitLines(mediaSection);\n const parts = lines[0].substring(2).split(' ');\n return {\n kind: parts[0],\n port: parseInt(parts[1], 10),\n protocol: parts[2],\n fmt: parts.slice(3).join(' '),\n };\n};\n\nSDPUtils.parseOLine = function(mediaSection) {\n const line = SDPUtils.matchPrefix(mediaSection, 'o=')[0];\n const parts = line.substring(2).split(' ');\n return {\n username: parts[0],\n sessionId: parts[1],\n sessionVersion: parseInt(parts[2], 10),\n netType: parts[3],\n addressType: parts[4],\n address: parts[5],\n };\n};\n\n// a very naive interpretation of a valid SDP.\nSDPUtils.isValidSDP = function(blob) {\n if (typeof blob !== 'string' || blob.length === 0) {\n return false;\n }\n const lines = SDPUtils.splitLines(blob);\n for (let i = 0; i < lines.length; i++) {\n if (lines[i].length < 2 || lines[i].charAt(1) !== '=') {\n return false;\n }\n // TODO: check the modifier a bit more.\n }\n return true;\n};\n\n// Expose public methods.\nif (typeof module === 'object') {\n module.exports = SDPUtils;\n}\n", "export { PeerJsWrapper, VERSION } from './PeerJsWrapper';\nexport {\n initRoutingDB,\n loadRoutingTable,\n saveRouteEntry,\n saveRouteEntries,\n deleteRouteEntry,\n loadDirectNodes,\n saveDirectNode,\n saveDirectNodes,\n clearAllRoutingData\n} from './RoutingDB';\nexport type {\n Request,\n Response,\n SimpleHandler,\n CallOptions,\n CallSession,\n CallState,\n CallStateListener,\n IncomingCallEvent,\n IncomingCallListener,\n RouteEntry,\n NextHop,\n DirectNodeLatency,\n RelayConfig,\n RelayMessage,\n ServerConfig\n} from './types';\n", "import { BufferBuilder } from \"./bufferbuilder\";\n\nexport type Packable =\n\t| null\n\t| undefined\n\t| string\n\t| number\n\t| boolean\n\t| Date\n\t| ArrayBuffer\n\t| Blob\n\t| Array<Packable>\n\t| { [key: string]: Packable }\n\t| ({ BYTES_PER_ELEMENT: number } & ArrayBufferView);\nexport type Unpackable =\n\t| null\n\t| undefined\n\t| string\n\t| number\n\t| boolean\n\t| ArrayBuffer\n\t| Array<Unpackable>\n\t| { [key: string]: Unpackable };\n\nexport function unpack<T extends Unpackable>(data: ArrayBuffer) {\n\tconst unpacker = new Unpacker(data);\n\treturn unpacker.unpack() as T;\n}\n\nexport function pack(data: Packable) {\n\tconst packer = new Packer();\n\tconst res = packer.pack(data);\n\tif (res instanceof Promise) {\n\t\treturn res.then(() => packer.getBuffer());\n\t}\n\treturn packer.getBuffer();\n}\n\nclass Unpacker {\n\tprivate index: number;\n\tprivate readonly dataBuffer: ArrayBuffer;\n\tprivate readonly dataView: Uint8Array;\n\tprivate readonly length: number;\n\n\tconstructor(data: ArrayBuffer) {\n\t\tthis.index = 0;\n\t\tthis.dataBuffer = data;\n\t\tthis.dataView = new Uint8Array(this.dataBuffer);\n\t\tthis.length = this.dataBuffer.byteLength;\n\t}\n\n\tunpack(): Unpackable {\n\t\tconst type = this.unpack_uint8();\n\t\tif (type < 0x80) {\n\t\t\treturn type;\n\t\t} else if ((type ^ 0xe0) < 0x20) {\n\t\t\treturn (type ^ 0xe0) - 0x20;\n\t\t}\n\n\t\tlet size;\n\t\tif ((size = type ^ 0xa0) <= 0x0f) {\n\t\t\treturn this.unpack_raw(size);\n\t\t} else if ((size = type ^ 0xb0) <= 0x0f) {\n\t\t\treturn this.unpack_string(size);\n\t\t} else if ((size = type ^ 0x90) <= 0x0f) {\n\t\t\treturn this.unpack_array(size);\n\t\t} else if ((size = type ^ 0x80) <= 0x0f) {\n\t\t\treturn this.unpack_map(size);\n\t\t}\n\n\t\tswitch (type) {\n\t\t\tcase 0xc0:\n\t\t\t\treturn null;\n\t\t\tcase 0xc1:\n\t\t\t\treturn undefined;\n\t\t\tcase 0xc2:\n\t\t\t\treturn false;\n\t\t\tcase 0xc3:\n\t\t\t\treturn true;\n\t\t\tcase 0xca:\n\t\t\t\treturn this.unpack_float();\n\t\t\tcase 0xcb:\n\t\t\t\treturn this.unpack_double();\n\t\t\tcase 0xcc:\n\t\t\t\treturn this.unpack_uint8();\n\t\t\tcase 0xcd:\n\t\t\t\treturn this.unpack_uint16();\n\t\t\tcase 0xce:\n\t\t\t\treturn this.unpack_uint32();\n\t\t\tcase 0xcf:\n\t\t\t\treturn this.unpack_uint64();\n\t\t\tcase 0xd0:\n\t\t\t\treturn this.unpack_int8();\n\t\t\tcase 0xd1:\n\t\t\t\treturn this.unpack_int16();\n\t\t\tcase 0xd2:\n\t\t\t\treturn this.unpack_int32();\n\t\t\tcase 0xd3:\n\t\t\t\treturn this.unpack_int64();\n\t\t\tcase 0xd4:\n\t\t\t\treturn undefined;\n\t\t\tcase 0xd5:\n\t\t\t\treturn undefined;\n\t\t\tcase 0xd6:\n\t\t\t\treturn undefined;\n\t\t\tcase 0xd7:\n\t\t\t\treturn undefined;\n\t\t\tcase 0xd8:\n\t\t\t\tsize = this.unpack_uint16();\n\t\t\t\treturn this.unpack_string(size);\n\t\t\tcase 0xd9:\n\t\t\t\tsize = this.unpack_uint32();\n\t\t\t\treturn this.unpack_string(size);\n\t\t\tcase 0xda:\n\t\t\t\tsize = this.unpack_uint16();\n\t\t\t\treturn this.unpack_raw(size);\n\t\t\tcase 0xdb:\n\t\t\t\tsize = this.unpack_uint32();\n\t\t\t\treturn this.unpack_raw(size);\n\t\t\tcase 0xdc:\n\t\t\t\tsize = this.unpack_uint16();\n\t\t\t\treturn this.unpack_array(size);\n\t\t\tcase 0xdd:\n\t\t\t\tsize = this.unpack_uint32();\n\t\t\t\treturn this.unpack_array(size);\n\t\t\tcase 0xde:\n\t\t\t\tsize = this.unpack_uint16();\n\t\t\t\treturn this.unpack_map(size);\n\t\t\tcase 0xdf:\n\t\t\t\tsize = this.unpack_uint32();\n\t\t\t\treturn this.unpack_map(size);\n\t\t}\n\t}\n\n\tunpack_uint8() {\n\t\tconst byte = this.dataView[this.index] & 0xff;\n\t\tthis.index++;\n\t\treturn byte;\n\t}\n\n\tunpack_uint16() {\n\t\tconst bytes = this.read(2);\n\t\tconst uint16 = (bytes[0] & 0xff) * 256 + (bytes[1] & 0xff);\n\t\tthis.index += 2;\n\t\treturn uint16;\n\t}\n\n\tunpack_uint32() {\n\t\tconst bytes = this.read(4);\n\t\tconst uint32 =\n\t\t\t((bytes[0] * 256 + bytes[1]) * 256 + bytes[2]) * 256 + bytes[3];\n\t\tthis.index += 4;\n\t\treturn uint32;\n\t}\n\n\tunpack_uint64() {\n\t\tconst bytes = this.read(8);\n\t\tconst uint64 =\n\t\t\t((((((bytes[0] * 256 + bytes[1]) * 256 + bytes[2]) * 256 + bytes[3]) *\n\t\t\t\t256 +\n\t\t\t\tbytes[4]) *\n\t\t\t\t256 +\n\t\t\t\tbytes[5]) *\n\t\t\t\t256 +\n\t\t\t\tbytes[6]) *\n\t\t\t\t256 +\n\t\t\tbytes[7];\n\t\tthis.index += 8;\n\t\treturn uint64;\n\t}\n\n\tunpack_int8() {\n\t\tconst uint8 = this.unpack_uint8();\n\t\treturn uint8 < 0x80 ? uint8 : uint8 - (1 << 8);\n\t}\n\n\tunpack_int16() {\n\t\tconst uint16 = this.unpack_uint16();\n\t\treturn uint16 < 0x8000 ? uint16 : uint16 - (1 << 16);\n\t}\n\n\tunpack_int32() {\n\t\tconst uint32 = this.unpack_uint32();\n\t\treturn uint32 < 2 ** 31 ? uint32 : uint32 - 2 ** 32;\n\t}\n\n\tunpack_int64() {\n\t\tconst uint64 = this.unpack_uint64();\n\t\treturn uint64 < 2 ** 63 ? uint64 : uint64 - 2 ** 64;\n\t}\n\n\tunpack_raw(size: number) {\n\t\tif (this.length < this.index + size) {\n\t\t\tthrow new Error(\n\t\t\t\t`BinaryPackFailure: index is out of range ${this.index} ${size} ${this.length}`,\n\t\t\t);\n\t\t}\n\t\tconst buf = this.dataBuffer.slice(this.index, this.index + size);\n\t\tthis.index += size;\n\n\t\treturn buf;\n\t}\n\n\tunpack_string(size: number) {\n\t\tconst bytes = this.read(size);\n\t\tlet i = 0;\n\t\tlet str = \"\";\n\t\tlet c;\n\t\tlet code;\n\n\t\twhile (i < size) {\n\t\t\tc = bytes[i];\n\t\t\t// The length of a UTF-8 sequence is specified in the first byte:\n\t\t\t// 0xxxxxxx means length 1,\n\t\t\t// 110xxxxx means length 2,\n\t\t\t// 1110xxxx means length 3,\n\t\t\t// 11110xxx means length 4.\n\t\t\t// 10xxxxxx is for non-initial bytes.\n\t\t\tif (c < 0xa0) {\n\t\t\t\t// One-byte sequence: bits 0xxxxxxx\n\t\t\t\tcode = c;\n\t\t\t\ti++;\n\t\t\t} else if ((c ^ 0xc0) < 0x20) {\n\t\t\t\t// Two-byte sequence: bits 110xxxxx 10xxxxxx\n\t\t\t\tcode = ((c & 0x1f) << 6) | (bytes[i + 1] & 0x3f);\n\t\t\t\ti += 2;\n\t\t\t} else if ((c ^ 0xe0) < 0x10) {\n\t\t\t\t// Three-byte sequence: bits 1110xxxx 10xxxxxx 10xxxxxx\n\t\t\t\tcode =\n\t\t\t\t\t((c & 0x0f) << 12) |\n\t\t\t\t\t((bytes[i + 1] & 0x3f) << 6) |\n\t\t\t\t\t(bytes[i + 2] & 0x3f);\n\t\t\t\ti += 3;\n\t\t\t} else {\n\t\t\t\t// Four-byte sequence: bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n\t\t\t\tcode =\n\t\t\t\t\t((c & 0x07) << 18) |\n\t\t\t\t\t((bytes[i + 1] & 0x3f) << 12) |\n\t\t\t\t\t((bytes[i + 2] & 0x3f) << 6) |\n\t\t\t\t\t(bytes[i + 3] & 0x3f);\n\t\t\t\ti += 4;\n\t\t\t}\n\t\t\tstr += String.fromCodePoint(code);\n\t\t}\n\n\t\tthis.index += size;\n\t\treturn str;\n\t}\n\n\tunpack_array(size: number) {\n\t\tconst objects = new Array<Unpackable>(size);\n\t\tfor (let i = 0; i < size; i++) {\n\t\t\tobjects[i] = this.unpack();\n\t\t}\n\t\treturn objects;\n\t}\n\n\tunpack_map(size: number) {\n\t\tconst map: { [key: string]: Unpackable } = {};\n\t\tfor (let i = 0; i < size; i++) {\n\t\t\tconst key = this.unpack() as string;\n\t\t\tmap[key] = this.unpack();\n\t\t}\n\t\treturn map;\n\t}\n\n\tunpack_float() {\n\t\tconst uint32 = this.unpack_uint32();\n\t\tconst sign = uint32 >> 31;\n\t\tconst exp = ((uint32 >> 23) & 0xff) - 127;\n\t\tconst fraction = (uint32 & 0x7fffff) | 0x800000;\n\t\treturn (sign === 0 ? 1 : -1) * fraction * 2 ** (exp - 23);\n\t}\n\n\tunpack_double() {\n\t\tconst h32 = this.unpack_uint32();\n\t\tconst l32 = this.unpack_uint32();\n\t\tconst sign = h32 >> 31;\n\t\tconst exp = ((h32 >> 20) & 0x7ff) - 1023;\n\t\tconst hfrac = (h32 & 0xfffff) | 0x100000;\n\t\tconst frac = hfrac * 2 ** (exp - 20) + l32 * 2 ** (exp - 52);\n\t\treturn (sign === 0 ? 1 : -1) * frac;\n\t}\n\n\tread(length: number) {\n\t\tconst j = this.index;\n\t\tif (j + length <= this.length) {\n\t\t\treturn this.dataView.subarray(j, j + length);\n\t\t} else {\n\t\t\tthrow new Error(\"BinaryPackFailure: read index out of range\");\n\t\t}\n\t}\n}\n\nexport class Packer {\n\tprivate _bufferBuilder = new BufferBuilder();\n\tprivate _textEncoder = new TextEncoder();\n\n\tgetBuffer() {\n\t\treturn this._bufferBuilder.toArrayBuffer();\n\t}\n\n\tpack(value: Packable) {\n\t\tif (typeof value === \"string\") {\n\t\t\tthis.pack_string(value);\n\t\t} else if (typeof value === \"number\") {\n\t\t\tif (Math.floor(value) === value) {\n\t\t\t\tthis.pack_integer(value);\n\t\t\t} else {\n\t\t\t\tthis.pack_double(value);\n\t\t\t}\n\t\t} else if (typeof value === \"boolean\") {\n\t\t\tif (value === true) {\n\t\t\t\tthis._bufferBuilder.append(0xc3);\n\t\t\t} else if (value === false) {\n\t\t\t\tthis._bufferBuilder.append(0xc2);\n\t\t\t}\n\t\t} else if (value === undefined) {\n\t\t\tthis._bufferBuilder.append(0xc0);\n\t\t} else if (typeof value === \"object\") {\n\t\t\tif (value === null) {\n\t\t\t\tthis._bufferBuilder.append(0xc0);\n\t\t\t} else {\n\t\t\t\tconst constructor = value.constructor;\n\t\t\t\tif (value instanceof Array) {\n\t\t\t\t\tconst res = this.pack_array(value);\n\t\t\t\t\tif (res instanceof Promise) {\n\t\t\t\t\t\treturn res.then(() => this._bufferBuilder.flush());\n\t\t\t\t\t}\n\t\t\t\t} else if (value instanceof ArrayBuffer) {\n\t\t\t\t\tthis.pack_bin(new Uint8Array(value));\n\t\t\t\t} else if (\"BYTES_PER_ELEMENT\" in value) {\n\t\t\t\t\tconst v = value as unknown as DataView;\n\t\t\t\t\tthis.pack_bin(new Uint8Array(v.buffer, v.byteOffset, v.byteLength));\n\t\t\t\t} else if (value instanceof Date) {\n\t\t\t\t\tthis.pack_string(value.toString());\n\t\t\t\t} else if (value instanceof Blob) {\n\t\t\t\t\treturn value.arrayBuffer().then((buffer) => {\n\t\t\t\t\t\tthis.pack_bin(new Uint8Array(buffer));\n\t\t\t\t\t\tthis._bufferBuilder.flush();\n\t\t\t\t\t});\n\t\t\t\t\t// this.pack_bin(new Uint8Array(await value.arrayBuffer()));\n\t\t\t\t} else if (\n\t\t\t\t\tconstructor == Object ||\n\t\t\t\t\tconstructor.toString().startsWith(\"class\")\n\t\t\t\t) {\n\t\t\t\t\tconst res = this.pack_object(value);\n\t\t\t\t\tif (res instanceof Promise) {\n\t\t\t\t\t\treturn res.then(() => this._bufferBuilder.flush());\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(`Type \"${constructor.toString()}\" not yet supported`);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new Error(`Type \"${typeof value}\" not yet supported`);\n\t\t}\n\t\tthis._bufferBuilder.flush();\n\t}\n\n\tpack_bin(blob: Uint8Array) {\n\t\tconst length = blob.length;\n\n\t\tif (length <= 0x0f) {\n\t\t\tthis.pack_uint8(0xa0 + length);\n\t\t} else if (length <= 0xffff) {\n\t\t\tthis._bufferBuilder.append(0xda);\n\t\t\tthis.pack_uint16(length);\n\t\t} else if (length <= 0xffffffff) {\n\t\t\tthis._bufferBuilder.append(0xdb);\n\t\t\tthis.pack_uint32(length);\n\t\t} else {\n\t\t\tthrow new Error(\"Invalid length\");\n\t\t}\n\t\tthis._bufferBuilder.append_buffer(blob);\n\t}\n\n\tpack_string(str: string) {\n\t\tconst encoded = this._textEncoder.encode(str);\n\t\tconst length = encoded.length;\n\n\t\tif (length <= 0x0f) {\n\t\t\tthis.pack_uint8(0xb0 + length);\n\t\t} else if (length <= 0xffff) {\n\t\t\tthis._bufferBuilder.append(0xd8);\n\t\t\tthis.pack_uint16(length);\n\t\t} else if (length <= 0xffffffff) {\n\t\t\tthis._bufferBuilder.append(0xd9);\n\t\t\tthis.pack_uint32(length);\n\t\t} else {\n\t\t\tthrow new Error(\"Invalid length\");\n\t\t}\n\t\tthis._bufferBuilder.append_buffer(encoded);\n\t}\n\n\tpack_array(ary: Packable[]) {\n\t\tconst length = ary.length;\n\t\tif (length <= 0x0f) {\n\t\t\tthis.pack_uint8(0x90 + length);\n\t\t} else if (length <= 0xffff) {\n\t\t\tthis._bufferBuilder.append(0xdc);\n\t\t\tthis.pack_uint16(length);\n\t\t} else if (length <= 0xffffffff) {\n\t\t\tthis._bufferBuilder.append(0xdd);\n\t\t\tthis.pack_uint32(length);\n\t\t} else {\n\t\t\tthrow new Error(\"Invalid length\");\n\t\t}\n\n\t\tconst packNext = (index: number): Promise<void> | void => {\n\t\t\tif (index < length) {\n\t\t\t\tconst res = this.pack(ary[index]);\n\t\t\t\tif (res instanceof Promise) {\n\t\t\t\t\treturn res.then(() => packNext(index + 1));\n\t\t\t\t}\n\t\t\t\treturn packNext(index + 1);\n\t\t\t}\n\t\t};\n\n\t\treturn packNext(0);\n\t}\n\n\tpack_integer(num: number) {\n\t\tif (num >= -0x20 && num <= 0x7f) {\n\t\t\tthis._bufferBuilder.append(num & 0xff);\n\t\t} else if (num >= 0x00 && num <= 0xff) {\n\t\t\tthis._bufferBuilder.append(0xcc);\n\t\t\tthis.pack_uint8(num);\n\t\t} else if (num >= -0x80 && num <= 0x7f) {\n\t\t\tthis._bufferBuilder.append(0xd0);\n\t\t\tthis.pack_int8(num);\n\t\t} else if (num >= 0x0000 && num <= 0xffff) {\n\t\t\tthis._bufferBuilder.append(0xcd);\n\t\t\tthis.pack_uint16(num);\n\t\t} else if (num >= -0x8000 && num <= 0x7fff) {\n\t\t\tthis._bufferBuilder.append(0xd1);\n\t\t\tthis.pack_int16(num);\n\t\t} else if (num >= 0x00000000 && num <= 0xffffffff) {\n\t\t\tthis._bufferBuilder.append(0xce);\n\t\t\tthis.pack_uint32(num);\n\t\t} else if (num >= -0x80000000 && num <= 0x7fffffff) {\n\t\t\tthis._bufferBuilder.append(0xd2);\n\t\t\tthis.pack_int32(num);\n\t\t} else if (num >= -0x8000000000000000 && num <= 0x7fffffffffffffff) {\n\t\t\tthis._bufferBuilder.append(0xd3);\n\t\t\tthis.pack_int64(num);\n\t\t} else if (num >= 0x0000000000000000 && num <= 0xffffffffffffffff) {\n\t\t\tthis._bufferBuilder.append(0xcf);\n\t\t\tthis.pack_uint64(num);\n\t\t} else {\n\t\t\tthrow new Error(\"Invalid integer\");\n\t\t}\n\t}\n\n\tpack_double(num: number) {\n\t\tlet sign = 0;\n\t\tif (num < 0) {\n\t\t\tsign = 1;\n\t\t\tnum = -num;\n\t\t}\n\t\tconst exp = Math.floor(Math.log(num) / Math.LN2);\n\t\tconst frac0 = num / 2 ** exp - 1;\n\t\tconst frac1 = Math.floor(frac0 * 2 ** 52);\n\t\tconst b32 = 2 ** 32;\n\t\tconst h32 =\n\t\t\t(sign << 31) | ((exp + 1023) << 20) | ((frac1 / b32) & 0x0fffff);\n\t\tconst l32 = frac1 % b32;\n\t\tthis._bufferBuilder.append(0xcb);\n\t\tthis.pack_int32(h32);\n\t\tthis.pack_int32(l32);\n\t}\n\n\tpack_object(obj: { [key: string]: Packable }) {\n\t\tconst keys = Object.keys(obj);\n\t\tconst length = keys.length;\n\t\tif (length <= 0x0f) {\n\t\t\tthis.pack_uint8(0x80 + length);\n\t\t} else if (length <= 0xffff) {\n\t\t\tthis._bufferBuilder.append(0xde);\n\t\t\tthis.pack_uint16(length);\n\t\t} else if (length <= 0xffffffff) {\n\t\t\tthis._bufferBuilder.append(0xdf);\n\t\t\tthis.pack_uint32(length);\n\t\t} else {\n\t\t\tthrow new Error(\"Invalid length\");\n\t\t}\n\n\t\tconst packNext = (index: number): Promise<void> | void => {\n\t\t\tif (index < keys.length) {\n\t\t\t\tconst prop = keys[index];\n\t\t\t\t// eslint-disable-next-line no-prototype-builtins\n\t\t\t\tif (obj.hasOwnProperty(prop)) {\n\t\t\t\t\tthis.pack(prop);\n\t\t\t\t\tconst res = this.pack(obj[prop]);\n\t\t\t\t\tif (res instanceof Promise) {\n\t\t\t\t\t\treturn res.then(() => packNext(index + 1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn packNext(index + 1);\n\t\t\t}\n\t\t};\n\n\t\treturn packNext(0);\n\t}\n\n\tpack_uint8(num: number) {\n\t\tthis._bufferBuilder.append(num);\n\t}\n\n\tpack_uint16(num: number) {\n\t\tthis._bufferBuilder.append(num >> 8);\n\t\tthis._bufferBuilder.append(num & 0xff);\n\t}\n\n\tpack_uint32(num: number) {\n\t\tconst n = num & 0xffffffff;\n\t\tthis._bufferBuilder.append((n & 0xff000000) >>> 24);\n\t\tthis._bufferBuilder.append((n & 0x00ff0000) >>> 16);\n\t\tthis._bufferBuilder.append((n & 0x0000ff00) >>> 8);\n\t\tthis._bufferBuilder.append(n & 0x000000ff);\n\t}\n\n\tpack_uint64(num: number) {\n\t\tconst high = num / 2 ** 32;\n\t\tconst low = num % 2 ** 32;\n\t\tthis._bufferBuilder.append((high & 0xff000000) >>> 24);\n\t\tthis._bufferBuilder.append((high & 0x00ff0000) >>> 16);\n\t\tthis._bufferBuilder.append((high & 0x0000ff00) >>> 8);\n\t\tthis._bufferBuilder.append(high & 0x000000ff);\n\t\tthis._bufferBuilder.append((low & 0xff000000) >>> 24);\n\t\tthis._bufferBuilder.append((low & 0x00ff0000) >>> 16);\n\t\tthis._bufferBuilder.append((low & 0x0000ff00) >>> 8);\n\t\tthis._bufferBuilder.append(low & 0x000000ff);\n\t}\n\n\tpack_int8(num: number) {\n\t\tthis._bufferBuilder.append(num & 0xff);\n\t}\n\n\tpack_int16(num: number) {\n\t\tthis._bufferBuilder.append((num & 0xff00) >> 8);\n\t\tthis._bufferBuilder.append(num & 0xff);\n\t}\n\n\tpack_int32(num: number) {\n\t\tthis._bufferBuilder.append((num >>> 24) & 0xff);\n\t\tthis._bufferBuilder.append((num & 0x00ff0000) >>> 16);\n\t\tthis._bufferBuilder.append((num & 0x0000ff00) >>> 8);\n\t\tthis._bufferBuilder.append(num & 0x000000ff);\n\t}\n\n\tpack_int64(num: number) {\n\t\tconst high = Math.floor(num / 2 ** 32);\n\t\tconst low = num % 2 ** 32;\n\t\tthis._bufferBuilder.append((high & 0xff000000) >>> 24);\n\t\tthis._bufferBuilder.append((high & 0x00ff0000) >>> 16);\n\t\tthis._bufferBuilder.append((high & 0x0000ff00) >>> 8);\n\t\tthis._bufferBuilder.append(high & 0x000000ff);\n\t\tthis._bufferBuilder.append((low & 0xff000000) >>> 24);\n\t\tthis._bufferBuilder.append((low & 0x00ff0000) >>> 16);\n\t\tthis._bufferBuilder.append((low & 0x0000ff00) >>> 8);\n\t\tthis._bufferBuilder.append(low & 0x000000ff);\n\t}\n}\n", "class BufferBuilder {\n\tprivate _pieces: number[];\n\tprivate readonly _parts: ArrayBufferView[];\n\n\tconstructor() {\n\t\tthis._pieces = [];\n\t\tthis._parts = [];\n\t}\n\n\tappend_buffer(data: ArrayBufferView) {\n\t\tthis.flush();\n\t\tthis._parts.push(data);\n\t}\n\n\tappend(data: number) {\n\t\tthis._pieces.push(data);\n\t}\n\n\tflush() {\n\t\tif (this._pieces.length > 0) {\n\t\t\tconst buf = new Uint8Array(this._pieces);\n\t\t\tthis._parts.push(buf);\n\t\t\tthis._pieces = [];\n\t\t}\n\t}\n\n\tprivate encoder = new TextEncoder();\n\n\tpublic toArrayBuffer() {\n\t\tconst buffer = [];\n\t\tfor (const part of this._parts) {\n\t\t\tbuffer.push(part);\n\t\t}\n\t\treturn concatArrayBuffers(buffer).buffer;\n\t}\n}\n\nexport { BufferBuilder };\n\nfunction concatArrayBuffers(bufs: ArrayBufferView[]) {\n\tlet size = 0;\n\tfor (const buf of bufs) {\n\t\tsize += buf.byteLength;\n\t}\n\tconst result = new Uint8Array(size);\n\tlet offset = 0;\n\tfor (const buf of bufs) {\n\t\tconst view = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n\t\tresult.set(view, offset);\n\t\toffset += buf.byteLength;\n\t}\n\treturn result;\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\n\nlet logDisabled_ = true;\nlet deprecationWarnings_ = true;\n\n/**\n * Extract browser version out of the provided user agent string.\n *\n * @param {!string} uastring userAgent string.\n * @param {!string} expr Regular expression used as match criteria.\n * @param {!number} pos position in the version string to be returned.\n * @return {!number} browser version.\n */\nexport function extractVersion(uastring, expr, pos) {\n const match = uastring.match(expr);\n return match && match.length >= pos && parseFloat(match[pos], 10);\n}\n\n// Wraps the peerconnection event eventNameToWrap in a function\n// which returns the modified event object (or false to prevent\n// the event).\nexport function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) {\n if (!window.RTCPeerConnection) {\n return;\n }\n const proto = window.RTCPeerConnection.prototype;\n const nativeAddEventListener = proto.addEventListener;\n proto.addEventListener = function(nativeEventName, cb) {\n if (nativeEventName !== eventNameToWrap) {\n return nativeAddEventListener.apply(this, arguments);\n }\n const wrappedCallback = (e) => {\n const modifiedEvent = wrapper(e);\n if (modifiedEvent) {\n if (cb.handleEvent) {\n cb.handleEvent(modifiedEvent);\n } else {\n cb(modifiedEvent);\n }\n }\n };\n this._eventMap = this._eventMap || {};\n if (!this._eventMap[eventNameToWrap]) {\n this._eventMap[eventNameToWrap] = new Map();\n }\n this._eventMap[eventNameToWrap].set(cb, wrappedCallback);\n return nativeAddEventListener.apply(this, [nativeEventName,\n wrappedCallback]);\n };\n\n const nativeRemoveEventListener = proto.removeEventListener;\n proto.removeEventListener = function(nativeEventName, cb) {\n if (nativeEventName !== eventNameToWrap || !this._eventMap\n || !this._eventMap[eventNameToWrap]) {\n return nativeRemoveEventListener.apply(this, arguments);\n }\n if (!this._eventMap[eventNameToWrap].has(cb)) {\n return nativeRemoveEventListener.apply(this, arguments);\n }\n const unwrappedCb = this._eventMap[eventNameToWrap].get(cb);\n this._eventMap[eventNameToWrap].delete(cb);\n if (this._eventMap[eventNameToWrap].size === 0) {\n delete this._eventMap[eventNameToWrap];\n }\n if (Object.keys(this._eventMap).length === 0) {\n delete this._eventMap;\n }\n return nativeRemoveEventListener.apply(this, [nativeEventName,\n unwrappedCb]);\n };\n\n Object.defineProperty(proto, 'on' + eventNameToWrap, {\n get() {\n return this['_on' + eventNameToWrap];\n },\n set(cb) {\n if (this['_on' + eventNameToWrap]) {\n this.removeEventListener(eventNameToWrap,\n this['_on' + eventNameToWrap]);\n delete this['_on' + eventNameToWrap];\n }\n if (cb) {\n this.addEventListener(eventNameToWrap,\n this['_on' + eventNameToWrap] = cb);\n }\n },\n enumerable: true,\n configurable: true\n });\n}\n\nexport function disableLog(bool) {\n if (typeof bool !== 'boolean') {\n return new Error('Argument type: ' + typeof bool +\n '. Please use a boolean.');\n }\n logDisabled_ = bool;\n return (bool) ? 'adapter.js logging disabled' :\n 'adapter.js logging enabled';\n}\n\n/**\n * Disable or enable deprecation warnings\n * @param {!boolean} bool set to true to disable warnings.\n */\nexport function disableWarnings(bool) {\n if (typeof bool !== 'boolean') {\n return new Error('Argument type: ' + typeof bool +\n '. Please use a boolean.');\n }\n deprecationWarnings_ = !bool;\n return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');\n}\n\nexport function log() {\n if (typeof window === 'object') {\n if (logDisabled_) {\n return;\n }\n if (typeof console !== 'undefined' && typeof console.log === 'function') {\n console.log.apply(console, arguments);\n }\n }\n}\n\n/**\n * Shows a deprecation warning suggesting the modern and spec-compatible API.\n */\nexport function deprecated(oldMethod, newMethod) {\n if (!deprecationWarnings_) {\n return;\n }\n console.warn(oldMethod + ' is deprecated, please use ' + newMethod +\n ' instead.');\n}\n\n/**\n * Browser detector.\n *\n * @return {object} result containing browser and version\n * properties.\n */\nexport function detectBrowser(window) {\n // Returned result object.\n const result = {browser: null, version: null};\n\n // Fail early if it's not a browser\n if (typeof window === 'undefined' || !window.navigator ||\n !window.navigator.userAgent) {\n result.browser = 'Not a browser.';\n return result;\n }\n\n const {navigator} = window;\n\n // Prefer navigator.userAgentData.\n if (navigator.userAgentData && navigator.userAgentData.brands) {\n const chromium = navigator.userAgentData.brands.find((brand) => {\n return brand.brand === 'Chromium';\n });\n if (chromium) {\n return {browser: 'chrome', version: parseInt(chromium.version, 10)};\n }\n }\n\n if (navigator.mozGetUserMedia) { // Firefox.\n result.browser = 'firefox';\n result.version = parseInt(extractVersion(navigator.userAgent,\n /Firefox\\/(\\d+)\\./, 1));\n } else if (navigator.webkitGetUserMedia ||\n (window.isSecureContext === false && window.webkitRTCPeerConnection)) {\n // Chrome, Chromium, Webview, Opera.\n // Version matches Chrome/WebRTC version.\n // Chrome 74 removed webkitGetUserMedia on http as well so we need the\n // more complicated fallback to webkitRTCPeerConnection.\n result.browser = 'chrome';\n result.version = parseInt(extractVersion(navigator.userAgent,\n /Chrom(e|ium)\\/(\\d+)\\./, 2));\n } else if (window.RTCPeerConnection &&\n navigator.userAgent.match(/AppleWebKit\\/(\\d+)\\./)) { // Safari.\n result.browser = 'safari';\n result.version = parseInt(extractVersion(navigator.userAgent,\n /AppleWebKit\\/(\\d+)\\./, 1));\n result.supportsUnifiedPlan = window.RTCRtpTransceiver &&\n 'currentDirection' in window.RTCRtpTransceiver.prototype;\n // Only for internal usage.\n result._safariVersion = extractVersion(navigator.userAgent,\n /Version\\/(\\d+(\\.?\\d+))/, 1);\n } else { // Default fallthrough: not supported.\n result.browser = 'Not a supported browser.';\n return result;\n }\n\n return result;\n}\n\n/**\n * Checks if something is an object.\n *\n * @param {*} val The something you want to check.\n * @return true if val is an object, false otherwise.\n */\nfunction isObject(val) {\n return Object.prototype.toString.call(val) === '[object Object]';\n}\n\n/**\n * Remove all empty objects and undefined values\n * from a nested object -- an enhanced and vanilla version\n * of Lodash's `compact`.\n */\nexport function compactObject(data) {\n if (!isObject(data)) {\n return data;\n }\n\n return Object.keys(data).reduce(function(accumulator, key) {\n const isObj = isObject(data[key]);\n const value = isObj ? compactObject(data[key]) : data[key];\n const isEmptyObject = isObj && !Object.keys(value).length;\n if (value === undefined || isEmptyObject) {\n return accumulator;\n }\n return Object.assign(accumulator, {[key]: value});\n }, {});\n}\n\n/* iterates the stats graph recursively. */\nexport function walkStats(stats, base, resultSet) {\n if (!base || resultSet.has(base.id)) {\n return;\n }\n resultSet.set(base.id, base);\n Object.keys(base).forEach(name => {\n if (name.endsWith('Id')) {\n walkStats(stats, stats.get(base[name]), resultSet);\n } else if (name.endsWith('Ids')) {\n base[name].forEach(id => {\n walkStats(stats, stats.get(id), resultSet);\n });\n }\n });\n}\n\n/* filter getStats for a sender/receiver track. */\nexport function filterStats(result, track, outbound) {\n const streamStatsType = outbound ? 'outbound-rtp' : 'inbound-rtp';\n const filteredResult = new Map();\n if (track === null) {\n return filteredResult;\n }\n const trackStats = [];\n result.forEach(value => {\n if (value.type === 'track' &&\n value.trackIdentifier === track.id) {\n trackStats.push(value);\n }\n });\n trackStats.forEach(trackStat => {\n result.forEach(stats => {\n if (stats.type === streamStatsType && stats.trackId === trackStat.id) {\n walkStats(result, stats, filteredResult);\n }\n });\n });\n return filteredResult;\n}\n\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\nimport * as utils from '../utils.js';\n\nexport {shimGetUserMedia} from './getusermedia';\n\nexport function shimMediaStream(window) {\n window.MediaStream = window.MediaStream || window.webkitMediaStream;\n}\n\nexport function shimOnTrack(window) {\n if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in\n window.RTCPeerConnection.prototype)) {\n Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {\n get() {\n return this._ontrack;\n },\n set(f) {\n if (this._ontrack) {\n this.removeEventListener('track', this._ontrack);\n }\n this.addEventListener('track', this._ontrack = f);\n },\n enumerable: true,\n configurable: true\n });\n const origSetRemoteDescription =\n window.RTCPeerConnection.prototype.setRemoteDescription;\n window.RTCPeerConnection.prototype.setRemoteDescription =\n function setRemoteDescription() {\n if (!this._ontrackpoly) {\n this._ontrackpoly = (e) => {\n // onaddstream does not fire when a track is added to an existing\n // stream. But stream.onaddtrack is implemented so we use that.\n e.stream.addEventListener('addtrack', te => {\n let receiver;\n if (window.RTCPeerConnection.prototype.getReceivers) {\n receiver = this.getReceivers()\n .find(r => r.track && r.track.id === te.track.id);\n } else {\n receiver = {track: te.track};\n }\n\n const event = new Event('track');\n event.track = te.track;\n event.receiver = receiver;\n event.transceiver = {receiver};\n event.streams = [e.stream];\n this.dispatchEvent(event);\n });\n e.stream.getTracks().forEach(track => {\n let receiver;\n if (window.RTCPeerConnection.prototype.getReceivers) {\n receiver = this.getReceivers()\n .find(r => r.track && r.track.id === track.id);\n } else {\n receiver = {track};\n }\n const event = new Event('track');\n event.track = track;\n event.receiver = receiver;\n event.transceiver = {receiver};\n event.streams = [e.stream];\n this.dispatchEvent(event);\n });\n };\n this.addEventListener('addstream', this._ontrackpoly);\n }\n return origSetRemoteDescription.apply(this, arguments);\n };\n } else {\n // even if RTCRtpTransceiver is in window, it is only used and\n // emitted in unified-plan. Unfortunately this means we need\n // to unconditionally wrap the event.\n utils.wrapPeerConnectionEvent(window, 'track', e => {\n if (!e.transceiver) {\n Object.defineProperty(e, 'transceiver',\n {value: {receiver: e.receiver}});\n }\n return e;\n });\n }\n}\n\nexport function shimGetSendersWithDtmf(window) {\n // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.\n if (typeof window === 'object' && window.RTCPeerConnection &&\n !('getSenders' in window.RTCPeerConnection.prototype) &&\n 'createDTMFSender' in window.RTCPeerConnection.prototype) {\n const shimSenderWithDtmf = function(pc, track) {\n return {\n track,\n get dtmf() {\n if (this._dtmf === undefined) {\n if (track.kind === 'audio') {\n this._dtmf = pc.createDTMFSender(track);\n } else {\n this._dtmf = null;\n }\n }\n return this._dtmf;\n },\n _pc: pc\n };\n };\n\n // augment addTrack when getSenders is not available.\n if (!window.RTCPeerConnection.prototype.getSenders) {\n window.RTCPeerConnection.prototype.getSenders = function getSenders() {\n this._senders = this._senders || [];\n return this._senders.slice(); // return a copy of the internal state.\n };\n const origAddTrack = window.RTCPeerConnection.prototype.addTrack;\n window.RTCPeerConnection.prototype.addTrack =\n function addTrack(track, stream) {\n let sender = origAddTrack.apply(this, arguments);\n if (!sender) {\n sender = shimSenderWithDtmf(this, track);\n this._senders.push(sender);\n }\n return sender;\n };\n\n const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;\n window.RTCPeerConnection.prototype.removeTrack =\n function removeTrack(sender) {\n origRemoveTrack.apply(this, arguments);\n const idx = this._senders.indexOf(sender);\n if (idx !== -1) {\n this._senders.splice(idx, 1);\n }\n };\n }\n const origAddStream = window.RTCPeerConnection.prototype.addStream;\n window.RTCPeerConnection.prototype.addStream = function addStream(stream) {\n this._senders = this._senders || [];\n origAddStream.apply(this, [stream]);\n stream.getTracks().forEach(track => {\n this._senders.push(shimSenderWithDtmf(this, track));\n });\n };\n\n const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;\n window.RTCPeerConnection.prototype.removeStream =\n function removeStream(stream) {\n this._senders = this._senders || [];\n origRemoveStream.apply(this, [stream]);\n\n stream.getTracks().forEach(track => {\n const sender = this._senders.find(s => s.track === track);\n if (sender) { // remove sender\n this._senders.splice(this._senders.indexOf(sender), 1);\n }\n });\n };\n } else if (typeof window === 'object' && window.RTCPeerConnection &&\n 'getSenders' in window.RTCPeerConnection.prototype &&\n 'createDTMFSender' in window.RTCPeerConnection.prototype &&\n window.RTCRtpSender &&\n !('dtmf' in window.RTCRtpSender.prototype)) {\n const origGetSenders = window.RTCPeerConnection.prototype.getSenders;\n window.RTCPeerConnection.prototype.getSenders = function getSenders() {\n const senders = origGetSenders.apply(this, []);\n senders.forEach(sender => sender._pc = this);\n return senders;\n };\n\n Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {\n get() {\n if (this._dtmf === undefined) {\n if (this.track.kind === 'audio') {\n this._dtmf = this._pc.createDTMFSender(this.track);\n } else {\n this._dtmf = null;\n }\n }\n return this._dtmf;\n }\n });\n }\n}\n\nexport function shimSenderReceiverGetStats(window) {\n if (!(typeof window === 'object' && window.RTCPeerConnection &&\n window.RTCRtpSender && window.RTCRtpReceiver)) {\n return;\n }\n\n // shim sender stats.\n if (!('getStats' in window.RTCRtpSender.prototype)) {\n const origGetSenders = window.RTCPeerConnection.prototype.getSenders;\n if (origGetSenders) {\n window.RTCPeerConnection.prototype.getSenders = function getSenders() {\n const senders = origGetSenders.apply(this, []);\n senders.forEach(sender => sender._pc = this);\n return senders;\n };\n }\n\n const origAddTrack = window.RTCPeerConnection.prototype.addTrack;\n if (origAddTrack) {\n window.RTCPeerConnection.prototype.addTrack = function addTrack() {\n const sender = origAddTrack.apply(this, arguments);\n sender._pc = this;\n return sender;\n };\n }\n window.RTCRtpSender.prototype.getStats = function getStats() {\n const sender = this;\n return this._pc.getStats().then(result =>\n /* Note: this will include stats of all senders that\n * send a track with the same id as sender.track as\n * it is not possible to identify the RTCRtpSender.\n */\n utils.filterStats(result, sender.track, true));\n };\n }\n\n // shim receiver stats.\n if (!('getStats' in window.RTCRtpReceiver.prototype)) {\n const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;\n if (origGetReceivers) {\n window.RTCPeerConnection.prototype.getReceivers =\n function getReceivers() {\n const receivers = origGetReceivers.apply(this, []);\n receivers.forEach(receiver => receiver._pc = this);\n return receivers;\n };\n }\n utils.wrapPeerConnectionEvent(window, 'track', e => {\n e.receiver._pc = e.srcElement;\n return e;\n });\n window.RTCRtpReceiver.prototype.getStats = function getStats() {\n const receiver = this;\n return this._pc.getStats().then(result =>\n utils.filterStats(result, receiver.track, false));\n };\n }\n\n if (!('getStats' in window.RTCRtpSender.prototype &&\n 'getStats' in window.RTCRtpReceiver.prototype)) {\n return;\n }\n\n // shim RTCPeerConnection.getStats(track).\n const origGetStats = window.RTCPeerConnection.prototype.getStats;\n window.RTCPeerConnection.prototype.getStats = function getStats() {\n if (arguments.length > 0 &&\n arguments[0] instanceof window.MediaStreamTrack) {\n const track = arguments[0];\n let sender;\n let receiver;\n let err;\n this.getSenders().forEach(s => {\n if (s.track === track) {\n if (sender) {\n err = true;\n } else {\n sender = s;\n }\n }\n });\n this.getReceivers().forEach(r => {\n if (r.track === track) {\n if (receiver) {\n err = true;\n } else {\n receiver = r;\n }\n }\n return r.track === track;\n });\n if (err || (sender && receiver)) {\n return Promise.reject(new DOMException(\n 'There are more than one sender or receiver for the track.',\n 'InvalidAccessError'));\n } else if (sender) {\n return sender.getStats();\n } else if (receiver) {\n return receiver.getStats();\n }\n return Promise.reject(new DOMException(\n 'There is no sender or receiver for the track.',\n 'InvalidAccessError'));\n }\n return origGetStats.apply(this, arguments);\n };\n}\n\nexport function shimAddTrackRemoveTrackWithNative(window) {\n // shim addTrack/removeTrack with native variants in order to make\n // the interactions with legacy getLocalStreams behave as in other browsers.\n // Keeps a mapping stream.id => [stream, rtpsenders...]\n window.RTCPeerConnection.prototype.getLocalStreams =\n function getLocalStreams() {\n this._shimmedLocalStreams = this._shimmedLocalStreams || {};\n return Object.keys(this._shimmedLocalStreams)\n .map(streamId => this._shimmedLocalStreams[streamId][0]);\n };\n\n const origAddTrack = window.RTCPeerConnection.prototype.addTrack;\n window.RTCPeerConnection.prototype.addTrack =\n function addTrack(track, stream) {\n if (!stream) {\n return origAddTrack.apply(this, arguments);\n }\n this._shimmedLocalStreams = this._shimmedLocalStreams || {};\n\n const sender = origAddTrack.apply(this, arguments);\n if (!this._shimmedLocalStreams[stream.id]) {\n this._shimmedLocalStreams[stream.id] = [stream, sender];\n } else if (this._shimmedLocalStreams[stream.id].indexOf(sender) === -1) {\n this._shimmedLocalStreams[stream.id].push(sender);\n }\n return sender;\n };\n\n const origAddStream = window.RTCPeerConnection.prototype.addStream;\n window.RTCPeerConnection.prototype.addStream = function addStream(stream) {\n this._shimmedLocalStreams = this._shimmedLocalStreams || {};\n\n stream.getTracks().forEach(track => {\n const alreadyExists = this.getSenders().find(s => s.track === track);\n if (alreadyExists) {\n throw new DOMException('Track already exists.',\n 'InvalidAccessError');\n }\n });\n const existingSenders = this.getSenders();\n origAddStream.apply(this, arguments);\n const newSenders = this.getSenders()\n .filter(newSender => existingSenders.indexOf(newSender) === -1);\n this._shimmedLocalStreams[stream.id] = [stream].concat(newSenders);\n };\n\n const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;\n window.RTCPeerConnection.prototype.removeStream =\n function removeStream(stream) {\n this._shimmedLocalStreams = this._shimmedLocalStreams || {};\n delete this._shimmedLocalStreams[stream.id];\n return origRemoveStream.apply(this, arguments);\n };\n\n const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;\n window.RTCPeerConnection.prototype.removeTrack =\n function removeTrack(sender) {\n this._shimmedLocalStreams = this._shimmedLocalStreams || {};\n if (sender) {\n Object.keys(this._shimmedLocalStreams).forEach(streamId => {\n const idx = this._shimmedLocalStreams[streamId].indexOf(sender);\n if (idx !== -1) {\n this._shimmedLocalStreams[streamId].splice(idx, 1);\n }\n if (this._shimmedLocalStreams[streamId].length === 1) {\n delete this._shimmedLocalStreams[streamId];\n }\n });\n }\n return origRemoveTrack.apply(this, arguments);\n };\n}\n\nexport function shimAddTrackRemoveTrack(window, browserDetails) {\n if (!window.RTCPeerConnection) {\n return;\n }\n // shim addTrack and removeTrack.\n if (window.RTCPeerConnection.prototype.addTrack &&\n browserDetails.version >= 65) {\n return shimAddTrackRemoveTrackWithNative(window);\n }\n\n // also shim pc.getLocalStreams when addTrack is shimmed\n // to return the original streams.\n const origGetLocalStreams = window.RTCPeerConnection.prototype\n .getLocalStreams;\n window.RTCPeerConnection.prototype.getLocalStreams =\n function getLocalStreams() {\n const nativeStreams = origGetLocalStreams.apply(this);\n this._reverseStreams = this._reverseStreams || {};\n return nativeStreams.map(stream => this._reverseStreams[stream.id]);\n };\n\n const origAddStream = window.RTCPeerConnection.prototype.addStream;\n window.RTCPeerConnection.prototype.addStream = function addStream(stream) {\n this._streams = this._streams || {};\n this._reverseStreams = this._reverseStreams || {};\n\n stream.getTracks().forEach(track => {\n const alreadyExists = this.getSenders().find(s => s.track === track);\n if (alreadyExists) {\n throw new DOMException('Track already exists.',\n 'InvalidAccessError');\n }\n });\n // Add identity mapping for consistency with addTrack.\n // Unless this is being used with a stream from addTrack.\n if (!this._reverseStreams[stream.id]) {\n const newStream = new window.MediaStream(stream.getTracks());\n this._streams[stream.id] = newStream;\n this._reverseStreams[newStream.id] = stream;\n stream = newStream;\n }\n origAddStream.apply(this, [stream]);\n };\n\n const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;\n window.RTCPeerConnection.prototype.removeStream =\n function removeStream(stream) {\n this._streams = this._streams || {};\n this._reverseStreams = this._reverseStreams || {};\n\n origRemoveStream.apply(this, [(this._streams[stream.id] || stream)]);\n delete this._reverseStreams[(this._streams[stream.id] ?\n this._streams[stream.id].id : stream.id)];\n delete this._streams[stream.id];\n };\n\n window.RTCPeerConnection.prototype.addTrack =\n function addTrack(track, stream) {\n if (this.signalingState === 'closed') {\n throw new DOMException(\n 'The RTCPeerConnection\\'s signalingState is \\'closed\\'.',\n 'InvalidStateError');\n }\n const streams = [].slice.call(arguments, 1);\n if (streams.length !== 1 ||\n !streams[0].getTracks().find(t => t === track)) {\n // this is not fully correct but all we can manage without\n // [[associated MediaStreams]] internal slot.\n throw new DOMException(\n 'The adapter.js addTrack polyfill only supports a single ' +\n ' stream which is associated with the specified track.',\n 'NotSupportedError');\n }\n\n const alreadyExists = this.getSenders().find(s => s.track === track);\n if (alreadyExists) {\n throw new DOMException('Track already exists.',\n 'InvalidAccessError');\n }\n\n this._streams = this._streams || {};\n this._reverseStreams = this._reverseStreams || {};\n const oldStream = this._streams[stream.id];\n if (oldStream) {\n // this is using odd Chrome behaviour, use with caution:\n // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815\n // Note: we rely on the high-level addTrack/dtmf shim to\n // create the sender with a dtmf sender.\n oldStream.addTrack(track);\n\n // Trigger ONN async.\n Promise.resolve().then(() => {\n this.dispatchEvent(new Event('negotiationneeded'));\n });\n } else {\n const newStream = new window.MediaStream([track]);\n this._streams[stream.id] = newStream;\n this._reverseStreams[newStream.id] = stream;\n this.addStream(newStream);\n }\n return this.getSenders().find(s => s.track === track);\n };\n\n // replace the internal stream id with the external one and\n // vice versa.\n function replaceInternalStreamId(pc, description) {\n let sdp = description.sdp;\n Object.keys(pc._reverseStreams || []).forEach(internalId => {\n const externalStream = pc._reverseStreams[internalId];\n const internalStream = pc._streams[externalStream.id];\n sdp = sdp.replace(new RegExp(internalStream.id, 'g'),\n externalStream.id);\n });\n return new RTCSessionDescription({\n type: description.type,\n sdp\n });\n }\n function replaceExternalStreamId(pc, description) {\n let sdp = description.sdp;\n Object.keys(pc._reverseStreams || []).forEach(internalId => {\n const externalStream = pc._reverseStreams[internalId];\n const internalStream = pc._streams[externalStream.id];\n sdp = sdp.replace(new RegExp(externalStream.id, 'g'),\n internalStream.id);\n });\n return new RTCSessionDescription({\n type: description.type,\n sdp\n });\n }\n ['createOffer', 'createAnswer'].forEach(function(method) {\n const nativeMethod = window.RTCPeerConnection.prototype[method];\n const methodObj = {[method]() {\n const args = arguments;\n const isLegacyCall = arguments.length &&\n typeof arguments[0] === 'function';\n if (isLegacyCall) {\n return nativeMethod.apply(this, [\n (description) => {\n const desc = replaceInternalStreamId(this, description);\n args[0].apply(null, [desc]);\n },\n (err) => {\n if (args[1]) {\n args[1].apply(null, err);\n }\n }, arguments[2]\n ]);\n }\n return nativeMethod.apply(this, arguments)\n .then(description => replaceInternalStreamId(this, description));\n }};\n window.RTCPeerConnection.prototype[method] = methodObj[method];\n });\n\n const origSetLocalDescription =\n window.RTCPeerConnection.prototype.setLocalDescription;\n window.RTCPeerConnection.prototype.setLocalDescription =\n function setLocalDescription() {\n if (!arguments.length || !arguments[0].type) {\n return origSetLocalDescription.apply(this, arguments);\n }\n arguments[0] = replaceExternalStreamId(this, arguments[0]);\n return origSetLocalDescription.apply(this, arguments);\n };\n\n // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier\n\n const origLocalDescription = Object.getOwnPropertyDescriptor(\n window.RTCPeerConnection.prototype, 'localDescription');\n Object.defineProperty(window.RTCPeerConnection.prototype,\n 'localDescription', {\n get() {\n const description = origLocalDescription.get.apply(this);\n if (description.type === '') {\n return description;\n }\n return replaceInternalStreamId(this, description);\n }\n });\n\n window.RTCPeerConnection.prototype.removeTrack =\n function removeTrack(sender) {\n if (this.signalingState === 'closed') {\n throw new DOMException(\n 'The RTCPeerConnection\\'s signalingState is \\'closed\\'.',\n 'InvalidStateError');\n }\n // We can not yet check for sender instanceof RTCRtpSender\n // since we shim RTPSender. So we check if sender._pc is set.\n if (!sender._pc) {\n throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' +\n 'does not implement interface RTCRtpSender.', 'TypeError');\n }\n const isLocal = sender._pc === this;\n if (!isLocal) {\n throw new DOMException('Sender was not created by this connection.',\n 'InvalidAccessError');\n }\n\n // Search for the native stream the senders track belongs to.\n this._streams = this._streams || {};\n let stream;\n Object.keys(this._streams).forEach(streamid => {\n const hasTrack = this._streams[streamid].getTracks()\n .find(track => sender.track === track);\n if (hasTrack) {\n stream = this._streams[streamid];\n }\n });\n\n if (stream) {\n if (stream.getTracks().length === 1) {\n // if this is the last track of the stream, remove the stream. This\n // takes care of any shimmed _senders.\n this.removeStream(this._reverseStreams[stream.id]);\n } else {\n // relying on the same odd chrome behaviour as above.\n stream.removeTrack(sender.track);\n }\n this.dispatchEvent(new Event('negotiationneeded'));\n }\n };\n}\n\nexport function shimPeerConnection(window, browserDetails) {\n if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) {\n // very basic support for old versions.\n window.RTCPeerConnection = window.webkitRTCPeerConnection;\n }\n if (!window.RTCPeerConnection) {\n return;\n }\n\n // shim implicit creation of RTCSessionDescription/RTCIceCandidate\n if (browserDetails.version < 53) {\n ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']\n .forEach(function(method) {\n const nativeMethod = window.RTCPeerConnection.prototype[method];\n const methodObj = {[method]() {\n arguments[0] = new ((method === 'addIceCandidate') ?\n window.RTCIceCandidate :\n window.RTCSessionDescription)(arguments[0]);\n return nativeMethod.apply(this, arguments);\n }};\n window.RTCPeerConnection.prototype[method] = methodObj[method];\n });\n }\n}\n\n// Attempt to fix ONN in plan-b mode.\nexport function fixNegotiationNeeded(window, browserDetails) {\n utils.wrapPeerConnectionEvent(window, 'negotiationneeded', e => {\n const pc = e.target;\n if (browserDetails.version < 72 || (pc.getConfiguration &&\n pc.getConfiguration().sdpSemantics === 'plan-b')) {\n if (pc.signalingState !== 'stable') {\n return;\n }\n }\n return e;\n });\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\nimport * as utils from '../utils.js';\nconst logging = utils.log;\n\nexport function shimGetUserMedia(window, browserDetails) {\n const navigator = window && window.navigator;\n\n if (!navigator.mediaDevices) {\n return;\n }\n\n const constraintsToChrome_ = function(c) {\n if (typeof c !== 'object' || c.mandatory || c.optional) {\n return c;\n }\n const cc = {};\n Object.keys(c).forEach(key => {\n if (key === 'require' || key === 'advanced' || key === 'mediaSource') {\n return;\n }\n const r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};\n if (r.exact !== undefined && typeof r.exact === 'number') {\n r.min = r.max = r.exact;\n }\n const oldname_ = function(prefix, name) {\n if (prefix) {\n return prefix + name.charAt(0).toUpperCase() + name.slice(1);\n }\n return (name === 'deviceId') ? 'sourceId' : name;\n };\n if (r.ideal !== undefined) {\n cc.optional = cc.optional || [];\n let oc = {};\n if (typeof r.ideal === 'number') {\n oc[oldname_('min', key)] = r.ideal;\n cc.optional.push(oc);\n oc = {};\n oc[oldname_('max', key)] = r.ideal;\n cc.optional.push(oc);\n } else {\n oc[oldname_('', key)] = r.ideal;\n cc.optional.push(oc);\n }\n }\n if (r.exact !== undefined && typeof r.exact !== 'number') {\n cc.mandatory = cc.mandatory || {};\n cc.mandatory[oldname_('', key)] = r.exact;\n } else {\n ['min', 'max'].forEach(mix => {\n if (r[mix] !== undefined) {\n cc.mandatory = cc.mandatory || {};\n cc.mandatory[oldname_(mix, key)] = r[mix];\n }\n });\n }\n });\n if (c.advanced) {\n cc.optional = (cc.optional || []).concat(c.advanced);\n }\n return cc;\n };\n\n const shimConstraints_ = function(constraints, func) {\n if (browserDetails.version >= 61) {\n return func(constraints);\n }\n constraints = JSON.parse(JSON.stringify(constraints));\n if (constraints && typeof constraints.audio === 'object') {\n const remap = function(obj, a, b) {\n if (a in obj && !(b in obj)) {\n obj[b] = obj[a];\n delete obj[a];\n }\n };\n constraints = JSON.parse(JSON.stringify(constraints));\n remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');\n remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');\n constraints.audio = constraintsToChrome_(constraints.audio);\n }\n if (constraints && typeof constraints.video === 'object') {\n // Shim facingMode for mobile & surface pro.\n let face = constraints.video.facingMode;\n face = face && ((typeof face === 'object') ? face : {ideal: face});\n const getSupportedFacingModeLies = browserDetails.version < 66;\n\n if ((face && (face.exact === 'user' || face.exact === 'environment' ||\n face.ideal === 'user' || face.ideal === 'environment')) &&\n !(navigator.mediaDevices.getSupportedConstraints &&\n navigator.mediaDevices.getSupportedConstraints().facingMode &&\n !getSupportedFacingModeLies)) {\n delete constraints.video.facingMode;\n let matches;\n if (face.exact === 'environment' || face.ideal === 'environment') {\n matches = ['back', 'rear'];\n } else if (face.exact === 'user' || face.ideal === 'user') {\n matches = ['front'];\n }\n if (matches) {\n // Look for matches in label, or use last cam for back (typical).\n return navigator.mediaDevices.enumerateDevices()\n .then(devices => {\n devices = devices.filter(d => d.kind === 'videoinput');\n let dev = devices.find(d => matches.some(match =>\n d.label.toLowerCase().includes(match)));\n if (!dev && devices.length && matches.includes('back')) {\n dev = devices[devices.length - 1]; // more likely the back cam\n }\n if (dev) {\n constraints.video.deviceId = face.exact\n ? {exact: dev.deviceId}\n : {ideal: dev.deviceId};\n }\n constraints.video = constraintsToChrome_(constraints.video);\n logging('chrome: ' + JSON.stringify(constraints));\n return func(constraints);\n });\n }\n }\n constraints.video = constraintsToChrome_(constraints.video);\n }\n logging('chrome: ' + JSON.stringify(constraints));\n return func(constraints);\n };\n\n const shimError_ = function(e) {\n if (browserDetails.version >= 64) {\n return e;\n }\n return {\n name: {\n PermissionDeniedError: 'NotAllowedError',\n PermissionDismissedError: 'NotAllowedError',\n InvalidStateError: 'NotAllowedError',\n DevicesNotFoundError: 'NotFoundError',\n ConstraintNotSatisfiedError: 'OverconstrainedError',\n TrackStartError: 'NotReadableError',\n MediaDeviceFailedDueToShutdown: 'NotAllowedError',\n MediaDeviceKillSwitchOn: 'NotAllowedError',\n TabCaptureError: 'AbortError',\n ScreenCaptureError: 'AbortError',\n DeviceCaptureError: 'AbortError'\n }[e.name] || e.name,\n message: e.message,\n constraint: e.constraint || e.constraintName,\n toString() {\n return this.name + (this.message && ': ') + this.message;\n }\n };\n };\n\n const getUserMedia_ = function(constraints, onSuccess, onError) {\n shimConstraints_(constraints, c => {\n navigator.webkitGetUserMedia(c, onSuccess, e => {\n if (onError) {\n onError(shimError_(e));\n }\n });\n });\n };\n navigator.getUserMedia = getUserMedia_.bind(navigator);\n\n // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia\n // function which returns a Promise, it does not accept spec-style\n // constraints.\n if (navigator.mediaDevices.getUserMedia) {\n const origGetUserMedia = navigator.mediaDevices.getUserMedia.\n bind(navigator.mediaDevices);\n navigator.mediaDevices.getUserMedia = function(cs) {\n return shimConstraints_(cs, c => origGetUserMedia(c).then(stream => {\n if (c.audio && !stream.getAudioTracks().length ||\n c.video && !stream.getVideoTracks().length) {\n stream.getTracks().forEach(track => {\n track.stop();\n });\n throw new DOMException('', 'NotFoundError');\n }\n return stream;\n }, e => Promise.reject(shimError_(e))));\n };\n }\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\n\nimport * as utils from '../utils';\nexport {shimGetUserMedia} from './getusermedia';\nexport {shimGetDisplayMedia} from './getdisplaymedia';\n\nexport function shimOnTrack(window) {\n if (typeof window === 'object' && window.RTCTrackEvent &&\n ('receiver' in window.RTCTrackEvent.prototype) &&\n !('transceiver' in window.RTCTrackEvent.prototype)) {\n Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {\n get() {\n return {receiver: this.receiver};\n }\n });\n }\n}\n\nexport function shimPeerConnection(window, browserDetails) {\n if (typeof window !== 'object' ||\n !(window.RTCPeerConnection || window.mozRTCPeerConnection)) {\n return; // probably media.peerconnection.enabled=false in about:config\n }\n if (!window.RTCPeerConnection && window.mozRTCPeerConnection) {\n // very basic support for old versions.\n window.RTCPeerConnection = window.mozRTCPeerConnection;\n }\n\n if (browserDetails.version < 53) {\n // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.\n ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']\n .forEach(function(method) {\n const nativeMethod = window.RTCPeerConnection.prototype[method];\n const methodObj = {[method]() {\n arguments[0] = new ((method === 'addIceCandidate') ?\n window.RTCIceCandidate :\n window.RTCSessionDescription)(arguments[0]);\n return nativeMethod.apply(this, arguments);\n }};\n window.RTCPeerConnection.prototype[method] = methodObj[method];\n });\n }\n\n const modernStatsTypes = {\n inboundrtp: 'inbound-rtp',\n outboundrtp: 'outbound-rtp',\n candidatepair: 'candidate-pair',\n localcandidate: 'local-candidate',\n remotecandidate: 'remote-candidate'\n };\n\n const nativeGetStats = window.RTCPeerConnection.prototype.getStats;\n window.RTCPeerConnection.prototype.getStats = function getStats() {\n const [selector, onSucc, onErr] = arguments;\n return nativeGetStats.apply(this, [selector || null])\n .then(stats => {\n if (browserDetails.version < 53 && !onSucc) {\n // Shim only promise getStats with spec-hyphens in type names\n // Leave callback version alone; misc old uses of forEach before Map\n try {\n stats.forEach(stat => {\n stat.type = modernStatsTypes[stat.type] || stat.type;\n });\n } catch (e) {\n if (e.name !== 'TypeError') {\n throw e;\n }\n // Avoid TypeError: \"type\" is read-only, in old versions. 34-43ish\n stats.forEach((stat, i) => {\n stats.set(i, Object.assign({}, stat, {\n type: modernStatsTypes[stat.type] || stat.type\n }));\n });\n }\n }\n return stats;\n })\n .then(onSucc, onErr);\n };\n}\n\nexport function shimSenderGetStats(window) {\n if (!(typeof window === 'object' && window.RTCPeerConnection &&\n window.RTCRtpSender)) {\n return;\n }\n if (window.RTCRtpSender && 'getStats' in window.RTCRtpSender.prototype) {\n return;\n }\n const origGetSenders = window.RTCPeerConnection.prototype.getSenders;\n if (origGetSenders) {\n window.RTCPeerConnection.prototype.getSenders = function getSenders() {\n const senders = origGetSenders.apply(this, []);\n senders.forEach(sender => sender._pc = this);\n return senders;\n };\n }\n\n const origAddTrack = window.RTCPeerConnection.prototype.addTrack;\n if (origAddTrack) {\n window.RTCPeerConnection.prototype.addTrack = function addTrack() {\n const sender = origAddTrack.apply(this, arguments);\n sender._pc = this;\n return sender;\n };\n }\n window.RTCRtpSender.prototype.getStats = function getStats() {\n return this.track ? this._pc.getStats(this.track) :\n Promise.resolve(new Map());\n };\n}\n\nexport function shimReceiverGetStats(window) {\n if (!(typeof window === 'object' && window.RTCPeerConnection &&\n window.RTCRtpSender)) {\n return;\n }\n if (window.RTCRtpSender && 'getStats' in window.RTCRtpReceiver.prototype) {\n return;\n }\n const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;\n if (origGetReceivers) {\n window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {\n const receivers = origGetReceivers.apply(this, []);\n receivers.forEach(receiver => receiver._pc = this);\n return receivers;\n };\n }\n utils.wrapPeerConnectionEvent(window, 'track', e => {\n e.receiver._pc = e.srcElement;\n return e;\n });\n window.RTCRtpReceiver.prototype.getStats = function getStats() {\n return this._pc.getStats(this.track);\n };\n}\n\nexport function shimRemoveStream(window) {\n if (!window.RTCPeerConnection ||\n 'removeStream' in window.RTCPeerConnection.prototype) {\n return;\n }\n window.RTCPeerConnection.prototype.removeStream =\n function removeStream(stream) {\n utils.deprecated('removeStream', 'removeTrack');\n this.getSenders().forEach(sender => {\n if (sender.track && stream.getTracks().includes(sender.track)) {\n this.removeTrack(sender);\n }\n });\n };\n}\n\nexport function shimRTCDataChannel(window) {\n // rename DataChannel to RTCDataChannel (native fix in FF60):\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1173851\n if (window.DataChannel && !window.RTCDataChannel) {\n window.RTCDataChannel = window.DataChannel;\n }\n}\n\nexport function shimAddTransceiver(window) {\n // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647\n // Firefox ignores the init sendEncodings options passed to addTransceiver\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918\n if (!(typeof window === 'object' && window.RTCPeerConnection)) {\n return;\n }\n const origAddTransceiver = window.RTCPeerConnection.prototype.addTransceiver;\n if (origAddTransceiver) {\n window.RTCPeerConnection.prototype.addTransceiver =\n function addTransceiver() {\n this.setParametersPromises = [];\n // WebIDL input coercion and validation\n let sendEncodings = arguments[1] && arguments[1].sendEncodings;\n if (sendEncodings === undefined) {\n sendEncodings = [];\n }\n sendEncodings = [...sendEncodings];\n const shouldPerformCheck = sendEncodings.length > 0;\n if (shouldPerformCheck) {\n // If sendEncodings params are provided, validate grammar\n sendEncodings.forEach((encodingParam) => {\n if ('rid' in encodingParam) {\n const ridRegex = /^[a-z0-9]{0,16}$/i;\n if (!ridRegex.test(encodingParam.rid)) {\n throw new TypeError('Invalid RID value provided.');\n }\n }\n if ('scaleResolutionDownBy' in encodingParam) {\n if (!(parseFloat(encodingParam.scaleResolutionDownBy) >= 1.0)) {\n throw new RangeError('scale_resolution_down_by must be >= 1.0');\n }\n }\n if ('maxFramerate' in encodingParam) {\n if (!(parseFloat(encodingParam.maxFramerate) >= 0)) {\n throw new RangeError('max_framerate must be >= 0.0');\n }\n }\n });\n }\n const transceiver = origAddTransceiver.apply(this, arguments);\n if (shouldPerformCheck) {\n // Check if the init options were applied. If not we do this in an\n // asynchronous way and save the promise reference in a global object.\n // This is an ugly hack, but at the same time is way more robust than\n // checking the sender parameters before and after the createOffer\n // Also note that after the createoffer we are not 100% sure that\n // the params were asynchronously applied so we might miss the\n // opportunity to recreate offer.\n const {sender} = transceiver;\n const params = sender.getParameters();\n if (!('encodings' in params) ||\n // Avoid being fooled by patched getParameters() below.\n (params.encodings.length === 1 &&\n Object.keys(params.encodings[0]).length === 0)) {\n params.encodings = sendEncodings;\n sender.sendEncodings = sendEncodings;\n this.setParametersPromises.push(sender.setParameters(params)\n .then(() => {\n delete sender.sendEncodings;\n }).catch(() => {\n delete sender.sendEncodings;\n })\n );\n }\n }\n return transceiver;\n };\n }\n}\n\nexport function shimGetParameters(window) {\n if (!(typeof window === 'object' && window.RTCRtpSender)) {\n return;\n }\n const origGetParameters = window.RTCRtpSender.prototype.getParameters;\n if (origGetParameters) {\n window.RTCRtpSender.prototype.getParameters =\n function getParameters() {\n const params = origGetParameters.apply(this, arguments);\n if (!('encodings' in params)) {\n params.encodings = [].concat(this.sendEncodings || [{}]);\n }\n return params;\n };\n }\n}\n\nexport function shimCreateOffer(window) {\n // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647\n // Firefox ignores the init sendEncodings options passed to addTransceiver\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918\n if (!(typeof window === 'object' && window.RTCPeerConnection)) {\n return;\n }\n const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;\n window.RTCPeerConnection.prototype.createOffer = function createOffer() {\n if (this.setParametersPromises && this.setParametersPromises.length) {\n return Promise.all(this.setParametersPromises)\n .then(() => {\n return origCreateOffer.apply(this, arguments);\n })\n .finally(() => {\n this.setParametersPromises = [];\n });\n }\n return origCreateOffer.apply(this, arguments);\n };\n}\n\nexport function shimCreateAnswer(window) {\n // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647\n // Firefox ignores the init sendEncodings options passed to addTransceiver\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918\n if (!(typeof window === 'object' && window.RTCPeerConnection)) {\n return;\n }\n const origCreateAnswer = window.RTCPeerConnection.prototype.createAnswer;\n window.RTCPeerConnection.prototype.createAnswer = function createAnswer() {\n if (this.setParametersPromises && this.setParametersPromises.length) {\n return Promise.all(this.setParametersPromises)\n .then(() => {\n return origCreateAnswer.apply(this, arguments);\n })\n .finally(() => {\n this.setParametersPromises = [];\n });\n }\n return origCreateAnswer.apply(this, arguments);\n };\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\n\nimport * as utils from '../utils';\n\nexport function shimGetUserMedia(window, browserDetails) {\n const navigator = window && window.navigator;\n const MediaStreamTrack = window && window.MediaStreamTrack;\n\n navigator.getUserMedia = function(constraints, onSuccess, onError) {\n // Replace Firefox 44+'s deprecation warning with unprefixed version.\n utils.deprecated('navigator.getUserMedia',\n 'navigator.mediaDevices.getUserMedia');\n navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);\n };\n\n if (!(browserDetails.version > 55 &&\n 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {\n const remap = function(obj, a, b) {\n if (a in obj && !(b in obj)) {\n obj[b] = obj[a];\n delete obj[a];\n }\n };\n\n const nativeGetUserMedia = navigator.mediaDevices.getUserMedia.\n bind(navigator.mediaDevices);\n navigator.mediaDevices.getUserMedia = function(c) {\n if (typeof c === 'object' && typeof c.audio === 'object') {\n c = JSON.parse(JSON.stringify(c));\n remap(c.audio, 'autoGainControl', 'mozAutoGainControl');\n remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');\n }\n return nativeGetUserMedia(c);\n };\n\n if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {\n const nativeGetSettings = MediaStreamTrack.prototype.getSettings;\n MediaStreamTrack.prototype.getSettings = function() {\n const obj = nativeGetSettings.apply(this, arguments);\n remap(obj, 'mozAutoGainControl', 'autoGainControl');\n remap(obj, 'mozNoiseSuppression', 'noiseSuppression');\n return obj;\n };\n }\n\n if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {\n const nativeApplyConstraints =\n MediaStreamTrack.prototype.applyConstraints;\n MediaStreamTrack.prototype.applyConstraints = function(c) {\n if (this.kind === 'audio' && typeof c === 'object') {\n c = JSON.parse(JSON.stringify(c));\n remap(c, 'autoGainControl', 'mozAutoGainControl');\n remap(c, 'noiseSuppression', 'mozNoiseSuppression');\n }\n return nativeApplyConstraints.apply(this, [c]);\n };\n }\n }\n}\n", "/*\n * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\n\nexport function shimGetDisplayMedia(window, preferredMediaSource) {\n if (window.navigator.mediaDevices &&\n 'getDisplayMedia' in window.navigator.mediaDevices) {\n return;\n }\n if (!(window.navigator.mediaDevices)) {\n return;\n }\n window.navigator.mediaDevices.getDisplayMedia =\n function getDisplayMedia(constraints) {\n if (!(constraints && constraints.video)) {\n const err = new DOMException('getDisplayMedia without video ' +\n 'constraints is undefined');\n err.name = 'NotFoundError';\n // from https://heycam.github.io/webidl/#idl-DOMException-error-names\n err.code = 8;\n return Promise.reject(err);\n }\n if (constraints.video === true) {\n constraints.video = {mediaSource: preferredMediaSource};\n } else {\n constraints.video.mediaSource = preferredMediaSource;\n }\n return window.navigator.mediaDevices.getUserMedia(constraints);\n };\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n'use strict';\nimport * as utils from '../utils';\n\nexport function shimLocalStreamsAPI(window) {\n if (typeof window !== 'object' || !window.RTCPeerConnection) {\n return;\n }\n if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {\n window.RTCPeerConnection.prototype.getLocalStreams =\n function getLocalStreams() {\n if (!this._localStreams) {\n this._localStreams = [];\n }\n return this._localStreams;\n };\n }\n if (!('addStream' in window.RTCPeerConnection.prototype)) {\n const _addTrack = window.RTCPeerConnection.prototype.addTrack;\n window.RTCPeerConnection.prototype.addStream = function addStream(stream) {\n if (!this._localStreams) {\n this._localStreams = [];\n }\n if (!this._localStreams.includes(stream)) {\n this._localStreams.push(stream);\n }\n // Try to emulate Chrome's behaviour of adding in audio-video order.\n // Safari orders by track id.\n stream.getAudioTracks().forEach(track => _addTrack.call(this, track,\n stream));\n stream.getVideoTracks().forEach(track => _addTrack.call(this, track,\n stream));\n };\n\n window.RTCPeerConnection.prototype.addTrack =\n function addTrack(track, ...streams) {\n if (streams) {\n streams.forEach((stream) => {\n if (!this._localStreams) {\n this._localStreams = [stream];\n } else if (!this._localStreams.includes(stream)) {\n this._localStreams.push(stream);\n }\n });\n }\n return _addTrack.apply(this, arguments);\n };\n }\n if (!('removeStream' in window.RTCPeerConnection.prototype)) {\n window.RTCPeerConnection.prototype.removeStream =\n function removeStream(stream) {\n if (!this._localStreams) {\n this._localStreams = [];\n }\n const index = this._localStreams.indexOf(stream);\n if (index === -1) {\n return;\n }\n this._localStreams.splice(index, 1);\n const tracks = stream.getTracks();\n this.getSenders().forEach(sender => {\n if (tracks.includes(sender.track)) {\n this.removeTrack(sender);\n }\n });\n };\n }\n}\n\nexport function shimRemoteStreamsAPI(window) {\n if (typeof window !== 'object' || !window.RTCPeerConnection) {\n return;\n }\n if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {\n window.RTCPeerConnection.prototype.getRemoteStreams =\n function getRemoteStreams() {\n return this._remoteStreams ? this._remoteStreams : [];\n };\n }\n if (!('onaddstream' in window.RTCPeerConnection.prototype)) {\n Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {\n get() {\n return this._onaddstream;\n },\n set(f) {\n if (this._onaddstream) {\n this.removeEventListener('addstream', this._onaddstream);\n this.removeEventListener('track', this._onaddstreampoly);\n }\n this.addEventListener('addstream', this._onaddstream = f);\n this.addEventListener('track', this._onaddstreampoly = (e) => {\n e.streams.forEach(stream => {\n if (!this._remoteStreams) {\n this._remoteStreams = [];\n }\n if (this._remoteStreams.includes(stream)) {\n return;\n }\n this._remoteStreams.push(stream);\n const event = new Event('addstream');\n event.stream = stream;\n this.dispatchEvent(event);\n });\n });\n }\n });\n const origSetRemoteDescription =\n window.RTCPeerConnection.prototype.setRemoteDescription;\n window.RTCPeerConnection.prototype.setRemoteDescription =\n function setRemoteDescription() {\n const pc = this;\n if (!this._onaddstreampoly) {\n this.addEventListener('track', this._onaddstreampoly = function(e) {\n e.streams.forEach(stream => {\n if (!pc._remoteStreams) {\n pc._remoteStreams = [];\n }\n if (pc._remoteStreams.indexOf(stream) >= 0) {\n return;\n }\n pc._remoteStreams.push(stream);\n const event = new Event('addstream');\n event.stream = stream;\n pc.dispatchEvent(event);\n });\n });\n }\n return origSetRemoteDescription.apply(pc, arguments);\n };\n }\n}\n\nexport function shimCallbacksAPI(window) {\n if (typeof window !== 'object' || !window.RTCPeerConnection) {\n return;\n }\n const prototype = window.RTCPeerConnection.prototype;\n const origCreateOffer = prototype.createOffer;\n const origCreateAnswer = prototype.createAnswer;\n const setLocalDescription = prototype.setLocalDescription;\n const setRemoteDescription = prototype.setRemoteDescription;\n const addIceCandidate = prototype.addIceCandidate;\n\n prototype.createOffer =\n function createOffer(successCallback, failureCallback) {\n const options = (arguments.length >= 2) ? arguments[2] : arguments[0];\n const promise = origCreateOffer.apply(this, [options]);\n if (!failureCallback) {\n return promise;\n }\n promise.then(successCallback, failureCallback);\n return Promise.resolve();\n };\n\n prototype.createAnswer =\n function createAnswer(successCallback, failureCallback) {\n const options = (arguments.length >= 2) ? arguments[2] : arguments[0];\n const promise = origCreateAnswer.apply(this, [options]);\n if (!failureCallback) {\n return promise;\n }\n promise.then(successCallback, failureCallback);\n return Promise.resolve();\n };\n\n let withCallback = function(description, successCallback, failureCallback) {\n const promise = setLocalDescription.apply(this, [description]);\n if (!failureCallback) {\n return promise;\n }\n promise.then(successCallback, failureCallback);\n return Promise.resolve();\n };\n prototype.setLocalDescription = withCallback;\n\n withCallback = function(description, successCallback, failureCallback) {\n const promise = setRemoteDescription.apply(this, [description]);\n if (!failureCallback) {\n return promise;\n }\n promise.then(successCallback, failureCallback);\n return Promise.resolve();\n };\n prototype.setRemoteDescription = withCallback;\n\n withCallback = function(candidate, successCallback, failureCallback) {\n const promise = addIceCandidate.apply(this, [candidate]);\n if (!failureCallback) {\n return promise;\n }\n promise.then(successCallback, failureCallback);\n return Promise.resolve();\n };\n prototype.addIceCandidate = withCallback;\n}\n\nexport function shimGetUserMedia(window) {\n const navigator = window && window.navigator;\n\n if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {\n // shim not needed in Safari 12.1\n const mediaDevices = navigator.mediaDevices;\n const _getUserMedia = mediaDevices.getUserMedia.bind(mediaDevices);\n navigator.mediaDevices.getUserMedia = (constraints) => {\n return _getUserMedia(shimConstraints(constraints));\n };\n }\n\n if (!navigator.getUserMedia && navigator.mediaDevices &&\n navigator.mediaDevices.getUserMedia) {\n navigator.getUserMedia = function getUserMedia(constraints, cb, errcb) {\n navigator.mediaDevices.getUserMedia(constraints)\n .then(cb, errcb);\n }.bind(navigator);\n }\n}\n\nexport function shimConstraints(constraints) {\n if (constraints && constraints.video !== undefined) {\n return Object.assign({},\n constraints,\n {video: utils.compactObject(constraints.video)}\n );\n }\n\n return constraints;\n}\n\nexport function shimRTCIceServerUrls(window) {\n if (!window.RTCPeerConnection) {\n return;\n }\n // migrate from non-spec RTCIceServer.url to RTCIceServer.urls\n const OrigPeerConnection = window.RTCPeerConnection;\n window.RTCPeerConnection =\n function RTCPeerConnection(pcConfig, pcConstraints) {\n if (pcConfig && pcConfig.iceServers) {\n const newIceServers = [];\n for (let i = 0; i < pcConfig.iceServers.length; i++) {\n let server = pcConfig.iceServers[i];\n if (server.urls === undefined && server.url) {\n utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');\n server = JSON.parse(JSON.stringify(server));\n server.urls = server.url;\n delete server.url;\n newIceServers.push(server);\n } else {\n newIceServers.push(pcConfig.iceServers[i]);\n }\n }\n pcConfig.iceServers = newIceServers;\n }\n return new OrigPeerConnection(pcConfig, pcConstraints);\n };\n window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;\n // wrap static methods. Currently just generateCertificate.\n if ('generateCertificate' in OrigPeerConnection) {\n Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {\n get() {\n return OrigPeerConnection.generateCertificate;\n }\n });\n }\n}\n\nexport function shimTrackEventTransceiver(window) {\n // Add event.transceiver member over deprecated event.receiver\n if (typeof window === 'object' && window.RTCTrackEvent &&\n 'receiver' in window.RTCTrackEvent.prototype &&\n !('transceiver' in window.RTCTrackEvent.prototype)) {\n Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {\n get() {\n return {receiver: this.receiver};\n }\n });\n }\n}\n\nexport function shimCreateOfferLegacy(window) {\n const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;\n window.RTCPeerConnection.prototype.createOffer =\n function createOffer(offerOptions) {\n if (offerOptions) {\n if (typeof offerOptions.offerToReceiveAudio !== 'undefined') {\n // support bit values\n offerOptions.offerToReceiveAudio =\n !!offerOptions.offerToReceiveAudio;\n }\n const audioTransceiver = this.getTransceivers().find(transceiver =>\n transceiver.receiver.track.kind === 'audio');\n if (offerOptions.offerToReceiveAudio === false && audioTransceiver) {\n if (audioTransceiver.direction === 'sendrecv') {\n if (audioTransceiver.setDirection) {\n audioTransceiver.setDirection('sendonly');\n } else {\n audioTransceiver.direction = 'sendonly';\n }\n } else if (audioTransceiver.direction === 'recvonly') {\n if (audioTransceiver.setDirection) {\n audioTransceiver.setDirection('inactive');\n } else {\n audioTransceiver.direction = 'inactive';\n }\n }\n } else if (offerOptions.offerToReceiveAudio === true &&\n !audioTransceiver) {\n this.addTransceiver('audio', {direction: 'recvonly'});\n }\n\n if (typeof offerOptions.offerToReceiveVideo !== 'undefined') {\n // support bit values\n offerOptions.offerToReceiveVideo =\n !!offerOptions.offerToReceiveVideo;\n }\n const videoTransceiver = this.getTransceivers().find(transceiver =>\n transceiver.receiver.track.kind === 'video');\n if (offerOptions.offerToReceiveVideo === false && videoTransceiver) {\n if (videoTransceiver.direction === 'sendrecv') {\n if (videoTransceiver.setDirection) {\n videoTransceiver.setDirection('sendonly');\n } else {\n videoTransceiver.direction = 'sendonly';\n }\n } else if (videoTransceiver.direction === 'recvonly') {\n if (videoTransceiver.setDirection) {\n videoTransceiver.setDirection('inactive');\n } else {\n videoTransceiver.direction = 'inactive';\n }\n }\n } else if (offerOptions.offerToReceiveVideo === true &&\n !videoTransceiver) {\n this.addTransceiver('video', {direction: 'recvonly'});\n }\n }\n return origCreateOffer.apply(this, arguments);\n };\n}\n\nexport function shimAudioContext(window) {\n if (typeof window !== 'object' || window.AudioContext) {\n return;\n }\n window.AudioContext = window.webkitAudioContext;\n}\n\n", "/*\n * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n'use strict';\n\nimport SDPUtils from 'sdp';\nimport * as utils from './utils';\n\nexport function shimRTCIceCandidate(window) {\n // foundation is arbitrarily chosen as an indicator for full support for\n // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface\n if (!window.RTCIceCandidate || (window.RTCIceCandidate && 'foundation' in\n window.RTCIceCandidate.prototype)) {\n return;\n }\n\n const NativeRTCIceCandidate = window.RTCIceCandidate;\n window.RTCIceCandidate = function RTCIceCandidate(args) {\n // Remove the a= which shouldn't be part of the candidate string.\n if (typeof args === 'object' && args.candidate &&\n args.candidate.indexOf('a=') === 0) {\n args = JSON.parse(JSON.stringify(args));\n args.candidate = args.candidate.substring(2);\n }\n\n if (args.candidate && args.candidate.length) {\n // Augment the native candidate with the parsed fields.\n const nativeCandidate = new NativeRTCIceCandidate(args);\n const parsedCandidate = SDPUtils.parseCandidate(args.candidate);\n for (const key in parsedCandidate) {\n if (!(key in nativeCandidate)) {\n Object.defineProperty(nativeCandidate, key,\n {value: parsedCandidate[key]});\n }\n }\n\n // Override serializer to not serialize the extra attributes.\n nativeCandidate.toJSON = function toJSON() {\n return {\n candidate: nativeCandidate.candidate,\n sdpMid: nativeCandidate.sdpMid,\n sdpMLineIndex: nativeCandidate.sdpMLineIndex,\n usernameFragment: nativeCandidate.usernameFragment,\n };\n };\n return nativeCandidate;\n }\n return new NativeRTCIceCandidate(args);\n };\n window.RTCIceCandidate.prototype = NativeRTCIceCandidate.prototype;\n\n // Hook up the augmented candidate in onicecandidate and\n // addEventListener('icecandidate', ...)\n utils.wrapPeerConnectionEvent(window, 'icecandidate', e => {\n if (e.candidate) {\n Object.defineProperty(e, 'candidate', {\n value: new window.RTCIceCandidate(e.candidate),\n writable: 'false'\n });\n }\n return e;\n });\n}\n\nexport function shimRTCIceCandidateRelayProtocol(window) {\n if (!window.RTCIceCandidate || (window.RTCIceCandidate && 'relayProtocol' in\n window.RTCIceCandidate.prototype)) {\n return;\n }\n\n // Hook up the augmented candidate in onicecandidate and\n // addEventListener('icecandidate', ...)\n utils.wrapPeerConnectionEvent(window, 'icecandidate', e => {\n if (e.candidate) {\n const parsedCandidate = SDPUtils.parseCandidate(e.candidate.candidate);\n if (parsedCandidate.type === 'relay') {\n // This is a libwebrtc-specific mapping of local type preference\n // to relayProtocol.\n e.candidate.relayProtocol = {\n 0: 'tls',\n 1: 'tcp',\n 2: 'udp',\n }[parsedCandidate.priority >> 24];\n }\n }\n return e;\n });\n}\n\nexport function shimMaxMessageSize(window, browserDetails) {\n if (!window.RTCPeerConnection) {\n return;\n }\n\n if (!('sctp' in window.RTCPeerConnection.prototype)) {\n Object.defineProperty(window.RTCPeerConnection.prototype, 'sctp', {\n get() {\n return typeof this._sctp === 'undefined' ? null : this._sctp;\n }\n });\n }\n\n const sctpInDescription = function(description) {\n if (!description || !description.sdp) {\n return false;\n }\n const sections = SDPUtils.splitSections(description.sdp);\n sections.shift();\n return sections.some(mediaSection => {\n const mLine = SDPUtils.parseMLine(mediaSection);\n return mLine && mLine.kind === 'application'\n && mLine.protocol.indexOf('SCTP') !== -1;\n });\n };\n\n const getRemoteFirefoxVersion = function(description) {\n // TODO: Is there a better solution for detecting Firefox?\n const match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\\d+)/);\n if (match === null || match.length < 2) {\n return -1;\n }\n const version = parseInt(match[1], 10);\n // Test for NaN (yes, this is ugly)\n return version !== version ? -1 : version;\n };\n\n const getCanSendMaxMessageSize = function(remoteIsFirefox) {\n // Every implementation we know can send at least 64 KiB.\n // Note: Although Chrome is technically able to send up to 256 KiB, the\n // data does not reach the other peer reliably.\n // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8419\n let canSendMaxMessageSize = 65536;\n if (browserDetails.browser === 'firefox') {\n if (browserDetails.version < 57) {\n if (remoteIsFirefox === -1) {\n // FF < 57 will send in 16 KiB chunks using the deprecated PPID\n // fragmentation.\n canSendMaxMessageSize = 16384;\n } else {\n // However, other FF (and RAWRTC) can reassemble PPID-fragmented\n // messages. Thus, supporting ~2 GiB when sending.\n canSendMaxMessageSize = 2147483637;\n }\n } else if (browserDetails.version < 60) {\n // Currently, all FF >= 57 will reset the remote maximum message size\n // to the default value when a data channel is created at a later\n // stage. :(\n // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831\n canSendMaxMessageSize =\n browserDetails.version === 57 ? 65535 : 65536;\n } else {\n // FF >= 60 supports sending ~2 GiB\n canSendMaxMessageSize = 2147483637;\n }\n }\n return canSendMaxMessageSize;\n };\n\n const getMaxMessageSize = function(description, remoteIsFirefox) {\n // Note: 65536 bytes is the default value from the SDP spec. Also,\n // every implementation we know supports receiving 65536 bytes.\n let maxMessageSize = 65536;\n\n // FF 57 has a slightly incorrect default remote max message size, so\n // we need to adjust it here to avoid a failure when sending.\n // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1425697\n if (browserDetails.browser === 'firefox'\n && browserDetails.version === 57) {\n maxMessageSize = 65535;\n }\n\n const match = SDPUtils.matchPrefix(description.sdp,\n 'a=max-message-size:');\n if (match.length > 0) {\n maxMessageSize = parseInt(match[0].substring(19), 10);\n } else if (browserDetails.browser === 'firefox' &&\n remoteIsFirefox !== -1) {\n // If the maximum message size is not present in the remote SDP and\n // both local and remote are Firefox, the remote peer can receive\n // ~2 GiB.\n maxMessageSize = 2147483637;\n }\n return maxMessageSize;\n };\n\n const origSetRemoteDescription =\n window.RTCPeerConnection.prototype.setRemoteDescription;\n window.RTCPeerConnection.prototype.setRemoteDescription =\n function setRemoteDescription() {\n this._sctp = null;\n // Chrome decided to not expose .sctp in plan-b mode.\n // As usual, adapter.js has to do an 'ugly worakaround'\n // to cover up the mess.\n if (browserDetails.browser === 'chrome' && browserDetails.version >= 76) {\n const {sdpSemantics} = this.getConfiguration();\n if (sdpSemantics === 'plan-b') {\n Object.defineProperty(this, 'sctp', {\n get() {\n return typeof this._sctp === 'undefined' ? null : this._sctp;\n },\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n if (sctpInDescription(arguments[0])) {\n // Check if the remote is FF.\n const isFirefox = getRemoteFirefoxVersion(arguments[0]);\n\n // Get the maximum message size the local peer is capable of sending\n const canSendMMS = getCanSendMaxMessageSize(isFirefox);\n\n // Get the maximum message size of the remote peer.\n const remoteMMS = getMaxMessageSize(arguments[0], isFirefox);\n\n // Determine final maximum message size\n let maxMessageSize;\n if (canSendMMS === 0 && remoteMMS === 0) {\n maxMessageSize = Number.POSITIVE_INFINITY;\n } else if (canSendMMS === 0 || remoteMMS === 0) {\n maxMessageSize = Math.max(canSendMMS, remoteMMS);\n } else {\n maxMessageSize = Math.min(canSendMMS, remoteMMS);\n }\n\n // Create a dummy RTCSctpTransport object and the 'maxMessageSize'\n // attribute.\n const sctp = {};\n Object.defineProperty(sctp, 'maxMessageSize', {\n get() {\n return maxMessageSize;\n }\n });\n this._sctp = sctp;\n }\n\n return origSetRemoteDescription.apply(this, arguments);\n };\n}\n\nexport function shimSendThrowTypeError(window) {\n if (!(window.RTCPeerConnection &&\n 'createDataChannel' in window.RTCPeerConnection.prototype)) {\n return;\n }\n\n // Note: Although Firefox >= 57 has a native implementation, the maximum\n // message size can be reset for all data channels at a later stage.\n // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831\n\n function wrapDcSend(dc, pc) {\n const origDataChannelSend = dc.send;\n dc.send = function send() {\n const data = arguments[0];\n const length = data.length || data.size || data.byteLength;\n if (dc.readyState === 'open' &&\n pc.sctp && length > pc.sctp.maxMessageSize) {\n throw new TypeError('Message too large (can send a maximum of ' +\n pc.sctp.maxMessageSize + ' bytes)');\n }\n return origDataChannelSend.apply(dc, arguments);\n };\n }\n const origCreateDataChannel =\n window.RTCPeerConnection.prototype.createDataChannel;\n window.RTCPeerConnection.prototype.createDataChannel =\n function createDataChannel() {\n const dataChannel = origCreateDataChannel.apply(this, arguments);\n wrapDcSend(dataChannel, this);\n return dataChannel;\n };\n utils.wrapPeerConnectionEvent(window, 'datachannel', e => {\n wrapDcSend(e.channel, e.target);\n return e;\n });\n}\n\n\n/* shims RTCConnectionState by pretending it is the same as iceConnectionState.\n * See https://bugs.chromium.org/p/webrtc/issues/detail?id=6145#c12\n * for why this is a valid hack in Chrome. In Firefox it is slightly incorrect\n * since DTLS failures would be hidden. See\n * https://bugzilla.mozilla.org/show_bug.cgi?id=1265827\n * for the Firefox tracking bug.\n */\nexport function shimConnectionState(window) {\n if (!window.RTCPeerConnection ||\n 'connectionState' in window.RTCPeerConnection.prototype) {\n return;\n }\n const proto = window.RTCPeerConnection.prototype;\n Object.defineProperty(proto, 'connectionState', {\n get() {\n return {\n completed: 'connected',\n checking: 'connecting'\n }[this.iceConnectionState] || this.iceConnectionState;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(proto, 'onconnectionstatechange', {\n get() {\n return this._onconnectionstatechange || null;\n },\n set(cb) {\n if (this._onconnectionstatechange) {\n this.removeEventListener('connectionstatechange',\n this._onconnectionstatechange);\n delete this._onconnectionstatechange;\n }\n if (cb) {\n this.addEventListener('connectionstatechange',\n this._onconnectionstatechange = cb);\n }\n },\n enumerable: true,\n configurable: true\n });\n\n ['setLocalDescription', 'setRemoteDescription'].forEach((method) => {\n const origMethod = proto[method];\n proto[method] = function() {\n if (!this._connectionstatechangepoly) {\n this._connectionstatechangepoly = e => {\n const pc = e.target;\n if (pc._lastConnectionState !== pc.connectionState) {\n pc._lastConnectionState = pc.connectionState;\n const newEvent = new Event('connectionstatechange', e);\n pc.dispatchEvent(newEvent);\n }\n return e;\n };\n this.addEventListener('iceconnectionstatechange',\n this._connectionstatechangepoly);\n }\n return origMethod.apply(this, arguments);\n };\n });\n}\n\nexport function removeExtmapAllowMixed(window, browserDetails) {\n /* remove a=extmap-allow-mixed for webrtc.org < M71 */\n if (!window.RTCPeerConnection) {\n return;\n }\n if (browserDetails.browser === 'chrome' && browserDetails.version >= 71) {\n return;\n }\n if (browserDetails.browser === 'safari' &&\n browserDetails._safariVersion >= 13.1) {\n return;\n }\n const nativeSRD = window.RTCPeerConnection.prototype.setRemoteDescription;\n window.RTCPeerConnection.prototype.setRemoteDescription =\n function setRemoteDescription(desc) {\n if (desc && desc.sdp && desc.sdp.indexOf('\\na=extmap-allow-mixed') !== -1) {\n const sdp = desc.sdp.split('\\n').filter((line) => {\n return line.trim() !== 'a=extmap-allow-mixed';\n }).join('\\n');\n // Safari enforces read-only-ness of RTCSessionDescription fields.\n if (window.RTCSessionDescription &&\n desc instanceof window.RTCSessionDescription) {\n arguments[0] = new window.RTCSessionDescription({\n type: desc.type,\n sdp,\n });\n } else {\n desc.sdp = sdp;\n }\n }\n return nativeSRD.apply(this, arguments);\n };\n}\n\nexport function shimAddIceCandidateNullOrEmpty(window, browserDetails) {\n // Support for addIceCandidate(null or undefined)\n // as well as addIceCandidate({candidate: \"\", ...})\n // https://bugs.chromium.org/p/chromium/issues/detail?id=978582\n // Note: must be called before other polyfills which change the signature.\n if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) {\n return;\n }\n const nativeAddIceCandidate =\n window.RTCPeerConnection.prototype.addIceCandidate;\n if (!nativeAddIceCandidate || nativeAddIceCandidate.length === 0) {\n return;\n }\n window.RTCPeerConnection.prototype.addIceCandidate =\n function addIceCandidate() {\n if (!arguments[0]) {\n if (arguments[1]) {\n arguments[1].apply(null);\n }\n return Promise.resolve();\n }\n // Firefox 68+ emits and processes {candidate: \"\", ...}, ignore\n // in older versions.\n // Native support for ignoring exists for Chrome M77+.\n // Safari ignores as well, exact version unknown but works in the same\n // version that also ignores addIceCandidate(null).\n if (((browserDetails.browser === 'chrome' && browserDetails.version < 78)\n || (browserDetails.browser === 'firefox'\n && browserDetails.version < 68)\n || (browserDetails.browser === 'safari'))\n && arguments[0] && arguments[0].candidate === '') {\n return Promise.resolve();\n }\n return nativeAddIceCandidate.apply(this, arguments);\n };\n}\n\n// Note: Make sure to call this ahead of APIs that modify\n// setLocalDescription.length\nexport function shimParameterlessSetLocalDescription(window, browserDetails) {\n if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) {\n return;\n }\n const nativeSetLocalDescription =\n window.RTCPeerConnection.prototype.setLocalDescription;\n if (!nativeSetLocalDescription || nativeSetLocalDescription.length === 0) {\n return;\n }\n window.RTCPeerConnection.prototype.setLocalDescription =\n function setLocalDescription() {\n let desc = arguments[0] || {};\n if (typeof desc !== 'object' || (desc.type && desc.sdp)) {\n return nativeSetLocalDescription.apply(this, arguments);\n }\n // The remaining steps should technically happen when SLD comes off the\n // RTCPeerConnection's operations chain (not ahead of going on it), but\n // this is too difficult to shim. Instead, this shim only covers the\n // common case where the operations chain is empty. This is imperfect, but\n // should cover many cases. Rationale: Even if we can't reduce the glare\n // window to zero on imperfect implementations, there's value in tapping\n // into the perfect negotiation pattern that several browsers support.\n desc = {type: desc.type, sdp: desc.sdp};\n if (!desc.type) {\n switch (this.signalingState) {\n case 'stable':\n case 'have-local-offer':\n case 'have-remote-pranswer':\n desc.type = 'offer';\n break;\n default:\n desc.type = 'answer';\n break;\n }\n }\n if (desc.sdp || (desc.type !== 'offer' && desc.type !== 'answer')) {\n return nativeSetLocalDescription.apply(this, [desc]);\n }\n const func = desc.type === 'offer' ? this.createOffer : this.createAnswer;\n return func.apply(this)\n .then(d => nativeSetLocalDescription.apply(this, [d]));\n };\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\nimport * as utils from './utils';\n\n// Browser shims.\nimport * as chromeShim from './chrome/chrome_shim';\nimport * as firefoxShim from './firefox/firefox_shim';\nimport * as safariShim from './safari/safari_shim';\nimport * as commonShim from './common_shim';\nimport * as sdp from 'sdp';\n\n// Shimming starts here.\nexport function adapterFactory({window} = {}, options = {\n shimChrome: true,\n shimFirefox: true,\n shimSafari: true,\n}) {\n // Utils.\n const logging = utils.log;\n const browserDetails = utils.detectBrowser(window);\n\n const adapter = {\n browserDetails,\n commonShim,\n extractVersion: utils.extractVersion,\n disableLog: utils.disableLog,\n disableWarnings: utils.disableWarnings,\n // Expose sdp as a convenience. For production apps include directly.\n sdp,\n };\n\n // Shim browser if found.\n switch (browserDetails.browser) {\n case 'chrome':\n if (!chromeShim || !chromeShim.shimPeerConnection ||\n !options.shimChrome) {\n logging('Chrome shim is not included in this adapter release.');\n return adapter;\n }\n if (browserDetails.version === null) {\n logging('Chrome shim can not determine version, not shimming.');\n return adapter;\n }\n logging('adapter.js shimming chrome.');\n // Export to the adapter global object visible in the browser.\n adapter.browserShim = chromeShim;\n\n // Must be called before shimPeerConnection.\n commonShim.shimAddIceCandidateNullOrEmpty(window, browserDetails);\n commonShim.shimParameterlessSetLocalDescription(window, browserDetails);\n\n chromeShim.shimGetUserMedia(window, browserDetails);\n chromeShim.shimMediaStream(window, browserDetails);\n chromeShim.shimPeerConnection(window, browserDetails);\n chromeShim.shimOnTrack(window, browserDetails);\n chromeShim.shimAddTrackRemoveTrack(window, browserDetails);\n chromeShim.shimGetSendersWithDtmf(window, browserDetails);\n chromeShim.shimSenderReceiverGetStats(window, browserDetails);\n chromeShim.fixNegotiationNeeded(window, browserDetails);\n\n commonShim.shimRTCIceCandidate(window, browserDetails);\n commonShim.shimRTCIceCandidateRelayProtocol(window, browserDetails);\n commonShim.shimConnectionState(window, browserDetails);\n commonShim.shimMaxMessageSize(window, browserDetails);\n commonShim.shimSendThrowTypeError(window, browserDetails);\n commonShim.removeExtmapAllowMixed(window, browserDetails);\n break;\n case 'firefox':\n if (!firefoxShim || !firefoxShim.shimPeerConnection ||\n !options.shimFirefox) {\n logging('Firefox shim is not included in this adapter release.');\n return adapter;\n }\n logging('adapter.js shimming firefox.');\n // Export to the adapter global object visible in the browser.\n adapter.browserShim = firefoxShim;\n\n // Must be called before shimPeerConnection.\n commonShim.shimAddIceCandidateNullOrEmpty(window, browserDetails);\n commonShim.shimParameterlessSetLocalDescription(window, browserDetails);\n\n firefoxShim.shimGetUserMedia(window, browserDetails);\n firefoxShim.shimPeerConnection(window, browserDetails);\n firefoxShim.shimOnTrack(window, browserDetails);\n firefoxShim.shimRemoveStream(window, browserDetails);\n firefoxShim.shimSenderGetStats(window, browserDetails);\n firefoxShim.shimReceiverGetStats(window, browserDetails);\n firefoxShim.shimRTCDataChannel(window, browserDetails);\n firefoxShim.shimAddTransceiver(window, browserDetails);\n firefoxShim.shimGetParameters(window, browserDetails);\n firefoxShim.shimCreateOffer(window, browserDetails);\n firefoxShim.shimCreateAnswer(window, browserDetails);\n\n commonShim.shimRTCIceCandidate(window, browserDetails);\n commonShim.shimConnectionState(window, browserDetails);\n commonShim.shimMaxMessageSize(window, browserDetails);\n commonShim.shimSendThrowTypeError(window, browserDetails);\n break;\n case 'safari':\n if (!safariShim || !options.shimSafari) {\n logging('Safari shim is not included in this adapter release.');\n return adapter;\n }\n logging('adapter.js shimming safari.');\n // Export to the adapter global object visible in the browser.\n adapter.browserShim = safariShim;\n\n // Must be called before shimCallbackAPI.\n commonShim.shimAddIceCandidateNullOrEmpty(window, browserDetails);\n commonShim.shimParameterlessSetLocalDescription(window, browserDetails);\n\n safariShim.shimRTCIceServerUrls(window, browserDetails);\n safariShim.shimCreateOfferLegacy(window, browserDetails);\n safariShim.shimCallbacksAPI(window, browserDetails);\n safariShim.shimLocalStreamsAPI(window, browserDetails);\n safariShim.shimRemoteStreamsAPI(window, browserDetails);\n safariShim.shimTrackEventTransceiver(window, browserDetails);\n safariShim.shimGetUserMedia(window, browserDetails);\n safariShim.shimAudioContext(window, browserDetails);\n\n commonShim.shimRTCIceCandidate(window, browserDetails);\n commonShim.shimRTCIceCandidateRelayProtocol(window, browserDetails);\n commonShim.shimMaxMessageSize(window, browserDetails);\n commonShim.shimSendThrowTypeError(window, browserDetails);\n commonShim.removeExtmapAllowMixed(window, browserDetails);\n break;\n default:\n logging('Unsupported browser!');\n break;\n }\n\n return adapter;\n}\n", "/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n/* eslint-env node */\n\n'use strict';\n\nimport {adapterFactory} from './adapter_factory.js';\n\nconst adapter =\n adapterFactory({window: typeof window === 'undefined' ? undefined : window});\nexport default adapter;\n", "export { util, type Util } from \"./util\";\nimport { Peer } from \"./peer\";\nimport { MsgPackPeer } from \"./msgPackPeer\";\n\nexport type { PeerEvents, PeerOptions } from \"./peer\";\n\nexport type {\n\tPeerJSOption,\n\tPeerConnectOption,\n\tAnswerOption,\n\tCallOption,\n} from \"./optionInterfaces\";\nexport type { UtilSupportsObj } from \"./util\";\nexport type { DataConnection } from \"./dataconnection/DataConnection\";\nexport type { MediaConnection } from \"./mediaconnection\";\nexport type { LogLevel } from \"./logger\";\nexport * from \"./enums\";\n\nexport { BufferedConnection } from \"./dataconnection/BufferedConnection/BufferedConnection\";\nexport { StreamConnection } from \"./dataconnection/StreamConnection/StreamConnection\";\nexport { MsgPack } from \"./dataconnection/StreamConnection/MsgPack\";\nexport type { SerializerMapping } from \"./peer\";\n\nexport { Peer, MsgPackPeer };\n\nexport { PeerError } from \"./peerError\";\nexport default Peer;\n", "import { BinaryPackChunker } from \"./dataconnection/BufferedConnection/binaryPackChunker\";\nimport * as BinaryPack from \"peerjs-js-binarypack\";\nimport { Supports } from \"./supports\";\nimport { validateId } from \"./utils/validateId\";\nimport { randomToken } from \"./utils/randomToken\";\n\nexport interface UtilSupportsObj {\n\t/**\n\t * The current browser.\n\t * This property can be useful in determining whether two peers can connect.\n\t *\n\t * ```ts\n\t * if (util.browser === 'firefox') {\n\t * // OK to peer with Firefox peers.\n\t * }\n\t * ```\n\t *\n\t * `util.browser` can currently have the values\n\t * `'firefox', 'chrome', 'safari', 'edge', 'Not a supported browser.', 'Not a browser.' (unknown WebRTC-compatible agent).\n\t */\n\tbrowser: boolean;\n\twebRTC: boolean;\n\t/**\n\t * True if the current browser supports media streams and PeerConnection.\n\t */\n\taudioVideo: boolean;\n\t/**\n\t * True if the current browser supports DataChannel and PeerConnection.\n\t */\n\tdata: boolean;\n\tbinaryBlob: boolean;\n\t/**\n\t * True if the current browser supports reliable DataChannels.\n\t */\n\treliable: boolean;\n}\n\nconst DEFAULT_CONFIG = {\n\ticeServers: [\n\t\t{ urls: \"stun:stun.l.google.com:19302\" },\n\t\t{\n\t\t\turls: [\n\t\t\t\t\"turn:eu-0.turn.peerjs.com:3478\",\n\t\t\t\t\"turn:us-0.turn.peerjs.com:3478\",\n\t\t\t],\n\t\t\tusername: \"peerjs\",\n\t\t\tcredential: \"peerjsp\",\n\t\t},\n\t],\n\tsdpSemantics: \"unified-plan\",\n};\n\nexport class Util extends BinaryPackChunker {\n\tnoop(): void {}\n\n\treadonly CLOUD_HOST = \"0.peerjs.com\";\n\treadonly CLOUD_PORT = 443;\n\n\t// Browsers that need chunking:\n\treadonly chunkedBrowsers = { Chrome: 1, chrome: 1 };\n\n\t// Returns browser-agnostic default config\n\treadonly defaultConfig = DEFAULT_CONFIG;\n\n\treadonly browser = Supports.getBrowser();\n\treadonly browserVersion = Supports.getVersion();\n\n\tpack = BinaryPack.pack;\n\tunpack = BinaryPack.unpack;\n\n\t/**\n\t * A hash of WebRTC features mapped to booleans that correspond to whether the feature is supported by the current browser.\n\t *\n\t * :::caution\n\t * Only the properties documented here are guaranteed to be present on `util.supports`\n\t * :::\n\t */\n\treadonly supports = (function () {\n\t\tconst supported: UtilSupportsObj = {\n\t\t\tbrowser: Supports.isBrowserSupported(),\n\t\t\twebRTC: Supports.isWebRTCSupported(),\n\t\t\taudioVideo: false,\n\t\t\tdata: false,\n\t\t\tbinaryBlob: false,\n\t\t\treliable: false,\n\t\t};\n\n\t\tif (!supported.webRTC) return supported;\n\n\t\tlet pc: RTCPeerConnection;\n\n\t\ttry {\n\t\t\tpc = new RTCPeerConnection(DEFAULT_CONFIG);\n\n\t\t\tsupported.audioVideo = true;\n\n\t\t\tlet dc: RTCDataChannel;\n\n\t\t\ttry {\n\t\t\t\tdc = pc.createDataChannel(\"_PEERJSTEST\", { ordered: true });\n\t\t\t\tsupported.data = true;\n\t\t\t\tsupported.reliable = !!dc.ordered;\n\n\t\t\t\t// Binary test\n\t\t\t\ttry {\n\t\t\t\t\tdc.binaryType = \"blob\";\n\t\t\t\t\tsupported.binaryBlob = !Supports.isIOS;\n\t\t\t\t} catch (e) {}\n\t\t\t} catch (e) {\n\t\t\t} finally {\n\t\t\t\tif (dc) {\n\t\t\t\t\tdc.close();\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t} finally {\n\t\t\tif (pc) {\n\t\t\t\tpc.close();\n\t\t\t}\n\t\t}\n\n\t\treturn supported;\n\t})();\n\n\t// Ensure alphanumeric ids\n\tvalidateId = validateId;\n\trandomToken = randomToken;\n\n\tblobToArrayBuffer(\n\t\tblob: Blob,\n\t\tcb: (arg: ArrayBuffer | null) => void,\n\t): FileReader {\n\t\tconst fr = new FileReader();\n\n\t\tfr.onload = function (evt) {\n\t\t\tif (evt.target) {\n\t\t\t\tcb(evt.target.result as ArrayBuffer);\n\t\t\t}\n\t\t};\n\n\t\tfr.readAsArrayBuffer(blob);\n\n\t\treturn fr;\n\t}\n\n\tbinaryStringToArrayBuffer(binary: string): ArrayBuffer | SharedArrayBuffer {\n\t\tconst byteArray = new Uint8Array(binary.length);\n\n\t\tfor (let i = 0; i < binary.length; i++) {\n\t\t\tbyteArray[i] = binary.charCodeAt(i) & 0xff;\n\t\t}\n\n\t\treturn byteArray.buffer;\n\t}\n\tisSecure(): boolean {\n\t\treturn location.protocol === \"https:\";\n\t}\n}\n\n/**\n * Provides a variety of helpful utilities.\n *\n * :::caution\n * Only the utilities documented here are guaranteed to be present on `util`.\n * Undocumented utilities can be removed without warning.\n * We don't consider these to be breaking changes.\n * :::\n */\nexport const util = new Util();\n", "export class BinaryPackChunker {\n\treadonly chunkedMTU = 16300; // The original 60000 bytes setting does not work when sending data from Firefox to Chrome, which is \"cut off\" after 16384 bytes and delivered individually.\n\n\t// Binary stuff\n\n\tprivate _dataCount: number = 1;\n\n\tchunk = (\n\t\tblob: ArrayBuffer,\n\t): { __peerData: number; n: number; total: number; data: Uint8Array }[] => {\n\t\tconst chunks = [];\n\t\tconst size = blob.byteLength;\n\t\tconst total = Math.ceil(size / this.chunkedMTU);\n\n\t\tlet index = 0;\n\t\tlet start = 0;\n\n\t\twhile (start < size) {\n\t\t\tconst end = Math.min(size, start + this.chunkedMTU);\n\t\t\tconst b = blob.slice(start, end);\n\n\t\t\tconst chunk = {\n\t\t\t\t__peerData: this._dataCount,\n\t\t\t\tn: index,\n\t\t\t\tdata: b,\n\t\t\t\ttotal,\n\t\t\t};\n\n\t\t\tchunks.push(chunk);\n\n\t\t\tstart = end;\n\t\t\tindex++;\n\t\t}\n\n\t\tthis._dataCount++;\n\n\t\treturn chunks;\n\t};\n}\n\nexport function concatArrayBuffers(bufs: Uint8Array[]) {\n\tlet size = 0;\n\tfor (const buf of bufs) {\n\t\tsize += buf.byteLength;\n\t}\n\tconst result = new Uint8Array(size);\n\tlet offset = 0;\n\tfor (const buf of bufs) {\n\t\tresult.set(buf, offset);\n\t\toffset += buf.byteLength;\n\t}\n\treturn result;\n}\n", "import webRTCAdapter_import from \"webrtc-adapter\";\n\nconst webRTCAdapter: typeof webRTCAdapter_import =\n\t//@ts-ignore\n\twebRTCAdapter_import.default || webRTCAdapter_import;\n\nexport const Supports = new (class {\n\treadonly isIOS =\n\t\ttypeof navigator !== \"undefined\"\n\t\t\t? [\"iPad\", \"iPhone\", \"iPod\"].includes(navigator.platform)\n\t\t\t: false;\n\treadonly supportedBrowsers = [\"firefox\", \"chrome\", \"safari\"];\n\n\treadonly minFirefoxVersion = 59;\n\treadonly minChromeVersion = 72;\n\treadonly minSafariVersion = 605;\n\n\tisWebRTCSupported(): boolean {\n\t\treturn typeof RTCPeerConnection !== \"undefined\";\n\t}\n\n\tisBrowserSupported(): boolean {\n\t\tconst browser = this.getBrowser();\n\t\tconst version = this.getVersion();\n\n\t\tconst validBrowser = this.supportedBrowsers.includes(browser);\n\n\t\tif (!validBrowser) return false;\n\n\t\tif (browser === \"chrome\") return version >= this.minChromeVersion;\n\t\tif (browser === \"firefox\") return version >= this.minFirefoxVersion;\n\t\tif (browser === \"safari\")\n\t\t\treturn !this.isIOS && version >= this.minSafariVersion;\n\n\t\treturn false;\n\t}\n\n\tgetBrowser(): string {\n\t\treturn webRTCAdapter.browserDetails.browser;\n\t}\n\n\tgetVersion(): number {\n\t\treturn webRTCAdapter.browserDetails.version || 0;\n\t}\n\n\tisUnifiedPlanSupported(): boolean {\n\t\tconst browser = this.getBrowser();\n\t\tconst version = webRTCAdapter.browserDetails.version || 0;\n\n\t\tif (browser === \"chrome\" && version < this.minChromeVersion) return false;\n\t\tif (browser === \"firefox\" && version >= this.minFirefoxVersion) return true;\n\t\tif (\n\t\t\t!window.RTCRtpTransceiver ||\n\t\t\t!(\"currentDirection\" in RTCRtpTransceiver.prototype)\n\t\t)\n\t\t\treturn false;\n\n\t\tlet tempPc: RTCPeerConnection;\n\t\tlet supported = false;\n\n\t\ttry {\n\t\t\ttempPc = new RTCPeerConnection();\n\t\t\ttempPc.addTransceiver(\"audio\");\n\t\t\tsupported = true;\n\t\t} catch (e) {\n\t\t} finally {\n\t\t\tif (tempPc) {\n\t\t\t\ttempPc.close();\n\t\t\t}\n\t\t}\n\n\t\treturn supported;\n\t}\n\n\ttoString(): string {\n\t\treturn `Supports:\n browser:${this.getBrowser()}\n version:${this.getVersion()}\n isIOS:${this.isIOS}\n isWebRTCSupported:${this.isWebRTCSupported()}\n isBrowserSupported:${this.isBrowserSupported()}\n isUnifiedPlanSupported:${this.isUnifiedPlanSupported()}`;\n\t}\n})();\n", "export const validateId = (id: string): boolean => {\n\t// Allow empty ids\n\treturn !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(id);\n};\n", "export const randomToken = () => Math.random().toString(36).slice(2);\n", "import { util } from \"./util\";\nimport logger, { LogLevel } from \"./logger\";\nimport { Socket } from \"./socket\";\nimport { MediaConnection } from \"./mediaconnection\";\nimport type { DataConnection } from \"./dataconnection/DataConnection\";\nimport {\n\tConnectionType,\n\tPeerErrorType,\n\tServerMessageType,\n\tSocketEventType,\n} from \"./enums\";\nimport type { ServerMessage } from \"./servermessage\";\nimport { API } from \"./api\";\nimport type {\n\tCallOption,\n\tPeerConnectOption,\n\tPeerJSOption,\n} from \"./optionInterfaces\";\nimport { BinaryPack } from \"./dataconnection/BufferedConnection/BinaryPack\";\nimport { Raw } from \"./dataconnection/BufferedConnection/Raw\";\nimport { Json } from \"./dataconnection/BufferedConnection/Json\";\n\nimport { EventEmitterWithError, PeerError } from \"./peerError\";\n\nclass PeerOptions implements PeerJSOption {\n\t/**\n\t * Prints log messages depending on the debug level passed in.\n\t */\n\tdebug?: LogLevel;\n\t/**\n\t * Server host. Defaults to `0.peerjs.com`.\n\t * Also accepts `'/'` to signify relative hostname.\n\t */\n\thost?: string;\n\t/**\n\t * Server port. Defaults to `443`.\n\t */\n\tport?: number;\n\t/**\n\t * The path where your self-hosted PeerServer is running. Defaults to `'/'`\n\t */\n\tpath?: string;\n\t/**\n\t * API key for the PeerServer.\n\t * This is not used anymore.\n\t * @deprecated\n\t */\n\tkey?: string;\n\ttoken?: string;\n\t/**\n\t * Configuration hash passed to RTCPeerConnection.\n\t * This hash contains any custom ICE/TURN server configuration.\n\t *\n\t * Defaults to {@apilink util.defaultConfig}\n\t */\n\tconfig?: any;\n\t/**\n\t * Set to true `true` if you're using TLS.\n\t * :::danger\n\t * If possible *always use TLS*\n\t * :::\n\t */\n\tsecure?: boolean;\n\tpingInterval?: number;\n\treferrerPolicy?: ReferrerPolicy;\n\tlogFunction?: (logLevel: LogLevel, ...rest: any[]) => void;\n\tserializers?: SerializerMapping;\n}\n\nexport { type PeerOptions };\n\nexport interface SerializerMapping {\n\t[key: string]: new (\n\t\tpeerId: string,\n\t\tprovider: Peer,\n\t\toptions: any,\n\t) => DataConnection;\n}\n\nexport interface PeerEvents {\n\t/**\n\t * Emitted when a connection to the PeerServer is established.\n\t *\n\t * You may use the peer before this is emitted, but messages to the server will be queued. <code>id</code> is the brokering ID of the peer (which was either provided in the constructor or assigned by the server).<span class='tip'>You should not wait for this event before connecting to other peers if connection speed is important.</span>\n\t */\n\topen: (id: string) => void;\n\t/**\n\t * Emitted when a new data connection is established from a remote peer.\n\t */\n\tconnection: (dataConnection: DataConnection) => void;\n\t/**\n\t * Emitted when a remote peer attempts to call you.\n\t */\n\tcall: (mediaConnection: MediaConnection) => void;\n\t/**\n\t * Emitted when the peer is destroyed and can no longer accept or create any new connections.\n\t */\n\tclose: () => void;\n\t/**\n\t * Emitted when the peer is disconnected from the signalling server\n\t */\n\tdisconnected: (currentId: string) => void;\n\t/**\n\t * Errors on the peer are almost always fatal and will destroy the peer.\n\t *\n\t * Errors from the underlying socket and PeerConnections are forwarded here.\n\t */\n\terror: (error: PeerError<`${PeerErrorType}`>) => void;\n}\n/**\n * A peer who can initiate connections with other peers.\n */\nexport class Peer extends EventEmitterWithError<PeerErrorType, PeerEvents> {\n\tprivate static readonly DEFAULT_KEY = \"peerjs\";\n\n\tprotected readonly _serializers: SerializerMapping = {\n\t\traw: Raw,\n\t\tjson: Json,\n\t\tbinary: BinaryPack,\n\t\t\"binary-utf8\": BinaryPack,\n\n\t\tdefault: BinaryPack,\n\t};\n\tprivate readonly _options: PeerOptions;\n\tprivate readonly _api: API;\n\tprivate readonly _socket: Socket;\n\n\tprivate _id: string | null = null;\n\tprivate _lastServerId: string | null = null;\n\n\t// States.\n\tprivate _destroyed = false; // Connections have been killed\n\tprivate _disconnected = false; // Connection to PeerServer killed but P2P connections still active\n\tprivate _open = false; // Sockets and such are not yet open.\n\tprivate readonly _connections: Map<\n\t\tstring,\n\t\t(DataConnection | MediaConnection)[]\n\t> = new Map(); // All connections for this peer.\n\tprivate readonly _lostMessages: Map<string, ServerMessage[]> = new Map(); // src => [list of messages]\n\t/**\n\t * The brokering ID of this peer\n\t *\n\t * If no ID was specified in {@apilink Peer | the constructor},\n\t * this will be `undefined` until the {@apilink PeerEvents | `open`} event is emitted.\n\t */\n\tget id() {\n\t\treturn this._id;\n\t}\n\n\tget options() {\n\t\treturn this._options;\n\t}\n\n\tget open() {\n\t\treturn this._open;\n\t}\n\n\t/**\n\t * @internal\n\t */\n\tget socket() {\n\t\treturn this._socket;\n\t}\n\n\t/**\n\t * A hash of all connections associated with this peer, keyed by the remote peer's ID.\n\t * @deprecated\n\t * Return type will change from Object to Map<string,[]>\n\t */\n\tget connections(): Object {\n\t\tconst plainConnections = Object.create(null);\n\n\t\tfor (const [k, v] of this._connections) {\n\t\t\tplainConnections[k] = v;\n\t\t}\n\n\t\treturn plainConnections;\n\t}\n\n\t/**\n\t * true if this peer and all of its connections can no longer be used.\n\t */\n\tget destroyed() {\n\t\treturn this._destroyed;\n\t}\n\t/**\n\t * false if there is an active connection to the PeerServer.\n\t */\n\tget disconnected() {\n\t\treturn this._disconnected;\n\t}\n\n\t/**\n\t * A peer can connect to other peers and listen for connections.\n\t */\n\tconstructor();\n\n\t/**\n\t * A peer can connect to other peers and listen for connections.\n\t * @param options for specifying details about PeerServer\n\t */\n\tconstructor(options: PeerOptions);\n\n\t/**\n\t * A peer can connect to other peers and listen for connections.\n\t * @param id Other peers can connect to this peer using the provided ID.\n\t * If no ID is given, one will be generated by the brokering server.\n\t * The ID must start and end with an alphanumeric character (lower or upper case character or a digit). In the middle of the ID spaces, dashes (-) and underscores (_) are allowed. Use {@apilink PeerOptions.metadata } to send identifying information.\n\t * @param options for specifying details about PeerServer\n\t */\n\tconstructor(id: string, options?: PeerOptions);\n\n\tconstructor(id?: string | PeerOptions, options?: PeerOptions) {\n\t\tsuper();\n\n\t\tlet userId: string | undefined;\n\n\t\t// Deal with overloading\n\t\tif (id && id.constructor == Object) {\n\t\t\toptions = id as PeerOptions;\n\t\t} else if (id) {\n\t\t\tuserId = id.toString();\n\t\t}\n\n\t\t// Configurize options\n\t\toptions = {\n\t\t\tdebug: 0, // 1: Errors, 2: Warnings, 3: All logs\n\t\t\thost: util.CLOUD_HOST,\n\t\t\tport: util.CLOUD_PORT,\n\t\t\tpath: \"/\",\n\t\t\tkey: Peer.DEFAULT_KEY,\n\t\t\ttoken: util.randomToken(),\n\t\t\tconfig: util.defaultConfig,\n\t\t\treferrerPolicy: \"strict-origin-when-cross-origin\",\n\t\t\tserializers: {},\n\t\t\t...options,\n\t\t};\n\t\tthis._options = options;\n\t\tthis._serializers = { ...this._serializers, ...this.options.serializers };\n\n\t\t// Detect relative URL host.\n\t\tif (this._options.host === \"/\") {\n\t\t\tthis._options.host = window.location.hostname;\n\t\t}\n\n\t\t// Set path correctly.\n\t\tif (this._options.path) {\n\t\t\tif (this._options.path[0] !== \"/\") {\n\t\t\t\tthis._options.path = \"/\" + this._options.path;\n\t\t\t}\n\t\t\tif (this._options.path[this._options.path.length - 1] !== \"/\") {\n\t\t\t\tthis._options.path += \"/\";\n\t\t\t}\n\t\t}\n\n\t\t// Set whether we use SSL to same as current host\n\t\tif (\n\t\t\tthis._options.secure === undefined &&\n\t\t\tthis._options.host !== util.CLOUD_HOST\n\t\t) {\n\t\t\tthis._options.secure = util.isSecure();\n\t\t} else if (this._options.host == util.CLOUD_HOST) {\n\t\t\tthis._options.secure = true;\n\t\t}\n\t\t// Set a custom log function if present\n\t\tif (this._options.logFunction) {\n\t\t\tlogger.setLogFunction(this._options.logFunction);\n\t\t}\n\n\t\tlogger.logLevel = this._options.debug || 0;\n\n\t\tthis._api = new API(options);\n\t\tthis._socket = this._createServerConnection();\n\n\t\t// Sanity checks\n\t\t// Ensure WebRTC supported\n\t\tif (!util.supports.audioVideo && !util.supports.data) {\n\t\t\tthis._delayedAbort(\n\t\t\t\tPeerErrorType.BrowserIncompatible,\n\t\t\t\t\"The current browser does not support WebRTC\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// Ensure alphanumeric id\n\t\tif (!!userId && !util.validateId(userId)) {\n\t\t\tthis._delayedAbort(PeerErrorType.InvalidID, `ID \"${userId}\" is invalid`);\n\t\t\treturn;\n\t\t}\n\n\t\tif (userId) {\n\t\t\tthis._initialize(userId);\n\t\t} else {\n\t\t\tthis._api\n\t\t\t\t.retrieveId()\n\t\t\t\t.then((id) => this._initialize(id))\n\t\t\t\t.catch((error) => this._abort(PeerErrorType.ServerError, error));\n\t\t}\n\t}\n\n\tprivate _createServerConnection(): Socket {\n\t\tconst socket = new Socket(\n\t\t\tthis._options.secure,\n\t\t\tthis._options.host!,\n\t\t\tthis._options.port!,\n\t\t\tthis._options.path!,\n\t\t\tthis._options.key!,\n\t\t\tthis._options.pingInterval,\n\t\t);\n\n\t\tsocket.on(SocketEventType.Message, (data: ServerMessage) => {\n\t\t\tthis._handleMessage(data);\n\t\t});\n\n\t\tsocket.on(SocketEventType.Error, (error: string) => {\n\t\t\tthis._abort(PeerErrorType.SocketError, error);\n\t\t});\n\n\t\tsocket.on(SocketEventType.Disconnected, () => {\n\t\t\tif (this.disconnected) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.emitError(PeerErrorType.Network, \"Lost connection to server.\");\n\t\t\tthis.disconnect();\n\t\t});\n\n\t\tsocket.on(SocketEventType.Close, () => {\n\t\t\tif (this.disconnected) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._abort(\n\t\t\t\tPeerErrorType.SocketClosed,\n\t\t\t\t\"Underlying socket is already closed.\",\n\t\t\t);\n\t\t});\n\n\t\treturn socket;\n\t}\n\n\t/** Initialize a connection with the server. */\n\tprivate _initialize(id: string): void {\n\t\tthis._id = id;\n\t\tthis.socket.start(id, this._options.token!);\n\t}\n\n\t/** Handles messages from the server. */\n\tprivate _handleMessage(message: ServerMessage): void {\n\t\tconst type = message.type;\n\t\tconst payload = message.payload;\n\t\tconst peerId = message.src;\n\n\t\tswitch (type) {\n\t\t\tcase ServerMessageType.Open: // The connection to the server is open.\n\t\t\t\tthis._lastServerId = this.id;\n\t\t\t\tthis._open = true;\n\t\t\t\tthis.emit(\"open\", this.id);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Error: // Server error.\n\t\t\t\tthis._abort(PeerErrorType.ServerError, payload.msg);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.IdTaken: // The selected ID is taken.\n\t\t\t\tthis._abort(PeerErrorType.UnavailableID, `ID \"${this.id}\" is taken`);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.InvalidKey: // The given API key cannot be found.\n\t\t\t\tthis._abort(\n\t\t\t\t\tPeerErrorType.InvalidKey,\n\t\t\t\t\t`API KEY \"${this._options.key}\" is invalid`,\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Leave: // Another peer has closed its connection to this peer.\n\t\t\t\tlogger.log(`Received leave message from ${peerId}`);\n\t\t\t\tthis._cleanupPeer(peerId);\n\t\t\t\tthis._connections.delete(peerId);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Expire: // The offer sent to a peer has expired without response.\n\t\t\t\tthis.emitError(\n\t\t\t\t\tPeerErrorType.PeerUnavailable,\n\t\t\t\t\t`Could not connect to peer ${peerId}`,\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Offer: {\n\t\t\t\t// we should consider switching this to CALL/CONNECT, but this is the least breaking option.\n\t\t\t\tconst connectionId = payload.connectionId;\n\t\t\t\tlet connection = this.getConnection(peerId, connectionId);\n\n\t\t\t\tif (connection) {\n\t\t\t\t\tconnection.close();\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t`Offer received for existing Connection ID:${connectionId}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Create a new connection.\n\t\t\t\tif (payload.type === ConnectionType.Media) {\n\t\t\t\t\tconst mediaConnection = new MediaConnection(peerId, this, {\n\t\t\t\t\t\tconnectionId: connectionId,\n\t\t\t\t\t\t_payload: payload,\n\t\t\t\t\t\tmetadata: payload.metadata,\n\t\t\t\t\t});\n\t\t\t\t\tconnection = mediaConnection;\n\t\t\t\t\tthis._addConnection(peerId, connection);\n\t\t\t\t\tthis.emit(\"call\", mediaConnection);\n\t\t\t\t} else if (payload.type === ConnectionType.Data) {\n\t\t\t\t\tconst dataConnection = new this._serializers[payload.serialization](\n\t\t\t\t\t\tpeerId,\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconnectionId: connectionId,\n\t\t\t\t\t\t\t_payload: payload,\n\t\t\t\t\t\t\tmetadata: payload.metadata,\n\t\t\t\t\t\t\tlabel: payload.label,\n\t\t\t\t\t\t\tserialization: payload.serialization,\n\t\t\t\t\t\t\treliable: payload.reliable,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\tconnection = dataConnection;\n\n\t\t\t\t\tthis._addConnection(peerId, connection);\n\t\t\t\t\tthis.emit(\"connection\", dataConnection);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn(`Received malformed connection type:${payload.type}`);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Find messages.\n\t\t\t\tconst messages = this._getMessages(connectionId);\n\t\t\t\tfor (const message of messages) {\n\t\t\t\t\tconnection.handleMessage(message);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tif (!payload) {\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t`You received a malformed message from ${peerId} of type ${type}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst connectionId = payload.connectionId;\n\t\t\t\tconst connection = this.getConnection(peerId, connectionId);\n\n\t\t\t\tif (connection && connection.peerConnection) {\n\t\t\t\t\t// Pass it on.\n\t\t\t\t\tconnection.handleMessage(message);\n\t\t\t\t} else if (connectionId) {\n\t\t\t\t\t// Store for possible later use\n\t\t\t\t\tthis._storeMessage(connectionId, message);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn(\"You received an unrecognized message:\", message);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Stores messages without a set up connection, to be claimed later. */\n\tprivate _storeMessage(connectionId: string, message: ServerMessage): void {\n\t\tif (!this._lostMessages.has(connectionId)) {\n\t\t\tthis._lostMessages.set(connectionId, []);\n\t\t}\n\n\t\tthis._lostMessages.get(connectionId).push(message);\n\t}\n\n\t/**\n\t * Retrieve messages from lost message store\n\t * @internal\n\t */\n\t//TODO Change it to private\n\tpublic _getMessages(connectionId: string): ServerMessage[] {\n\t\tconst messages = this._lostMessages.get(connectionId);\n\n\t\tif (messages) {\n\t\t\tthis._lostMessages.delete(connectionId);\n\t\t\treturn messages;\n\t\t}\n\n\t\treturn [];\n\t}\n\n\t/**\n\t * Connects to the remote peer specified by id and returns a data connection.\n\t * @param peer The brokering ID of the remote peer (their {@apilink Peer.id}).\n\t * @param options for specifying details about Peer Connection\n\t */\n\tconnect(peer: string, options: PeerConnectOption = {}): DataConnection {\n\t\toptions = {\n\t\t\tserialization: \"default\",\n\t\t\t...options,\n\t\t};\n\t\tif (this.disconnected) {\n\t\t\tlogger.warn(\n\t\t\t\t\"You cannot connect to a new Peer because you called \" +\n\t\t\t\t\t\".disconnect() on this Peer and ended your connection with the \" +\n\t\t\t\t\t\"server. You can create a new Peer to reconnect, or call reconnect \" +\n\t\t\t\t\t\"on this peer if you believe its ID to still be available.\",\n\t\t\t);\n\t\t\tthis.emitError(\n\t\t\t\tPeerErrorType.Disconnected,\n\t\t\t\t\"Cannot connect to new Peer after disconnecting from server.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst dataConnection = new this._serializers[options.serialization](\n\t\t\tpeer,\n\t\t\tthis,\n\t\t\toptions,\n\t\t);\n\t\tthis._addConnection(peer, dataConnection);\n\t\treturn dataConnection;\n\t}\n\n\t/**\n\t * Calls the remote peer specified by id and returns a media connection.\n\t * @param peer The brokering ID of the remote peer (their peer.id).\n\t * @param stream The caller's media stream\n\t * @param options Metadata associated with the connection, passed in by whoever initiated the connection.\n\t */\n\tcall(\n\t\tpeer: string,\n\t\tstream: MediaStream,\n\t\toptions: CallOption = {},\n\t): MediaConnection {\n\t\tif (this.disconnected) {\n\t\t\tlogger.warn(\n\t\t\t\t\"You cannot connect to a new Peer because you called \" +\n\t\t\t\t\t\".disconnect() on this Peer and ended your connection with the \" +\n\t\t\t\t\t\"server. You can create a new Peer to reconnect.\",\n\t\t\t);\n\t\t\tthis.emitError(\n\t\t\t\tPeerErrorType.Disconnected,\n\t\t\t\t\"Cannot connect to new Peer after disconnecting from server.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!stream) {\n\t\t\tlogger.error(\n\t\t\t\t\"To call a peer, you must provide a stream from your browser's `getUserMedia`.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst mediaConnection = new MediaConnection(peer, this, {\n\t\t\t...options,\n\t\t\t_stream: stream,\n\t\t});\n\t\tthis._addConnection(peer, mediaConnection);\n\t\treturn mediaConnection;\n\t}\n\n\t/** Add a data/media connection to this peer. */\n\tprivate _addConnection(\n\t\tpeerId: string,\n\t\tconnection: MediaConnection | DataConnection,\n\t): void {\n\t\tlogger.log(\n\t\t\t`add connection ${connection.type}:${connection.connectionId} to peerId:${peerId}`,\n\t\t);\n\n\t\tif (!this._connections.has(peerId)) {\n\t\t\tthis._connections.set(peerId, []);\n\t\t}\n\t\tthis._connections.get(peerId).push(connection);\n\t}\n\n\t//TODO should be private\n\t_removeConnection(connection: DataConnection | MediaConnection): void {\n\t\tconst connections = this._connections.get(connection.peer);\n\n\t\tif (connections) {\n\t\t\tconst index = connections.indexOf(connection);\n\n\t\t\tif (index !== -1) {\n\t\t\t\tconnections.splice(index, 1);\n\t\t\t}\n\t\t}\n\n\t\t//remove from lost messages\n\t\tthis._lostMessages.delete(connection.connectionId);\n\t}\n\n\t/** Retrieve a data/media connection for this peer. */\n\tgetConnection(\n\t\tpeerId: string,\n\t\tconnectionId: string,\n\t): null | DataConnection | MediaConnection {\n\t\tconst connections = this._connections.get(peerId);\n\t\tif (!connections) {\n\t\t\treturn null;\n\t\t}\n\n\t\tfor (const connection of connections) {\n\t\t\tif (connection.connectionId === connectionId) {\n\t\t\t\treturn connection;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tprivate _delayedAbort(type: PeerErrorType, message: string | Error): void {\n\t\tsetTimeout(() => {\n\t\t\tthis._abort(type, message);\n\t\t}, 0);\n\t}\n\n\t/**\n\t * Emits an error message and destroys the Peer.\n\t * The Peer is not destroyed if it's in a disconnected state, in which case\n\t * it retains its disconnected state and its existing connections.\n\t */\n\tprivate _abort(type: PeerErrorType, message: string | Error): void {\n\t\tlogger.error(\"Aborting!\");\n\n\t\tthis.emitError(type, message);\n\n\t\tif (!this._lastServerId) {\n\t\t\tthis.destroy();\n\t\t} else {\n\t\t\tthis.disconnect();\n\t\t}\n\t}\n\n\t/**\n\t * Destroys the Peer: closes all active connections as well as the connection\n\t * to the server.\n\t *\n\t * :::caution\n\t * This cannot be undone; the respective peer object will no longer be able\n\t * to create or receive any connections, its ID will be forfeited on the server,\n\t * and all of its data and media connections will be closed.\n\t * :::\n\t */\n\tdestroy(): void {\n\t\tif (this.destroyed) {\n\t\t\treturn;\n\t\t}\n\n\t\tlogger.log(`Destroy peer with ID:${this.id}`);\n\n\t\tthis.disconnect();\n\t\tthis._cleanup();\n\n\t\tthis._destroyed = true;\n\n\t\tthis.emit(\"close\");\n\t}\n\n\t/** Disconnects every connection on this peer. */\n\tprivate _cleanup(): void {\n\t\tfor (const peerId of this._connections.keys()) {\n\t\t\tthis._cleanupPeer(peerId);\n\t\t\tthis._connections.delete(peerId);\n\t\t}\n\n\t\tthis.socket.removeAllListeners();\n\t}\n\n\t/** Closes all connections to this peer. */\n\tprivate _cleanupPeer(peerId: string): void {\n\t\tconst connections = this._connections.get(peerId);\n\n\t\tif (!connections) return;\n\n\t\tfor (const connection of connections) {\n\t\t\tconnection.close();\n\t\t}\n\t}\n\n\t/**\n\t * Disconnects the Peer's connection to the PeerServer. Does not close any\n\t * active connections.\n\t * Warning: The peer can no longer create or accept connections after being\n\t * disconnected. It also cannot reconnect to the server.\n\t */\n\tdisconnect(): void {\n\t\tif (this.disconnected) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst currentId = this.id;\n\n\t\tlogger.log(`Disconnect peer with ID:${currentId}`);\n\n\t\tthis._disconnected = true;\n\t\tthis._open = false;\n\n\t\tthis.socket.close();\n\n\t\tthis._lastServerId = currentId;\n\t\tthis._id = null;\n\n\t\tthis.emit(\"disconnected\", currentId);\n\t}\n\n\t/** Attempts to reconnect with the same ID.\n\t *\n\t * Only {@apilink Peer.disconnect | disconnected peers} can be reconnected.\n\t * Destroyed peers cannot be reconnected.\n\t * If the connection fails (as an example, if the peer's old ID is now taken),\n\t * the peer's existing connections will not close, but any associated errors events will fire.\n\t */\n\treconnect(): void {\n\t\tif (this.disconnected && !this.destroyed) {\n\t\t\tlogger.log(\n\t\t\t\t`Attempting reconnection to server with ID ${this._lastServerId}`,\n\t\t\t);\n\t\t\tthis._disconnected = false;\n\t\t\tthis._initialize(this._lastServerId!);\n\t\t} else if (this.destroyed) {\n\t\t\tthrow new Error(\n\t\t\t\t\"This peer cannot reconnect to the server. It has already been destroyed.\",\n\t\t\t);\n\t\t} else if (!this.disconnected && !this.open) {\n\t\t\t// Do nothing. We're still connecting the first time.\n\t\t\tlogger.error(\n\t\t\t\t\"In a hurry? We're still trying to make the initial connection!\",\n\t\t\t);\n\t\t} else {\n\t\t\tthrow new Error(\n\t\t\t\t`Peer ${this.id} cannot reconnect because it is not disconnected from the server!`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Get a list of available peer IDs. If you're running your own server, you'll\n\t * want to set allow_discovery: true in the PeerServer options. If you're using\n\t * the cloud server, email team@peerjs.com to get the functionality enabled for\n\t * your key.\n\t */\n\tlistAllPeers(cb = (_: any[]) => {}): void {\n\t\tthis._api\n\t\t\t.listAllPeers()\n\t\t\t.then((peers) => cb(peers))\n\t\t\t.catch((error) => this._abort(PeerErrorType.ServerError, error));\n\t}\n}\n", "const LOG_PREFIX = \"PeerJS: \";\n\n/*\nPrints log messages depending on the debug level passed in. Defaults to 0.\n0 Prints no logs.\n1 Prints only errors.\n2 Prints errors and warnings.\n3 Prints all logs.\n*/\nexport enum LogLevel {\n\t/**\n\t * Prints no logs.\n\t */\n\tDisabled,\n\t/**\n\t * Prints only errors.\n\t */\n\tErrors,\n\t/**\n\t * Prints errors and warnings.\n\t */\n\tWarnings,\n\t/**\n\t * Prints all logs.\n\t */\n\tAll,\n}\n\nclass Logger {\n\tprivate _logLevel = LogLevel.Disabled;\n\n\tget logLevel(): LogLevel {\n\t\treturn this._logLevel;\n\t}\n\n\tset logLevel(logLevel: LogLevel) {\n\t\tthis._logLevel = logLevel;\n\t}\n\n\tlog(...args: any[]) {\n\t\tif (this._logLevel >= LogLevel.All) {\n\t\t\tthis._print(LogLevel.All, ...args);\n\t\t}\n\t}\n\n\twarn(...args: any[]) {\n\t\tif (this._logLevel >= LogLevel.Warnings) {\n\t\t\tthis._print(LogLevel.Warnings, ...args);\n\t\t}\n\t}\n\n\terror(...args: any[]) {\n\t\tif (this._logLevel >= LogLevel.Errors) {\n\t\t\tthis._print(LogLevel.Errors, ...args);\n\t\t}\n\t}\n\n\tsetLogFunction(fn: (logLevel: LogLevel, ..._: any[]) => void): void {\n\t\tthis._print = fn;\n\t}\n\n\tprivate _print(logLevel: LogLevel, ...rest: any[]): void {\n\t\tconst copy = [LOG_PREFIX, ...rest];\n\n\t\tfor (const i in copy) {\n\t\t\tif (copy[i] instanceof Error) {\n\t\t\t\tcopy[i] = \"(\" + copy[i].name + \") \" + copy[i].message;\n\t\t\t}\n\t\t}\n\n\t\tif (logLevel >= LogLevel.All) {\n\t\t\tconsole.log(...copy);\n\t\t} else if (logLevel >= LogLevel.Warnings) {\n\t\t\tconsole.warn(\"WARNING\", ...copy);\n\t\t} else if (logLevel >= LogLevel.Errors) {\n\t\t\tconsole.error(\"ERROR\", ...copy);\n\t\t}\n\t}\n}\n\nexport default new Logger();\n", "import { EventEmitter } from \"eventemitter3\";\nimport logger from \"./logger\";\nimport { ServerMessageType, SocketEventType } from \"./enums\";\nimport { version } from \"./version\";\n\n/**\n * An abstraction on top of WebSockets to provide fastest\n * possible connection for peers.\n */\nexport class Socket extends EventEmitter {\n\tprivate _disconnected: boolean = true;\n\tprivate _id?: string;\n\tprivate _messagesQueue: Array<object> = [];\n\tprivate _socket?: WebSocket;\n\tprivate _wsPingTimer?: any;\n\tprivate readonly _baseUrl: string;\n\n\tconstructor(\n\t\tsecure: any,\n\t\thost: string,\n\t\tport: number,\n\t\tpath: string,\n\t\tkey: string,\n\t\tprivate readonly pingInterval: number = 5000,\n\t) {\n\t\tsuper();\n\n\t\tconst wsProtocol = secure ? \"wss://\" : \"ws://\";\n\n\t\tthis._baseUrl = wsProtocol + host + \":\" + port + path + \"peerjs?key=\" + key;\n\t}\n\n\tstart(id: string, token: string): void {\n\t\tthis._id = id;\n\n\t\tconst wsUrl = `${this._baseUrl}&id=${id}&token=${token}`;\n\n\t\tif (!!this._socket || !this._disconnected) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._socket = new WebSocket(wsUrl + \"&version=\" + version);\n\t\tthis._disconnected = false;\n\n\t\tthis._socket.onmessage = (event) => {\n\t\t\tlet data;\n\n\t\t\ttry {\n\t\t\t\tdata = JSON.parse(event.data);\n\t\t\t\tlogger.log(\"Server message received:\", data);\n\t\t\t} catch (e) {\n\t\t\t\tlogger.log(\"Invalid server message\", event.data);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.emit(SocketEventType.Message, data);\n\t\t};\n\n\t\tthis._socket.onclose = (event) => {\n\t\t\tif (this._disconnected) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogger.log(\"Socket closed.\", event);\n\n\t\t\tthis._cleanup();\n\t\t\tthis._disconnected = true;\n\n\t\t\tthis.emit(SocketEventType.Disconnected);\n\t\t};\n\n\t\t// Take care of the queue of connections if necessary and make sure Peer knows\n\t\t// socket is open.\n\t\tthis._socket.onopen = () => {\n\t\t\tif (this._disconnected) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._sendQueuedMessages();\n\n\t\t\tlogger.log(\"Socket open\");\n\n\t\t\tthis._scheduleHeartbeat();\n\t\t};\n\t}\n\n\tprivate _scheduleHeartbeat(): void {\n\t\tthis._wsPingTimer = setTimeout(() => {\n\t\t\tthis._sendHeartbeat();\n\t\t}, this.pingInterval);\n\t}\n\n\tprivate _sendHeartbeat(): void {\n\t\tif (!this._wsOpen()) {\n\t\t\tlogger.log(`Cannot send heartbeat, because socket closed`);\n\t\t\treturn;\n\t\t}\n\n\t\tconst message = JSON.stringify({ type: ServerMessageType.Heartbeat });\n\n\t\tthis._socket!.send(message);\n\n\t\tthis._scheduleHeartbeat();\n\t}\n\n\t/** Is the websocket currently open? */\n\tprivate _wsOpen(): boolean {\n\t\treturn !!this._socket && this._socket.readyState === 1;\n\t}\n\n\t/** Send queued messages. */\n\tprivate _sendQueuedMessages(): void {\n\t\t//Create copy of queue and clear it,\n\t\t//because send method push the message back to queue if smth will go wrong\n\t\tconst copiedQueue = [...this._messagesQueue];\n\t\tthis._messagesQueue = [];\n\n\t\tfor (const message of copiedQueue) {\n\t\t\tthis.send(message);\n\t\t}\n\t}\n\n\t/** Exposed send for DC & Peer. */\n\tsend(data: any): void {\n\t\tif (this._disconnected) {\n\t\t\treturn;\n\t\t}\n\n\t\t// If we didn't get an ID yet, we can't yet send anything so we should queue\n\t\t// up these messages.\n\t\tif (!this._id) {\n\t\t\tthis._messagesQueue.push(data);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!data.type) {\n\t\t\tthis.emit(SocketEventType.Error, \"Invalid message\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this._wsOpen()) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst message = JSON.stringify(data);\n\n\t\tthis._socket!.send(message);\n\t}\n\n\tclose(): void {\n\t\tif (this._disconnected) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._cleanup();\n\n\t\tthis._disconnected = true;\n\t}\n\n\tprivate _cleanup(): void {\n\t\tif (this._socket) {\n\t\t\tthis._socket.onopen =\n\t\t\t\tthis._socket.onmessage =\n\t\t\t\tthis._socket.onclose =\n\t\t\t\t\tnull;\n\t\t\tthis._socket.close();\n\t\t\tthis._socket = undefined;\n\t\t}\n\n\t\tclearTimeout(this._wsPingTimer!);\n\t}\n}\n", "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n", "export enum ConnectionType {\n\tData = \"data\",\n\tMedia = \"media\",\n}\n\nexport enum PeerErrorType {\n\t/**\n\t * The client's browser does not support some or all WebRTC features that you are trying to use.\n\t */\n\tBrowserIncompatible = \"browser-incompatible\",\n\t/**\n\t * You've already disconnected this peer from the server and can no longer make any new connections on it.\n\t */\n\tDisconnected = \"disconnected\",\n\t/**\n\t * The ID passed into the Peer constructor contains illegal characters.\n\t */\n\tInvalidID = \"invalid-id\",\n\t/**\n\t * The API key passed into the Peer constructor contains illegal characters or is not in the system (cloud server only).\n\t */\n\tInvalidKey = \"invalid-key\",\n\t/**\n\t * Lost or cannot establish a connection to the signalling server.\n\t */\n\tNetwork = \"network\",\n\t/**\n\t * The peer you're trying to connect to does not exist.\n\t */\n\tPeerUnavailable = \"peer-unavailable\",\n\t/**\n\t * PeerJS is being used securely, but the cloud server does not support SSL. Use a custom PeerServer.\n\t */\n\tSslUnavailable = \"ssl-unavailable\",\n\t/**\n\t * Unable to reach the server.\n\t */\n\tServerError = \"server-error\",\n\t/**\n\t * An error from the underlying socket.\n\t */\n\tSocketError = \"socket-error\",\n\t/**\n\t * The underlying socket closed unexpectedly.\n\t */\n\tSocketClosed = \"socket-closed\",\n\t/**\n\t * The ID passed into the Peer constructor is already taken.\n\t *\n\t * :::caution\n\t * This error is not fatal if your peer has open peer-to-peer connections.\n\t * This can happen if you attempt to {@apilink Peer.reconnect} a peer that has been disconnected from the server,\n\t * but its old ID has now been taken.\n\t * :::\n\t */\n\tUnavailableID = \"unavailable-id\",\n\t/**\n\t * Native WebRTC errors.\n\t */\n\tWebRTC = \"webrtc\",\n}\n\nexport enum BaseConnectionErrorType {\n\tNegotiationFailed = \"negotiation-failed\",\n\tConnectionClosed = \"connection-closed\",\n}\n\nexport enum DataConnectionErrorType {\n\tNotOpenYet = \"not-open-yet\",\n\tMessageToBig = \"message-too-big\",\n}\n\nexport enum SerializationType {\n\tBinary = \"binary\",\n\tBinaryUTF8 = \"binary-utf8\",\n\tJSON = \"json\",\n\tNone = \"raw\",\n}\n\nexport enum SocketEventType {\n\tMessage = \"message\",\n\tDisconnected = \"disconnected\",\n\tError = \"error\",\n\tClose = \"close\",\n}\n\nexport enum ServerMessageType {\n\tHeartbeat = \"HEARTBEAT\",\n\tCandidate = \"CANDIDATE\",\n\tOffer = \"OFFER\",\n\tAnswer = \"ANSWER\",\n\tOpen = \"OPEN\", // The connection to the server is open.\n\tError = \"ERROR\", // Server error.\n\tIdTaken = \"ID-TAKEN\", // The selected ID is taken.\n\tInvalidKey = \"INVALID-KEY\", // The given API key cannot be found.\n\tLeave = \"LEAVE\", // Another peer has closed its connection to this peer.\n\tExpire = \"EXPIRE\", // The offer sent to a peer has expired without response.\n}\n", "export const version = \"1.5.5\";\n", "import { util } from \"./util\";\nimport logger from \"./logger\";\nimport { Negotiator } from \"./negotiator\";\nimport { ConnectionType, ServerMessageType } from \"./enums\";\nimport type { Peer } from \"./peer\";\nimport { BaseConnection, type BaseConnectionEvents } from \"./baseconnection\";\nimport type { ServerMessage } from \"./servermessage\";\nimport type { AnswerOption } from \"./optionInterfaces\";\n\nexport interface MediaConnectionEvents extends BaseConnectionEvents<never> {\n\t/**\n\t * Emitted when a connection to the PeerServer is established.\n\t *\n\t * ```ts\n\t * mediaConnection.on('stream', (stream) => { ... });\n\t * ```\n\t */\n\tstream: (stream: MediaStream) => void;\n\t/**\n\t * Emitted when the auxiliary data channel is established.\n\t * After this event, hanging up will close the connection cleanly on the remote peer.\n\t * @beta\n\t */\n\twillCloseOnRemote: () => void;\n}\n\n/**\n * Wraps WebRTC's media streams.\n * To get one, use {@apilink Peer.call} or listen for the {@apilink PeerEvents | `call`} event.\n */\nexport class MediaConnection extends BaseConnection<MediaConnectionEvents> {\n\tprivate static readonly ID_PREFIX = \"mc_\";\n\treadonly label: string;\n\n\tprivate _negotiator: Negotiator<MediaConnectionEvents, this>;\n\tprivate _localStream: MediaStream;\n\tprivate _remoteStream: MediaStream;\n\n\t/**\n\t * For media connections, this is always 'media'.\n\t */\n\tget type() {\n\t\treturn ConnectionType.Media;\n\t}\n\n\tget localStream(): MediaStream {\n\t\treturn this._localStream;\n\t}\n\n\tget remoteStream(): MediaStream {\n\t\treturn this._remoteStream;\n\t}\n\n\tconstructor(peerId: string, provider: Peer, options: any) {\n\t\tsuper(peerId, provider, options);\n\n\t\tthis._localStream = this.options._stream;\n\t\tthis.connectionId =\n\t\t\tthis.options.connectionId ||\n\t\t\tMediaConnection.ID_PREFIX + util.randomToken();\n\n\t\tthis._negotiator = new Negotiator(this);\n\n\t\tif (this._localStream) {\n\t\t\tthis._negotiator.startConnection({\n\t\t\t\t_stream: this._localStream,\n\t\t\t\toriginator: true,\n\t\t\t});\n\t\t}\n\t}\n\n\t/** Called by the Negotiator when the DataChannel is ready. */\n\toverride _initializeDataChannel(dc: RTCDataChannel): void {\n\t\tthis.dataChannel = dc;\n\n\t\tthis.dataChannel.onopen = () => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc connection success`);\n\t\t\tthis.emit(\"willCloseOnRemote\");\n\t\t};\n\n\t\tthis.dataChannel.onclose = () => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc closed for:`, this.peer);\n\t\t\tthis.close();\n\t\t};\n\t}\n\taddStream(remoteStream) {\n\t\tlogger.log(\"Receiving stream\", remoteStream);\n\n\t\tthis._remoteStream = remoteStream;\n\t\tsuper.emit(\"stream\", remoteStream); // Should we call this `open`?\n\t}\n\n\t/**\n\t * @internal\n\t */\n\thandleMessage(message: ServerMessage): void {\n\t\tconst type = message.type;\n\t\tconst payload = message.payload;\n\n\t\tswitch (message.type) {\n\t\t\tcase ServerMessageType.Answer:\n\t\t\t\t// Forward to negotiator\n\t\t\t\tvoid this._negotiator.handleSDP(type, payload.sdp);\n\t\t\t\tthis._open = true;\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Candidate:\n\t\t\t\tvoid this._negotiator.handleCandidate(payload.candidate);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(`Unrecognized message type:${type} from peer:${this.peer}`);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/**\n * When receiving a {@apilink PeerEvents | `call`} event on a peer, you can call\n * `answer` on the media connection provided by the callback to accept the call\n * and optionally send your own media stream.\n\n *\n * @param stream A WebRTC media stream.\n * @param options\n * @returns\n */\n\tanswer(stream?: MediaStream, options: AnswerOption = {}): void {\n\t\tif (this._localStream) {\n\t\t\tlogger.warn(\n\t\t\t\t\"Local stream already exists on this MediaConnection. Are you answering a call twice?\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis._localStream = stream;\n\n\t\tif (options && options.sdpTransform) {\n\t\t\tthis.options.sdpTransform = options.sdpTransform;\n\t\t}\n\n\t\tthis._negotiator.startConnection({\n\t\t\t...this.options._payload,\n\t\t\t_stream: stream,\n\t\t});\n\t\t// Retrieve lost messages stored because PeerConnection not set up.\n\t\tconst messages = this.provider._getMessages(this.connectionId);\n\n\t\tfor (const message of messages) {\n\t\t\tthis.handleMessage(message);\n\t\t}\n\n\t\tthis._open = true;\n\t}\n\n\t/**\n\t * Exposed functionality for users.\n\t */\n\n\t/**\n\t * Closes the media connection.\n\t */\n\tclose(): void {\n\t\tif (this._negotiator) {\n\t\t\tthis._negotiator.cleanup();\n\t\t\tthis._negotiator = null;\n\t\t}\n\n\t\tthis._localStream = null;\n\t\tthis._remoteStream = null;\n\n\t\tif (this.provider) {\n\t\t\tthis.provider._removeConnection(this);\n\n\t\t\tthis.provider = null;\n\t\t}\n\n\t\tif (this.options && this.options._stream) {\n\t\t\tthis.options._stream = null;\n\t\t}\n\n\t\tif (!this.open) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._open = false;\n\n\t\tsuper.emit(\"close\");\n\t}\n}\n", "import logger from \"./logger\";\nimport type { MediaConnection } from \"./mediaconnection\";\nimport type { DataConnection } from \"./dataconnection/DataConnection\";\nimport {\n\tBaseConnectionErrorType,\n\tConnectionType,\n\tPeerErrorType,\n\tServerMessageType,\n} from \"./enums\";\nimport type { BaseConnection, BaseConnectionEvents } from \"./baseconnection\";\nimport type { ValidEventTypes } from \"eventemitter3\";\n\n/**\n * Manages all negotiations between Peers.\n */\nexport class Negotiator<\n\tEvents extends ValidEventTypes,\n\tConnectionType extends BaseConnection<Events | BaseConnectionEvents>,\n> {\n\tconstructor(readonly connection: ConnectionType) {}\n\n\t/** Returns a PeerConnection object set up correctly (for data, media). */\n\tstartConnection(options: any) {\n\t\tconst peerConnection = this._startPeerConnection();\n\n\t\t// Set the connection's PC.\n\t\tthis.connection.peerConnection = peerConnection;\n\n\t\tif (this.connection.type === ConnectionType.Media && options._stream) {\n\t\t\tthis._addTracksToConnection(options._stream, peerConnection);\n\t\t}\n\n\t\t// What do we need to do now?\n\t\tif (options.originator) {\n\t\t\tconst dataConnection = this.connection;\n\n\t\t\tconst config: RTCDataChannelInit = { ordered: !!options.reliable };\n\n\t\t\tconst dataChannel = peerConnection.createDataChannel(\n\t\t\t\tdataConnection.label,\n\t\t\t\tconfig,\n\t\t\t);\n\t\t\tdataConnection._initializeDataChannel(dataChannel);\n\n\t\t\tvoid this._makeOffer();\n\t\t} else {\n\t\t\tvoid this.handleSDP(\"OFFER\", options.sdp);\n\t\t}\n\t}\n\n\t/** Start a PC. */\n\tprivate _startPeerConnection(): RTCPeerConnection {\n\t\tlogger.log(\"Creating RTCPeerConnection.\");\n\n\t\tconst peerConnection = new RTCPeerConnection(\n\t\t\tthis.connection.provider.options.config,\n\t\t);\n\n\t\tthis._setupListeners(peerConnection);\n\n\t\treturn peerConnection;\n\t}\n\n\t/** Set up various WebRTC listeners. */\n\tprivate _setupListeners(peerConnection: RTCPeerConnection) {\n\t\tconst peerId = this.connection.peer;\n\t\tconst connectionId = this.connection.connectionId;\n\t\tconst connectionType = this.connection.type;\n\t\tconst provider = this.connection.provider;\n\n\t\t// ICE CANDIDATES.\n\t\tlogger.log(\"Listening for ICE candidates.\");\n\n\t\tpeerConnection.onicecandidate = (evt) => {\n\t\t\tif (!evt.candidate || !evt.candidate.candidate) return;\n\n\t\t\tlogger.log(`Received ICE candidates for ${peerId}:`, evt.candidate);\n\n\t\t\tprovider.socket.send({\n\t\t\t\ttype: ServerMessageType.Candidate,\n\t\t\t\tpayload: {\n\t\t\t\t\tcandidate: evt.candidate,\n\t\t\t\t\ttype: connectionType,\n\t\t\t\t\tconnectionId: connectionId,\n\t\t\t\t},\n\t\t\t\tdst: peerId,\n\t\t\t});\n\t\t};\n\n\t\tpeerConnection.oniceconnectionstatechange = () => {\n\t\t\tswitch (peerConnection.iceConnectionState) {\n\t\t\t\tcase \"failed\":\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t\"iceConnectionState is failed, closing connections to \" + peerId,\n\t\t\t\t\t);\n\t\t\t\t\tthis.connection.emitError(\n\t\t\t\t\t\tBaseConnectionErrorType.NegotiationFailed,\n\t\t\t\t\t\t\"Negotiation of connection to \" + peerId + \" failed.\",\n\t\t\t\t\t);\n\t\t\t\t\tthis.connection.close();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"closed\":\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t\"iceConnectionState is closed, closing connections to \" + peerId,\n\t\t\t\t\t);\n\t\t\t\t\tthis.connection.emitError(\n\t\t\t\t\t\tBaseConnectionErrorType.ConnectionClosed,\n\t\t\t\t\t\t\"Connection to \" + peerId + \" closed.\",\n\t\t\t\t\t);\n\t\t\t\t\tthis.connection.close();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"disconnected\":\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t\"iceConnectionState changed to disconnected on the connection with \" +\n\t\t\t\t\t\t\tpeerId,\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"completed\":\n\t\t\t\t\tpeerConnection.onicecandidate = () => {};\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tthis.connection.emit(\n\t\t\t\t\"iceStateChanged\",\n\t\t\t\tpeerConnection.iceConnectionState,\n\t\t\t);\n\t\t};\n\n\t\t// DATACONNECTION.\n\t\tlogger.log(\"Listening for data channel\");\n\t\t// Fired between offer and answer, so options should already be saved\n\t\t// in the options hash.\n\t\tpeerConnection.ondatachannel = (evt) => {\n\t\t\tlogger.log(\"Received data channel\");\n\n\t\t\tconst dataChannel = evt.channel;\n\t\t\tconst connection = <DataConnection>(\n\t\t\t\tprovider.getConnection(peerId, connectionId)\n\t\t\t);\n\n\t\t\tconnection._initializeDataChannel(dataChannel);\n\t\t};\n\n\t\t// MEDIACONNECTION.\n\t\tlogger.log(\"Listening for remote stream\");\n\n\t\tpeerConnection.ontrack = (evt) => {\n\t\t\tlogger.log(\"Received remote stream\");\n\n\t\t\tconst stream = evt.streams[0];\n\t\t\tconst connection = provider.getConnection(peerId, connectionId);\n\n\t\t\tif (connection.type === ConnectionType.Media) {\n\t\t\t\tconst mediaConnection = <MediaConnection>connection;\n\n\t\t\t\tthis._addStreamToMediaConnection(stream, mediaConnection);\n\t\t\t}\n\t\t};\n\t}\n\n\tcleanup(): void {\n\t\tlogger.log(\"Cleaning up PeerConnection to \" + this.connection.peer);\n\n\t\tconst peerConnection = this.connection.peerConnection;\n\n\t\tif (!peerConnection) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.connection.peerConnection = null;\n\n\t\t//unsubscribe from all PeerConnection's events\n\t\tpeerConnection.onicecandidate =\n\t\t\tpeerConnection.oniceconnectionstatechange =\n\t\t\tpeerConnection.ondatachannel =\n\t\t\tpeerConnection.ontrack =\n\t\t\t\t() => {};\n\n\t\tconst peerConnectionNotClosed = peerConnection.signalingState !== \"closed\";\n\t\tlet dataChannelNotClosed = false;\n\n\t\tconst dataChannel = this.connection.dataChannel;\n\n\t\tif (dataChannel) {\n\t\t\tdataChannelNotClosed =\n\t\t\t\t!!dataChannel.readyState && dataChannel.readyState !== \"closed\";\n\t\t}\n\n\t\tif (peerConnectionNotClosed || dataChannelNotClosed) {\n\t\t\tpeerConnection.close();\n\t\t}\n\t}\n\n\tprivate async _makeOffer(): Promise<void> {\n\t\tconst peerConnection = this.connection.peerConnection;\n\t\tconst provider = this.connection.provider;\n\n\t\ttry {\n\t\t\tconst offer = await peerConnection.createOffer(\n\t\t\t\tthis.connection.options.constraints,\n\t\t\t);\n\n\t\t\tlogger.log(\"Created offer.\");\n\n\t\t\tif (\n\t\t\t\tthis.connection.options.sdpTransform &&\n\t\t\t\ttypeof this.connection.options.sdpTransform === \"function\"\n\t\t\t) {\n\t\t\t\toffer.sdp =\n\t\t\t\t\tthis.connection.options.sdpTransform(offer.sdp) || offer.sdp;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait peerConnection.setLocalDescription(offer);\n\n\t\t\t\tlogger.log(\n\t\t\t\t\t\"Set localDescription:\",\n\t\t\t\t\toffer,\n\t\t\t\t\t`for:${this.connection.peer}`,\n\t\t\t\t);\n\n\t\t\t\tlet payload: any = {\n\t\t\t\t\tsdp: offer,\n\t\t\t\t\ttype: this.connection.type,\n\t\t\t\t\tconnectionId: this.connection.connectionId,\n\t\t\t\t\tmetadata: this.connection.metadata,\n\t\t\t\t};\n\n\t\t\t\tif (this.connection.type === ConnectionType.Data) {\n\t\t\t\t\tconst dataConnection = <DataConnection>(<unknown>this.connection);\n\n\t\t\t\t\tpayload = {\n\t\t\t\t\t\t...payload,\n\t\t\t\t\t\tlabel: dataConnection.label,\n\t\t\t\t\t\treliable: dataConnection.reliable,\n\t\t\t\t\t\tserialization: dataConnection.serialization,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tprovider.socket.send({\n\t\t\t\t\ttype: ServerMessageType.Offer,\n\t\t\t\t\tpayload,\n\t\t\t\t\tdst: this.connection.peer,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\t// TODO: investigate why _makeOffer is being called from the answer\n\t\t\t\tif (\n\t\t\t\t\terr !=\n\t\t\t\t\t\"OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer\"\n\t\t\t\t) {\n\t\t\t\t\tprovider.emitError(PeerErrorType.WebRTC, err);\n\t\t\t\t\tlogger.log(\"Failed to setLocalDescription, \", err);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err_1) {\n\t\t\tprovider.emitError(PeerErrorType.WebRTC, err_1);\n\t\t\tlogger.log(\"Failed to createOffer, \", err_1);\n\t\t}\n\t}\n\n\tprivate async _makeAnswer(): Promise<void> {\n\t\tconst peerConnection = this.connection.peerConnection;\n\t\tconst provider = this.connection.provider;\n\n\t\ttry {\n\t\t\tconst answer = await peerConnection.createAnswer();\n\t\t\tlogger.log(\"Created answer.\");\n\n\t\t\tif (\n\t\t\t\tthis.connection.options.sdpTransform &&\n\t\t\t\ttypeof this.connection.options.sdpTransform === \"function\"\n\t\t\t) {\n\t\t\t\tanswer.sdp =\n\t\t\t\t\tthis.connection.options.sdpTransform(answer.sdp) || answer.sdp;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait peerConnection.setLocalDescription(answer);\n\n\t\t\t\tlogger.log(\n\t\t\t\t\t`Set localDescription:`,\n\t\t\t\t\tanswer,\n\t\t\t\t\t`for:${this.connection.peer}`,\n\t\t\t\t);\n\n\t\t\t\tprovider.socket.send({\n\t\t\t\t\ttype: ServerMessageType.Answer,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tsdp: answer,\n\t\t\t\t\t\ttype: this.connection.type,\n\t\t\t\t\t\tconnectionId: this.connection.connectionId,\n\t\t\t\t\t},\n\t\t\t\t\tdst: this.connection.peer,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tprovider.emitError(PeerErrorType.WebRTC, err);\n\t\t\t\tlogger.log(\"Failed to setLocalDescription, \", err);\n\t\t\t}\n\t\t} catch (err_1) {\n\t\t\tprovider.emitError(PeerErrorType.WebRTC, err_1);\n\t\t\tlogger.log(\"Failed to create answer, \", err_1);\n\t\t}\n\t}\n\n\t/** Handle an SDP. */\n\tasync handleSDP(type: string, sdp: any): Promise<void> {\n\t\tsdp = new RTCSessionDescription(sdp);\n\t\tconst peerConnection = this.connection.peerConnection;\n\t\tconst provider = this.connection.provider;\n\n\t\tlogger.log(\"Setting remote description\", sdp);\n\n\t\tconst self = this;\n\n\t\ttry {\n\t\t\tawait peerConnection.setRemoteDescription(sdp);\n\t\t\tlogger.log(`Set remoteDescription:${type} for:${this.connection.peer}`);\n\t\t\tif (type === \"OFFER\") {\n\t\t\t\tawait self._makeAnswer();\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tprovider.emitError(PeerErrorType.WebRTC, err);\n\t\t\tlogger.log(\"Failed to setRemoteDescription, \", err);\n\t\t}\n\t}\n\n\t/** Handle a candidate. */\n\tasync handleCandidate(ice: RTCIceCandidate) {\n\t\tlogger.log(`handleCandidate:`, ice);\n\n\t\ttry {\n\t\t\tawait this.connection.peerConnection.addIceCandidate(ice);\n\t\t\tlogger.log(`Added ICE candidate for:${this.connection.peer}`);\n\t\t} catch (err) {\n\t\t\tthis.connection.provider.emitError(PeerErrorType.WebRTC, err);\n\t\t\tlogger.log(\"Failed to handleCandidate, \", err);\n\t\t}\n\t}\n\n\tprivate _addTracksToConnection(\n\t\tstream: MediaStream,\n\t\tpeerConnection: RTCPeerConnection,\n\t): void {\n\t\tlogger.log(`add tracks from stream ${stream.id} to peer connection`);\n\n\t\tif (!peerConnection.addTrack) {\n\t\t\treturn logger.error(\n\t\t\t\t`Your browser does't support RTCPeerConnection#addTrack. Ignored.`,\n\t\t\t);\n\t\t}\n\n\t\tstream.getTracks().forEach((track) => {\n\t\t\tpeerConnection.addTrack(track, stream);\n\t\t});\n\t}\n\n\tprivate _addStreamToMediaConnection(\n\t\tstream: MediaStream,\n\t\tmediaConnection: MediaConnection,\n\t): void {\n\t\tlogger.log(\n\t\t\t`add stream ${stream.id} to media connection ${mediaConnection.connectionId}`,\n\t\t);\n\n\t\tmediaConnection.addStream(stream);\n\t}\n}\n", "import type { Peer } from \"./peer\";\nimport type { ServerMessage } from \"./servermessage\";\nimport type { ConnectionType } from \"./enums\";\nimport { BaseConnectionErrorType } from \"./enums\";\nimport {\n\tEventEmitterWithError,\n\ttype EventsWithError,\n\tPeerError,\n} from \"./peerError\";\nimport type { ValidEventTypes } from \"eventemitter3\";\n\nexport interface BaseConnectionEvents<\n\tErrorType extends string = BaseConnectionErrorType,\n> extends EventsWithError<ErrorType> {\n\t/**\n\t * Emitted when either you or the remote peer closes the connection.\n\t *\n\t * ```ts\n\t * connection.on('close', () => { ... });\n\t * ```\n\t */\n\tclose: () => void;\n\t/**\n\t * ```ts\n\t * connection.on('error', (error) => { ... });\n\t * ```\n\t */\n\terror: (error: PeerError<`${ErrorType}`>) => void;\n\ticeStateChanged: (state: RTCIceConnectionState) => void;\n}\n\nexport abstract class BaseConnection<\n\tSubClassEvents extends ValidEventTypes,\n\tErrorType extends string = never,\n> extends EventEmitterWithError<\n\tErrorType | BaseConnectionErrorType,\n\tSubClassEvents & BaseConnectionEvents<BaseConnectionErrorType | ErrorType>\n> {\n\tprotected _open = false;\n\n\t/**\n\t * Any type of metadata associated with the connection,\n\t * passed in by whoever initiated the connection.\n\t */\n\treadonly metadata: any;\n\tconnectionId: string;\n\n\tpeerConnection: RTCPeerConnection;\n\tdataChannel: RTCDataChannel;\n\n\tabstract get type(): ConnectionType;\n\n\t/**\n\t * The optional label passed in or assigned by PeerJS when the connection was initiated.\n\t */\n\tlabel: string;\n\n\t/**\n\t * Whether the media connection is active (e.g. your call has been answered).\n\t * You can check this if you want to set a maximum wait time for a one-sided call.\n\t */\n\tget open() {\n\t\treturn this._open;\n\t}\n\n\tprotected constructor(\n\t\t/**\n\t\t * The ID of the peer on the other end of this connection.\n\t\t */\n\t\treadonly peer: string,\n\t\tpublic provider: Peer,\n\t\treadonly options: any,\n\t) {\n\t\tsuper();\n\n\t\tthis.metadata = options.metadata;\n\t}\n\n\tabstract close(): void;\n\n\t/**\n\t * @internal\n\t */\n\tabstract handleMessage(message: ServerMessage): void;\n\n\t/**\n\t * Called by the Negotiator when the DataChannel is ready.\n\t * @internal\n\t * */\n\tabstract _initializeDataChannel(dc: RTCDataChannel): void;\n}\n", "import { EventEmitter } from \"eventemitter3\";\nimport logger from \"./logger\";\n\nexport interface EventsWithError<ErrorType extends string> {\n\terror: (error: PeerError<`${ErrorType}`>) => void;\n}\n\nexport class EventEmitterWithError<\n\tErrorType extends string,\n\tEvents extends EventsWithError<ErrorType>,\n> extends EventEmitter<Events, never> {\n\t/**\n\t * Emits a typed error message.\n\t *\n\t * @internal\n\t */\n\temitError(type: ErrorType, err: string | Error): void {\n\t\tlogger.error(\"Error:\", err);\n\n\t\t// @ts-ignore\n\t\tthis.emit(\"error\", new PeerError<`${ErrorType}`>(`${type}`, err));\n\t}\n}\n/**\n * A PeerError is emitted whenever an error occurs.\n * It always has a `.type`, which can be used to identify the error.\n */\nexport class PeerError<T extends string> extends Error {\n\t/**\n\t * @internal\n\t */\n\tconstructor(type: T, err: Error | string) {\n\t\tif (typeof err === \"string\") {\n\t\t\tsuper(err);\n\t\t} else {\n\t\t\tsuper();\n\t\t\tObject.assign(this, err);\n\t\t}\n\n\t\tthis.type = type;\n\t}\n\n\tpublic type: T;\n}\n", "import { util } from \"./util\";\nimport logger from \"./logger\";\nimport type { PeerJSOption } from \"./optionInterfaces\";\nimport { version } from \"./version\";\n\nexport class API {\n\tconstructor(private readonly _options: PeerJSOption) {}\n\n\tprivate _buildRequest(method: string): Promise<Response> {\n\t\tconst protocol = this._options.secure ? \"https\" : \"http\";\n\t\tconst { host, port, path, key } = this._options;\n\t\tconst url = new URL(`${protocol}://${host}:${port}${path}${key}/${method}`);\n\t\t// TODO: Why timestamp, why random?\n\t\turl.searchParams.set(\"ts\", `${Date.now()}${Math.random()}`);\n\t\turl.searchParams.set(\"version\", version);\n\t\treturn fetch(url.href, {\n\t\t\treferrerPolicy: this._options.referrerPolicy,\n\t\t});\n\t}\n\n\t/** Get a unique ID from the server via XHR and initialize with it. */\n\tasync retrieveId(): Promise<string> {\n\t\ttry {\n\t\t\tconst response = await this._buildRequest(\"id\");\n\n\t\t\tif (response.status !== 200) {\n\t\t\t\tthrow new Error(`Error. Status:${response.status}`);\n\t\t\t}\n\n\t\t\treturn response.text();\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error retrieving ID\", error);\n\n\t\t\tlet pathError = \"\";\n\n\t\t\tif (\n\t\t\t\tthis._options.path === \"/\" &&\n\t\t\t\tthis._options.host !== util.CLOUD_HOST\n\t\t\t) {\n\t\t\t\tpathError =\n\t\t\t\t\t\" If you passed in a `path` to your self-hosted PeerServer, \" +\n\t\t\t\t\t\"you'll also need to pass in that same path when creating a new \" +\n\t\t\t\t\t\"Peer.\";\n\t\t\t}\n\n\t\t\tthrow new Error(\"Could not get an ID from the server.\" + pathError);\n\t\t}\n\t}\n\n\t/** @deprecated */\n\tasync listAllPeers(): Promise<any[]> {\n\t\ttry {\n\t\t\tconst response = await this._buildRequest(\"peers\");\n\n\t\t\tif (response.status !== 200) {\n\t\t\t\tif (response.status === 401) {\n\t\t\t\t\tlet helpfulError = \"\";\n\n\t\t\t\t\tif (this._options.host === util.CLOUD_HOST) {\n\t\t\t\t\t\thelpfulError =\n\t\t\t\t\t\t\t\"It looks like you're using the cloud server. You can email \" +\n\t\t\t\t\t\t\t\"team@peerjs.com to enable peer listing for your API key.\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\thelpfulError =\n\t\t\t\t\t\t\t\"You need to enable `allow_discovery` on your self-hosted \" +\n\t\t\t\t\t\t\t\"PeerServer to use this feature.\";\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"It doesn't look like you have permission to list peers IDs. \" +\n\t\t\t\t\t\t\thelpfulError,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tthrow new Error(`Error. Status:${response.status}`);\n\t\t\t}\n\n\t\t\treturn response.json();\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error retrieving list peers\", error);\n\n\t\t\tthrow new Error(\"Could not get list peers from the server.\" + error);\n\t\t}\n\t}\n}\n", "import { BinaryPackChunker, concatArrayBuffers } from \"./binaryPackChunker\";\nimport logger from \"../../logger\";\nimport type { Peer } from \"../../peer\";\nimport { BufferedConnection } from \"./BufferedConnection\";\nimport { SerializationType } from \"../../enums\";\nimport { pack, type Packable, unpack } from \"peerjs-js-binarypack\";\n\nexport class BinaryPack extends BufferedConnection {\n\tprivate readonly chunker = new BinaryPackChunker();\n\treadonly serialization = SerializationType.Binary;\n\n\tprivate _chunkedData: {\n\t\t[id: number]: {\n\t\t\tdata: Uint8Array[];\n\t\t\tcount: number;\n\t\t\ttotal: number;\n\t\t};\n\t} = {};\n\n\tpublic override close(options?: { flush?: boolean }) {\n\t\tsuper.close(options);\n\t\tthis._chunkedData = {};\n\t}\n\n\tconstructor(peerId: string, provider: Peer, options: any) {\n\t\tsuper(peerId, provider, options);\n\t}\n\n\t// Handles a DataChannel message.\n\tprotected override _handleDataMessage({ data }: { data: Uint8Array }): void {\n\t\tconst deserializedData = unpack(data);\n\n\t\t// PeerJS specific message\n\t\tconst peerData = deserializedData[\"__peerData\"];\n\t\tif (peerData) {\n\t\t\tif (peerData.type === \"close\") {\n\t\t\t\tthis.close();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Chunked data -- piece things back together.\n\t\t\t// @ts-ignore\n\t\t\tthis._handleChunk(deserializedData);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.emit(\"data\", deserializedData);\n\t}\n\n\tprivate _handleChunk(data: {\n\t\t__peerData: number;\n\t\tn: number;\n\t\ttotal: number;\n\t\tdata: ArrayBuffer;\n\t}): void {\n\t\tconst id = data.__peerData;\n\t\tconst chunkInfo = this._chunkedData[id] || {\n\t\t\tdata: [],\n\t\t\tcount: 0,\n\t\t\ttotal: data.total,\n\t\t};\n\n\t\tchunkInfo.data[data.n] = new Uint8Array(data.data);\n\t\tchunkInfo.count++;\n\t\tthis._chunkedData[id] = chunkInfo;\n\n\t\tif (chunkInfo.total === chunkInfo.count) {\n\t\t\t// Clean up before making the recursive call to `_handleDataMessage`.\n\t\t\tdelete this._chunkedData[id];\n\n\t\t\t// We've received all the chunks--time to construct the complete data.\n\t\t\t// const data = new Blob(chunkInfo.data);\n\t\t\tconst data = concatArrayBuffers(chunkInfo.data);\n\t\t\tthis._handleDataMessage({ data });\n\t\t}\n\t}\n\n\tprotected override _send(data: Packable, chunked: boolean) {\n\t\tconst blob = pack(data);\n\t\tif (blob instanceof Promise) {\n\t\t\treturn this._send_blob(blob);\n\t\t}\n\n\t\tif (!chunked && blob.byteLength > this.chunker.chunkedMTU) {\n\t\t\tthis._sendChunks(blob);\n\t\t\treturn;\n\t\t}\n\n\t\tthis._bufferedSend(blob);\n\t}\n\tprivate async _send_blob(blobPromise: Promise<ArrayBufferLike>) {\n\t\tconst blob = await blobPromise;\n\t\tif (blob.byteLength > this.chunker.chunkedMTU) {\n\t\t\tthis._sendChunks(blob);\n\t\t\treturn;\n\t\t}\n\n\t\tthis._bufferedSend(blob);\n\t}\n\n\tprivate _sendChunks(blob: ArrayBuffer) {\n\t\tconst blobs = this.chunker.chunk(blob);\n\t\tlogger.log(`DC#${this.connectionId} Try to send ${blobs.length} chunks...`);\n\n\t\tfor (const blob of blobs) {\n\t\t\tthis.send(blob, true);\n\t\t}\n\t}\n}\n", "import logger from \"../../logger\";\nimport { DataConnection } from \"../DataConnection\";\n\nexport abstract class BufferedConnection extends DataConnection {\n\tprivate _buffer: any[] = [];\n\tprivate _bufferSize = 0;\n\tprivate _buffering = false;\n\n\tpublic get bufferSize(): number {\n\t\treturn this._bufferSize;\n\t}\n\n\tpublic override _initializeDataChannel(dc: RTCDataChannel) {\n\t\tsuper._initializeDataChannel(dc);\n\t\tthis.dataChannel.binaryType = \"arraybuffer\";\n\t\tthis.dataChannel.addEventListener(\"message\", (e) =>\n\t\t\tthis._handleDataMessage(e),\n\t\t);\n\t}\n\n\tprotected abstract _handleDataMessage(e: MessageEvent): void;\n\n\tprotected _bufferedSend(msg: ArrayBuffer): void {\n\t\tif (this._buffering || !this._trySend(msg)) {\n\t\t\tthis._buffer.push(msg);\n\t\t\tthis._bufferSize = this._buffer.length;\n\t\t}\n\t}\n\n\t// Returns true if the send succeeds.\n\tprivate _trySend(msg: ArrayBuffer): boolean {\n\t\tif (!this.open) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (this.dataChannel.bufferedAmount > DataConnection.MAX_BUFFERED_AMOUNT) {\n\t\t\tthis._buffering = true;\n\t\t\tsetTimeout(() => {\n\t\t\t\tthis._buffering = false;\n\t\t\t\tthis._tryBuffer();\n\t\t\t}, 50);\n\n\t\t\treturn false;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.dataChannel.send(msg);\n\t\t} catch (e) {\n\t\t\tlogger.error(`DC#:${this.connectionId} Error when sending:`, e);\n\t\t\tthis._buffering = true;\n\n\t\t\tthis.close();\n\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t// Try to send the first message in the buffer.\n\tprivate _tryBuffer(): void {\n\t\tif (!this.open) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._buffer.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst msg = this._buffer[0];\n\n\t\tif (this._trySend(msg)) {\n\t\t\tthis._buffer.shift();\n\t\t\tthis._bufferSize = this._buffer.length;\n\t\t\tthis._tryBuffer();\n\t\t}\n\t}\n\n\tpublic override close(options?: { flush?: boolean }) {\n\t\tif (options?.flush) {\n\t\t\tthis.send({\n\t\t\t\t__peerData: {\n\t\t\t\t\ttype: \"close\",\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tthis._buffer = [];\n\t\tthis._bufferSize = 0;\n\t\tsuper.close();\n\t}\n}\n", "import logger from \"../logger\";\nimport { Negotiator } from \"../negotiator\";\nimport {\n\tBaseConnectionErrorType,\n\tConnectionType,\n\tDataConnectionErrorType,\n\tServerMessageType,\n} from \"../enums\";\nimport type { Peer } from \"../peer\";\nimport { BaseConnection, type BaseConnectionEvents } from \"../baseconnection\";\nimport type { ServerMessage } from \"../servermessage\";\nimport type { EventsWithError } from \"../peerError\";\nimport { randomToken } from \"../utils/randomToken\";\n\nexport interface DataConnectionEvents\n\textends EventsWithError<DataConnectionErrorType | BaseConnectionErrorType>,\n\t\tBaseConnectionEvents<DataConnectionErrorType | BaseConnectionErrorType> {\n\t/**\n\t * Emitted when data is received from the remote peer.\n\t */\n\tdata: (data: unknown) => void;\n\t/**\n\t * Emitted when the connection is established and ready-to-use.\n\t */\n\topen: () => void;\n}\n\n/**\n * Wraps a DataChannel between two Peers.\n */\nexport abstract class DataConnection extends BaseConnection<\n\tDataConnectionEvents,\n\tDataConnectionErrorType\n> {\n\tprotected static readonly ID_PREFIX = \"dc_\";\n\tprotected static readonly MAX_BUFFERED_AMOUNT = 8 * 1024 * 1024;\n\n\tprivate _negotiator: Negotiator<DataConnectionEvents, this>;\n\tabstract readonly serialization: string;\n\treadonly reliable: boolean;\n\n\tpublic get type() {\n\t\treturn ConnectionType.Data;\n\t}\n\n\tconstructor(peerId: string, provider: Peer, options: any) {\n\t\tsuper(peerId, provider, options);\n\n\t\tthis.connectionId =\n\t\t\tthis.options.connectionId || DataConnection.ID_PREFIX + randomToken();\n\n\t\tthis.label = this.options.label || this.connectionId;\n\t\tthis.reliable = !!this.options.reliable;\n\n\t\tthis._negotiator = new Negotiator(this);\n\n\t\tthis._negotiator.startConnection(\n\t\t\tthis.options._payload || {\n\t\t\t\toriginator: true,\n\t\t\t\treliable: this.reliable,\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Called by the Negotiator when the DataChannel is ready. */\n\toverride _initializeDataChannel(dc: RTCDataChannel): void {\n\t\tthis.dataChannel = dc;\n\n\t\tthis.dataChannel.onopen = () => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc connection success`);\n\t\t\tthis._open = true;\n\t\t\tthis.emit(\"open\");\n\t\t};\n\n\t\tthis.dataChannel.onmessage = (e) => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc onmessage:`, e.data);\n\t\t\t// this._handleDataMessage(e);\n\t\t};\n\n\t\tthis.dataChannel.onclose = () => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc closed for:`, this.peer);\n\t\t\tthis.close();\n\t\t};\n\t}\n\n\t/**\n\t * Exposed functionality for users.\n\t */\n\n\t/** Allows user to close connection. */\n\tclose(options?: { flush?: boolean }): void {\n\t\tif (options?.flush) {\n\t\t\tthis.send({\n\t\t\t\t__peerData: {\n\t\t\t\t\ttype: \"close\",\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (this._negotiator) {\n\t\t\tthis._negotiator.cleanup();\n\t\t\tthis._negotiator = null;\n\t\t}\n\n\t\tif (this.provider) {\n\t\t\tthis.provider._removeConnection(this);\n\n\t\t\tthis.provider = null;\n\t\t}\n\n\t\tif (this.dataChannel) {\n\t\t\tthis.dataChannel.onopen = null;\n\t\t\tthis.dataChannel.onmessage = null;\n\t\t\tthis.dataChannel.onclose = null;\n\t\t\tthis.dataChannel = null;\n\t\t}\n\n\t\tif (!this.open) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._open = false;\n\n\t\tsuper.emit(\"close\");\n\t}\n\n\tprotected abstract _send(data: any, chunked: boolean): void | Promise<void>;\n\n\t/** Allows user to send data. */\n\tpublic send(data: any, chunked = false) {\n\t\tif (!this.open) {\n\t\t\tthis.emitError(\n\t\t\t\tDataConnectionErrorType.NotOpenYet,\n\t\t\t\t\"Connection is not open. You should listen for the `open` event before sending messages.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\treturn this._send(data, chunked);\n\t}\n\n\tasync handleMessage(message: ServerMessage) {\n\t\tconst payload = message.payload;\n\n\t\tswitch (message.type) {\n\t\t\tcase ServerMessageType.Answer:\n\t\t\t\tawait this._negotiator.handleSDP(message.type, payload.sdp);\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Candidate:\n\t\t\t\tawait this._negotiator.handleCandidate(payload.candidate);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(\n\t\t\t\t\t\"Unrecognized message type:\",\n\t\t\t\t\tmessage.type,\n\t\t\t\t\t\"from peer:\",\n\t\t\t\t\tthis.peer,\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n", "import { BufferedConnection } from \"./BufferedConnection\";\nimport { SerializationType } from \"../../enums\";\n\nexport class Raw extends BufferedConnection {\n\treadonly serialization = SerializationType.None;\n\n\tprotected _handleDataMessage({ data }) {\n\t\tsuper.emit(\"data\", data);\n\t}\n\n\toverride _send(data, _chunked) {\n\t\tthis._bufferedSend(data);\n\t}\n}\n", "import { BufferedConnection } from \"./BufferedConnection\";\nimport { DataConnectionErrorType, SerializationType } from \"../../enums\";\nimport { util } from \"../../util\";\n\nexport class Json extends BufferedConnection {\n\treadonly serialization = SerializationType.JSON;\n\tprivate readonly encoder = new TextEncoder();\n\tprivate readonly decoder = new TextDecoder();\n\n\tstringify: (data: any) => string = JSON.stringify;\n\tparse: (data: string) => any = JSON.parse;\n\n\t// Handles a DataChannel message.\n\tprotected override _handleDataMessage({ data }: { data: Uint8Array }): void {\n\t\tconst deserializedData = this.parse(this.decoder.decode(data));\n\n\t\t// PeerJS specific message\n\t\tconst peerData = deserializedData[\"__peerData\"];\n\t\tif (peerData && peerData.type === \"close\") {\n\t\t\tthis.close();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.emit(\"data\", deserializedData);\n\t}\n\n\toverride _send(data, _chunked) {\n\t\tconst encodedData = this.encoder.encode(this.stringify(data));\n\t\tif (encodedData.byteLength >= util.chunkedMTU) {\n\t\t\tthis.emitError(\n\t\t\t\tDataConnectionErrorType.MessageToBig,\n\t\t\t\t\"Message too big for JSON channel\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis._bufferedSend(encodedData);\n\t}\n}\n", "import { Peer, type SerializerMapping } from \"./peer\";\nimport { MsgPack } from \"./exports\";\n\n/**\n * @experimental\n */\nexport class MsgPackPeer extends Peer {\n\toverride _serializers: SerializerMapping = {\n\t\tMsgPack,\n\t\tdefault: MsgPack,\n\t};\n}\n", "import { decodeMultiStream, Encoder } from \"@msgpack/msgpack\";\nimport { StreamConnection } from \"./StreamConnection.js\";\nimport type { Peer } from \"../../peer.js\";\n\nexport class MsgPack extends StreamConnection {\n\treadonly serialization = \"MsgPack\";\n\tprivate _encoder = new Encoder();\n\n\tconstructor(peerId: string, provider: Peer, options: any) {\n\t\tsuper(peerId, provider, options);\n\n\t\t(async () => {\n\t\t\tfor await (const msg of decodeMultiStream(this._rawReadStream)) {\n\t\t\t\t// @ts-ignore\n\t\t\t\tif (msg.__peerData?.type === \"close\") {\n\t\t\t\t\tthis.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.emit(\"data\", msg);\n\t\t\t}\n\t\t})();\n\t}\n\n\tprotected override _send(data) {\n\t\treturn this.writer.write(this._encoder.encode(data));\n\t}\n}\n", "import logger from \"../../logger.js\";\nimport type { Peer } from \"../../peer.js\";\nimport { DataConnection } from \"../DataConnection.js\";\n\nexport abstract class StreamConnection extends DataConnection {\n\tprivate _CHUNK_SIZE = 1024 * 8 * 4;\n\tprivate _splitStream = new TransformStream<Uint8Array>({\n\t\ttransform: (chunk, controller) => {\n\t\t\tfor (let split = 0; split < chunk.length; split += this._CHUNK_SIZE) {\n\t\t\t\tcontroller.enqueue(chunk.subarray(split, split + this._CHUNK_SIZE));\n\t\t\t}\n\t\t},\n\t});\n\tprivate _rawSendStream = new WritableStream<ArrayBuffer>({\n\t\twrite: async (chunk, controller) => {\n\t\t\tconst openEvent = new Promise((resolve) =>\n\t\t\t\tthis.dataChannel.addEventListener(\"bufferedamountlow\", resolve, {\n\t\t\t\t\tonce: true,\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\t// if we can send the chunk now, send it\n\t\t\t// if not, we wait until at least half of the sending buffer is free again\n\t\t\tawait (this.dataChannel.bufferedAmount <=\n\t\t\t\tDataConnection.MAX_BUFFERED_AMOUNT - chunk.byteLength || openEvent);\n\n\t\t\t// TODO: what can go wrong here?\n\t\t\ttry {\n\t\t\t\tthis.dataChannel.send(chunk);\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error(`DC#:${this.connectionId} Error when sending:`, e);\n\t\t\t\tcontroller.error(e);\n\t\t\t\tthis.close();\n\t\t\t}\n\t\t},\n\t});\n\tprotected writer = this._splitStream.writable.getWriter();\n\n\tprotected _rawReadStream = new ReadableStream<ArrayBuffer>({\n\t\tstart: (controller) => {\n\t\t\tthis.once(\"open\", () => {\n\t\t\t\tthis.dataChannel.addEventListener(\"message\", (e) => {\n\t\t\t\t\tcontroller.enqueue(e.data);\n\t\t\t\t});\n\t\t\t});\n\t\t},\n\t});\n\n\tprotected constructor(peerId: string, provider: Peer, options: any) {\n\t\tsuper(peerId, provider, { ...options, reliable: true });\n\n\t\tvoid this._splitStream.readable.pipeTo(this._rawSendStream);\n\t}\n\n\tpublic override _initializeDataChannel(dc) {\n\t\tsuper._initializeDataChannel(dc);\n\t\tthis.dataChannel.binaryType = \"arraybuffer\";\n\t\tthis.dataChannel.bufferedAmountLowThreshold =\n\t\t\tDataConnection.MAX_BUFFERED_AMOUNT / 2;\n\t}\n}\n", "/**\n * CallSessionImpl - \u901A\u8BDD\u4F1A\u8BDD\u7684\u5185\u90E8\u5B9E\u73B0\n * \n * \u8D1F\u8D23\u7BA1\u7406\u5355\u4E2A\u8BED\u97F3/\u89C6\u9891\u901A\u8BDD\u7684\u5B8C\u6574\u751F\u547D\u5468\u671F\uFF1A\n * - \u97F3\u89C6\u9891\u6D41\u7BA1\u7406\n * - \u9759\u97F3/\u89C6\u9891\u5F00\u5173\u72B6\u6001\n * - \u901A\u8BDD\u72B6\u6001\u53D8\u5316\u901A\u77E5\n * \n * @example\n * const session = new CallSessionImpl(peerId, mediaConnection, hasVideo, debugLog, onCleanup);\n * session.toggleMute(); // \u5207\u6362\u9759\u97F3\n * session.toggleVideo(); // \u5207\u6362\u89C6\u9891\n * session.hangUp(); // \u6302\u65AD\u901A\u8BDD\n */\n\nimport type { MediaConnection } from 'peerjs';\nimport type { CallSession, CallState, CallStateListener } from './types';\n\n/**\n * \u901A\u8BDD\u4F1A\u8BDD\u5B9E\u73B0\u7C7B\n * \u5B9E\u73B0 CallSession \u63A5\u53E3\uFF0C\u63D0\u4F9B\u901A\u8BDD\u63A7\u5236\u529F\u80FD\n */\nexport class CallSessionImpl implements CallSession {\n /** \u5BF9\u7AEF\u7684 Peer ID */\n readonly peerId: string;\n /** \u662F\u5426\u5305\u542B\u89C6\u9891 */\n readonly hasVideo: boolean;\n\n /** PeerJS MediaConnection \u5B9E\u4F8B */\n private mediaConnection: MediaConnection;\n /** \u672C\u5730\u5A92\u4F53\u6D41\uFF08\u9EA6\u514B\u98CE/\u6444\u50CF\u5934\uFF09 */\n private localStream: MediaStream | null = null;\n /** \u8FDC\u7A0B\u5A92\u4F53\u6D41\uFF08\u5BF9\u65B9\u7684\u97F3\u9891/\u89C6\u9891\uFF09 */\n private remoteStream: MediaStream | null = null;\n /** \u901A\u8BDD\u72B6\u6001\u76D1\u542C\u5668\u96C6\u5408 */\n private stateListeners = new Set<CallStateListener>();\n /** \u8C03\u8BD5\u65E5\u5FD7\u51FD\u6570 */\n private debugLogFn: (obj: string, event: string, data?: unknown) => void;\n /** \u6E05\u7406\u56DE\u8C03\uFF08\u901A\u8BDD\u7ED3\u675F\u65F6\u8C03\u7528\uFF09 */\n private onCleanup: (session: CallSessionImpl) => void;\n\n /** \u5F53\u524D\u901A\u8BDD\u72B6\u6001 */\n private _state: CallState = 'connecting';\n /** \u662F\u5426\u5DF2\u9759\u97F3 */\n private isMuted = false;\n /** \u89C6\u9891\u662F\u5426\u5F00\u542F */\n private isVideoEnabled = true;\n\n /**\n * \u521B\u5EFA\u901A\u8BDD\u4F1A\u8BDD\u5B9E\u4F8B\n * @param peerId \u5BF9\u7AEF Peer ID\n * @param mediaConnection PeerJS MediaConnection \u5B9E\u4F8B\n * @param hasVideo \u662F\u5426\u5305\u542B\u89C6\u9891\n * @param debugLog \u8C03\u8BD5\u65E5\u5FD7\u51FD\u6570\n * @param onCleanup \u901A\u8BDD\u7ED3\u675F\u65F6\u7684\u6E05\u7406\u56DE\u8C03\n */\n constructor(\n peerId: string,\n mediaConnection: MediaConnection,\n hasVideo: boolean,\n debugLog: (obj: string, event: string, data?: unknown) => void,\n onCleanup: (session: CallSessionImpl) => void\n ) {\n this.peerId = peerId;\n this.mediaConnection = mediaConnection;\n this.hasVideo = hasVideo;\n this.debugLogFn = debugLog;\n this.onCleanup = onCleanup;\n }\n\n /** \u662F\u5426\u5DF2\u8FDE\u63A5 */\n get isConnected(): boolean {\n return this._state === 'connected';\n }\n\n /** \u5F53\u524D\u901A\u8BDD\u72B6\u6001 */\n get state(): CallState {\n return this._state;\n }\n\n /**\n * \u8BBE\u7F6E\u901A\u8BDD\u72B6\u6001\n * @param state \u65B0\u7684\u901A\u8BDD\u72B6\u6001\n * @param reason \u72B6\u6001\u53D8\u5316\u539F\u56E0\uFF08\u53EF\u9009\uFF09\n */\n setState(state: CallState, reason?: string): void {\n this._state = state;\n this.notifyStateChange(state, reason);\n }\n\n /** \u8BBE\u7F6E\u672C\u5730\u5A92\u4F53\u6D41 */\n setLocalStream(stream: MediaStream): void {\n this.localStream = stream;\n }\n\n /** \u8BBE\u7F6E\u8FDC\u7A0B\u5A92\u4F53\u6D41 */\n setRemoteStream(stream: MediaStream): void {\n this.remoteStream = stream;\n }\n\n /** \u83B7\u53D6\u672C\u5730\u5A92\u4F53\u6D41 */\n getLocalStream(): MediaStream | null {\n return this.localStream;\n }\n\n /** \u83B7\u53D6\u8FDC\u7A0B\u5A92\u4F53\u6D41 */\n getRemoteStream(): MediaStream | null {\n return this.remoteStream;\n }\n\n /**\n * \u5207\u6362\u9759\u97F3\u72B6\u6001\n * @returns \u5207\u6362\u540E\u7684\u9759\u97F3\u72B6\u6001\uFF08true = \u5DF2\u9759\u97F3\uFF09\n */\n toggleMute(): boolean {\n if (!this.localStream) return this.isMuted;\n\n const audioTracks = this.localStream.getAudioTracks();\n for (const track of audioTracks) {\n track.enabled = this.isMuted;\n }\n this.isMuted = !this.isMuted;\n this.debugLogFn('CallSession', 'toggleMute', this.isMuted);\n return this.isMuted;\n }\n\n /**\n * \u5207\u6362\u89C6\u9891\u5F00\u5173\uFF08\u4EC5\u89C6\u9891\u901A\u8BDD\u6709\u6548\uFF09\n * @returns \u5207\u6362\u540E\u7684\u89C6\u9891\u72B6\u6001\uFF08true = \u89C6\u9891\u5F00\u542F\uFF09\n */\n toggleVideo(): boolean {\n if (!this.hasVideo || !this.localStream) return this.isVideoEnabled;\n\n const videoTracks = this.localStream.getVideoTracks();\n for (const track of videoTracks) {\n track.enabled = !this.isVideoEnabled;\n }\n this.isVideoEnabled = !this.isVideoEnabled;\n this.debugLogFn('CallSession', 'toggleVideo', this.isVideoEnabled);\n return this.isVideoEnabled;\n }\n\n /** \u6302\u65AD\u901A\u8BDD */\n hangUp(): void {\n this.debugLogFn('CallSession', 'hangUp', this.peerId);\n this.mediaConnection.close();\n }\n\n /**\n * \u5173\u95ED\u901A\u8BDD\u4F1A\u8BDD\n * \u505C\u6B62\u672C\u5730\u6D41\uFF0C\u6E05\u7406\u8D44\u6E90\n */\n close(): void {\n if (this.localStream) {\n this.localStream.getTracks().forEach(track => track.stop());\n this.localStream = null;\n }\n this.remoteStream = null;\n this._state = 'ended';\n }\n\n /** \u6CE8\u518C\u901A\u8BDD\u72B6\u6001\u53D8\u5316\u76D1\u542C\u5668 */\n onStateChange(listener: CallStateListener): void {\n this.stateListeners.add(listener);\n }\n\n /** \u79FB\u9664\u901A\u8BDD\u72B6\u6001\u53D8\u5316\u76D1\u542C\u5668 */\n offStateChange(listener: CallStateListener): void {\n this.stateListeners.delete(listener);\n }\n\n /**\n * \u901A\u77E5\u72B6\u6001\u53D8\u5316\n * @param state \u65B0\u72B6\u6001\n * @param reason \u53D8\u5316\u539F\u56E0\uFF08\u53EF\u9009\uFF09\n */\n private notifyStateChange(state: CallState, reason?: string): void {\n this.debugLogFn('CallSession', 'stateChange', { peer: this.peerId, state, reason });\n this.stateListeners.forEach(listener => {\n try {\n listener(state, reason);\n } catch (err) {\n this.debugLogFn('CallSession', 'listenerError', err);\n }\n });\n\n // \u901A\u8BDD\u7ED3\u675F\u65F6\u6267\u884C\u6E05\u7406\n if (state === 'ended') {\n this.onCleanup(this);\n }\n }\n}\n", "/**\n * \u5E38\u91CF\u5B9A\u4E49\n * \u96C6\u4E2D\u7BA1\u7406\u6240\u6709\u9B54\u6CD5\u6570\u5B57\u548C\u914D\u7F6E\u503C\n */\n\n/** \u8FDE\u63A5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09 */\nexport const CONNECTION_TIMEOUT_MS = 30000;\n\n/** \u53D1\u9001\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09 */\nexport const SEND_TIMEOUT_MS = 10000;\n\n/** \u91CD\u8FDE\u5EF6\u8FDF\uFF08\u6BEB\u79D2\uFF09 */\nexport const RECONNECT_DELAY_MS = 1000;\n\n/** \u8DEF\u7531\u8FC7\u671F\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09 */\nexport const ROUTE_EXPIRE_AGE_MS = 5 * 60 * 1000;\n\n/** \u8DEF\u7531\u8868\u5BB9\u91CF\u9650\u5236 */\nexport const MAX_ROUTING_ENTRIES = 50;\n\n/** \u76F4\u8FDE\u8282\u70B9\u5BB9\u91CF\u9650\u5236 */\nexport const MAX_DIRECT_NODES = 5;\n\n/** \u8DEF\u7531\u6E05\u7406\u5468\u671F\uFF08\u6BEB\u79D2\uFF09 */\nexport const ROUTE_CLEANUP_INTERVAL_MS = 60 * 1000;\n\n/** \u8DEF\u7531\u5E7F\u64AD\u5468\u671F\uFF08\u6BEB\u79D2\uFF09 */\nexport const ROUTE_BROADCAST_INTERVAL_MS = 30 * 1000;\n\n/** \u9ED8\u8BA4 TTL\uFF08Time To Live\uFF09- \u6D88\u606F\u6700\u5927\u8DF3\u6570 */\nexport const DEFAULT_TTL = 128;\n", "/**\n * RoutingDB.ts - \u8DEF\u7531\u8868 IndexedDB \u6301\u4E45\u5316\u6A21\u5757\n *\n * \u63D0\u4F9B\u8DEF\u7531\u8868\u7684\u6301\u4E45\u5316\u5B58\u50A8\u529F\u80FD\uFF0C\u4F7F\u7528 IndexedDB \u800C\u975E localStorage\n * \u4EE5\u652F\u6301\u5927\u89C4\u6A21\u8DEF\u7531\u8868\u5B58\u50A8\n *\n * \u6570\u636E\u5E93\u7ED3\u6784\uFF1A\n * - peerjs-routing-db (\u7248\u672C 1)\n * - routing-table: \u8DEF\u7531\u8868\u6761\u76EE (keyPath: target)\n * - direct-nodes: \u76F4\u8FDE\u8282\u70B9 (keyPath: nodeId)\n */\n\nimport type { RouteEntry, DirectNodeLatency } from './types';\nimport { ROUTE_EXPIRE_AGE_MS } from './constants';\n\nconst DB_NAME = 'peerjs-routing-db';\nconst DB_VERSION = 1;\nconst ROUTING_TABLE_STORE = 'routing-table';\nconst DIRECT_NODES_STORE = 'direct-nodes';\n\nlet db: IDBDatabase | null = null;\n\n/**\n * \u521B\u5EFA\u901A\u7528\u7684 Object Store \u64CD\u4F5C\n * @param storeName Object Store \u540D\u79F0\n * @param mode \u4E8B\u52A1\u6A21\u5F0F\n * @param operation \u8981\u6267\u884C\u7684\u64CD\u4F5C\n * @returns Promise<T>\n */\nfunction withStore<T>(\n storeName: string,\n mode: IDBTransactionMode,\n operation: (store: IDBObjectStore) => IDBRequest | void\n): Promise<T> {\n return openDB().then(database => {\n return new Promise<T>((resolve, reject) => {\n const tx = database.transaction(storeName, mode);\n const store = tx.objectStore(storeName);\n const request = operation(store) as IDBRequest;\n \n if (request) {\n request.onerror = () => reject(request.error);\n request.onsuccess = () => resolve(request.result);\n } else {\n tx.oncomplete = () => resolve(undefined as T);\n tx.onerror = () => reject(tx.error);\n }\n });\n });\n}\n\n/**\n * \u6253\u5F00\u6570\u636E\u5E93\u8FDE\u63A5\n * @returns Promise<IDBDatabase>\n */\nfunction openDB(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n if (db) {\n resolve(db);\n return;\n }\n\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n db = request.result;\n resolve(db);\n };\n\n request.onupgradeneeded = (e: IDBVersionChangeEvent) => {\n const req = e.target as IDBOpenDBRequest;\n const database = req.result;\n\n if (!database.objectStoreNames.contains(ROUTING_TABLE_STORE)) {\n const routingStore = database.createObjectStore(ROUTING_TABLE_STORE, {\n keyPath: 'target',\n });\n routingStore.createIndex('timestamp', 'timestamp', { unique: false });\n }\n\n if (!database.objectStoreNames.contains(DIRECT_NODES_STORE)) {\n const nodesStore = database.createObjectStore(DIRECT_NODES_STORE, {\n keyPath: 'nodeId',\n });\n nodesStore.createIndex('timestamp', 'timestamp', { unique: false });\n }\n };\n });\n}\n\n/**\n * \u521D\u59CB\u5316\u6570\u636E\u5E93\n * @returns Promise<void>\n */\nexport async function initRoutingDB(): Promise<void> {\n await openDB();\n}\n\n/**\n * \u4FDD\u5B58\u8DEF\u7531\u8868\u6761\u76EE\n * @param entry \u8DEF\u7531\u8868\u6761\u76EE\n */\nexport async function saveRouteEntry(entry: RouteEntry): Promise<void> {\n await withStore(ROUTING_TABLE_STORE, 'readwrite', store => store.put(entry));\n}\n\n/**\n * \u6279\u91CF\u4FDD\u5B58\u8DEF\u7531\u8868\u6761\u76EE\n * @param entries \u8DEF\u7531\u8868\u6761\u76EE\u6570\u7EC4\n */\nexport async function saveRouteEntries(entries: RouteEntry[]): Promise<void> {\n await openDB().then(database => {\n return new Promise<void>((resolve, reject) => {\n const tx = database.transaction(ROUTING_TABLE_STORE, 'readwrite');\n const store = tx.objectStore(ROUTING_TABLE_STORE);\n\n for (const entry of entries) {\n store.put(entry);\n }\n\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n });\n}\n\n/**\n * \u5220\u9664\u8DEF\u7531\u8868\u6761\u76EE\n * @param target \u76EE\u6807\u8282\u70B9 ID\n */\nexport async function deleteRouteEntry(target: string): Promise<void> {\n await withStore(ROUTING_TABLE_STORE, 'readwrite', store => store.delete(target));\n}\n\n/**\n * \u52A0\u8F7D\u5168\u90E8\u8DEF\u7531\u8868\n * @returns Promise<RouteEntry[]>\n */\nexport async function loadRoutingTable(): Promise<RouteEntry[]> {\n return withStore<RouteEntry[]>(ROUTING_TABLE_STORE, 'readonly', store => store.getAll());\n}\n\n/**\n * \u6E05\u7406\u8FC7\u671F\u8DEF\u7531\u8868\u6761\u76EE\n * @param maxAgeMs \u6700\u5927\u4FDD\u7559\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09\uFF0C\u9ED8\u8BA4 5 \u5206\u949F\n * @returns Promise<number> \u5220\u9664\u7684\u6761\u76EE\u6570\u91CF\n */\nexport async function cleanupExpiredRoutes(maxAgeMs: number = ROUTE_EXPIRE_AGE_MS): Promise<number> {\n const database = await openDB();\n const now = Date.now();\n\n return new Promise((resolve, reject) => {\n const tx = database.transaction(ROUTING_TABLE_STORE, 'readwrite');\n const store = tx.objectStore(ROUTING_TABLE_STORE);\n const index = store.index('timestamp');\n const range = IDBKeyRange.upperBound(now - maxAgeMs);\n const request = index.openCursor(range);\n let deletedCount = 0;\n\n request.onsuccess = (e) => {\n const cursor = (e.target as IDBRequest).result;\n if (cursor) {\n cursor.delete();\n deletedCount++;\n cursor.continue();\n }\n };\n\n tx.oncomplete = () => resolve(deletedCount);\n tx.onerror = () => reject(tx.error);\n });\n}\n\n/**\n * \u4FDD\u5B58\u76F4\u8FDE\u8282\u70B9\n * @param node \u76F4\u8FDE\u8282\u70B9\n */\nexport async function saveDirectNode(node: DirectNodeLatency): Promise<void> {\n await withStore(DIRECT_NODES_STORE, 'readwrite', store => store.put(node));\n}\n\n/**\n * \u6279\u91CF\u4FDD\u5B58\u76F4\u8FDE\u8282\u70B9\n * @param nodes \u76F4\u8FDE\u8282\u70B9\u6570\u7EC4\n */\nexport async function saveDirectNodes(nodes: DirectNodeLatency[]): Promise<void> {\n await openDB().then(database => {\n return new Promise<void>((resolve, reject) => {\n const tx = database.transaction(DIRECT_NODES_STORE, 'readwrite');\n const store = tx.objectStore(DIRECT_NODES_STORE);\n\n for (const node of nodes) {\n store.put(node);\n }\n\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n });\n}\n\n/**\n * \u52A0\u8F7D\u5168\u90E8\u76F4\u8FDE\u8282\u70B9\n * @returns Promise<DirectNodeLatency[]>\n */\nexport async function loadDirectNodes(): Promise<DirectNodeLatency[]> {\n return withStore<DirectNodeLatency[]>(DIRECT_NODES_STORE, 'readonly', store => store.getAll());\n}\n\n/**\n * \u5220\u9664\u76F4\u8FDE\u8282\u70B9\n * @param nodeId \u8282\u70B9 ID\n */\nexport async function deleteDirectNode(nodeId: string): Promise<void> {\n await withStore(DIRECT_NODES_STORE, 'readwrite', store => store.delete(nodeId));\n}\n\n/**\n * \u6E05\u7406\u8FC7\u671F\u76F4\u8FDE\u8282\u70B9\n * @param maxAgeMs \u6700\u5927\u4FDD\u7559\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09\uFF0C\u9ED8\u8BA4 5 \u5206\u949F\n * @returns Promise<number> \u5220\u9664\u7684\u8282\u70B9\u6570\u91CF\n */\nexport async function cleanupExpiredNodes(maxAgeMs: number = ROUTE_EXPIRE_AGE_MS): Promise<number> {\n const database = await openDB();\n const now = Date.now();\n\n return new Promise((resolve, reject) => {\n const tx = database.transaction(DIRECT_NODES_STORE, 'readwrite');\n const store = tx.objectStore(DIRECT_NODES_STORE);\n const index = store.index('timestamp');\n const range = IDBKeyRange.upperBound(now - maxAgeMs);\n const request = index.openCursor(range);\n let deletedCount = 0;\n\n request.onsuccess = (e) => {\n const cursor = (e.target as IDBRequest).result;\n if (cursor) {\n cursor.delete();\n deletedCount++;\n cursor.continue();\n }\n };\n\n tx.oncomplete = () => resolve(deletedCount);\n tx.onerror = () => reject(tx.error);\n });\n}\n\n/**\n * \u6E05\u9664\u5168\u90E8\u8DEF\u7531\u6570\u636E\n * @returns Promise<void>\n */\nexport async function clearAllRoutingData(): Promise<void> {\n const database = await openDB();\n\n await new Promise<void>((resolve, reject) => {\n const tx = database.transaction(ROUTING_TABLE_STORE, 'readwrite');\n const store = tx.objectStore(ROUTING_TABLE_STORE);\n store.clear();\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n\n await new Promise<void>((resolve, reject) => {\n const tx = database.transaction(DIRECT_NODES_STORE, 'readwrite');\n const store = tx.objectStore(DIRECT_NODES_STORE);\n store.clear();\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n}\n", "/**\n * Router - \u8DEF\u7531\u7BA1\u7406\u5668\n * \n * \u8D1F\u8D23\u4E2D\u7EE7\u901A\u4FE1\u7684\u6838\u5FC3\u529F\u80FD\uFF1A\n * - \u7EF4\u62A4\u76F4\u8FDE\u8282\u70B9\u5217\u8868\u53CA\u5EF6\u8FDF\uFF08directNodes\uFF09\n * - \u7EF4\u62A4\u8DEF\u7531\u8868\uFF08routingTable\uFF09\uFF1A\u76EE\u6807\u8282\u70B9 -> \u591A\u4E2A\u4E0B\u4E00\u8DF3\uFF08\u542B\u5EF6\u8FDF\uFF09\n * - \u5E7F\u64AD\u8DEF\u7531\u66F4\u65B0\u5230\u90BB\u5C45\u8282\u70B9\n * - \u8DEF\u7531\u53D1\u73B0\uFF1A\u5F53\u76F4\u8FDE\u548C\u8DEF\u7531\u8868\u90FD\u5931\u8D25\u65F6\uFF0C\u5E7F\u64AD\u8BE2\u95EE\u8C01\u80FD\u8FDE\u901A\u76EE\u6807\n * - \u5904\u7406\u8DEF\u7531\u67E5\u8BE2\u548C\u54CD\u5E94\n * \n * \u8DEF\u7531\u673A\u5236\uFF1A\n * 1. \u6BCF\u6B21\u6210\u529F\u901A\u4FE1\u540E\uFF0C\u8BB0\u5F55\u5BF9\u65B9\u8282\u70B9\u4E3A\u76F4\u8FDE\u8282\u70B9\u5E76\u6D4B\u91CF\u5EF6\u8FDF\n * 2. \u6210\u529F\u540E\u5E7F\u64AD\u8DEF\u7531\u66F4\u65B0\uFF0C\u544A\u77E5\u5BF9\u65B9\u81EA\u5DF1\u53EF\u8FBE\u7684\u8282\u70B9\n * 3. \u6536\u5230\u8DEF\u7531\u66F4\u65B0\u540E\uFF0C\u5408\u5E76\u5230\u672C\u5730\u8DEF\u7531\u8868\n * 4. \u76F4\u8FDE\u5931\u8D25\u4E14\u8DEF\u7531\u8868\u4E3A\u7A7A\u65F6\uFF0C\u6267\u884C\u8DEF\u7531\u53D1\u73B0\u5E7F\u64AD\n */\n\nimport type { Peer } from 'peerjs';\nimport type { RouteEntry, NextHop, DirectNodeLatency, RelayConfig, RelayMessage } from './types';\nimport {\n initRoutingDB,\n loadRoutingTable,\n saveRouteEntry,\n saveRouteEntries,\n deleteRouteEntry,\n loadDirectNodes,\n saveDirectNode,\n saveDirectNodes,\n cleanupExpiredRoutes,\n cleanupExpiredNodes,\n} from './RoutingDB';\nimport {\n MAX_ROUTING_ENTRIES,\n MAX_DIRECT_NODES,\n ROUTE_EXPIRE_AGE_MS,\n ROUTE_CLEANUP_INTERVAL_MS,\n ROUTE_BROADCAST_INTERVAL_MS,\n CONNECTION_TIMEOUT_MS,\n DEFAULT_TTL,\n} from './constants';\n\n/**\n * \u8DEF\u7531\u7BA1\u7406\u5668\u56DE\u8C03\u63A5\u53E3\n */\nexport interface RoutingCallbacks {\n /** \u83B7\u53D6\u672C\u5730 Peer ID */\n getMyPeerId(): string;\n /** \u83B7\u53D6 PeerJS \u5B9E\u4F8B */\n getPeerInstance(): Peer | null;\n /** \u8C03\u8BD5\u65E5\u5FD7\u51FD\u6570 */\n debugLog: (obj: string, event: string, data?: unknown) => void;\n /** \u53D1\u9001\u4E2D\u7EE7\u6D88\u606F */\n sendRelayMessage(targetId: string, message: RelayMessage): Promise<void>;\n /** \u5904\u7406\u8DEF\u7531\u67E5\u8BE2\u54CD\u5E94 */\n onRouteDiscoveryResponse?: (targetId: string, latency: number) => void;\n}\n\n/**\n * \u8DEF\u7531\u5668\u7C7B\n * \u8D1F\u8D23\u7EF4\u62A4\u8DEF\u7531\u8868\u3001\u8282\u70B9\u53D1\u73B0\u548C\u81EA\u52A8\u8DEF\u7531\u9009\u62E9\n */\nexport class Router {\n /** \u8DEF\u7531\u8868\uFF1Atarget -> RouteEntry */\n private routingTable = new Map<string, RouteEntry>();\n /** \u76F4\u8FDE\u8282\u70B9\u53CA\u5EF6\u8FDF\u5217\u8868 */\n private directNodes: DirectNodeLatency[] = [];\n /** \u4E2D\u7EE7\u914D\u7F6E */\n private relayConfig: RelayConfig;\n /** \u56DE\u8C03\u51FD\u6570\u96C6\u5408 */\n private callbacks: RoutingCallbacks;\n /** \u7B49\u5F85\u8DEF\u7531\u53D1\u73B0\u54CD\u5E94\u7684 pending \u961F\u5217 */\n private pendingRouteQueries = new Map<string, { resolve: (entry: RouteEntry) => void; reject: (err: Error) => void; timer: ReturnType<typeof setTimeout> }>();\n /** \u5B9A\u65F6\u6E05\u7406\u5B9A\u65F6\u5668 */\n private cleanupTimer: ReturnType<typeof setInterval> | null = null;\n /** \u5468\u671F\u5E7F\u64AD\u5B9A\u65F6\u5668 */\n private broadcastTimer: ReturnType<typeof setInterval> | null = null;\n\n /**\n * \u521B\u5EFA\u8DEF\u7531\u7BA1\u7406\u5668\n * @param callbacks \u56DE\u8C03\u51FD\u6570\u96C6\u5408\n * @param relayConfig \u4E2D\u7EE7\u914D\u7F6E\uFF08\u53EF\u9009\uFF09\n */\n constructor(callbacks: RoutingCallbacks, relayConfig?: RelayConfig) {\n this.callbacks = callbacks;\n this.relayConfig = relayConfig ?? {};\n }\n\n /**\n * \u521D\u59CB\u5316\u8DEF\u7531\u7BA1\u7406\u5668\uFF08\u4ECE IndexedDB \u52A0\u8F7D\u6570\u636E\u5E76\u542F\u52A8\u5B9A\u65F6\u4EFB\u52A1\uFF09\n */\n async init(): Promise<void> {\n await initRoutingDB();\n await this.loadFromDB();\n this.startMaintenanceTasks();\n }\n\n /**\n * \u4ECE IndexedDB \u52A0\u8F7D\u8DEF\u7531\u6570\u636E\n */\n private async loadFromDB(): Promise<void> {\n try {\n const routes = await loadRoutingTable();\n for (const entry of routes) {\n this.routingTable.set(entry.target, entry);\n }\n this.callbacks.debugLog('Routing', 'loadedRoutes', routes.length);\n } catch (e) {\n this.callbacks.debugLog('Routing', 'loadError', e);\n }\n\n try {\n const nodes = await loadDirectNodes();\n this.directNodes = nodes;\n this.callbacks.debugLog('Routing', 'loadedNodes', nodes.length);\n } catch (e) {\n this.callbacks.debugLog('Routing', 'loadNodesError', e);\n }\n }\n\n /**\n * \u542F\u52A8\u5B9A\u65F6\u7EF4\u62A4\u4EFB\u52A1\n */\n private startMaintenanceTasks(): void {\n this.cleanupTimer = setInterval(() => {\n this.cleanupExpiredEntries();\n }, ROUTE_CLEANUP_INTERVAL_MS);\n\n this.broadcastTimer = setInterval(() => {\n this.broadcastRouteUpdate();\n }, ROUTE_BROADCAST_INTERVAL_MS);\n }\n\n /**\n * \u6E05\u7406\u8FC7\u671F\u8DEF\u7531\u6761\u76EE\n */\n private async cleanupExpiredEntries(): Promise<void> {\n const now = Date.now();\n\n for (const [target, entry] of this.routingTable) {\n if (now - entry.timestamp > ROUTE_EXPIRE_AGE_MS) {\n this.routingTable.delete(target);\n deleteRouteEntry(target).catch(() => {});\n }\n }\n\n this.directNodes = this.directNodes.filter((node) => {\n const isExpired = now - node.timestamp > ROUTE_EXPIRE_AGE_MS;\n if (isExpired) {\n return false;\n }\n return true;\n });\n\n this.callbacks.debugLog('Routing', 'cleanup', {\n routes: this.routingTable.size,\n nodes: this.directNodes.length,\n });\n }\n\n /**\n * \u6301\u4E45\u5316\u8DEF\u7531\u8868\u5230 IndexedDB\n */\n async persist(): Promise<void> {\n try {\n const entries = Array.from(this.routingTable.values());\n await saveRouteEntries(entries);\n } catch (e) {\n this.callbacks.debugLog('Routing', 'persistError', e);\n }\n\n try {\n await saveDirectNodes(this.directNodes);\n } catch (e) {\n this.callbacks.debugLog('Routing', 'persistNodesError', e);\n }\n }\n\n /**\n * \u9500\u6BC1\u8DEF\u7531\u7BA1\u7406\u5668\uFF08\u6E05\u7406\u5B9A\u65F6\u5668\uFF09\n */\n destroy(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n if (this.broadcastTimer) {\n clearInterval(this.broadcastTimer);\n this.broadcastTimer = null;\n }\n this.pendingRouteQueries.forEach((pending) => {\n clearTimeout(pending.timer);\n });\n this.pendingRouteQueries.clear();\n }\n\n /**\n * \u8BB0\u5F55\u6210\u529F\u7684\u76F4\u8FDE\u901A\u4FE1\n * @param nodeId \u8282\u70B9 ID\n * @param latency \u5EF6\u8FDF\uFF08\u6BEB\u79D2\uFF09\n */\n recordDirectNode(nodeId: string, latency: number): void {\n const myPeerId = this.callbacks.getMyPeerId();\n if (nodeId === myPeerId) return;\n\n const existing = this.directNodes.find(n => n.nodeId === nodeId);\n const timestamp = Date.now();\n\n if (existing) {\n existing.latency = latency;\n existing.timestamp = timestamp;\n } else {\n const maxRelayNodes = this.relayConfig.maxRelayNodes ?? MAX_DIRECT_NODES;\n this.directNodes.push({ nodeId, latency, timestamp });\n if (this.directNodes.length > maxRelayNodes) {\n this.directNodes.sort((a, b) => a.latency - b.latency);\n this.directNodes.shift();\n }\n }\n\n this.callbacks.debugLog('Routing', 'directNode', { nodeId, latency });\n }\n\n /**\n * \u83B7\u53D6\u76F4\u8FDE\u8282\u70B9\u5217\u8868\uFF08\u6309\u5EF6\u8FDF\u5347\u5E8F\uFF09\n * @returns \u76F4\u8FDE\u8282\u70B9\u5217\u8868\n */\n getDirectNodes(): DirectNodeLatency[] {\n return [...this.directNodes].sort((a, b) => a.latency - b.latency);\n }\n\n /**\n * \u68C0\u67E5\u662F\u5426\u53EF\u4EE5\u76F4\u8FDE\u76EE\u6807\u8282\u70B9\n * @param targetId \u76EE\u6807\u8282\u70B9 ID\n * @returns \u662F\u5426\u53EF\u4EE5\u76F4\u8FDE\n */\n canReachDirectly(targetId: string): boolean {\n return this.directNodes.some(n => n.nodeId === targetId);\n }\n\n /**\n * \u83B7\u53D6\u5230\u76F4\u8FDE\u8282\u70B9\u7684\u5EF6\u8FDF\n * @param nodeId \u8282\u70B9 ID\n * @returns \u5EF6\u8FDF\uFF08\u6BEB\u79D2\uFF09\uFF0C\u5982\u679C\u4E0D\u5B58\u5728\u8FD4\u56DE null\n */\n getDirectLatency(nodeId: string): number | null {\n const node = this.directNodes.find(n => n.nodeId === nodeId);\n return node ? node.latency : null;\n }\n\n /**\n * \u79FB\u9664\u5931\u6548\u7684\u8DEF\u7531\uFF08\u901A\u4FE1\u5931\u8D25\u65F6\u8C03\u7528\uFF09\n * @param nodeId \u5931\u6548\u7684\u8282\u70B9 ID\n */\n removeRoute(nodeId: string): void {\n let removed = false;\n for (const [target, entry] of this.routingTable) {\n const originalLength = entry.nextHops.length;\n entry.nextHops = entry.nextHops.filter(h => h.nodeId !== nodeId);\n if (entry.nextHops.length === 0) {\n this.routingTable.delete(target);\n deleteRouteEntry(target).catch(() => {});\n removed = true;\n } else if (entry.nextHops.length < originalLength) {\n entry.timestamp = Date.now();\n saveRouteEntry(entry).catch(() => {});\n removed = true;\n }\n }\n\n const nodeIndex = this.directNodes.findIndex(n => n.nodeId === nodeId);\n if (nodeIndex !== -1) {\n this.directNodes.splice(nodeIndex, 1);\n removed = true;\n }\n\n if (removed) {\n this.callbacks.debugLog('Routing', 'routeRemoved', nodeId);\n }\n }\n\n /**\n * \u68C0\u67E5\u8DEF\u7531\u8868\u662F\u5426\u4E3A\u7A7A\n * @returns \u662F\u5426\u4E3A\u7A7A\n */\n isRoutingTableEmpty(): boolean {\n return this.routingTable.size === 0;\n }\n\n /**\n * \u8BB0\u5F55\u6210\u529F\u901A\u4FE1\u7684\u8282\u70B9\uFF08\u517C\u5BB9\u65E7\u63A5\u53E3\uFF09\n * @param nodeId \u8282\u70B9 ID\n */\n recordSuccessfulNode(nodeId: string): void {\n const myPeerId = this.callbacks.getMyPeerId();\n if (nodeId === myPeerId) return;\n\n const existing = this.directNodes.find(n => n.nodeId === nodeId);\n if (!existing) {\n const maxRelayNodes = this.relayConfig.maxRelayNodes ?? 5;\n this.directNodes.push({ nodeId, latency: 100, timestamp: Date.now() });\n if (this.directNodes.length > maxRelayNodes) {\n this.directNodes.sort((a, b) => a.latency - b.latency);\n this.directNodes.shift();\n }\n }\n }\n\n /**\n * \u5E7F\u64AD\u8DEF\u7531\u66F4\u65B0\n * \u5411\u6240\u6709\u76F4\u8FDE\u8282\u70B9\u53D1\u9001\u8DEF\u7531\u66F4\u65B0\u6D88\u606F\uFF0C\u544A\u77E5\u5B83\u4EEC\u672C\u8282\u70B9\u53EF\u8FBE\u7684\u8282\u70B9\u5217\u8868\n */\n async broadcastRouteUpdate(): Promise<void> {\n const myPeerId = this.callbacks.getMyPeerId();\n const reachableNodes = this.getReachableNodes();\n\n for (const node of this.directNodes) {\n try {\n await this.sendRouteUpdate(node.nodeId, reachableNodes);\n } catch {\n // \u5FFD\u7565\u5355\u4E2A\u8282\u70B9\u7684\u5E7F\u64AD\u5931\u8D25\n }\n }\n }\n\n /**\n * \u83B7\u53D6\u672C\u8282\u70B9\u53EF\u8FBE\u7684\u8282\u70B9\u5217\u8868\n * @returns \u53EF\u8FBE\u8282\u70B9\u6570\u7EC4\uFF08\u76F4\u8FDE\u8282\u70B9 + \u81EA\u5DF1\uFF09\n */\n private getReachableNodes(): string[] {\n const myPeerId = this.callbacks.getMyPeerId();\n const directNodeIds = this.directNodes.map(n => n.nodeId);\n return [...new Set([...directNodeIds, myPeerId])];\n }\n\n /**\n * \u53D1\u9001\u8DEF\u7531\u66F4\u65B0\u5230\u6307\u5B9A\u8282\u70B9\n * @param targetId \u76EE\u6807\u8282\u70B9 ID\n * @param reachableNodes \u53EF\u8FBE\u7684\u8282\u70B9\u5217\u8868\n */\n private async sendRouteUpdate(targetId: string, reachableNodes: string[]): Promise<void> {\n const myPeerId = this.callbacks.getMyPeerId();\n\n const message: RelayMessage = {\n type: 'route-update',\n id: `${myPeerId}-route-${Date.now()}`,\n originalTarget: targetId,\n relayPath: [],\n forwardPath: [],\n ttl: DEFAULT_TTL,\n routeUpdate: { reachableNodes },\n };\n\n await this.callbacks.sendRelayMessage(targetId, message);\n }\n\n /**\n * \u5904\u7406\u6536\u5230\u7684\u8DEF\u7531\u66F4\u65B0\n * \u5408\u5E76\u5BF9\u7AEF\u53D1\u6765\u7684\u53EF\u8FBE\u8282\u70B9\u4FE1\u606F\u5230\u672C\u5730\u8DEF\u7531\u8868\n * @param fromPeerId \u53D1\u9001\u8DEF\u7531\u66F4\u65B0\u7684\u8282\u70B9 ID\n * @param message \u8DEF\u7531\u66F4\u65B0\u6D88\u606F\n */\n handleRouteUpdate(fromPeerId: string, message: RelayMessage): void {\n if (!message.routeUpdate) return;\n\n const myPeerId = this.callbacks.getMyPeerId();\n const { reachableNodes } = message.routeUpdate;\n const timestamp = Date.now();\n\n const viaLatency = this.getDirectLatency(fromPeerId) ?? 100;\n\n for (const target of reachableNodes) {\n if (target === myPeerId) continue;\n\n let entry = this.routingTable.get(target);\n const totalLatency = viaLatency + 100;\n\n if (!entry) {\n entry = {\n target,\n nextHops: [],\n hops: 1,\n timestamp,\n };\n this.routingTable.set(target, entry);\n }\n\n const existingHop = entry.nextHops.find(h => h.nodeId === fromPeerId);\n if (existingHop) {\n existingHop.latency = totalLatency;\n } else {\n entry.nextHops.push({ nodeId: fromPeerId, latency: totalLatency });\n }\n\n entry.nextHops.sort((a, b) => a.latency - b.latency);\n entry.hops = Math.min(entry.hops, 1);\n entry.timestamp = timestamp;\n\n this.callbacks.debugLog('Routing', 'update', { target, nextHop: fromPeerId, latency: totalLatency });\n }\n }\n\n /**\n * \u6267\u884C\u8DEF\u7531\u53D1\u73B0\u5E7F\u64AD\n * \u5F53\u76F4\u8FDE\u548C\u8DEF\u7531\u8868\u90FD\u5931\u8D25\u65F6\uFF0C\u5411\u6240\u6709\u76F4\u8FDE\u8282\u70B9\u5E7F\u64AD\u8BE2\u95EE\u8C01\u80FD\u8FDE\u901A\u76EE\u6807\n * @param targetId \u76EE\u6807\u8282\u70B9 ID\n * @returns \u8DEF\u7531\u6761\u76EE\uFF08\u5982\u679C\u53D1\u73B0\uFF09\n */\n async discoverRoute(targetId: string): Promise<RouteEntry | null> {\n const myPeerId = this.callbacks.getMyPeerId();\n const directNodes = this.getDirectNodes();\n\n if (directNodes.length === 0) {\n this.callbacks.debugLog('Routing', 'discoverRoute', 'no direct nodes');\n return null;\n }\n\n this.callbacks.debugLog('Routing', 'discoverRoute', { targetId, directNodes: directNodes.length });\n\n const queryId = `${myPeerId}-query-${Date.now()}`;\n\n const routeEntry = await new Promise<RouteEntry | null>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pendingRouteQueries.delete(queryId);\n resolve(null);\n }, CONNECTION_TIMEOUT_MS);\n\n this.pendingRouteQueries.set(queryId, { resolve, reject, timer });\n\n const message: RelayMessage = {\n type: 'route-query',\n id: queryId,\n originalTarget: targetId,\n relayPath: [myPeerId],\n forwardPath: [],\n ttl: DEFAULT_TTL,\n routeQuery: {\n queryOrigin: myPeerId,\n targetNode: targetId,\n queryPath: [myPeerId],\n },\n };\n\n for (const node of directNodes) {\n this.callbacks.sendRelayMessage(node.nodeId, message).catch(() => {});\n }\n });\n\n return routeEntry;\n }\n\n /**\n * \u5904\u7406\u8DEF\u7531\u67E5\u8BE2\u6D88\u606F\n * @param fromPeerId \u53D1\u9001\u67E5\u8BE2\u7684\u8282\u70B9\n * @param message \u8DEF\u7531\u67E5\u8BE2\u6D88\u606F\n */\n handleRouteQuery(fromPeerId: string, message: RelayMessage): void {\n if (!message.routeQuery) return;\n\n const myPeerId = this.callbacks.getMyPeerId();\n const { queryOrigin, targetNode, queryPath } = message.routeQuery;\n\n if (targetNode === myPeerId) {\n const latency = this.getDirectLatency(fromPeerId) ?? 100;\n const response: RelayMessage = {\n type: 'route-response',\n id: `${myPeerId}-resp-${Date.now()}`,\n originalTarget: queryOrigin,\n relayPath: [],\n forwardPath: [],\n ttl: DEFAULT_TTL,\n routeResponse: {\n queryOrigin,\n responder: myPeerId,\n targetNode,\n latency,\n },\n };\n this.callbacks.sendRelayMessage(fromPeerId, response);\n return;\n }\n\n if (queryPath.includes(myPeerId)) {\n return;\n }\n\n const currentTTL = message.ttl ?? DEFAULT_TTL;\n if (currentTTL <= 0) {\n this.callbacks.debugLog('Routing', 'ttlExpired', { type: 'route-query', id: message.id });\n return;\n }\n\n const nextHop = this.findNextHopToTarget(targetNode);\n if (nextHop) {\n const latency = (this.getDirectLatency(fromPeerId) ?? 100) + nextHop.latency;\n const response: RelayMessage = {\n type: 'route-response',\n id: `${myPeerId}-resp-${Date.now()}`,\n originalTarget: queryOrigin,\n relayPath: [],\n forwardPath: [],\n ttl: DEFAULT_TTL,\n routeResponse: {\n queryOrigin,\n responder: myPeerId,\n targetNode,\n latency,\n },\n };\n this.callbacks.sendRelayMessage(fromPeerId, response);\n return;\n }\n\n const newPath = [...queryPath, myPeerId];\n const forwardMessage: RelayMessage = {\n ...message,\n relayPath: newPath,\n ttl: currentTTL - 1,\n routeQuery: {\n ...message.routeQuery,\n queryPath: newPath,\n },\n };\n\n for (const node of this.directNodes) {\n if (node.nodeId !== fromPeerId) {\n this.callbacks.sendRelayMessage(node.nodeId, forwardMessage).catch(() => {});\n }\n }\n }\n\n /**\n * \u5904\u7406\u8DEF\u7531\u67E5\u8BE2\u54CD\u5E94\n * @param fromPeerId \u54CD\u5E94\u8005\u8282\u70B9\n * @param message \u8DEF\u7531\u54CD\u5E94\u6D88\u606F\n */\n handleRouteResponse(fromPeerId: string, message: RelayMessage): void {\n if (!message.routeResponse) return;\n\n const { queryOrigin, targetNode, latency } = message.routeResponse;\n const myPeerId = this.callbacks.getMyPeerId();\n\n if (queryOrigin !== myPeerId) return;\n\n const pending = Array.from(this.pendingRouteQueries.values())[0];\n if (!pending) return;\n\n let entry = this.routingTable.get(targetNode);\n const timestamp = Date.now();\n\n if (!entry) {\n entry = {\n target: targetNode,\n nextHops: [],\n hops: 1,\n timestamp,\n };\n this.routingTable.set(targetNode, entry);\n }\n\n const existingHop = entry.nextHops.find(h => h.nodeId === fromPeerId);\n if (existingHop) {\n existingHop.latency = latency;\n } else {\n entry.nextHops.push({ nodeId: fromPeerId, latency });\n }\n\n entry.nextHops.sort((a, b) => a.latency - b.latency);\n entry.timestamp = timestamp;\n\n this.callbacks.debugLog('Routing', 'discovered', { targetNode, nextHop: fromPeerId, latency });\n\n clearTimeout(pending.timer);\n pending.resolve(entry);\n }\n\n /**\n * \u67E5\u627E\u5230\u76EE\u6807\u8282\u70B9\u7684\u4E0B\u4E00\u8DF3\n * @param targetId \u76EE\u6807\u8282\u70B9 ID\n * @returns \u4E0B\u4E00\u8DF3\u4FE1\u606F\uFF0C\u5982\u679C\u6CA1\u6709\u5219\u8FD4\u56DE null\n */\n findNextHopToTarget(targetId: string): NextHop | null {\n const entry = this.routingTable.get(targetId);\n if (!entry || entry.nextHops.length === 0) return null;\n return entry.nextHops[0];\n }\n\n /**\n * \u83B7\u53D6\u5230\u76EE\u6807\u8282\u70B9\u7684\u6240\u6709\u4E0B\u4E00\u8DF3\uFF08\u6309\u5EF6\u8FDF\u5347\u5E8F\uFF09\n * @param targetId \u76EE\u6807\u8282\u70B9 ID\n * @returns \u4E0B\u4E00\u8DF3\u5217\u8868\n */\n getNextHopsToTarget(targetId: string): NextHop[] {\n const entry = this.routingTable.get(targetId);\n return entry ? [...entry.nextHops] : [];\n }\n\n /**\n * \u83B7\u53D6\u8DEF\u7531\u8868\n * @returns \u8DEF\u7531\u8868\u5BF9\u8C61\n */\n getRoutingTable(): Record<string, RouteEntry> {\n const result: Record<string, RouteEntry> = {};\n this.routingTable.forEach((entry, target) => {\n result[target] = { ...entry, nextHops: [...entry.nextHops] };\n });\n return result;\n }\n\n /**\n * \u83B7\u53D6\u5DF2\u77E5\u8282\u70B9\u5217\u8868\uFF08\u517C\u5BB9\u65E7\u63A5\u53E3\uFF09\n * @returns \u8282\u70B9 ID \u6570\u7EC4\n */\n getKnownNodes(): string[] {\n return this.directNodes.map(n => n.nodeId);\n }\n}\n", "/**\n * MessageHandler - \u6D88\u606F\u5904\u7406\u6A21\u5757\n * \n * \u8D1F\u8D23\u5904\u7406\u63A5\u6536\u5230\u7684\u5404\u7C7B\u6D88\u606F\uFF1A\n * - \u76F4\u8FDE\u8BF7\u6C42\uFF08request\uFF09\n * - \u4E2D\u7EE7\u8BF7\u6C42\uFF08relay-request\uFF09\n * - \u8DEF\u7531\u66F4\u65B0\uFF08route-update\uFF09\n * \n * \u4E2D\u7EE7\u8BF7\u6C42\u5904\u7406\u6D41\u7A0B\uFF1A\n * 1. \u6536\u5230 relay-request \u6D88\u606F\n * 2. \u5982\u679C\u662F\u76EE\u6807\u8282\u70B9\uFF0C\u5904\u7406\u8BF7\u6C42\u5E76\u8FD4\u56DE\u54CD\u5E94\n * 3. \u5982\u679C\u4E0D\u662F\u76EE\u6807\u8282\u70B9\uFF0C\u6839\u636E forwardPath \u8F6C\u53D1\u5230\u4E0B\u4E00\u4E2A\u8282\u70B9\n * 4. \u5982\u679C forwardPath \u4E3A\u7A7A\uFF0C\u5C1D\u8BD5\u76F4\u8FDE\u5230\u76EE\u6807\u8282\u70B9\n * \n * @example\n * const handler = new MessageHandler(callbacks);\n * const response = await handler.handleRequest(from, request, relayMessage);\n */\n\nimport type { Peer } from 'peerjs';\nimport type { Request, Response, SimpleHandler, RelayMessage } from './types';\nimport { CONNECTION_TIMEOUT_MS, DEFAULT_TTL } from './constants';\n\n/**\n * \u6D88\u606F\u5904\u7406\u5668\u56DE\u8C03\u63A5\u53E3\n */\nexport interface MessageHandlerCallbacks {\n /** \u83B7\u53D6\u672C\u5730 Peer ID */\n getMyPeerId(): string;\n /** \u83B7\u53D6 PeerJS \u5B9E\u4F8B */\n getPeerInstance(): Peer | null;\n /** \u7B49\u5F85\u8FDE\u63A5\u5C31\u7EEA */\n waitForReady(): Promise<void>;\n /** \u83B7\u53D6\u5904\u7406\u5668\u6620\u5C04\u8868 */\n getSimpleHandlers(): Map<string, SimpleHandler>;\n /** \u8C03\u8BD5\u65E5\u5FD7\u51FD\u6570 */\n debugLog: (obj: string, event: string, data?: unknown) => void;\n /** \u8DEF\u7531\u66F4\u65B0\u56DE\u8C03\uFF08\u53EF\u9009\uFF09 */\n onRouteUpdate?: (fromPeerId: string, message: RelayMessage) => void;\n}\n\n/**\n * \u6D88\u606F\u5904\u7406\u5668\u7C7B\n * \u8D1F\u8D23\u89E3\u6790\u548C\u5904\u7406\u63A5\u6536\u5230\u7684\u5404\u7C7B\u6D88\u606F\n */\nexport class MessageHandler {\n /** \u56DE\u8C03\u51FD\u6570\u96C6\u5408 */\n private callbacks: MessageHandlerCallbacks;\n\n /**\n * \u521B\u5EFA\u6D88\u606F\u5904\u7406\u5668\n * @param callbacks \u56DE\u8C03\u51FD\u6570\u96C6\u5408\n */\n constructor(callbacks: MessageHandlerCallbacks) {\n this.callbacks = callbacks;\n }\n\n /**\n * \u5904\u7406\u6536\u5230\u7684\u8BF7\u6C42\n * \u6839\u636E\u662F\u5426\u6709\u4E2D\u7EE7\u6D88\u606F\u4E0A\u4E0B\u6587\u5224\u65AD\u662F\u76F4\u8FDE\u8BF7\u6C42\u8FD8\u662F\u4E2D\u7EE7\u8BF7\u6C42\n * @param from \u53D1\u9001\u8005 Peer ID\n * @param request \u8BF7\u6C42\u6570\u636E\n * @param relayMessage \u4E2D\u7EE7\u6D88\u606F\u4E0A\u4E0B\u6587\uFF08\u53EF\u9009\uFF0C\u6709\u5219\u4E3A\u4E2D\u7EE7\u8BF7\u6C42\uFF09\n * @returns \u54CD\u5E94\u6570\u636E\n */\n async handleRequest(from: string, request: Request, relayMessage?: RelayMessage): Promise<Response> {\n if (relayMessage) {\n return this.handleRelayRequest(from, request, relayMessage);\n }\n return this.handleDirectRequest(from, request);\n }\n\n /**\n * \u5904\u7406\u76F4\u8FDE\u8BF7\u6C42\n * @param from \u53D1\u9001\u8005 Peer ID\n * @param request \u8BF7\u6C42\u6570\u636E\n * @returns \u54CD\u5E94\u6570\u636E\n */\n private async handleDirectRequest(from: string, request: Request): Promise<Response> {\n const result = await this.processHandler(request.path, from, request.data);\n if (this.isErrorResponse(result)) {\n return result as Response;\n }\n return { status: 200, data: result };\n }\n\n /**\n * \u5904\u7406\u4E2D\u7EE7\u8BF7\u6C42\n * @param from \u53D1\u9001\u8005 Peer ID\n * @param request \u8BF7\u6C42\u6570\u636E\n * @param relayMessage \u4E2D\u7EE7\u6D88\u606F\u4E0A\u4E0B\u6587\n * @returns \u54CD\u5E94\u6570\u636E\n */\n private async handleRelayRequest(from: string, request: Request, relayMessage: RelayMessage): Promise<Response> {\n const myPeerId = this.callbacks.getMyPeerId();\n const { originalTarget, relayPath, forwardPath } = relayMessage;\n\n if (myPeerId === originalTarget) {\n const result = await this.processHandler(request.path, from, request.data);\n if (this.isErrorResponse(result)) {\n return result as Response;\n }\n return { status: 200, data: result };\n }\n\n const currentTTL = relayMessage.ttl ?? DEFAULT_TTL;\n if (currentTTL <= 0) {\n this.callbacks.debugLog('MessageHandler', 'ttlExpired', { type: 'relay-request', id: relayMessage.id });\n return {\n status: 502,\n data: { error: 'TTL expired - message dropped to prevent routing loop' },\n };\n }\n\n if (forwardPath.length > 0) {\n const nextHop = forwardPath[0];\n const remainingPath = forwardPath.slice(1);\n \n try {\n const response = await this.forwardRelay(nextHop, {\n type: 'relay-request',\n id: relayMessage.id,\n originalTarget,\n relayPath: [...relayPath, myPeerId],\n forwardPath: remainingPath,\n ttl: currentTTL - 1,\n request,\n });\n return response;\n } catch (err) {\n return {\n status: 500,\n data: { error: `Forward failed: ${err instanceof Error ? err.message : 'Unknown error'}` },\n };\n }\n }\n\n try {\n const data = await this.forwardToTarget(originalTarget, request, relayMessage);\n return { status: 200, data };\n } catch (err) {\n return {\n status: 500,\n data: { error: `Forward to target failed: ${err instanceof Error ? err.message : 'Unknown error'}` },\n };\n }\n }\n\n /**\n * \u8C03\u7528\u6CE8\u518C\u7684\u5904\u7406\u5668\n * @param path \u8BF7\u6C42\u8DEF\u5F84\n * @param from \u53D1\u9001\u8005 Peer ID\n * @param data \u8BF7\u6C42\u6570\u636E\n * @returns \u5904\u7406\u5668\u8FD4\u56DE\u7684\u6570\u636E\uFF0C\u6216 404 \u9519\u8BEF\n */\n async processHandler(path: string, from: string, data?: unknown): Promise<unknown> {\n const handlers = this.callbacks.getSimpleHandlers();\n const simpleHandler = handlers.get(path);\n if (simpleHandler) {\n return await simpleHandler(from, data);\n }\n // \u8FD4\u56DE 404 \u9519\u8BEF\u54CD\u5E94\u683C\u5F0F\n return { status: 404, data: { error: `Path not found: ${path}` } };\n }\n\n /**\n * \u5224\u65AD\u7ED3\u679C\u662F\u5426\u4E3A\u9519\u8BEF\u54CD\u5E94\n */\n private isErrorResponse(result: unknown): result is { status: number; data: unknown } {\n return typeof result === 'object' && result !== null && 'status' in result && 'data' in result;\n }\n\n /**\n * \u521B\u5EFA\u8FDE\u63A5\u5E76\u53D1\u9001\u4E2D\u7EE7\u6D88\u606F\u7684\u901A\u7528\u65B9\u6CD5\n * @param targetId \u76EE\u6807\u8282\u70B9 ID\n * @param message \u8981\u53D1\u9001\u7684\u6D88\u606F\n * @param extractResponse \u4ECE\u54CD\u5E94\u6D88\u606F\u4E2D\u63D0\u53D6\u6570\u636E\u7684\u51FD\u6570\n * @returns Promise<Response>\n */\n private createConnectionAndSend(\n targetId: string,\n message: RelayMessage,\n extractResponse: (response: RelayMessage) => Response | null\n ): Promise<Response> {\n return new Promise((resolve, reject) => {\n this.callbacks.debugLog('MessageHandler', 'createConnectionAndSend', { targetId });\n\n this.callbacks.waitForReady()\n .then(() => {\n const peerInstance = this.callbacks.getPeerInstance();\n if (!peerInstance) {\n reject(new Error('Peer instance not available'));\n return;\n }\n\n const conn = peerInstance.connect(targetId, { reliable: true });\n\n const timeout = setTimeout(() => {\n conn.close();\n reject(new Error(`Connection timeout: ${targetId}`));\n }, CONNECTION_TIMEOUT_MS);\n\n conn.on('open', () => {\n this.callbacks.debugLog('Conn', 'open', targetId);\n conn.send(message);\n });\n\n conn.on('data', (responseData: unknown) => {\n const response = responseData as RelayMessage;\n const extracted = extractResponse(response);\n if (extracted) {\n clearTimeout(timeout);\n conn.close();\n resolve(extracted);\n }\n });\n\n conn.on('error', (err) => {\n this.callbacks.debugLog('Conn', 'error', { peer: targetId, error: err });\n clearTimeout(timeout);\n reject(err);\n });\n\n conn.on('close', () => {\n this.callbacks.debugLog('Conn', 'close', targetId);\n clearTimeout(timeout);\n reject(new Error('Connection closed'));\n });\n })\n .catch(reject);\n });\n }\n\n /**\n * \u8F6C\u53D1\u4E2D\u7EE7\u8BF7\u6C42\u5230\u4E0B\u4E00\u4E2A\u8282\u70B9\n * @param nextHop \u4E0B\u4E00\u8DF3\u8282\u70B9 ID\n * @param message \u8981\u8F6C\u53D1\u7684\u6D88\u606F\n * @returns \u54CD\u5E94\u6570\u636E\n */\n private async forwardRelay(nextHop: string, message: RelayMessage): Promise<Response> {\n return this.createConnectionAndSend(\n nextHop,\n message,\n (response) => {\n if (response.type === 'relay-response' && response.response) {\n return response.response;\n }\n return null;\n }\n );\n }\n\n /**\n * \u8F6C\u53D1\u5230\u6700\u7EC8\u76EE\u6807\u8282\u70B9\uFF08\u5F53\u6CA1\u6709\u66F4\u591A\u4E2D\u7EE7\u8282\u70B9\u65F6\u4F7F\u7528\uFF09\n * @param targetId \u76EE\u6807\u8282\u70B9 ID\n * @param request \u8BF7\u6C42\u6570\u636E\n * @param originalMessage \u539F\u59CB\u4E2D\u7EE7\u6D88\u606F\n * @returns \u54CD\u5E94\u6570\u636E\n */\n private async forwardToTarget(targetId: string, request: Request, originalMessage: RelayMessage): Promise<unknown> {\n const myPeerId = this.callbacks.getMyPeerId();\n const currentTTL = originalMessage.ttl ?? DEFAULT_TTL;\n \n const message: RelayMessage = {\n type: 'relay-request',\n id: originalMessage.id,\n originalTarget: originalMessage.originalTarget,\n relayPath: [...originalMessage.relayPath, myPeerId],\n forwardPath: [],\n ttl: currentTTL - 1,\n request,\n };\n\n const response = await this.createConnectionAndSend(\n targetId,\n message,\n (resp) => {\n if (resp.type === 'relay-response' && resp.response) {\n return resp.response;\n }\n return null;\n }\n );\n\n return response.data;\n }\n}\n", "/**\n * PeerJsWrapper - \u5C01\u88C5 PeerJS \u4E3A\u7C7B\u4F3C HTTP \u7684 API\n * \n * \u6838\u5FC3\u529F\u80FD\uFF1A\n * 1. \u7C7B\u4F3C HTTP \u7684\u8BF7\u6C42/\u54CD\u5E94\u673A\u5236\uFF08send/relaySend\uFF09\n * 2. \u8BED\u97F3/\u89C6\u9891\u901A\u8BDD\uFF08call/onIncomingCall\uFF09\n * 3. \u4E2D\u7EE7\u8DEF\u7531\uFF08relaySend/getRoutingTable/getKnownNodes\uFF09\n * \n * @example\n * // \u57FA\u672C\u8BF7\u6C42\n * const wrapper = new PeerJsWrapper();\n * const data = await wrapper.send(peerId, '/api/hello', { name: 'world' });\n * \n * // \u4E2D\u7EE7\u8BF7\u6C42\n * await wrapper.relaySend(targetId, '/api/data', 'test', ['relayNode1', 'relayNode2']);\n * \n * // \u8BED\u97F3\u901A\u8BDD\n * const call = await wrapper.call(peerId, { video: true });\n */\n\nimport { Peer, DataConnection, MediaConnection } from 'peerjs';\nimport { CallSessionImpl } from './CallSession';\nimport { Router } from './Router';\nimport { MessageHandler } from './MessageHandler';\nimport {\n CONNECTION_TIMEOUT_MS,\n SEND_TIMEOUT_MS,\n RECONNECT_DELAY_MS,\n DEFAULT_TTL,\n} from './constants';\nimport type {\n Request,\n Response,\n SimpleHandler,\n CallOptions,\n CallSession,\n CallState,\n CallStateListener,\n IncomingCallEvent,\n IncomingCallListener,\n RouteEntry,\n RelayConfig,\n RelayMessage,\n ServerConfig\n} from './types';\n\n/** \u7248\u672C\u53F7\uFF08\u6784\u5EFA\u65F6\u6CE8\u5165\uFF09 */\ndeclare const __VERSION__: string;\nexport const VERSION = __VERSION__;\nconsole.log(`[sx-peerjs-http-util] v${VERSION}`);\n\n/**\n * \u751F\u6210 UUID v4\n */\nfunction generateUUID(): string {\n return crypto.randomUUID();\n}\n\n/**\n * \u5F85\u5904\u7406\u7684\u8BF7\u6C42\n */\ninterface PendingRequest {\n /** \u6210\u529F\u56DE\u8C03 */\n resolve: (data: unknown) => void;\n /** \u5931\u8D25\u56DE\u8C03 */\n reject: (error: Error) => void;\n /** \u8D85\u65F6\u5B9A\u65F6\u5668 */\n timeout: ReturnType<typeof setTimeout>;\n}\n\n/**\n * \u5185\u90E8\u6D88\u606F\u683C\u5F0F\uFF08\u7528\u4E8E\u76F4\u8FDE\u8BF7\u6C42\uFF09\n */\ninterface InternalMessage {\n /** \u6D88\u606F\u7C7B\u578B */\n type: 'request' | 'response';\n /** \u6D88\u606F ID\uFF0C\u7528\u4E8E\u5339\u914D\u8BF7\u6C42\u548C\u54CD\u5E94 */\n id: string;\n /** \u8BF7\u6C42\u6570\u636E */\n request?: Request;\n /** \u54CD\u5E94\u6570\u636E */\n response?: Response;\n}\n\n/**\n * PeerJsWrapper \u4E3B\u7C7B\n * \u5C01\u88C5 PeerJS\uFF0C\u63D0\u4F9B\u7C7B\u4F3C HTTP \u7684 API\n */\nexport class PeerJsWrapper {\n /** \u672C\u5730 Peer ID */\n private myPeerId: string;\n /** PeerJS \u5B9E\u4F8B */\n private peerInstance: Peer | null = null;\n /** \u5F53\u524D\u6D3B\u8DC3\u7684\u4F20\u5165\u8FDE\u63A5\u96C6\u5408 */\n private connections = new Set<DataConnection>();\n /** \u5F85\u5904\u7406\u7684\u8BF7\u6C42\u6620\u5C04\u8868\uFF08\u7528\u4E8E\u8BF7\u6C42-\u54CD\u5E94\u5339\u914D\uFF09 */\n private pendingRequests = new Map<string, PendingRequest>();\n /** \u8DEF\u5F84\u5904\u7406\u5668\u6620\u5C04\u8868 */\n private simpleHandlers = new Map<string, SimpleHandler>();\n /** \u91CD\u8FDE\u5B9A\u65F6\u5668 */\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n /** \u662F\u5426\u5DF2\u9500\u6BC1 */\n private isDestroyed = false;\n /** \u662F\u5426\u5F00\u542F\u8C03\u8BD5\u6A21\u5F0F */\n private isDebug: boolean;\n /** \u670D\u52A1\u5668\u914D\u7F6E */\n private serverConfig?: ServerConfig;\n /** \u5F53\u524D\u6D3B\u8DC3\u7684\u901A\u8BDD */\n private activeCall: CallSessionImpl | null = null;\n /** \u6765\u7535\u76D1\u542C\u5668\u96C6\u5408 */\n private incomingCallListeners = new Set<IncomingCallListener>();\n\n /** \u8DEF\u7531\u7BA1\u7406\u5668 */\n private router: Router;\n /** \u6D88\u606F\u5904\u7406\u5668 */\n private messageHandler: MessageHandler;\n\n /**\n * \u521B\u5EFA PeerJsWrapper \u5B9E\u4F8B\n * @param peerId \u53EF\u9009\u7684 Peer ID\uFF0C\u5982\u679C\u4E0D\u63D0\u4F9B\u5219\u81EA\u52A8\u751F\u6210 UUID\n * @param isDebug \u662F\u5426\u5F00\u542F\u8C03\u8BD5\u6A21\u5F0F\uFF0C\u5F00\u542F\u540E\u4F1A\u6253\u5370\u4E8B\u4EF6\u65E5\u5FD7\n * @param server \u53EF\u9009\u7684\u4FE1\u4EE4\u670D\u52A1\u5668\u914D\u7F6E\uFF0C\u4E0D\u63D0\u4F9B\u5219\u4F7F\u7528 PeerJS \u516C\u5171\u670D\u52A1\u5668\n * @param relayConfig \u53EF\u9009\u7684\u4E2D\u7EE7\u914D\u7F6E\n */\n constructor(peerId?: string, isDebug?: boolean, server?: ServerConfig, relayConfig?: RelayConfig) {\n this.myPeerId = peerId || generateUUID();\n this.isDebug = isDebug ?? false;\n this.serverConfig = server;\n\n const callbacks = {\n getMyPeerId: () => this.myPeerId,\n getPeerInstance: () => this.peerInstance,\n debugLog: this.debugLog.bind(this),\n sendRelayMessage: (targetId: string, message: RelayMessage) => this.sendRelayMessage(targetId, message),\n };\n\n this.router = new Router(callbacks, relayConfig);\n this.router.init();\n this.messageHandler = new MessageHandler({\n ...callbacks,\n waitForReady: () => this.waitForReady(),\n getSimpleHandlers: () => this.simpleHandlers,\n onRouteUpdate: (fromPeerId, message) => this.router.handleRouteUpdate(fromPeerId, message),\n });\n\n this.connect();\n }\n\n /**\n * \u521B\u5EFA\u5B9E\u4F8B\u5E76\u7B49\u5F85\u5C31\u7EEA\uFF08\u8BED\u6CD5\u7CD6\uFF09\n * @param peerId \u53EF\u9009\u7684 Peer ID\n * @param isDebug \u662F\u5426\u5F00\u542F\u8C03\u8BD5\u6A21\u5F0F\n * @param server \u53EF\u9009\u7684\u4FE1\u4EE4\u670D\u52A1\u5668\u914D\u7F6E\n * @param relayConfig \u53EF\u9009\u7684\u4E2D\u7EE7\u914D\u7F6E\n * @returns Promise<PeerJsWrapper>\n */\n static async create(\n peerId?: string,\n isDebug?: boolean,\n server?: ServerConfig,\n relayConfig?: RelayConfig\n ): Promise<PeerJsWrapper> {\n const wrapper = new PeerJsWrapper(peerId, isDebug, server, relayConfig);\n await wrapper.whenReady();\n return wrapper;\n }\n\n private debugLog(obj: string, event: string, data?: unknown): void {\n if (this.isDebug) {\n console.log(obj, event, data);\n }\n }\n\n private connect(): void {\n if (this.isDestroyed) return;\n\n this.peerInstance = this.serverConfig\n ? new Peer(this.myPeerId, { ...this.serverConfig })\n : new Peer(this.myPeerId);\n\n this.setupPeerEventHandlers();\n }\n\n private setupPeerEventHandlers(): void {\n if (!this.peerInstance) return;\n\n this.peerInstance.on('open', (id) => {\n this.debugLog('Peer', 'open', id);\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n });\n\n this.peerInstance.on('disconnected', () => {\n this.debugLog('Peer', 'disconnected');\n this.scheduleReconnect();\n });\n\n this.peerInstance.on('error', (err) => {\n this.debugLog('Peer', 'error', { type: err.type, message: err.message });\n if (\n err.type === 'network' ||\n err.type === 'server-error' ||\n err.type === 'socket-error' ||\n err.type === 'socket-closed'\n ) {\n this.scheduleReconnect();\n }\n });\n\n this.peerInstance.on('close', () => {\n this.debugLog('Peer', 'close');\n });\n\n this.peerInstance.on('call', (mediaConnection: MediaConnection) => {\n this.handleIncomingCall(mediaConnection);\n });\n\n this.setupIncomingConnectionHandler();\n }\n\n private scheduleReconnect(): void {\n if (this.isDestroyed) return;\n if (this.reconnectTimer) return;\n\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n this.reconnect();\n }, RECONNECT_DELAY_MS);\n }\n\n private reconnect(): void {\n if (this.isDestroyed) return;\n this.debugLog('PeerJsWrapper', 'reconnect');\n\n if (this.peerInstance) {\n try {\n this.peerInstance.destroy();\n } catch {\n // ignore\n }\n this.peerInstance = null;\n }\n\n this.connect();\n }\n\n getPeerId(): string {\n return this.myPeerId;\n }\n\n private whenReady(): Promise<void> {\n return this.waitForReady();\n }\n\n private waitForReady(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!this.peerInstance) {\n reject(new Error('Peer instance not initialized'));\n return;\n }\n\n if (this.peerInstance.open) {\n resolve();\n return;\n }\n\n const onOpen = () => {\n this.peerInstance?.off('open', onOpen);\n this.peerInstance?.off('error', onError);\n resolve();\n };\n\n const onError = (err: Error) => {\n this.peerInstance?.off('open', onOpen);\n this.peerInstance?.off('error', onError);\n reject(err);\n };\n\n this.peerInstance.on('open', onOpen);\n this.peerInstance.on('error', onError);\n });\n }\n\n getRoutingTable(): Record<string, RouteEntry> {\n return this.router.getRoutingTable();\n }\n\n getKnownNodes(): string[] {\n return this.router.getKnownNodes();\n }\n\n /**\n * \u53D1\u9001\u4E2D\u7EE7\u6D88\u606F\u7684\u8F85\u52A9\u65B9\u6CD5\n * @param targetId \u76EE\u6807\u8282\u70B9 ID\n * @param message \u4E2D\u7EE7\u6D88\u606F\n */\n private sendRelayMessage(targetId: string, message: RelayMessage): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!this.peerInstance) {\n reject(new Error('Peer instance not available'));\n return;\n }\n\n const conn = this.peerInstance.connect(targetId, { reliable: true });\n const timeout = setTimeout(() => {\n conn.close();\n reject(new Error(`Send to ${targetId} timeout`));\n }, SEND_TIMEOUT_MS);\n\n conn.on('open', () => {\n conn.send(message);\n clearTimeout(timeout);\n conn.close();\n resolve();\n });\n\n conn.on('error', () => {\n clearTimeout(timeout);\n reject(new Error(`Send to ${targetId} failed`));\n });\n\n conn.on('close', () => {\n clearTimeout(timeout);\n resolve();\n });\n });\n }\n\n /**\n * \u5C1D\u8BD5\u76F4\u8FDE\u76EE\u6807\u8282\u70B9\n * @param targetId \u76EE\u6807\u8282\u70B9 ID\n * @param path \u8BF7\u6C42\u8DEF\u5F84\n * @param data \u8BF7\u6C42\u6570\u636E\n * @param requestId \u8BF7\u6C42 ID\n * @returns Promise<unknown> - \u54CD\u5E94\u6570\u636E\n */\n private tryDirectConnect(targetId: string, path: string, data: unknown, requestId: string): Promise<unknown> {\n return new Promise((resolve, reject) => {\n if (!this.peerInstance) {\n reject(new Error('Peer instance not available'));\n return;\n }\n\n const startTime = Date.now();\n const conn = this.peerInstance.connect(targetId, { reliable: true });\n let resolved = false;\n\n const timeout = setTimeout(() => {\n if (!resolved) {\n resolved = true;\n conn.close();\n reject(new Error(`Request timeout: ${targetId}${path}`));\n }\n }, CONNECTION_TIMEOUT_MS);\n\n conn.on('open', () => {\n const latency = Date.now() - startTime;\n this.debugLog('Conn', 'open', { peer: targetId, latency });\n\n const request: Request = { path, data };\n const message: InternalMessage = {\n type: 'request',\n id: requestId,\n request,\n };\n conn.send(message);\n });\n\n conn.on('data', (responseData: unknown) => {\n this.debugLog('Conn', 'data', { peer: targetId, data: responseData });\n const message = responseData as InternalMessage;\n if (message.type === 'response' && message.id === requestId) {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n\n const response = message.response!;\n if (response.status < 200 || response.status >= 300) {\n conn.close();\n reject(new Error(`Request failed: ${response.status} ${JSON.stringify(response.data)}`));\n } else {\n const latency = Date.now() - startTime;\n this.router.recordDirectNode(targetId, latency);\n this.router.broadcastRouteUpdate();\n resolve(response.data);\n }\n }\n }\n });\n\n conn.on('error', (err) => {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n this.debugLog('Conn', 'error', { peer: targetId, error: err });\n reject(err);\n }\n });\n\n conn.on('close', () => {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n this.debugLog('Conn', 'close', targetId);\n reject(new Error('Connection closed'));\n }\n });\n });\n }\n\n /**\n * \u901A\u8FC7\u4E2D\u7EE7\u8282\u70B9\u8F6C\u53D1\u8BF7\u6C42\n * @param nextHopId \u4E0B\u4E00\u8DF3\u8282\u70B9 ID\n * @param targetId \u539F\u59CB\u76EE\u6807\u8282\u70B9 ID\n * @param path \u8BF7\u6C42\u8DEF\u5F84\n * @param data \u8BF7\u6C42\u6570\u636E\n * @returns Promise<unknown> - \u54CD\u5E94\u6570\u636E\n */\n private relayVia(nextHopId: string, targetId: string, path: string, data: unknown): Promise<unknown> {\n return new Promise((resolve, reject) => {\n this.debugLog('PeerJsWrapper', 'relayVia', { targetId, nextHop: nextHopId });\n\n this.waitForReady()\n .then(() => {\n if (!this.peerInstance) {\n reject(new Error('Peer instance not available'));\n return;\n }\n\n const conn = this.peerInstance.connect(nextHopId, { reliable: true });\n const startTime = Date.now();\n\n const timeout = setTimeout(() => {\n conn.close();\n reject(new Error(`Relay timeout: ${nextHopId}${path}`));\n }, CONNECTION_TIMEOUT_MS);\n\n conn.on('open', () => {\n this.debugLog('Conn', 'open', nextHopId);\n\n const request: Request = { path, data };\n const message: RelayMessage = {\n type: 'relay-request',\n id: `${this.myPeerId}-${Date.now()}-${Math.random()}`,\n originalTarget: targetId,\n relayPath: [this.myPeerId],\n forwardPath: [],\n ttl: DEFAULT_TTL,\n request,\n };\n conn.send(message);\n });\n\n conn.on('data', (responseData: unknown) => {\n const message = responseData as RelayMessage;\n\n if (message.type === 'relay-response') {\n clearTimeout(timeout);\n conn.close();\n\n const response = message.response;\n if (response) {\n if (response.status < 200 || response.status >= 300) {\n reject(new Error(`Relay failed: ${response.status} ${JSON.stringify(response.data)}`));\n } else {\n const latency = Date.now() - startTime;\n this.router.recordDirectNode(nextHopId, latency);\n this.router.broadcastRouteUpdate();\n resolve(response.data);\n }\n }\n } else if (message.type === 'route-update') {\n this.router.handleRouteUpdate(nextHopId, message);\n } else if (message.type === 'route-query') {\n this.router.handleRouteQuery(nextHopId, message);\n } else if (message.type === 'route-response') {\n this.router.handleRouteResponse(nextHopId, message);\n }\n });\n\n conn.on('error', (err) => {\n this.debugLog('Conn', 'error', { peer: nextHopId, error: err });\n clearTimeout(timeout);\n reject(err);\n });\n\n conn.on('close', () => {\n this.debugLog('Conn', 'close', nextHopId);\n clearTimeout(timeout);\n reject(new Error('Relay connection closed'));\n });\n })\n .catch(reject);\n });\n }\n\n /**\n * \u81EA\u52A8\u8DEF\u7531\u53D1\u9001\n * \n * 1. \u67E5\u8DEF\u7531\u8868 \u2192 \u6709\u8DEF\u7531 \u2192 \u5C1D\u8BD5\u4E2D\u7EE7 \u2192 \u5168\u90E8\u5931\u8D25 \u2192 \u964D\u7EA7\u76F4\u8FDE \u2192 \u5931\u8D25 \u2192 \u7ED3\u675F\n * 2. \u8DEF\u7531\u8868\u65E0\u76EE\u6807 \u2192 \u76F4\u8FDE \u2192 \u5931\u8D25 \u2192 \u7ED3\u675F\n * @param peerId \u76EE\u6807\u8282\u70B9 ID\n * @param path \u8BF7\u6C42\u8DEF\u5F84\n * @param data \u8BF7\u6C42\u6570\u636E\n * @returns Promise<unknown> - \u54CD\u5E94\u6570\u636E\n */\n send(peerId: string, path: string, data?: unknown): Promise<unknown> {\n const requestId = `${this.myPeerId}-${Date.now()}-${Math.random()}`;\n return new Promise((resolve, reject) => {\n this.debugLog('PeerJsWrapper', 'send', { peerId, path, data });\n\n const nextHops = this.router.getNextHopsToTarget(peerId);\n\n if (nextHops.length > 0) {\n this.tryRelayChain(peerId, path, data, nextHops, 0)\n .then(resolve)\n .catch((relayErr) => {\n this.debugLog('PeerJsWrapper', 'relayFailed', { peerId, error: relayErr.message });\n this.fallbackToDirect(peerId, path, data, requestId)\n .then(resolve)\n .catch(reject);\n });\n } else {\n this.tryDirectConnect(peerId, path, data, requestId)\n .then(resolve)\n .catch((directErr) => {\n this.debugLog('PeerJsWrapper', 'directFailed', { peerId, error: directErr.message });\n this.handleSendError(peerId, directErr)\n .then(resolve)\n .catch(reject);\n });\n }\n });\n }\n\n /**\n * \u5904\u7406\u53D1\u9001\u9519\u8BEF\n * @param peerId \u76EE\u6807\u8282\u70B9 ID\n * @param error \u9519\u8BEF\u5BF9\u8C61\n * @returns Promise\n */\n private async handleSendError(peerId: string, error: Error): Promise<unknown> {\n const errorMsg = error.message;\n const isHttpError = errorMsg.includes('Request failed:') || errorMsg.includes('404') || errorMsg.includes('500');\n const isConnectionError = errorMsg.includes('timeout') || errorMsg.includes('Connection closed') || errorMsg.includes('Peer instance not available');\n\n if (isHttpError) {\n throw error;\n }\n\n if (!isConnectionError) {\n throw error;\n }\n\n this.router.removeRoute(peerId);\n this.debugLog('PeerJsWrapper', 'routeRemoved', peerId);\n\n if (!this.router.isRoutingTableEmpty()) {\n return this.performRouteDiscovery(peerId, '', undefined, '');\n }\n\n throw new Error(`Cannot reach ${peerId}: no route found and routing table is empty`);\n }\n\n /**\n * \u964D\u7EA7\u5230\u76F4\u8FDE\u5C1D\u8BD5\n * @param peerId \u76EE\u6807\u8282\u70B9 ID\n * @param path \u8BF7\u6C42\u8DEF\u5F84\n * @param data \u8BF7\u6C42\u6570\u636E\n * @param requestId \u8BF7\u6C42 ID\n * @returns Promise\n */\n private async fallbackToDirect(peerId: string, path: string, data: unknown, requestId: string): Promise<unknown> {\n this.debugLog('PeerJsWrapper', 'fallbackToDirect', peerId);\n\n return this.tryDirectConnect(peerId, path, data, requestId)\n .catch((directErr) => {\n this.debugLog('PeerJsWrapper', 'directFailed', { peerId, error: directErr.message });\n this.handleSendError(peerId, directErr);\n });\n }\n\n /**\n * \u5C1D\u8BD5\u901A\u8FC7\u4E2D\u7EE7\u94FE\u8F6C\u53D1\n * @param targetId \u76EE\u6807\u8282\u70B9 ID\n * @param path \u8BF7\u6C42\u8DEF\u5F84\n * @param data \u8BF7\u6C42\u6570\u636E\n * @param nextHops \u4E0B\u4E00\u8DF3\u5217\u8868\n * @param index \u5F53\u524D\u5C1D\u8BD5\u7684\u4E0B\u4E00\u8DF3\u7D22\u5F15\n * @returns Promise<unknown>\n */\n private tryRelayChain(targetId: string, path: string, data: unknown, nextHops: { nodeId: string; latency: number }[], index: number): Promise<unknown> {\n if (index >= nextHops.length) {\n return Promise.reject(new Error('All relay nodes failed'));\n }\n\n const nextHop = nextHops[index];\n this.debugLog('PeerJsWrapper', 'tryRelay', { targetId, nextHop: nextHop.nodeId, latency: nextHop.latency });\n\n return this.relayVia(nextHop.nodeId, targetId, path, data).catch(() => {\n return this.tryRelayChain(targetId, path, data, nextHops, index + 1);\n });\n }\n\n /**\n * \u6267\u884C\u8DEF\u7531\u53D1\u73B0\n * @param targetId \u76EE\u6807\u8282\u70B9 ID\n * @param path \u8BF7\u6C42\u8DEF\u5F84\n * @param data \u8BF7\u6C42\u6570\u636E\n * @param requestId \u8BF7\u6C42 ID\n * @returns Promise<unknown>\n */\n private async performRouteDiscovery(targetId: string, path: string, data: unknown, requestId: string): Promise<unknown> {\n this.debugLog('PeerJsWrapper', 'routeDiscovery', { targetId });\n\n const routeEntry = await this.router.discoverRoute(targetId);\n\n if (!routeEntry || routeEntry.nextHops.length === 0) {\n throw new Error(`Cannot reach ${targetId}: no route found`);\n }\n\n this.debugLog('PeerJsWrapper', 'routeFound', { targetId, nextHops: routeEntry.nextHops });\n\n return this.tryRelayChain(targetId, path, data, routeEntry.nextHops, 0);\n }\n\n /**\n * \u4E2D\u7EE7\u53D1\u9001\uFF08\u5185\u90E8\u65B9\u6CD5\uFF0C\u4E0D\u5BF9\u5916\u66B4\u9732\uFF09\n * @param targetId \u76EE\u6807\u8282\u70B9 ID\n * @param path \u8BF7\u6C42\u8DEF\u5F84\n * @param data \u8BF7\u6C42\u6570\u636E\n * @param relayNodes \u624B\u52A8\u6307\u5B9A\u7684\u4E2D\u7EE7\u8282\u70B9\uFF08\u53EF\u9009\uFF0C\u4E0D\u6307\u5B9A\u5219\u81EA\u52A8\u8DEF\u7531\uFF09\n * @returns Promise<unknown>\n */\n private relaySend(targetId: string, path: string, data: unknown, relayNodes?: string[]): Promise<unknown> {\n if (!relayNodes || relayNodes.length === 0) {\n return this.send(targetId, path, data);\n }\n\n const [firstRelay, ...remainingRelays] = relayNodes;\n\n return new Promise((resolve, reject) => {\n this.debugLog('PeerJsWrapper', 'relaySend', { targetId, firstRelay, remainingRelays });\n\n this.waitForReady()\n .then(() => {\n if (!this.peerInstance) {\n reject(new Error('Peer instance not available'));\n return;\n }\n\n const conn = this.peerInstance.connect(firstRelay, { reliable: true });\n\n const timeout = setTimeout(() => {\n conn.close();\n reject(new Error(`Relay timeout: ${firstRelay}${path}`));\n }, CONNECTION_TIMEOUT_MS);\n\n conn.on('open', () => {\n this.debugLog('Conn', 'open', firstRelay);\n\n const request: Request = { path, data };\n const message: RelayMessage = {\n type: 'relay-request',\n id: `${this.myPeerId}-${Date.now()}-${Math.random()}`,\n originalTarget: targetId,\n relayPath: [],\n forwardPath: remainingRelays,\n ttl: DEFAULT_TTL,\n request,\n };\n conn.send(message);\n });\n\n conn.on('data', (responseData: unknown) => {\n const message = responseData as RelayMessage;\n\n if (message.type === 'relay-response') {\n clearTimeout(timeout);\n conn.close();\n\n const response = message.response;\n if (response) {\n if (response.status < 200 || response.status >= 300) {\n reject(new Error(`Relay failed: ${response.status} ${JSON.stringify(response.data)}`));\n } else {\n this.router.recordSuccessfulNode(firstRelay);\n this.router.broadcastRouteUpdate();\n resolve(response.data);\n }\n }\n } else if (message.type === 'route-update') {\n this.router.handleRouteUpdate(firstRelay, message);\n }\n });\n\n conn.on('error', (err) => {\n this.debugLog('Conn', 'error', { peer: firstRelay, error: err });\n clearTimeout(timeout);\n reject(err);\n });\n\n conn.on('close', () => {\n this.debugLog('Conn', 'close', firstRelay);\n clearTimeout(timeout);\n reject(new Error('Relay connection closed'));\n });\n })\n .catch(reject);\n });\n }\n\n private setupIncomingConnectionHandler(): void {\n if (!this.peerInstance) return;\n\n this.peerInstance.on('connection', (conn: DataConnection) => {\n this.debugLog('Peer', 'connection', conn.peer);\n this.connections.add(conn);\n\n conn.on('open', () => {\n this.debugLog('Conn', 'open', conn.peer);\n });\n\n conn.on('data', async (data: unknown) => {\n this.debugLog('Conn', 'data', { peer: conn.peer, data });\n\n const message = data as RelayMessage | InternalMessage;\n\n if (message.type === 'request') {\n const internalMsg = message as InternalMessage;\n if (internalMsg.request) {\n try {\n const response = await this.messageHandler.handleRequest(conn.peer, internalMsg.request);\n\n const responseMessage: InternalMessage = {\n type: 'response',\n id: internalMsg.id,\n response,\n };\n\n conn.send(responseMessage);\n } catch (error) {\n const errorResponse: InternalMessage = {\n type: 'response',\n id: internalMsg.id,\n response: {\n status: 500,\n data: { error: error instanceof Error ? error.message : 'Unknown error' },\n },\n };\n\n conn.send(errorResponse);\n }\n }\n } else if (message.type === 'relay-request') {\n const relayMsg = message as RelayMessage;\n if (relayMsg.request) {\n try {\n const response = await this.messageHandler.handleRequest(conn.peer, relayMsg.request, relayMsg);\n\n const responseMessage: RelayMessage = {\n type: 'relay-response',\n id: relayMsg.id,\n originalTarget: relayMsg.originalTarget,\n relayPath: relayMsg.relayPath,\n forwardPath: [],\n response,\n };\n\n conn.send(responseMessage);\n } catch (error) {\n const errorResponse: RelayMessage = {\n type: 'relay-response',\n id: relayMsg.id,\n originalTarget: relayMsg.originalTarget,\n relayPath: relayMsg.relayPath,\n forwardPath: [],\n response: {\n status: 500,\n data: { error: error instanceof Error ? error.message : 'Unknown error' },\n },\n };\n\n conn.send(errorResponse);\n }\n }\n } else if (message.type === 'route-update') {\n this.router.handleRouteUpdate(conn.peer, message as RelayMessage);\n }\n });\n\n conn.on('close', () => {\n this.debugLog('Conn', 'close', conn.peer);\n this.connections.delete(conn);\n });\n\n conn.on('error', (err) => {\n this.debugLog('Conn', 'error', { peer: conn.peer, error: err });\n this.connections.delete(conn);\n });\n });\n }\n\n call(peerId: string, options?: CallOptions): Promise<CallSession> {\n return new Promise((resolve, reject) => {\n this.debugLog('PeerJsWrapper', 'call', { peerId, options });\n\n if (this.activeCall) {\n reject(new Error('Already in a call'));\n return;\n }\n\n this.waitForReady()\n .then(async () => {\n if (!this.peerInstance) {\n reject(new Error('Peer instance not available'));\n return;\n }\n\n const hasVideo = options?.video ?? false;\n\n let localStream: MediaStream;\n try {\n localStream = await navigator.mediaDevices.getUserMedia({\n audio: true,\n video: hasVideo\n });\n } catch (err) {\n reject(new Error(`Failed to get media: ${err instanceof Error ? err.message : err}`));\n return;\n }\n\n const mediaConnection = this.peerInstance.call(peerId, localStream, {\n metadata: {\n video: hasVideo,\n custom: options?.metadata\n }\n });\n\n const session = new CallSessionImpl(\n peerId,\n mediaConnection,\n hasVideo,\n this.debugLog.bind(this),\n this.cleanupCall.bind(this)\n );\n session.setLocalStream(localStream);\n\n this.setupMediaConnectionHandlers(session, mediaConnection);\n\n this.activeCall = session;\n\n const timeout = setTimeout(() => {\n if (!session.isConnected) {\n session.hangUp();\n reject(new Error('Call timeout - no answer'));\n }\n }, 30000);\n\n const onConnected = () => {\n clearTimeout(timeout);\n session.offStateChange(onConnected);\n session.offStateChange(onEnded);\n resolve(session);\n };\n\n const onEnded = (state: CallState, reason?: string) => {\n clearTimeout(timeout);\n session.offStateChange(onConnected);\n session.offStateChange(onEnded);\n if (state === 'ended') {\n reject(new Error(reason || 'Call ended before connected'));\n }\n };\n\n session.onStateChange(onConnected);\n session.onStateChange(onEnded);\n })\n .catch(reject);\n });\n }\n\n onIncomingCall(listener: IncomingCallListener): void {\n this.incomingCallListeners.add(listener);\n }\n\n offIncomingCall(listener: IncomingCallListener): void {\n this.incomingCallListeners.delete(listener);\n }\n\n getActiveCall(): CallSession | null {\n return this.activeCall;\n }\n\n private setupMediaConnectionHandlers(session: CallSessionImpl, mediaConnection: MediaConnection): void {\n mediaConnection.on('stream', (remoteStream: MediaStream) => {\n this.debugLog('MediaConnection', 'stream', { peer: mediaConnection.peer });\n session.setRemoteStream(remoteStream);\n session.setState('connected');\n });\n\n mediaConnection.on('close', () => {\n this.debugLog('MediaConnection', 'close', mediaConnection.peer);\n session.close();\n session.setState('ended', 'Connection closed');\n });\n\n mediaConnection.on('error', (err) => {\n this.debugLog('MediaConnection', 'error', { peer: mediaConnection.peer, error: err });\n session.close();\n session.setState('ended', err.message || 'Media error');\n });\n }\n\n private cleanupCall(session: CallSessionImpl): void {\n if (this.activeCall === session) {\n this.activeCall = null;\n }\n }\n\n private handleIncomingCall(mediaConnection: MediaConnection): void {\n this.debugLog('Peer', 'call', { from: mediaConnection.peer, metadata: mediaConnection.metadata });\n\n const metadata = mediaConnection.metadata as { video?: boolean; custom?: unknown } | undefined;\n const hasVideo = metadata?.video ?? false;\n\n const event: IncomingCallEvent = {\n from: mediaConnection.peer,\n hasVideo,\n metadata: metadata?.custom,\n\n answer: async () => {\n if (this.activeCall) {\n mediaConnection.close();\n throw new Error('Already in a call');\n }\n\n let localStream: MediaStream;\n try {\n localStream = await navigator.mediaDevices.getUserMedia({\n audio: true,\n video: hasVideo\n });\n } catch (err) {\n mediaConnection.close();\n throw new Error(`Failed to get media: ${err instanceof Error ? err.message : err}`);\n }\n\n const session = new CallSessionImpl(\n mediaConnection.peer,\n mediaConnection,\n hasVideo,\n this.debugLog.bind(this),\n this.cleanupCall.bind(this)\n );\n session.setLocalStream(localStream);\n\n this.setupMediaConnectionHandlers(session, mediaConnection);\n\n this.activeCall = session;\n\n mediaConnection.answer(localStream);\n\n return session;\n },\n\n reject: () => {\n mediaConnection.close();\n this.debugLog('Call', 'rejected', mediaConnection.peer);\n }\n };\n\n this.incomingCallListeners.forEach(listener => {\n try {\n listener(event);\n } catch (err) {\n this.debugLog('IncomingCallListener', 'error', err);\n }\n });\n }\n\n registerHandler(path: string, handler: SimpleHandler): void {\n this.simpleHandlers.set(path, handler);\n }\n\n unregisterHandler(path: string): void {\n this.simpleHandlers.delete(path);\n }\n\n destroy(): void {\n this.isDestroyed = true;\n\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n if (this.activeCall) {\n this.activeCall.hangUp();\n this.activeCall = null;\n }\n\n this.incomingCallListeners.clear();\n\n for (const conn of this.connections.values()) {\n conn.close();\n }\n this.connections.clear();\n\n for (const pending of this.pendingRequests.values()) {\n clearTimeout(pending.timeout);\n pending.reject(new Error('Peer destroyed'));\n }\n this.pendingRequests.clear();\n this.simpleHandlers.clear();\n\n if (this.peerInstance) {\n this.peerInstance.destroy();\n this.peerInstance = null;\n }\n\n if (this.router) {\n this.router.persist();\n this.router.destroy();\n }\n }\n}\n\nexport type {\n Request,\n Response,\n SimpleHandler,\n CallOptions,\n CallSession,\n CallState,\n CallStateListener,\n IncomingCallEvent,\n IncomingCallListener,\n RouteEntry,\n RelayConfig,\n RelayMessage\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAIA,UAAMA,YAAW,CAAC;AAIlB,MAAAA,UAAS,qBAAqB,WAAW;AACvC,eAAO,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,UAAU,GAAG,EAAE;AAAA,MACnD;AAGA,MAAAA,UAAS,aAAaA,UAAS,mBAAmB;AAGlD,MAAAA,UAAS,aAAa,SAAS,MAAM;AACnC,eAAO,KAAK,KAAK,EAAE,MAAM,IAAI,EAAE,IAAI,UAAQ,KAAK,KAAK,CAAC;AAAA,MACxD;AAEA,MAAAA,UAAS,gBAAgB,SAAS,MAAM;AACtC,cAAM,QAAQ,KAAK,MAAM,MAAM;AAC/B,eAAO,MAAM,IAAI,CAAC,MAAM,WAAW,QAAQ,IACzC,OAAO,OAAO,MAAM,KAAK,IAAI,MAAM;AAAA,MACvC;AAGA,MAAAA,UAAS,iBAAiB,SAAS,MAAM;AACvC,cAAM,WAAWA,UAAS,cAAc,IAAI;AAC5C,eAAO,YAAY,SAAS,CAAC;AAAA,MAC/B;AAGA,MAAAA,UAAS,mBAAmB,SAAS,MAAM;AACzC,cAAM,WAAWA,UAAS,cAAc,IAAI;AAC5C,iBAAS,MAAM;AACf,eAAO;AAAA,MACT;AAGA,MAAAA,UAAS,cAAc,SAAS,MAAM,QAAQ;AAC5C,eAAOA,UAAS,WAAW,IAAI,EAAE,OAAO,UAAQ,KAAK,QAAQ,MAAM,MAAM,CAAC;AAAA,MAC5E;AAMA,MAAAA,UAAS,iBAAiB,SAAS,MAAM;AACvC,YAAI;AAEJ,YAAI,KAAK,QAAQ,cAAc,MAAM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ACb;AACA,WAAK,YAAY,MAAM;AAEvB,iBAAW,WAAW,KAAK,gBAAgB,OAAO,GAAG;AACnD,qBAAa,QAAQ,OAAO;AAC5B,gBAAQ,OAAO,IAAI,MAAM,gBAAgB,CAAC;AAAA,MAC5C;AACA,WAAK,gBAAgB,MAAM;AAC3B,WAAK,eAAe,MAAM;AAE1B,UAAI,KAAK,cAAc;AACrB,aAAK,aAAa,QAAQ;AAC1B,aAAK,eAAe;AAAA,MACtB;AAEA,UAAI,KAAK,QAAQ;AACf,aAAK,OAAO,QAAQ;AACpB,aAAK,OAAO,QAAQ;AAAA,MACtB;AAAA,IACF;AAAA,EACF;",
6
6
  "names": ["SDPUtils", "sdp", "window", "navigator", "window", "navigator", "window", "sdp", "shimGetUserMedia", "shimOnTrack", "shimPeerConnection", "shimGetUserMedia", "window", "navigator", "window", "shimOnTrack", "window", "shimPeerConnection", "shimGetUserMedia", "window", "shimGetUserMedia", "navigator", "RTCPeerConnection", "window", "SDPUtils", "sdp", "window", "logging", "adapter", "shimPeerConnection", "shimGetUserMedia", "shimOnTrack", "once", "listeners", "sdp", "data", "blob", "id", "message"]
7
7
  }