From 8e12c1b6b448bb48f75fc450f75b0251d2de87fa Mon Sep 17 00:00:00 2001 From: Leo Herzog Date: Wed, 11 Nov 2020 21:44:28 -0500 Subject: [PATCH] Improve Accessibility --- bundle.js | 191 +++++++++++++++++++++++++++----------------------- bundle.min.js | 6 +- index.html | 54 +++++++------- parse.js | 1 + style.css | 11 +++ 5 files changed, 145 insertions(+), 118 deletions(-) diff --git a/bundle.js b/bundle.js index dbeaa1c..75b8acc 100644 --- a/bundle.js +++ b/bundle.js @@ -2123,9 +2123,7 @@ function fromByteArray (uint8) { // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk( - uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) - )) + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes @@ -27514,18 +27512,18 @@ simpleGet.concat = (opts, cb) => { }).call(this)}).call(this,require("buffer").Buffer) },{"buffer":60,"decompress-response":55,"http":264,"https":116,"once":183,"querystring":192,"simple-concat":221,"url":299}],223:[function(require,module,exports){ -(function (Buffer){(function (){ /*! simple-peer. MIT License. Feross Aboukhadijeh */ -var debug = require('debug')('simple-peer') -var getBrowserRTC = require('get-browser-rtc') -var randombytes = require('randombytes') -var stream = require('readable-stream') -var queueMicrotask = require('queue-microtask') // TODO: remove when Node 10 is not supported -var errCode = require('err-code') +const debug = require('debug')('simple-peer') +const getBrowserRTC = require('get-browser-rtc') +const randombytes = require('randombytes') +const stream = require('readable-stream') +const queueMicrotask = require('queue-microtask') // TODO: remove when Node 10 is not supported +const errCode = require('err-code') +const { Buffer } = require('buffer') -var MAX_BUFFERED_AMOUNT = 64 * 1024 -var ICECOMPLETE_TIMEOUT = 5 * 1000 -var CHANNEL_CLOSING_TIMEOUT = 5 * 1000 +const MAX_BUFFERED_AMOUNT = 64 * 1024 +const ICECOMPLETE_TIMEOUT = 5 * 1000 +const CHANNEL_CLOSING_TIMEOUT = 5 * 1000 // HACK: Filter trickle lines when trickle is disabled #354 function filterTrickle (sdp) { @@ -27569,6 +27567,7 @@ class Peer extends stream.Duplex { this.iceCompleteTimeout = opts.iceCompleteTimeout || ICECOMPLETE_TIMEOUT this.destroyed = false + this.destroying = false this._connected = false this.remoteAddress = undefined @@ -27735,7 +27734,7 @@ class Peer extends stream.Duplex { } _addIceCandidate (candidate) { - var iceCandidateObj = new this._wrtc.RTCIceCandidate(candidate) + const iceCandidateObj = new this._wrtc.RTCIceCandidate(candidate) this._pc.addIceCandidate(iceCandidateObj) .catch(err => { if (!iceCandidateObj.address || iceCandidateObj.address.endsWith('.local')) { @@ -27771,6 +27770,7 @@ class Peer extends stream.Duplex { } } else { this.emit('signal', { // request initiator to renegotiate + type: 'transceiverRequest', transceiverRequest: { kind, init } }) } @@ -27796,8 +27796,8 @@ class Peer extends stream.Duplex { addTrack (track, stream) { this._debug('addTrack()') - var submap = this._senderMap.get(track) || new Map() // nested Maps map [track, stream] to sender - var sender = submap.get(stream) + const submap = this._senderMap.get(track) || new Map() // nested Maps map [track, stream] to sender + let sender = submap.get(stream) if (!sender) { sender = this._pc.addTrack(track, stream) submap.set(stream, sender) @@ -27819,8 +27819,8 @@ class Peer extends stream.Duplex { replaceTrack (oldTrack, newTrack, stream) { this._debug('replaceTrack()') - var submap = this._senderMap.get(oldTrack) - var sender = submap ? submap.get(stream) : null + const submap = this._senderMap.get(oldTrack) + const sender = submap ? submap.get(stream) : null if (!sender) { throw errCode(new Error('Cannot replace track that was never added.'), 'ERR_TRACK_NOT_ADDED') } @@ -27841,8 +27841,8 @@ class Peer extends stream.Duplex { removeTrack (track, stream) { this._debug('removeSender()') - var submap = this._senderMap.get(track) - var sender = submap ? submap.get(stream) : null + const submap = this._senderMap.get(track) + const sender = submap ? submap.get(stream) : null if (!sender) { throw errCode(new Error('Cannot remove track that was never added.'), 'ERR_TRACK_NOT_ADDED') } @@ -27905,6 +27905,7 @@ class Peer extends stream.Duplex { } else { this._debug('requesting negotiation from initiator') this.emit('signal', { // request initiator to renegotiate + type: 'renegotiate', renegotiate: true }) } @@ -27920,62 +27921,71 @@ class Peer extends stream.Duplex { } _destroy (err, cb) { - if (this.destroyed) return + if (this.destroyed || this.destroying) return + this.destroying = true - this._debug('destroy (error: %s)', err && (err.message || err)) + this._debug('destroying (error: %s)', err && (err.message || err)) - this.readable = this.writable = false + queueMicrotask(() => { // allow events concurrent with the call to _destroy() to fire (see #692) + this.destroyed = true + this.destroying = false - if (!this._readableState.ended) this.push(null) - if (!this._writableState.finished) this.end() + this._debug('destroy (error: %s)', err && (err.message || err)) - this.destroyed = true - this._connected = false - this._pcReady = false - this._channelReady = false - this._remoteTracks = null - this._remoteStreams = null - this._senderMap = null + this.readable = this.writable = false - clearInterval(this._closingInterval) - this._closingInterval = null + if (!this._readableState.ended) this.push(null) + if (!this._writableState.finished) this.end() - clearInterval(this._interval) - this._interval = null - this._chunk = null - this._cb = null + this._connected = false + this._pcReady = false + this._channelReady = false + this._remoteTracks = null + this._remoteStreams = null + this._senderMap = null - if (this._onFinishBound) this.removeListener('finish', this._onFinishBound) - this._onFinishBound = null + clearInterval(this._closingInterval) + this._closingInterval = null - if (this._channel) { - try { - this._channel.close() - } catch (err) {} + clearInterval(this._interval) + this._interval = null + this._chunk = null + this._cb = null - this._channel.onmessage = null - this._channel.onopen = null - this._channel.onclose = null - this._channel.onerror = null - } - if (this._pc) { - try { - this._pc.close() - } catch (err) {} + if (this._onFinishBound) this.removeListener('finish', this._onFinishBound) + this._onFinishBound = null - this._pc.oniceconnectionstatechange = null - this._pc.onicegatheringstatechange = null - this._pc.onsignalingstatechange = null - this._pc.onicecandidate = null - this._pc.ontrack = null - this._pc.ondatachannel = null - } - this._pc = null - this._channel = null + if (this._channel) { + try { + this._channel.close() + } catch (err) {} - if (err) this.emit('error', err) - this.emit('close') - cb() + // allow events concurrent with destruction to be handled + this._channel.onmessage = null + this._channel.onopen = null + this._channel.onclose = null + this._channel.onerror = null + } + if (this._pc) { + try { + this._pc.close() + } catch (err) {} + + // allow events concurrent with destruction to be handled + this._pc.oniceconnectionstatechange = null + this._pc.onicegatheringstatechange = null + this._pc.onsignalingstatechange = null + this._pc.onicecandidate = null + this._pc.ontrack = null + this._pc.ondatachannel = null + } + this._pc = null + this._channel = null + + if (err) this.emit('error', err) + this.emit('close') + cb() + }) } _setupData (event) { @@ -28013,7 +28023,7 @@ class Peer extends stream.Duplex { // HACK: Chrome will sometimes get stuck in readyState "closing", let's check for this condition // https://bugs.chromium.org/p/chromium/issues/detail?id=882743 - var isClosing = false + let isClosing = false this._closingInterval = setInterval(() => { // No "onclosing" event if (this._channel && this._channel.readyState === 'closing') { if (isClosing) this._onChannelClose() // closing timed out: equivalent to onclose firing @@ -28091,7 +28101,7 @@ class Peer extends stream.Duplex { const sendOffer = () => { if (this.destroyed) return - var signal = this._pc.localDescription || offer + const signal = this._pc.localDescription || offer this._debug('signal') this.emit('signal', { type: signal.type, @@ -28141,7 +28151,7 @@ class Peer extends stream.Duplex { const sendAnswer = () => { if (this.destroyed) return - var signal = this._pc.localDescription || answer + const signal = this._pc.localDescription || answer this._debug('signal') this.emit('signal', { type: signal.type, @@ -28178,8 +28188,8 @@ class Peer extends stream.Duplex { _onIceStateChange () { if (this.destroyed) return - var iceConnectionState = this._pc.iceConnectionState - var iceGatheringState = this._pc.iceGatheringState + const iceConnectionState = this._pc.iceConnectionState + const iceGatheringState = this._pc.iceGatheringState this._debug( 'iceStateChange (connection: %s) (gathering: %s)', @@ -28215,7 +28225,7 @@ class Peer extends stream.Duplex { if (this._pc.getStats.length === 0 || this._isReactNativeWebrtc) { this._pc.getStats() .then(res => { - var reports = [] + const reports = [] res.forEach(report => { reports.push(flattenValues(report)) }) @@ -28228,9 +28238,9 @@ class Peer extends stream.Duplex { // If we destroy connection in `connect` callback this code might happen to run when actual connection is already closed if (this.destroyed) return - var reports = [] + const reports = [] res.result().forEach(result => { - var report = {} + const report = {} result.names().forEach(name => { report[name] = result.stat(name) }) @@ -28265,10 +28275,10 @@ class Peer extends stream.Duplex { // Treat getStats error as non-fatal. It's not essential. if (err) items = [] - var remoteCandidates = {} - var localCandidates = {} - var candidatePairs = {} - var foundSelectedCandidatePair = false + const remoteCandidates = {} + const localCandidates = {} + const candidatePairs = {} + let foundSelectedCandidatePair = false items.forEach(item => { // TODO: Once all browsers support the hyphenated stats report types, remove @@ -28287,7 +28297,7 @@ class Peer extends stream.Duplex { const setSelectedCandidatePair = selectedCandidatePair => { foundSelectedCandidatePair = true - var local = localCandidates[selectedCandidatePair.localCandidateId] + let local = localCandidates[selectedCandidatePair.localCandidateId] if (local && (local.ip || local.address)) { // Spec @@ -28307,7 +28317,7 @@ class Peer extends stream.Duplex { this.localFamily = this.localAddress.includes(':') ? 'IPv6' : 'IPv4' } - var remote = remoteCandidates[selectedCandidatePair.remoteCandidateId] + let remote = remoteCandidates[selectedCandidatePair.remoteCandidateId] if (remote && (remote.ip || remote.address)) { // Spec @@ -28329,7 +28339,10 @@ class Peer extends stream.Duplex { this._debug( 'connect local: %s:%s remote: %s:%s', - this.localAddress, this.localPort, this.remoteAddress, this.remotePort + this.localAddress, + this.localPort, + this.remoteAddress, + this.remotePort ) } @@ -28367,7 +28380,7 @@ class Peer extends stream.Duplex { this._chunk = null this._debug('sent chunk from "write before connect"') - var cb = this._cb + const cb = this._cb this._cb = null cb(null) } @@ -28412,8 +28425,8 @@ class Peer extends stream.Duplex { this._queuedNegotiation = false this._needsNegotiation() // negotiate again } else { - this._debug('negotiate') - this.emit('negotiate') + this._debug('negotiated') + this.emit('negotiated') } } @@ -28425,6 +28438,7 @@ class Peer extends stream.Duplex { if (this.destroyed) return if (event.candidate && this.trickle) { this.emit('signal', { + type: 'candidate', candidate: { candidate: event.candidate.candidate, sdpMLineIndex: event.candidate.sdpMLineIndex, @@ -28443,7 +28457,7 @@ class Peer extends stream.Duplex { _onChannelMessage (event) { if (this.destroyed) return - var data = event.data + let data = event.data if (data instanceof ArrayBuffer) data = Buffer.from(data) this.push(data) } @@ -28451,7 +28465,7 @@ class Peer extends stream.Duplex { _onChannelBufferedAmountLow () { if (this.destroyed || !this._cb) return this._debug('ending backpressure: bufferedAmount %d', this._channel.bufferedAmount) - var cb = this._cb + const cb = this._cb this._cb = null cb(null) } @@ -28487,13 +28501,14 @@ class Peer extends stream.Duplex { this._remoteStreams.push(eventStream) queueMicrotask(() => { + this._debug('on stream') this.emit('stream', eventStream) // ensure all tracks have been added }) }) } _debug () { - var args = [].slice.call(arguments) + const args = [].slice.call(arguments) args[0] = '[' + this._id + '] ' + args[0] debug.apply(null, args) } @@ -28522,7 +28537,6 @@ Peer.channelConfig = {} module.exports = Peer -}).call(this)}).call(this,require("buffer").Buffer) },{"buffer":60,"debug":224,"err-code":97,"get-browser-rtc":115,"queue-microtask":193,"randombytes":195,"readable-stream":241}],224:[function(require,module,exports){ arguments[4][13][0].apply(exports,arguments) },{"./common":225,"_process":187,"dup":13}],225:[function(require,module,exports){ @@ -37970,7 +37984,8 @@ function start() { getFiles.addEventListener('click', getFilesFromPeers); tippy('[data-tippy-content]', {"theme": "torrent-parts", "animation": "shift-away-subtle"}); // all element-defined tooltips - + source.disable(); + if (window.location.hash) { originalSourceIcon.innerHTML = ''; source.setContent("Currently loaded information sourced from shared torrent.parts link"); diff --git a/bundle.min.js b/bundle.min.js index 3491bdd..306cafe 100644 --- a/bundle.min.js +++ b/bundle.min.js @@ -64,9 +64,9 @@ var i=e("buffer"),r=i.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function s /*! simple-concat. MIT License. Feross Aboukhadijeh */ t.exports=function(t,n){var i=[];t.on("data",(function(e){i.push(e)})),t.once("end",(function(){n&&n(null,e.concat(i)),n=null})),t.once("error",(function(e){n&&n(e),n=null}))}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:60}],222:[function(e,t,n){(function(n){(function(){ /*! simple-get. MIT License. Feross Aboukhadijeh */ -t.exports=u;const i=e("simple-concat"),r=e("decompress-response"),o=e("http"),s=e("https"),a=e("once"),c=e("querystring"),l=e("url"),p=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe;function u(e,t){if(e=Object.assign({maxRedirects:10},"string"==typeof e?{url:e}:e),t=a(t),e.url){const{hostname:t,port:n,protocol:i,auth:r,path:o}=l.parse(e.url);delete e.url,t||n||i||r?Object.assign(e,{hostname:t,port:n,protocol:i,auth:r,path:o}):e.path=o}const i={"accept-encoding":"gzip, deflate"};let d;e.headers&&Object.keys(e.headers).forEach((t=>i[t.toLowerCase()]=e.headers[t])),e.headers=i,e.body?d=e.json&&!p(e.body)?JSON.stringify(e.body):e.body:e.form&&(d="string"==typeof e.form?e.form:c.stringify(e.form),e.headers["content-type"]="application/x-www-form-urlencoded"),d&&(e.method||(e.method="POST"),p(d)||(e.headers["content-length"]=n.byteLength(d)),e.json&&!e.form&&(e.headers["content-type"]="application/json")),delete e.body,delete e.form,e.json&&(e.headers.accept="application/json"),e.method&&(e.method=e.method.toUpperCase());const f=("https:"===e.protocol?s:o).request(e,(n=>{if(!1!==e.followRedirects&&n.statusCode>=300&&n.statusCode<400&&n.headers.location)return e.url=n.headers.location,delete e.headers.host,n.resume(),"POST"===e.method&&[301,302].includes(n.statusCode)&&(e.method="GET",delete e.headers["content-length"],delete e.headers["content-type"]),0==e.maxRedirects--?t(new Error("too many redirects")):u(e,t);const i="function"==typeof r&&"HEAD"!==e.method;t(null,i?r(n):n)}));return f.on("timeout",(()=>{f.abort(),t(new Error("Request timed out"))})),f.on("error",t),p(d)?d.on("error",t).pipe(f):f.end(d),f}u.concat=(e,t)=>u(e,((n,r)=>{if(n)return t(n);i(r,((n,i)=>{if(n)return t(n);if(e.json)try{i=JSON.parse(i.toString())}catch(n){return t(n,r,i)}t(null,r,i)}))})),["get","post","put","patch","head","delete"].forEach((e=>{u[e]=(t,n)=>("string"==typeof t&&(t={url:t}),u(Object.assign({method:e.toUpperCase()},t),n))}))}).call(this)}).call(this,e("buffer").Buffer)},{buffer:60,"decompress-response":55,http:264,https:116,once:183,querystring:192,"simple-concat":221,url:299}],223:[function(e,t,n){(function(n){(function(){ +t.exports=u;const i=e("simple-concat"),r=e("decompress-response"),o=e("http"),s=e("https"),a=e("once"),c=e("querystring"),l=e("url"),p=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe;function u(e,t){if(e=Object.assign({maxRedirects:10},"string"==typeof e?{url:e}:e),t=a(t),e.url){const{hostname:t,port:n,protocol:i,auth:r,path:o}=l.parse(e.url);delete e.url,t||n||i||r?Object.assign(e,{hostname:t,port:n,protocol:i,auth:r,path:o}):e.path=o}const i={"accept-encoding":"gzip, deflate"};let d;e.headers&&Object.keys(e.headers).forEach((t=>i[t.toLowerCase()]=e.headers[t])),e.headers=i,e.body?d=e.json&&!p(e.body)?JSON.stringify(e.body):e.body:e.form&&(d="string"==typeof e.form?e.form:c.stringify(e.form),e.headers["content-type"]="application/x-www-form-urlencoded"),d&&(e.method||(e.method="POST"),p(d)||(e.headers["content-length"]=n.byteLength(d)),e.json&&!e.form&&(e.headers["content-type"]="application/json")),delete e.body,delete e.form,e.json&&(e.headers.accept="application/json"),e.method&&(e.method=e.method.toUpperCase());const f=("https:"===e.protocol?s:o).request(e,(n=>{if(!1!==e.followRedirects&&n.statusCode>=300&&n.statusCode<400&&n.headers.location)return e.url=n.headers.location,delete e.headers.host,n.resume(),"POST"===e.method&&[301,302].includes(n.statusCode)&&(e.method="GET",delete e.headers["content-length"],delete e.headers["content-type"]),0==e.maxRedirects--?t(new Error("too many redirects")):u(e,t);const i="function"==typeof r&&"HEAD"!==e.method;t(null,i?r(n):n)}));return f.on("timeout",(()=>{f.abort(),t(new Error("Request timed out"))})),f.on("error",t),p(d)?d.on("error",t).pipe(f):f.end(d),f}u.concat=(e,t)=>u(e,((n,r)=>{if(n)return t(n);i(r,((n,i)=>{if(n)return t(n);if(e.json)try{i=JSON.parse(i.toString())}catch(n){return t(n,r,i)}t(null,r,i)}))})),["get","post","put","patch","head","delete"].forEach((e=>{u[e]=(t,n)=>("string"==typeof t&&(t={url:t}),u(Object.assign({method:e.toUpperCase()},t),n))}))}).call(this)}).call(this,e("buffer").Buffer)},{buffer:60,"decompress-response":55,http:264,https:116,once:183,querystring:192,"simple-concat":221,url:299}],223:[function(e,t,n){ /*! simple-peer. MIT License. Feross Aboukhadijeh */ -var i=e("debug")("simple-peer"),r=e("get-browser-rtc"),o=e("randombytes"),s=e("readable-stream"),a=e("queue-microtask"),c=e("err-code"),l=65536;function p(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class u extends s.Duplex{constructor(e){if(super(e=Object.assign({allowHalfOpen:!1},e)),this._id=o(4).toString("hex").slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||o(20).toString("hex"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||u.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},u.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:r(),!this._wrtc)throw"undefined"==typeof window?c(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):c(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void a((()=>this.destroy(c(e,"ERR_PC_CONSTRUCTOR"))))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach((e=>{this.addStream(e)})),this._pc.ontrack=e=>{this._onTrack(e)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(this.destroyed)throw c(new Error("cannot signal after peer is destroyed"),"ERR_SIGNALING");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.destroy(c(e,"ERR_SET_REMOTE_DESCRIPTION"))})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(c(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}_addIceCandidate(e){var t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var n;!t.address||t.address.endsWith(".local")?(n="Ignoring unsupported ICE candidate.",console.warn(n)):this.destroy(c(e,"ERR_ADD_ICE_CANDIDATE"))}))}send(e){this._channel.send(e)}addTransceiver(e,t){if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(c(e,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{transceiverRequest:{kind:e,init:t}})}addStream(e){this._debug("addStream()"),e.getTracks().forEach((t=>{this.addTrack(t,e)}))}addTrack(e,t){this._debug("addTrack()");var n=this._senderMap.get(e)||new Map,i=n.get(t);if(i)throw i.removed?c(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):c(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");i=this._pc.addTrack(e,t),n.set(t,i),this._senderMap.set(e,n),this._needsNegotiation()}replaceTrack(e,t,n){this._debug("replaceTrack()");var i=this._senderMap.get(e),r=i?i.get(n):null;if(!r)throw c(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");t&&this._senderMap.set(t,i),null!=r.replaceTrack?r.replaceTrack(t):this.destroy(c(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(e,t){this._debug("removeSender()");var n=this._senderMap.get(e),i=n?n.get(t):null;if(!i)throw c(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{i.removed=!0,this._pc.removeTrack(i)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(i):this.destroy(c(e,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(e){this._debug("removeSenders()"),e.getTracks().forEach((t=>{this.removeTrack(t,e)}))}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,a((()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout((()=>{this._createOffer()}),0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{renegotiate:!0})),this._isNegotiating=!0}destroy(e){this._destroy(e,(()=>{}))}_destroy(e,t){if(!this.destroyed){if(this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.destroyed=!0,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close"),t()}}_setupData(e){if(!e.channel)return this.destroy(c(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=l),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{this.destroy(c(e,"ERR_DATA_CHANNEL"))};var t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}_read(){}_write(e,t,n){if(this.destroyed)return n(c(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(c(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>l?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n}_onFinish(){if(this.destroyed)return;const e=()=>{setTimeout((()=>this.destroy()),1e3)};this._connected?e():this.once("connect",e)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=p(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){var t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp})}};this._pc.setLocalDescription(e).then((()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.destroy(c(e,"ERR_CREATE_OFFER"))}))}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=p(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){var t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.destroy(c(e,"ERR_CREATE_ANSWER"))}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(c(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(!this.destroyed){var e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(c(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(c(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((n=>{var i=[];n.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((n=>{if(!this.destroyed){var i=[];n.result().forEach((e=>{var n={};e.names().forEach((t=>{n[t]=e.stat(t)})),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,i.push(t(n))})),e(null,i)}}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,n)=>{if(this.destroyed)return;t&&(n=[]);var i={},r={},o={},s=!1;n.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(r[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(o[e.id]=e)}));const a=e=>{s=!0;var t=r[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");var n=i[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=Number(n.port)):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=Number(n.portNumber)):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=Number(n[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(o[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)})),s||Object.keys(o).length&&!Object.keys(r).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(c(t,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');var l=this._cb;this._cb=null,l(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>l||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiate"),this.emit("negotiate"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(!this.destroyed){var t=e.data;t instanceof ArrayBuffer&&(t=n.from(t)),this.push(t)}}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);var e=this._cb;this._cb=null,e(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(e){this.destroyed||e.streams.forEach((t=>{this._debug("on track"),this.emit("track",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some((e=>e.id===t.id))||(this._remoteStreams.push(t),a((()=>{this.emit("stream",t)})))}))}_debug(){var e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],i.apply(null,e)}}u.WEBRTC_SUPPORT=!!r(),u.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},u.channelConfig={},t.exports=u}).call(this)}).call(this,e("buffer").Buffer)},{buffer:60,debug:224,"err-code":97,"get-browser-rtc":115,"queue-microtask":193,randombytes:195,"readable-stream":241}],224:[function(e,t,n){arguments[4][13][0].apply(n,arguments)},{"./common":225,_process:187,dup:13}],225:[function(e,t,n){arguments[4][14][0].apply(n,arguments)},{dup:14,ms:226}],226:[function(e,t,n){arguments[4][15][0].apply(n,arguments)},{dup:15}],227:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{dup:16}],228:[function(e,t,n){arguments[4][17][0].apply(n,arguments)},{"./_stream_readable":230,"./_stream_writable":232,_process:187,dup:17,inherits:119}],229:[function(e,t,n){arguments[4][18][0].apply(n,arguments)},{"./_stream_transform":231,dup:18,inherits:119}],230:[function(e,t,n){arguments[4][19][0].apply(n,arguments)},{"../errors":227,"./_stream_duplex":228,"./internal/streams/async_iterator":233,"./internal/streams/buffer_list":234,"./internal/streams/destroy":235,"./internal/streams/from":237,"./internal/streams/state":239,"./internal/streams/stream":240,_process:187,buffer:60,dup:19,events:98,inherits:119,"string_decoder/":286,util:55}],231:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{"../errors":227,"./_stream_duplex":228,dup:20,inherits:119}],232:[function(e,t,n){arguments[4][21][0].apply(n,arguments)},{"../errors":227,"./_stream_duplex":228,"./internal/streams/destroy":235,"./internal/streams/state":239,"./internal/streams/stream":240,_process:187,buffer:60,dup:21,inherits:119,"util-deprecate":306}],233:[function(e,t,n){arguments[4][22][0].apply(n,arguments)},{"./end-of-stream":236,_process:187,dup:22}],234:[function(e,t,n){arguments[4][23][0].apply(n,arguments)},{buffer:60,dup:23,util:55}],235:[function(e,t,n){arguments[4][24][0].apply(n,arguments)},{_process:187,dup:24}],236:[function(e,t,n){arguments[4][25][0].apply(n,arguments)},{"../../../errors":227,dup:25}],237:[function(e,t,n){arguments[4][26][0].apply(n,arguments)},{dup:26}],238:[function(e,t,n){arguments[4][27][0].apply(n,arguments)},{"../../../errors":227,"./end-of-stream":236,dup:27}],239:[function(e,t,n){arguments[4][28][0].apply(n,arguments)},{"../../../errors":227,dup:28}],240:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29,events:98}],241:[function(e,t,n){arguments[4][30][0].apply(n,arguments)},{"./lib/_stream_duplex.js":228,"./lib/_stream_passthrough.js":229,"./lib/_stream_readable.js":230,"./lib/_stream_transform.js":231,"./lib/_stream_writable.js":232,"./lib/internal/streams/end-of-stream.js":236,"./lib/internal/streams/pipeline.js":238,dup:30}],242:[function(e,t,n){var i=e("rusha"),r=e("./rusha-worker-sha1"),o=new i,s="undefined"!=typeof window?window:self,a=s.crypto||s.msCrypto||{},c=a.subtle||a.webkitSubtle;function l(e){return o.digest(e)}try{c.digest({name:"sha-1"},new Uint8Array).catch((function(){c=!1}))}catch(e){c=!1}t.exports=function(e,t){c?("string"==typeof e&&(e=function(e){for(var t=e.length,n=new Uint8Array(t),i=0;i>>4).toString(16)),n.push((15&r).toString(16))}return n.join("")}(new Uint8Array(e)))}),(function(){t(l(e))}))):"undefined"!=typeof window?r(e,(function(n,i){t(n?l(e):i)})):queueMicrotask((()=>t(l(e))))},t.exports.sync=l},{"./rusha-worker-sha1":243,rusha:219}],243:[function(e,t,n){var i,r,o,s=e("rusha");t.exports=function(e,t){i||(i=s.createWorker(),r=1,o={},i.onmessage=function(e){var t=e.data.id,n=o[t];delete o[t],null!=e.data.error?n(new Error("Rusha worker error: "+e.data.error)):n(null,e.data.hash)}),o[r]=t,i.postMessage({id:r,data:e}),r+=1}},{rusha:219}],244:[function(e,t,n){(function(n){(function(){const i=e("debug")("simple-websocket"),r=e("randombytes"),o=e("readable-stream"),s=e("queue-microtask"),a=e("ws"),c="function"!=typeof a?WebSocket:a;class l extends o.Duplex{constructor(e={}){if("string"==typeof e&&(e={url:e}),super(e=Object.assign({allowHalfOpen:!1},e)),null==e.url&&null==e.socket)throw new Error("Missing required `url` or `socket` option");if(null!=e.url&&null!=e.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=r(4).toString("hex").slice(0,7),this._debug("new websocket: %o",e),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,e.socket)this.url=e.socket.url,this._ws=e.socket,this.connected=e.socket.readyState===c.OPEN;else{this.url=e.url;try{this._ws="function"==typeof a?new c(e.url,e):new c(e.url)}catch(e){return void s((()=>this.destroy(e)))}}this._ws.binaryType="arraybuffer",this._ws.onopen=()=>{this._onOpen()},this._ws.onmessage=e=>{this._onMessage(e)},this._ws.onclose=()=>{this._onClose()},this._ws.onerror=()=>{this.destroy(new Error("connection error to "+this.url))},this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}send(e){this._ws.send(e)}destroy(e){this._destroy(e,(()=>{}))}_destroy(e,t){if(!this.destroyed){if(this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._ws){const t=this._ws,n=()=>{t.onclose=null};if(t.readyState===c.CLOSED)n();else try{t.onclose=n,t.close()}catch(e){n()}t.onopen=null,t.onmessage=null,t.onerror=()=>{}}if(this._ws=null,e){if("undefined"!=typeof DOMException&&e instanceof DOMException){const t=e.code;(e=new Error(e.message)).code=t}this.emit("error",e)}this.emit("close"),t()}}_read(){}_write(e,t,n){if(this.destroyed)return n(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(e)}catch(e){return this.destroy(e)}"function"!=typeof a&&this._ws.bufferedAmount>65536?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n}_onFinish(){if(this.destroyed)return;const e=()=>{setTimeout((()=>this.destroy()),1e3)};this.connected?e():this.once("connect",e)}_onMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=n.from(t)),this.push(t)}_onOpen(){if(!this.connected&&!this.destroyed){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(e)}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"function"!=typeof a&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_onInterval(){if(!this._cb||!this._ws||this._ws.bufferedAmount>65536)return;this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onClose(){this.destroyed||(this._debug("on close"),this.destroy())}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],i.apply(null,e)}}l.WEBSOCKET_SUPPORT=!!c,t.exports=l}).call(this)}).call(this,e("buffer").Buffer)},{buffer:60,debug:245,"queue-microtask":193,randombytes:195,"readable-stream":262,ws:55}],245:[function(e,t,n){arguments[4][13][0].apply(n,arguments)},{"./common":246,_process:187,dup:13}],246:[function(e,t,n){arguments[4][14][0].apply(n,arguments)},{dup:14,ms:247}],247:[function(e,t,n){arguments[4][15][0].apply(n,arguments)},{dup:15}],248:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{dup:16}],249:[function(e,t,n){arguments[4][17][0].apply(n,arguments)},{"./_stream_readable":251,"./_stream_writable":253,_process:187,dup:17,inherits:119}],250:[function(e,t,n){arguments[4][18][0].apply(n,arguments)},{"./_stream_transform":252,dup:18,inherits:119}],251:[function(e,t,n){arguments[4][19][0].apply(n,arguments)},{"../errors":248,"./_stream_duplex":249,"./internal/streams/async_iterator":254,"./internal/streams/buffer_list":255,"./internal/streams/destroy":256,"./internal/streams/from":258,"./internal/streams/state":260,"./internal/streams/stream":261,_process:187,buffer:60,dup:19,events:98,inherits:119,"string_decoder/":286,util:55}],252:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{"../errors":248,"./_stream_duplex":249,dup:20,inherits:119}],253:[function(e,t,n){arguments[4][21][0].apply(n,arguments)},{"../errors":248,"./_stream_duplex":249,"./internal/streams/destroy":256,"./internal/streams/state":260,"./internal/streams/stream":261,_process:187,buffer:60,dup:21,inherits:119,"util-deprecate":306}],254:[function(e,t,n){arguments[4][22][0].apply(n,arguments)},{"./end-of-stream":257,_process:187,dup:22}],255:[function(e,t,n){arguments[4][23][0].apply(n,arguments)},{buffer:60,dup:23,util:55}],256:[function(e,t,n){arguments[4][24][0].apply(n,arguments)},{_process:187,dup:24}],257:[function(e,t,n){arguments[4][25][0].apply(n,arguments)},{"../../../errors":248,dup:25}],258:[function(e,t,n){arguments[4][26][0].apply(n,arguments)},{dup:26}],259:[function(e,t,n){arguments[4][27][0].apply(n,arguments)},{"../../../errors":248,"./end-of-stream":257,dup:27}],260:[function(e,t,n){arguments[4][28][0].apply(n,arguments)},{"../../../errors":248,dup:28}],261:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29,events:98}],262:[function(e,t,n){arguments[4][30][0].apply(n,arguments)},{"./lib/_stream_duplex.js":249,"./lib/_stream_passthrough.js":250,"./lib/_stream_readable.js":251,"./lib/_stream_transform.js":252,"./lib/_stream_writable.js":253,"./lib/internal/streams/end-of-stream.js":257,"./lib/internal/streams/pipeline.js":259,dup:30}],263:[function(e,t,n){var i,r=1,o=65535,s=function(){r=r+1&o};t.exports=function(e){i||(i=setInterval(s,250)).unref&&i.unref();var t=4*(e||5),n=[0],a=1,c=r-1&o;return function(e){var i=r-c&o;for(i>t&&(i=t),c=r;i--;)a===t&&(a=0),n[a]=n[0===a?t-1:a-1],a++;e&&(n[a-1]+=e);var s=n[a-1],l=n.lengthe._pos){var o=n.substr(e._pos);if("x-user-defined"===e._charset){for(var s=r.alloc(o.length),a=0;ae._pos&&(e.push(r.from(new Uint8Array(l.result.slice(e._pos)))),e._pos=l.result.byteLength)},l.onload=function(){e.push(null)},l.readAsArrayBuffer(n)}e._xhr.readyState===c.DONE&&"ms-stream"!==e._mode&&e.push(null)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":265,_process:187,buffer:60,inherits:119,"readable-stream":282}],268:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{dup:16}],269:[function(e,t,n){arguments[4][17][0].apply(n,arguments)},{"./_stream_readable":271,"./_stream_writable":273,_process:187,dup:17,inherits:119}],270:[function(e,t,n){arguments[4][18][0].apply(n,arguments)},{"./_stream_transform":272,dup:18,inherits:119}],271:[function(e,t,n){arguments[4][19][0].apply(n,arguments)},{"../errors":268,"./_stream_duplex":269,"./internal/streams/async_iterator":274,"./internal/streams/buffer_list":275,"./internal/streams/destroy":276,"./internal/streams/from":278,"./internal/streams/state":280,"./internal/streams/stream":281,_process:187,buffer:60,dup:19,events:98,inherits:119,"string_decoder/":286,util:55}],272:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{"../errors":268,"./_stream_duplex":269,dup:20,inherits:119}],273:[function(e,t,n){arguments[4][21][0].apply(n,arguments)},{"../errors":268,"./_stream_duplex":269,"./internal/streams/destroy":276,"./internal/streams/state":280,"./internal/streams/stream":281,_process:187,buffer:60,dup:21,inherits:119,"util-deprecate":306}],274:[function(e,t,n){arguments[4][22][0].apply(n,arguments)},{"./end-of-stream":277,_process:187,dup:22}],275:[function(e,t,n){arguments[4][23][0].apply(n,arguments)},{buffer:60,dup:23,util:55}],276:[function(e,t,n){arguments[4][24][0].apply(n,arguments)},{_process:187,dup:24}],277:[function(e,t,n){arguments[4][25][0].apply(n,arguments)},{"../../../errors":268,dup:25}],278:[function(e,t,n){arguments[4][26][0].apply(n,arguments)},{dup:26}],279:[function(e,t,n){arguments[4][27][0].apply(n,arguments)},{"../../../errors":268,"./end-of-stream":277,dup:27}],280:[function(e,t,n){arguments[4][28][0].apply(n,arguments)},{"../../../errors":268,dup:28}],281:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29,events:98}],282:[function(e,t,n){arguments[4][30][0].apply(n,arguments)},{"./lib/_stream_duplex.js":269,"./lib/_stream_passthrough.js":270,"./lib/_stream_readable.js":271,"./lib/_stream_transform.js":272,"./lib/_stream_writable.js":273,"./lib/internal/streams/end-of-stream.js":277,"./lib/internal/streams/pipeline.js":279,dup:30}],283:[function(e,t,n){ +const i=e("debug")("simple-peer"),r=e("get-browser-rtc"),o=e("randombytes"),s=e("readable-stream"),a=e("queue-microtask"),c=e("err-code"),{Buffer:l}=e("buffer"),p=65536;function u(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class d extends s.Duplex{constructor(e){if(super(e=Object.assign({allowHalfOpen:!1},e)),this._id=o(4).toString("hex").slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||o(20).toString("hex"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||d.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},d.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:r(),!this._wrtc)throw"undefined"==typeof window?c(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):c(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void a((()=>this.destroy(c(e,"ERR_PC_CONSTRUCTOR"))))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach((e=>{this.addStream(e)})),this._pc.ontrack=e=>{this._onTrack(e)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(this.destroyed)throw c(new Error("cannot signal after peer is destroyed"),"ERR_SIGNALING");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.destroy(c(e,"ERR_SET_REMOTE_DESCRIPTION"))})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(c(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var n;!t.address||t.address.endsWith(".local")?(n="Ignoring unsupported ICE candidate.",console.warn(n)):this.destroy(c(e,"ERR_ADD_ICE_CANDIDATE"))}))}send(e){this._channel.send(e)}addTransceiver(e,t){if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(c(e,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}addStream(e){this._debug("addStream()"),e.getTracks().forEach((t=>{this.addTrack(t,e)}))}addTrack(e,t){this._debug("addTrack()");const n=this._senderMap.get(e)||new Map;let i=n.get(t);if(i)throw i.removed?c(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):c(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");i=this._pc.addTrack(e,t),n.set(t,i),this._senderMap.set(e,n),this._needsNegotiation()}replaceTrack(e,t,n){this._debug("replaceTrack()");const i=this._senderMap.get(e),r=i?i.get(n):null;if(!r)throw c(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");t&&this._senderMap.set(t,i),null!=r.replaceTrack?r.replaceTrack(t):this.destroy(c(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(e,t){this._debug("removeSender()");const n=this._senderMap.get(e),i=n?n.get(t):null;if(!i)throw c(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{i.removed=!0,this._pc.removeTrack(i)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(i):this.destroy(c(e,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(e){this._debug("removeSenders()"),e.getTracks().forEach((t=>{this.removeTrack(t,e)}))}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,a((()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout((()=>{this._createOffer()}),0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}destroy(e){this._destroy(e,(()=>{}))}_destroy(e,t){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",e&&(e.message||e)),a((()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close"),t()})))}_setupData(e){if(!e.channel)return this.destroy(c(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=p),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{this.destroy(c(e,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}_read(){}_write(e,t,n){if(this.destroyed)return n(c(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(c(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>p?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n}_onFinish(){if(this.destroyed)return;const e=()=>{setTimeout((()=>this.destroy()),1e3)};this._connected?e():this.once("connect",e)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=u(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.destroy(c(e,"ERR_CREATE_OFFER"))}))}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=u(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.destroy(c(e,"ERR_CREATE_ANSWER"))}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(c(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(c(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(c(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((n=>{const i=[];n.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((n=>{if(this.destroyed)return;const i=[];n.result().forEach((e=>{const n={};e.names().forEach((t=>{n[t]=e.stat(t)})),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,i.push(t(n))})),e(null,i)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,n)=>{if(this.destroyed)return;t&&(n=[]);const i={},r={},o={};let s=!1;n.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(r[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(o[e.id]=e)}));const a=e=>{s=!0;let t=r[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=i[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=Number(n.port)):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=Number(n.portNumber)):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=Number(n[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(o[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)})),s||Object.keys(o).length&&!Object.keys(r).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(c(t,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>p||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=l.from(t)),this.push(t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(e){this.destroyed||e.streams.forEach((t=>{this._debug("on track"),this.emit("track",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some((e=>e.id===t.id))||(this._remoteStreams.push(t),a((()=>{this._debug("on stream"),this.emit("stream",t)})))}))}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],i.apply(null,e)}}d.WEBRTC_SUPPORT=!!r(),d.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},d.channelConfig={},t.exports=d},{buffer:60,debug:224,"err-code":97,"get-browser-rtc":115,"queue-microtask":193,randombytes:195,"readable-stream":241}],224:[function(e,t,n){arguments[4][13][0].apply(n,arguments)},{"./common":225,_process:187,dup:13}],225:[function(e,t,n){arguments[4][14][0].apply(n,arguments)},{dup:14,ms:226}],226:[function(e,t,n){arguments[4][15][0].apply(n,arguments)},{dup:15}],227:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{dup:16}],228:[function(e,t,n){arguments[4][17][0].apply(n,arguments)},{"./_stream_readable":230,"./_stream_writable":232,_process:187,dup:17,inherits:119}],229:[function(e,t,n){arguments[4][18][0].apply(n,arguments)},{"./_stream_transform":231,dup:18,inherits:119}],230:[function(e,t,n){arguments[4][19][0].apply(n,arguments)},{"../errors":227,"./_stream_duplex":228,"./internal/streams/async_iterator":233,"./internal/streams/buffer_list":234,"./internal/streams/destroy":235,"./internal/streams/from":237,"./internal/streams/state":239,"./internal/streams/stream":240,_process:187,buffer:60,dup:19,events:98,inherits:119,"string_decoder/":286,util:55}],231:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{"../errors":227,"./_stream_duplex":228,dup:20,inherits:119}],232:[function(e,t,n){arguments[4][21][0].apply(n,arguments)},{"../errors":227,"./_stream_duplex":228,"./internal/streams/destroy":235,"./internal/streams/state":239,"./internal/streams/stream":240,_process:187,buffer:60,dup:21,inherits:119,"util-deprecate":306}],233:[function(e,t,n){arguments[4][22][0].apply(n,arguments)},{"./end-of-stream":236,_process:187,dup:22}],234:[function(e,t,n){arguments[4][23][0].apply(n,arguments)},{buffer:60,dup:23,util:55}],235:[function(e,t,n){arguments[4][24][0].apply(n,arguments)},{_process:187,dup:24}],236:[function(e,t,n){arguments[4][25][0].apply(n,arguments)},{"../../../errors":227,dup:25}],237:[function(e,t,n){arguments[4][26][0].apply(n,arguments)},{dup:26}],238:[function(e,t,n){arguments[4][27][0].apply(n,arguments)},{"../../../errors":227,"./end-of-stream":236,dup:27}],239:[function(e,t,n){arguments[4][28][0].apply(n,arguments)},{"../../../errors":227,dup:28}],240:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29,events:98}],241:[function(e,t,n){arguments[4][30][0].apply(n,arguments)},{"./lib/_stream_duplex.js":228,"./lib/_stream_passthrough.js":229,"./lib/_stream_readable.js":230,"./lib/_stream_transform.js":231,"./lib/_stream_writable.js":232,"./lib/internal/streams/end-of-stream.js":236,"./lib/internal/streams/pipeline.js":238,dup:30}],242:[function(e,t,n){var i=e("rusha"),r=e("./rusha-worker-sha1"),o=new i,s="undefined"!=typeof window?window:self,a=s.crypto||s.msCrypto||{},c=a.subtle||a.webkitSubtle;function l(e){return o.digest(e)}try{c.digest({name:"sha-1"},new Uint8Array).catch((function(){c=!1}))}catch(e){c=!1}t.exports=function(e,t){c?("string"==typeof e&&(e=function(e){for(var t=e.length,n=new Uint8Array(t),i=0;i>>4).toString(16)),n.push((15&r).toString(16))}return n.join("")}(new Uint8Array(e)))}),(function(){t(l(e))}))):"undefined"!=typeof window?r(e,(function(n,i){t(n?l(e):i)})):queueMicrotask((()=>t(l(e))))},t.exports.sync=l},{"./rusha-worker-sha1":243,rusha:219}],243:[function(e,t,n){var i,r,o,s=e("rusha");t.exports=function(e,t){i||(i=s.createWorker(),r=1,o={},i.onmessage=function(e){var t=e.data.id,n=o[t];delete o[t],null!=e.data.error?n(new Error("Rusha worker error: "+e.data.error)):n(null,e.data.hash)}),o[r]=t,i.postMessage({id:r,data:e}),r+=1}},{rusha:219}],244:[function(e,t,n){(function(n){(function(){const i=e("debug")("simple-websocket"),r=e("randombytes"),o=e("readable-stream"),s=e("queue-microtask"),a=e("ws"),c="function"!=typeof a?WebSocket:a;class l extends o.Duplex{constructor(e={}){if("string"==typeof e&&(e={url:e}),super(e=Object.assign({allowHalfOpen:!1},e)),null==e.url&&null==e.socket)throw new Error("Missing required `url` or `socket` option");if(null!=e.url&&null!=e.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=r(4).toString("hex").slice(0,7),this._debug("new websocket: %o",e),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,e.socket)this.url=e.socket.url,this._ws=e.socket,this.connected=e.socket.readyState===c.OPEN;else{this.url=e.url;try{this._ws="function"==typeof a?new c(e.url,e):new c(e.url)}catch(e){return void s((()=>this.destroy(e)))}}this._ws.binaryType="arraybuffer",this._ws.onopen=()=>{this._onOpen()},this._ws.onmessage=e=>{this._onMessage(e)},this._ws.onclose=()=>{this._onClose()},this._ws.onerror=()=>{this.destroy(new Error("connection error to "+this.url))},this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}send(e){this._ws.send(e)}destroy(e){this._destroy(e,(()=>{}))}_destroy(e,t){if(!this.destroyed){if(this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._ws){const t=this._ws,n=()=>{t.onclose=null};if(t.readyState===c.CLOSED)n();else try{t.onclose=n,t.close()}catch(e){n()}t.onopen=null,t.onmessage=null,t.onerror=()=>{}}if(this._ws=null,e){if("undefined"!=typeof DOMException&&e instanceof DOMException){const t=e.code;(e=new Error(e.message)).code=t}this.emit("error",e)}this.emit("close"),t()}}_read(){}_write(e,t,n){if(this.destroyed)return n(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(e)}catch(e){return this.destroy(e)}"function"!=typeof a&&this._ws.bufferedAmount>65536?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n}_onFinish(){if(this.destroyed)return;const e=()=>{setTimeout((()=>this.destroy()),1e3)};this.connected?e():this.once("connect",e)}_onMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=n.from(t)),this.push(t)}_onOpen(){if(!this.connected&&!this.destroyed){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(e)}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"function"!=typeof a&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_onInterval(){if(!this._cb||!this._ws||this._ws.bufferedAmount>65536)return;this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onClose(){this.destroyed||(this._debug("on close"),this.destroy())}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],i.apply(null,e)}}l.WEBSOCKET_SUPPORT=!!c,t.exports=l}).call(this)}).call(this,e("buffer").Buffer)},{buffer:60,debug:245,"queue-microtask":193,randombytes:195,"readable-stream":262,ws:55}],245:[function(e,t,n){arguments[4][13][0].apply(n,arguments)},{"./common":246,_process:187,dup:13}],246:[function(e,t,n){arguments[4][14][0].apply(n,arguments)},{dup:14,ms:247}],247:[function(e,t,n){arguments[4][15][0].apply(n,arguments)},{dup:15}],248:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{dup:16}],249:[function(e,t,n){arguments[4][17][0].apply(n,arguments)},{"./_stream_readable":251,"./_stream_writable":253,_process:187,dup:17,inherits:119}],250:[function(e,t,n){arguments[4][18][0].apply(n,arguments)},{"./_stream_transform":252,dup:18,inherits:119}],251:[function(e,t,n){arguments[4][19][0].apply(n,arguments)},{"../errors":248,"./_stream_duplex":249,"./internal/streams/async_iterator":254,"./internal/streams/buffer_list":255,"./internal/streams/destroy":256,"./internal/streams/from":258,"./internal/streams/state":260,"./internal/streams/stream":261,_process:187,buffer:60,dup:19,events:98,inherits:119,"string_decoder/":286,util:55}],252:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{"../errors":248,"./_stream_duplex":249,dup:20,inherits:119}],253:[function(e,t,n){arguments[4][21][0].apply(n,arguments)},{"../errors":248,"./_stream_duplex":249,"./internal/streams/destroy":256,"./internal/streams/state":260,"./internal/streams/stream":261,_process:187,buffer:60,dup:21,inherits:119,"util-deprecate":306}],254:[function(e,t,n){arguments[4][22][0].apply(n,arguments)},{"./end-of-stream":257,_process:187,dup:22}],255:[function(e,t,n){arguments[4][23][0].apply(n,arguments)},{buffer:60,dup:23,util:55}],256:[function(e,t,n){arguments[4][24][0].apply(n,arguments)},{_process:187,dup:24}],257:[function(e,t,n){arguments[4][25][0].apply(n,arguments)},{"../../../errors":248,dup:25}],258:[function(e,t,n){arguments[4][26][0].apply(n,arguments)},{dup:26}],259:[function(e,t,n){arguments[4][27][0].apply(n,arguments)},{"../../../errors":248,"./end-of-stream":257,dup:27}],260:[function(e,t,n){arguments[4][28][0].apply(n,arguments)},{"../../../errors":248,dup:28}],261:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29,events:98}],262:[function(e,t,n){arguments[4][30][0].apply(n,arguments)},{"./lib/_stream_duplex.js":249,"./lib/_stream_passthrough.js":250,"./lib/_stream_readable.js":251,"./lib/_stream_transform.js":252,"./lib/_stream_writable.js":253,"./lib/internal/streams/end-of-stream.js":257,"./lib/internal/streams/pipeline.js":259,dup:30}],263:[function(e,t,n){var i,r=1,o=65535,s=function(){r=r+1&o};t.exports=function(e){i||(i=setInterval(s,250)).unref&&i.unref();var t=4*(e||5),n=[0],a=1,c=r-1&o;return function(e){var i=r-c&o;for(i>t&&(i=t),c=r;i--;)a===t&&(a=0),n[a]=n[0===a?t-1:a-1],a++;e&&(n[a-1]+=e);var s=n[a-1],l=n.lengthe._pos){var o=n.substr(e._pos);if("x-user-defined"===e._charset){for(var s=r.alloc(o.length),a=0;ae._pos&&(e.push(r.from(new Uint8Array(l.result.slice(e._pos)))),e._pos=l.result.byteLength)},l.onload=function(){e.push(null)},l.readAsArrayBuffer(n)}e._xhr.readyState===c.DONE&&"ms-stream"!==e._mode&&e.push(null)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":265,_process:187,buffer:60,inherits:119,"readable-stream":282}],268:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{dup:16}],269:[function(e,t,n){arguments[4][17][0].apply(n,arguments)},{"./_stream_readable":271,"./_stream_writable":273,_process:187,dup:17,inherits:119}],270:[function(e,t,n){arguments[4][18][0].apply(n,arguments)},{"./_stream_transform":272,dup:18,inherits:119}],271:[function(e,t,n){arguments[4][19][0].apply(n,arguments)},{"../errors":268,"./_stream_duplex":269,"./internal/streams/async_iterator":274,"./internal/streams/buffer_list":275,"./internal/streams/destroy":276,"./internal/streams/from":278,"./internal/streams/state":280,"./internal/streams/stream":281,_process:187,buffer:60,dup:19,events:98,inherits:119,"string_decoder/":286,util:55}],272:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{"../errors":268,"./_stream_duplex":269,dup:20,inherits:119}],273:[function(e,t,n){arguments[4][21][0].apply(n,arguments)},{"../errors":268,"./_stream_duplex":269,"./internal/streams/destroy":276,"./internal/streams/state":280,"./internal/streams/stream":281,_process:187,buffer:60,dup:21,inherits:119,"util-deprecate":306}],274:[function(e,t,n){arguments[4][22][0].apply(n,arguments)},{"./end-of-stream":277,_process:187,dup:22}],275:[function(e,t,n){arguments[4][23][0].apply(n,arguments)},{buffer:60,dup:23,util:55}],276:[function(e,t,n){arguments[4][24][0].apply(n,arguments)},{_process:187,dup:24}],277:[function(e,t,n){arguments[4][25][0].apply(n,arguments)},{"../../../errors":268,dup:25}],278:[function(e,t,n){arguments[4][26][0].apply(n,arguments)},{dup:26}],279:[function(e,t,n){arguments[4][27][0].apply(n,arguments)},{"../../../errors":268,"./end-of-stream":277,dup:27}],280:[function(e,t,n){arguments[4][28][0].apply(n,arguments)},{"../../../errors":268,dup:28}],281:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29,events:98}],282:[function(e,t,n){arguments[4][30][0].apply(n,arguments)},{"./lib/_stream_duplex.js":269,"./lib/_stream_passthrough.js":270,"./lib/_stream_readable.js":271,"./lib/_stream_transform.js":272,"./lib/_stream_writable.js":273,"./lib/internal/streams/end-of-stream.js":277,"./lib/internal/streams/pipeline.js":279,dup:30}],283:[function(e,t,n){ /*! stream-to-blob-url. MIT License. Feross Aboukhadijeh */ t.exports=async function(e,t){const n=await i(e,t);return URL.createObjectURL(n)};const i=e("stream-to-blob")},{"stream-to-blob":284}],284:[function(e,t,n){ /*! stream-to-blob. MIT License. Feross Aboukhadijeh */ @@ -84,4 +84,4 @@ const i=e("debug")("torrent-discovery"),r=e("bittorrent-dht/client"),o=e("events /*! ut_metadata. MIT License. WebTorrent LLC */ const{EventEmitter:i}=e("events"),r=e("bencode"),o=e("bitfield").default,s=e("debug")("ut_metadata"),a=e("simple-sha1"),c=16384;t.exports=e=>{class t extends i{constructor(t){super(),this._wire=t,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new o(0,{grow:1e3}),n.isBuffer(e)&&this.setMetadata(e)}onHandshake(e,t,n){this._infoHash=e}onExtendedHandshake(e){return e.m&&e.m.ut_metadata?e.metadata_size?"number"!=typeof e.metadata_size||1e7this._metadataSize&&(n=this._metadataSize);const i=this.metadata.slice(t,n);this._data(e,i,this._metadataSize)}_onData(e,t,n){t.length>c||!this._fetching||(t.copy(this.metadata,e*c),this._bitfield.set(e),this._checkDone())}_onReject(e){this._remainingRejects>0&&this._fetching?(this._request(e),this._remainingRejects-=1):this.emit("warning",new Error('Peer sent "reject" too much'))}_requestPieces(){if(this._fetching){this.metadata=n.alloc(this._metadataSize);for(let e=0;e0?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return t.prototype.name="ut_metadata",t}}).call(this)}).call(this,e("buffer").Buffer)},{bencode:7,bitfield:302,buffer:60,debug:303,events:98,"simple-sha1":242}],302:[function(e,t,n){arguments[4][12][0].apply(n,arguments)},{dup:12}],303:[function(e,t,n){arguments[4][13][0].apply(n,arguments)},{"./common":304,_process:187,dup:13}],304:[function(e,t,n){arguments[4][14][0].apply(n,arguments)},{dup:14,ms:305}],305:[function(e,t,n){arguments[4][15][0].apply(n,arguments)},{dup:15}],306:[function(e,t,n){(function(e){(function(){function n(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=function(e,t){if(n("noDeprecation"))return e;var i=!1;return function(){if(!i){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation")?console.trace(t):console.warn(t),i=!0}return e.apply(this,arguments)}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],307:[function(e,t,n){(function(n){(function(){const i=e("binary-search"),r=e("events"),o=e("mp4-stream"),s=e("mp4-box-encoding"),a=e("range-slice-stream");class c{constructor(e,t){this._entries=e,this._countName=t||"count",this._index=0,this._offset=0,this.value=this._entries[0]}inc(){this._offset++,this._offset>=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}const l=1;t.exports=class extends r{constructor(e){super(),this._tracks=[],this._file=e,this._decoder=null,this._findMoov(0)}_findMoov(e){this._decoder&&this._decoder.destroy();let t=0;this._decoder=o.decode();const n=this._file.createReadStream({start:e});n.pipe(this._decoder);const i=r=>{"moov"===r.type?(this._decoder.removeListener("box",i),this._decoder.decode((e=>{n.destroy();try{this._processMoov(e)}catch(e){e.message="Cannot parse mp4 file: "+e.message,this.emit("error",e)}}))):r.length<4096?(t+=r.length,this._decoder.ignore()):(this._decoder.removeListener("box",i),t+=r.length,n.destroy(),this._decoder.destroy(),this._findMoov(e+t))};this._decoder.on("box",i)}_processMoov(e){const t=e.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let n=0;n=o.stsz.entries.length)break;if(f++,m+=e,f>=i.samplesPerChunk){f=0,m=0,h++;const e=o.stsc.entries[g+1];e&&h+1>=e.firstChunk&&g++}v+=t,b.inc(),x&&x.inc(),r&&y++}r.mdia.mdhd.duration=0,r.tkhd.duration=0;const _=i.sampleDescriptionId,w={type:"moov",mvhd:e.mvhd,traks:[{tkhd:r.tkhd,mdia:{mdhd:r.mdia.mdhd,hdlr:r.mdia.hdlr,elng:r.mdia.elng,minf:{vmhd:r.mdia.minf.vmhd,smhd:r.mdia.minf.smhd,dinf:r.mdia.minf.dinf,stbl:{stsd:o.stsd,stts:{version:0,flags:0,entries:[]},ctts:{version:0,flags:0,entries:[]},stsc:{version:0,flags:0,entries:[]},stsz:{version:0,flags:0,entries:[]},stco:{version:0,flags:0,entries:[]},stss:{version:0,flags:0,entries:[]}}}}}],mvex:{mehd:{fragmentDuration:e.mvhd.duration},trexs:[{trackId:r.tkhd.trackId,defaultSampleDescriptionIndex:_,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:r.tkhd.trackId,timeScale:r.mdia.mdhd.timeScale,samples:u,currSample:null,currTime:null,moov:w,mime:p})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));e.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const r=s.encode(this._ftyp),o=this._tracks.map((e=>{const t=s.encode(e.moov);return{mime:e.mime,init:n.concat([r,t])}}));this.emit("ready",o)}seek(e){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let t=-1;if(this._tracks.map(((n,i)=>{n.outStream&&n.outStream.destroy(),n.inStream&&(n.inStream.destroy(),n.inStream=null);const r=n.outStream=o.encode(),s=this._generateFragment(i,e);if(!s)return r.finalize();(-1===t||s.ranges[0].start{r.destroyed||r.box(e.moof,(t=>{if(t)return this.emit("error",t);if(r.destroyed)return;n.inStream.slice(e.ranges).pipe(r.mediaData(e.length,(e=>{if(e)return this.emit("error",e);if(r.destroyed)return;const t=this._generateFragment(i);if(!t)return r.finalize();a(t)})))}))};a(s)})),t>=0){const e=this._fileStream=this._file.createReadStream({start:t});this._tracks.forEach((n=>{n.inStream=new a(t,{highWaterMark:1e7}),e.pipe(n.inStream)}))}return this._tracks.map((e=>e.outStream))}_findSampleBefore(e,t){const n=this._tracks[e],r=Math.floor(n.timeScale*t);let o=i(n.samples,r,((e,t)=>e.dts+e.presentationOffset-t));for(-1===o?o=0:o<0&&(o=-o-2);!n.samples[o].sync;)o--;return o}_generateFragment(e,t){const n=this._tracks[e];let i;if(i=void 0!==t?this._findSampleBefore(e,t):n.currSample,i>=n.samples.length)return null;const r=n.samples[i].dts;let o=0;const s=[];for(var a=i;a=n.timeScale*l)break;o+=e.size;const t=s.length-1;t<0||s[t].end!==e.offset?s.push({start:e.offset,end:e.offset+e.size}):s[t].end+=e.size}return n.currSample=a,{moof:this._generateMoof(e,i,a),ranges:s,length:o}}_generateMoof(e,t,n){const i=this._tracks[e],r=[];let o=0;for(let e=t;e{this.detailedError=this._elemWrapper.detailedError,this.destroy()},this._onWaiting=()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()},t.autoplay&&(t.preload="auto"),t.addEventListener("waiting",this._onWaiting),t.addEventListener("error",this._onError)}s.prototype={_createMuxer(){this._muxer=new o(this._file),this._muxer.on("ready",(e=>{this._tracks=e.map((e=>{const t=this._elemWrapper.createWriteStream(e.mime);t.on("error",(e=>{this._elemWrapper.error(e)}));const n={muxed:null,mediaSource:t,initFlushed:!1,onInitFlushed:null};return t.write(e.init,(e=>{n.initFlushed=!0,n.onInitFlushed&&n.onInitFlushed(e)})),n})),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()})),this._muxer.on("error",(e=>{this._elemWrapper.error(e)}))},_pump(){const e=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach(((t,n)=>{const i=()=>{t.muxed&&(t.muxed.destroy(),t.mediaSource=this._elemWrapper.createWriteStream(t.mediaSource),t.mediaSource.on("error",(e=>{this._elemWrapper.error(e)}))),t.muxed=e[n],r(t.muxed,t.mediaSource)};t.initFlushed?i():t.onInitFlushed=e=>{e?this._elemWrapper.error(e):i()}}))},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach((e=>{e.muxed&&e.muxed.destroy()})),this._elem.src="")}},t.exports=s},{"./mp4-remuxer":307,mediasource:125,pump:188}],309:[function(e,t,n){(function(n,i,r){(function(){ /*! webtorrent. MIT License. WebTorrent LLC */ -const{EventEmitter:o}=e("events"),s=e("simple-concat"),a=e("create-torrent"),c=e("debug")("webtorrent"),l=e("bittorrent-dht/client"),p=e("load-ip-set"),u=e("run-parallel"),d=e("parse-torrent"),f=e("path"),h=e("simple-peer"),m=e("randombytes"),g=e("speedometer"),v=e("./lib/conn-pool"),b=e("./lib/torrent"),x=e("./package.json").version,y=x.replace(/\d*./g,(e=>("0"+e%100).slice(-2))).slice(0,4),_=`-WW${y}-`;class w extends o{constructor(e={}){super(),"string"==typeof e.peerId?this.peerId=e.peerId:r.isBuffer(e.peerId)?this.peerId=e.peerId.toString("hex"):this.peerId=r.from(_+m(9).toString("base64")).toString("hex"),this.peerIdBuffer=r.from(this.peerId,"hex"),"string"==typeof e.nodeId?this.nodeId=e.nodeId:r.isBuffer(e.nodeId)?this.nodeId=e.nodeId.toString("hex"):this.nodeId=m(20).toString("hex"),this.nodeIdBuffer=r.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=e.torrentPort||0,this.dhtPort=e.dhtPort||0,this.tracker=void 0!==e.tracker?e.tracker:{},this.torrents=[],this.maxConns=Number(e.maxConns)||55,this.utp=!0===e.utp,this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),e.rtcConfig&&(console.warn("WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead"),this.tracker.rtcConfig=e.rtcConfig),e.wrtc&&(console.warn("WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead"),this.tracker.wrtc=e.wrtc),i.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=i.WRTC)),"function"==typeof v?this._connPool=new v(this):n.nextTick((()=>{this._onListening()})),this._downloadSpeed=g(),this._uploadSpeed=g(),!1!==e.dht&&"function"==typeof l?(this.dht=new l(Object.assign({},{nodeId:this.nodeId},e.dht)),this.dht.once("error",(e=>{this._destroy(e)})),this.dht.once("listening",(()=>{const e=this.dht.address();e&&(this.dhtPort=e.port)})),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==e.webSeeds;const t=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof p&&null!=e.blocklist?p(e.blocklist,{headers:{"user-agent":`WebTorrent/${x} (https://webtorrent.io)`}},((e,n)=>{if(e)return this.error("Failed to load blocklist: "+e.message);this.blocked=n,t()})):n.nextTick(t)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const e=this.torrents.filter((e=>1!==e.progress));return e.reduce(((e,t)=>e+t.downloaded),0)/(e.reduce(((e,t)=>e+(t.length||0)),0)||1)}get ratio(){return this.torrents.reduce(((e,t)=>e+t.uploaded),0)/(this.torrents.reduce(((e,t)=>e+t.received),0)||1)}get(e){if(e instanceof b){if(this.torrents.includes(e))return e}else{let t;try{t=d(e)}catch(e){}if(!t)return null;if(!t.infoHash)throw new Error("Invalid torrent identifier");for(const e of this.torrents)if(e.infoHash===t.infoHash)return e}return null}download(e,t,n){return console.warn("WebTorrent: client.download() is deprecated. Use client.add() instead"),this.add(e,t,n)}add(e,t={},n=(()=>{})){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]);const i=()=>{if(!this.destroyed)for(const e of this.torrents)if(e.infoHash===o.infoHash&&e!==o)return void o._destroy(new Error("Cannot add duplicate torrent "+o.infoHash))},r=()=>{this.destroyed||(n(o),this.emit("torrent",o))};this._debug("add"),t=t?Object.assign({},t):{};const o=new b(e,this,t);return this.torrents.push(o),o.once("_infoHash",i),o.once("ready",r),o.once("close",(function e(){o.removeListener("_infoHash",i),o.removeListener("ready",r),o.removeListener("close",e)})),o}seed(e,t,n){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]),this._debug("seed"),(t=t?Object.assign({},t):{}).skipVerify=!0;const i="string"==typeof e;i&&(t.path=f.dirname(e)),t.createdBy||(t.createdBy="WebTorrent/"+y);const r=e=>{this._debug("on seed"),"function"==typeof n&&n(e),e.emit("seed"),this.emit("seed",e)},o=this.add(null,t,(e=>{const t=[t=>{if(i)return t();e.load(c,t)}];this.dht&&t.push((t=>{e.once("dhtAnnounce",t)})),u(t,(t=>{if(!this.destroyed)return t?e._destroy(t):void r(e)}))}));let c;var l;return l=e,"undefined"!=typeof FileList&&l instanceof FileList?e=Array.from(e):Array.isArray(e)||(e=[e]),u(e.map((e=>t=>{!function(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}(e)?t(null,e):s(e,t)})),((e,n)=>{if(!this.destroyed)return e?o._destroy(e):void a.parseInput(n,t,((e,i)=>{if(!this.destroyed){if(e)return o._destroy(e);c=i.map((e=>e.getStream)),a(n,t,((e,t)=>{if(this.destroyed)return;if(e)return o._destroy(e);const n=this.get(t);n?o._destroy(new Error("Cannot add duplicate torrent "+n.infoHash)):o._onTorrentId(t)}))}}))})),o}remove(e,t,n){if("function"==typeof t)return this.remove(e,null,t);this._debug("remove");if(!this.get(e))throw new Error("No torrent with id "+e);this._remove(e,t,n)}_remove(e,t,n){if("function"==typeof t)return this._remove(e,null,t);const i=this.get(e);i&&(this.torrents.splice(this.torrents.indexOf(i),1),i.destroy(t,n))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}destroy(e){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,e)}_destroy(e,t){this._debug("client destroy"),this.destroyed=!0;const n=this.torrents.map((e=>t=>{e.destroy(t)}));this._connPool&&n.push((e=>{this._connPool.destroy(e)})),this.dht&&n.push((e=>{this.dht.destroy(e)})),u(n,t),e&&this.emit("error",e),this.torrents=[],this._connPool=null,this.dht=null}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const e=this._connPool.tcpServer.address();e&&(this.torrentPort=e.port)}this.emit("listening")}_debug(){const e=[].slice.call(arguments);e[0]=`[${this._debugId}] ${e[0]}`,c(...e)}}w.WEBRTC_SUPPORT=h.WEBRTC_SUPPORT,w.VERSION=x,t.exports=w}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./lib/conn-pool":55,"./lib/torrent":314,"./package.json":334,_process:187,"bittorrent-dht/client":55,buffer:60,"create-torrent":80,debug:316,events:98,"load-ip-set":55,"parse-torrent":184,path:185,randombytes:195,"run-parallel":218,"simple-concat":221,"simple-peer":223,speedometer:263}],310:[function(e,t,n){const i=e("debug")("webtorrent:file-stream"),r=e("readable-stream");class o extends r.Readable{constructor(e,t){super(t),this.destroyed=!1,this._torrent=e._torrent;const n=t&&t.start||0,i=t&&t.end&&t.end{if(this._notifying=!1,!this.destroyed){if(i("read %s (length %s) (err %s)",e,n.length,t&&t.message),t)return this._destroy(t);this._offset&&(n=n.slice(this._offset),this._offset=0),this._missing{e.end()})),e}const t=new u(this,e);return this._torrent.select(t._startPiece,t._endPiece,!0,(()=>{t._notify()})),o(t,(()=>{this._destroyed||this._torrent.destroyed||this._torrent.deselect(t._startPiece,t._endPiece,!0)})),t}getBuffer(e){p(this.createReadStream(),this.length,e)}getBlob(e){if("undefined"==typeof window)throw new Error("browser-only method");c(this.createReadStream(),this._getMimeType()).then((t=>e(null,t)),(t=>e(t)))}getBlobURL(e){if("undefined"==typeof window)throw new Error("browser-only method");l(this.createReadStream(),this._getMimeType()).then((t=>e(null,t)),(t=>e(t)))}appendTo(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");a.append(this,e,t,n)}renderTo(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");a.render(this,e,t,n)}_getMimeType(){return a.mime[s.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null}}}).call(this)}).call(this,e("_process"))},{"./file-stream":310,_process:187,"end-of-stream":96,events:98,path:185,"readable-stream":333,"render-media":212,"stream-to-blob":284,"stream-to-blob-url":283,"stream-with-known-length-to-buffer":285}],312:[function(e,t,n){const i=e("unordered-array-remove"),r=e("debug")("webtorrent:peer"),o=e("bittorrent-protocol"),s=e("./webconn");n.createWebRTCPeer=(e,t)=>{const n=new l(e.id,"webrtc");return n.conn=e,n.swarm=t,n.conn.connected?n.onConnect():(n.conn.once("connect",(()=>{n.onConnect()})),n.conn.once("error",(e=>{n.destroy(e)})),n.startConnectTimeout()),n},n.createTCPIncomingPeer=e=>a(e,"tcpIncoming"),n.createUTPIncomingPeer=e=>a(e,"utpIncoming"),n.createTCPOutgoingPeer=(e,t)=>c(e,t,"tcpOutgoing"),n.createUTPOutgoingPeer=(e,t)=>c(e,t,"utpOutgoing");const a=(e,t)=>{const n=`${e.remoteAddress}:${e.remotePort}`,i=new l(n,t);return i.conn=e,i.addr=n,i.onConnect(),i},c=(e,t,n)=>{const i=new l(e,n);return i.addr=e,i.swarm=t,i};n.createWebSeedPeer=(e,t)=>{const n=new l(e,"webSeed");return n.swarm=t,n.conn=new s(e,t),n.onConnect(),n};class l{constructor(e,t){this.id=e,this.type=t,r("new %s Peer %s",t,e),this.addr=null,this.conn=null,this.swarm=null,this.wire=null,this.connected=!1,this.destroyed=!1,this.timeout=null,this.retries=0,this.sentHandshake=!1}onConnect(){if(this.destroyed)return;this.connected=!0,r("Peer %s connected",this.id),clearTimeout(this.connectTimeout);const e=this.conn;e.once("end",(()=>{this.destroy()})),e.once("close",(()=>{this.destroy()})),e.once("finish",(()=>{this.destroy()})),e.once("error",(e=>{this.destroy(e)}));const t=this.wire=new o;t.type=this.type,t.once("end",(()=>{this.destroy()})),t.once("close",(()=>{this.destroy()})),t.once("finish",(()=>{this.destroy()})),t.once("error",(e=>{this.destroy(e)})),t.once("handshake",((e,t)=>{this.onHandshake(e,t)})),this.startHandshakeTimeout(),e.pipe(t).pipe(e),this.swarm&&!this.sentHandshake&&this.handshake()}onHandshake(e,t){if(!this.swarm)return;if(this.destroyed)return;if(this.swarm.destroyed)return this.destroy(new Error("swarm already destroyed"));if(e!==this.swarm.infoHash)return this.destroy(new Error("unexpected handshake info hash for this swarm"));if(t===this.swarm.peerId)return this.destroy(new Error("refusing to connect to ourselves"));r("Peer %s got handshake %s",this.id,e),clearTimeout(this.handshakeTimeout),this.retries=0;let n=this.addr;!n&&this.conn.remoteAddress&&this.conn.remotePort&&(n=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,n),this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const e={dht:!this.swarm.private&&!!this.swarm.client.dht};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,e),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout);const e={webrtc:25e3,tcpOutgoing:5e3,utpOutgoing:5e3};this.connectTimeout=setTimeout((()=>{this.destroy(new Error("connect timeout"))}),e[this.type]),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout((()=>{this.destroy(new Error("handshake timeout"))}),25e3),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(e){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,r("destroy %s %s (error: %s)",this.type,this.id,e&&(e.message||e)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const t=this.swarm,n=this.conn,o=this.wire;this.swarm=null,this.conn=null,this.wire=null,t&&o&&i(t.wires,t.wires.indexOf(o)),n&&(n.on("error",(()=>{})),n.destroy()),o&&o.destroy(),t&&t.removePeer(this.id)}}},{"./webconn":315,"bittorrent-protocol":11,debug:316,"unordered-array-remove":298}],313:[function(e,t,n){t.exports=class{constructor(e){this._torrent=e,this._numPieces=e.pieces.length,this._pieces=new Array(this._numPieces),this._onWire=e=>{this.recalculate(),this._initWire(e)},this._onWireHave=e=>{this._pieces[e]+=1},this._onWireBitfield=()=>{this.recalculate()},this._torrent.wires.forEach((e=>{this._initWire(e)})),this._torrent.on("wire",this._onWire),this.recalculate()}getRarestPiece(e){let t=[],n=1/0;for(let i=0;i{this._cleanupWireEvents(e)})),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(e){e._onClose=()=>{this._cleanupWireEvents(e);for(let t=0;t{this.destroyed||this._onParsedTorrent(t)}))):x.remote(e,((e,t)=>{if(!this.destroyed)return e?this._destroy(e):void this._onParsedTorrent(t)}))}_onParsedTorrent(e){if(!this.destroyed){if(this._processParsedTorrent(e),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));this.path||(this.path=y.join(N,this.infoHash)),this._rechokeIntervalId=setInterval((()=>{this._rechoke()}),1e4),this._rechokeIntervalId.unref&&this._rechokeIntervalId.unref(),this.emit("_infoHash",this.infoHash),this.destroyed||(this.emit("infoHash",this.infoHash),this.destroyed||(this.client.listening?this._onListening():this.client.once("listening",(()=>{this._onListening()}))))}}_processParsedTorrent(e){this._debugId=e.infoHash.toString("hex").substring(0,7),void 0!==this.private&&(e.private=this.private),this.announce&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&i.WEBTORRENT_ANNOUNCE&&!e.private&&(e.announce=e.announce.concat(i.WEBTORRENT_ANNOUNCE)),this.urlList&&(e.urlList=e.urlList.concat(this.urlList)),e.announce=Array.from(new Set(e.announce)),e.urlList=Array.from(new Set(e.urlList)),Object.assign(this,e),this.magnetURI=x.toMagnetURI(e),this.torrentFile=x.toTorrentFile(e)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let e=this.client.tracker;e&&(e=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{const e={uploaded:this.uploaded,downloaded:this.downloaded,left:Math.max(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(e,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(e,this._getAnnounceOpts()),e}})),this.peerAddresses&&this.peerAddresses.forEach((e=>this.addPeer(e))),this.discovery=new c({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:e,port:this.client.torrentPort,userAgent:P}),this.discovery.on("error",(e=>{this._destroy(e)})),this.discovery.on("peer",(e=>{"string"==typeof e&&this.done||this.addPeer(e)})),this.discovery.on("trackerAnnounce",(()=>{this.emit("trackerAnnounce"),0===this.numPeers&&this.emit("noPeers","tracker")})),this.discovery.on("dhtAnnounce",(()=>{this.emit("dhtAnnounce"),0===this.numPeers&&this.emit("noPeers","dht")})),this.discovery.on("warning",(e=>{this.emit("warning",e)}))}_getMetadataFromServer(){const e=this,t=(Array.isArray(this.xs)?this.xs:[this.xs]).map((t=>n=>{!function(t,n){if(0!==t.indexOf("http://")&&0!==t.indexOf("https://"))return e.emit("warning",new Error("skipping non-http xs param: "+t)),n(null);const i={url:t,method:"GET",headers:{"user-agent":P}};let r;try{r=d.concat(i,o)}catch(i){return e.emit("warning",new Error("skipping invalid url xs param: "+t)),n(null)}function o(i,r,o){if(e.destroyed)return n(null);if(e.metadata)return n(null);if(i)return e.emit("warning",new Error("http error from xs param: "+t)),n(null);if(200!==r.statusCode)return e.emit("warning",new Error(`non-200 status code ${r.statusCode} from xs param: ${t}`)),n(null);let s;try{s=x(o)}catch(i){}return s?s.infoHash!==e.infoHash?(e.emit("warning",new Error("got torrent file with incorrect info hash from xs param: "+t)),n(null)):(e._onMetadata(s),void n(null)):(e.emit("warning",new Error("got invalid torrent file from xs param: "+t)),n(null))}e._xsRequests.push(r)}(t,n)}));v(t)}_onMetadata(e){if(this.metadata||this.destroyed)return;let t;if(this._debug("got metadata"),this._xsRequests.forEach((e=>{e.abort()})),this._xsRequests=[],e&&e.infoHash)t=e;else try{t=x(e)}catch(e){return this._destroy(e)}if(this._processParsedTorrent(t),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach((e=>{this.addWebSeed(e)})),this._rarityMap=new I(this),this.store=new f(new this._store(this.pieceLength,{torrent:{infoHash:this.infoHash},files:this.files.map((e=>({path:y.join(this.path,e.path),length:e.length,offset:e.offset}))),length:this.length,name:this.infoHash})),this.files=this.files.map((e=>new A(this,e))),this.so?this.files.forEach(((e,t)=>{this.so.includes(t)?this.files[t].select():this.files[t].deselect()})):0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1),this._hashes=this.pieces,this.pieces=this.pieces.map(((e,t)=>{const n=t===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new _(n)})),this._reservations=this.pieces.map((()=>[])),this.bitfield=new o(this.pieces.length),this.wires.forEach((e=>{e.ut_metadata&&e.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(e)})),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const e=e=>{if(e)return this._destroy(e);this._debug("done verifying"),this._onStore()};this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===u?this.getFileModtimes(((t,n)=>{if(t)return this._destroy(t);this.files.map(((e,t)=>n[t]===this._fileModtimes[t])).every((e=>e))?(this._markAllVerified(),this._onStore()):this._verifyPieces(e)})):this._verifyPieces(e)}}getFileModtimes(e){const t=[];b(this.files.map(((e,n)=>i=>{p.stat(y.join(this.path,e.path),((e,r)=>{if(e&&"ENOENT"!==e.code)return i(e);t[n]=r&&r.mtime.getTime(),i(null)}))})),U,(n=>{this._debug("done getting file modtimes"),e(n,t)}))}_verifyPieces(e){b(this.pieces.map(((e,t)=>e=>{if(this.destroyed)return e(new Error("torrent is destroyed"));this.store.get(t,((i,r)=>this.destroyed?e(new Error("torrent is destroyed")):i?n.nextTick(e,null):void E(r,(n=>{if(this.destroyed)return e(new Error("torrent is destroyed"));if(n===this._hashes[t]){if(!this.pieces[t])return e(null);this._debug("piece verified %s",t),this._markVerified(t)}else this._debug("piece invalid %s",t);e(null)}))))})),U,e)}rescanFiles(e){if(this.destroyed)throw new Error("torrent is destroyed");e||(e=q),this._verifyPieces((t=>{if(t)return this._destroy(t),e(t);this._checkDone(),e(null)}))}_markAllVerified(){for(let e=0;e{e.abort()})),this._rarityMap&&this._rarityMap.destroy();for(const e in this._peers)this.removePeer(e);this.files.forEach((e=>{e instanceof A&&e._destroy()}));const i=this._servers.map((e=>t=>{e.destroy(t)}));this.discovery&&i.push((e=>{this.discovery.destroy(e)})),this.store&&i.push((e=>{t&&t.destroyStore?this.store.destroy(e):this.store.close(e)})),v(i,n),e&&(0===this.listenerCount("error")?this.client.emit("error",e):this.emit("error",e)),this.emit("close"),this.client=null,this.files=[],this.discovery=null,this.store=null,this._rarityMap=null,this._peers=null,this._servers=null,this._xsRequests=null}addPeer(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");if(this.client.blocked){let t;if("string"==typeof e){let n;try{n=r(e)}catch(t){return this._debug("ignoring peer: invalid %s",e),this.emit("invalidPeer",e),!1}t=n[0]}else"string"==typeof e.remoteAddress&&(t=e.remoteAddress);if(t&&this.client.blocked.contains(t))return this._debug("ignoring peer: blocked %s",e),"string"!=typeof e&&e.destroy(),this.emit("blockedPeer",e),!1}const t=!!this._addPeer(e,this.client.utp?"utp":"tcp");return t?this.emit("peer",e):this.emit("invalidPeer",e),t}_addPeer(e,t){if(this.destroyed)return"string"!=typeof e&&e.destroy(),null;if("string"==typeof e&&!this._validAddr(e))return this._debug("ignoring peer: invalid %s",e),null;const n=e&&e.id||e;if(this._peers[n])return this._debug("ignoring peer: duplicate (%s)",n),"string"!=typeof e&&e.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;let i;return this._debug("add peer %s",n),i="string"==typeof e?"utp"===t?L.createUTPOutgoingPeer(e,this):L.createTCPOutgoingPeer(e,this):L.createWebRTCPeer(e,this),this._peers[i.id]=i,this._peersLength+=1,"string"==typeof e&&(this._queue.push(i),this._drain()),i}addWebSeed(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!/^https?:\/\/.+/.test(e))return this.emit("warning",new Error("ignoring invalid web seed: "+e)),void this.emit("invalidPeer",e);if(this._peers[e])return this.emit("warning",new Error("ignoring duplicate web seed: "+e)),void this.emit("invalidPeer",e);this._debug("add web seed %s",e);const t=L.createWebSeedPeer(e,this);this._peers[t.id]=t,this._peersLength+=1,this.emit("peer",e)}_addIncomingPeer(e){return this.destroyed?e.destroy(new Error("torrent is destroyed")):this.paused?e.destroy(new Error("torrent is paused")):(this._debug("add incoming peer %s",e.id),this._peers[e.id]=e,void(this._peersLength+=1))}removePeer(e){const t=e&&e.id||e;(e=this._peers[t])&&(this._debug("removePeer %s",t),delete this._peers[t],this._peersLength-=1,e.destroy(),this._drain())}select(e,t,n,i){if(this.destroyed)throw new Error("torrent is destroyed");if(e<0||tt.priority-e.priority)),this._updateSelections()}deselect(e,t,n){if(this.destroyed)throw new Error("torrent is destroyed");n=Number(n)||0,this._debug("deselect %s-%s (priority %s)",e,t,n);for(let i=0;i{this.destroyed||(this.received+=e,this._downloadSpeed(e),this.client._downloadSpeed(e),this.emit("download",e),this.destroyed||this.client.emit("download",e))})),e.on("upload",(e=>{this.destroyed||(this.uploaded+=e,this._uploadSpeed(e),this.client._uploadSpeed(e),this.emit("upload",e),this.destroyed||this.client.emit("upload",e))})),this.wires.push(e),t){const n=r(t);e.remoteAddress=n[0],e.remotePort=n[1]}this.client.dht&&this.client.dht.listening&&e.on("port",(n=>{if(!this.destroyed&&!this.client.dht.destroyed){if(!e.remoteAddress)return this._debug("ignoring PORT from peer with no address");if(0===n||n>65536)return this._debug("ignoring invalid PORT from peer");this._debug("port: %s (from %s)",n,t),this.client.dht.addNode({host:e.remoteAddress,port:n})}})),e.on("timeout",(()=>{this._debug("wire timeout (%s)",t),e.destroy()})),e.setTimeout(3e4,!0),e.setKeepAlive(!0),e.use(C(this.metadata)),e.ut_metadata.on("warning",(e=>{this._debug("ut_metadata warning: %s",e.message)})),this.metadata||(e.ut_metadata.on("metadata",(e=>{this._debug("got metadata via ut_metadata"),this._onMetadata(e)})),e.ut_metadata.fetch()),"function"!=typeof T||this.private||(e.use(T()),e.ut_pex.on("peer",(e=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",e,t),this.addPeer(e))})),e.ut_pex.on("dropped",(e=>{const n=this._peers[e];n&&!n.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",e,t),this.removePeer(e))})),e.once("close",(()=>{e.ut_pex.reset()}))),this.emit("wire",e,t),this.metadata&&n.nextTick((()=>{this._onWireWithMetadata(e)}))}_onWireWithMetadata(e){let t=null;const n=()=>{this.destroyed||e.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&e.amInterested?e.destroy():(t=setTimeout(n,R),t.unref&&t.unref()))};let i;const r=()=>{if(e.peerPieces.buffer.length===this.bitfield.buffer.length){for(i=0;i{r(),this._update(),this._updateWireInterest(e)})),e.on("have",(()=>{r(),this._update(),this._updateWireInterest(e)})),e.once("interested",(()=>{e.unchoke()})),e.once("close",(()=>{clearTimeout(t)})),e.on("choke",(()=>{clearTimeout(t),t=setTimeout(n,R),t.unref&&t.unref()})),e.on("unchoke",(()=>{clearTimeout(t),this._update()})),e.on("request",((t,n,i,r)=>{if(i>131072)return e.destroy();this.pieces[t]||this.store.get(t,{offset:n,length:i},r)})),e.bitfield(this.bitfield),this._updateWireInterest(e),e.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&e.port(this.client.dht.address().port),"webSeed"!==e.type&&(t=setTimeout(n,R),t.unref&&t.unref()),e.isSeeder=!1,r()}_updateSelections(){this.ready&&!this.destroyed&&(n.nextTick((()=>{this._gcSelections()})),this._updateInterest(),this._update())}_gcSelections(){for(let e=0;ethis._updateWireInterest(e))),e!==this._amInterested&&(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(e){let t=!1;for(let n=0;n=i.from+i.offset;--o)if(e.peerPieces.get(o)&&t._request(e,o,!1))return}}();const n=D(e,.5);if(e.requests.length>=n)return;const i=D(e,1);function r(t,n,i,r){return o=>o>=t&&o<=n&&!(o in i)&&e.peerPieces.get(o)&&(!r||r(o))}function o(e){let n=e;for(let i=e;i=i)return!0;const s=function(){const n=e.downloadSpeed()||1;if(n>B)return()=>!0;const i=Math.max(1,e.requests.length)*_.BLOCK_LENGTH/n;let r=10,o=0;return e=>{if(!r||t.bitfield.get(e))return!0;let s=t.pieces[e].missing;for(;o0))return r--,!1}return!0}}();for(let a=0;a({wire:e,random:Math.random()}))).sort(((e,t)=>{const n=e.wire,i=t.wire;return n.downloadSpeed()!==i.downloadSpeed()?n.downloadSpeed()-i.downloadSpeed():n.uploadSpeed()!==i.uploadSpeed()?n.uploadSpeed()-i.uploadSpeed():n.amChoking!==i.amChoking?n.amChoking?-1:1:e.random-t.random})).map((e=>e.wire));this._rechokeOptimisticTime<=0?this._rechokeOptimisticWire=null:this._rechokeOptimisticTime-=1;let t=0;for(;e.length>0&&t0){const t=e.filter((e=>e.peerInterested));if(t.length>0){const e=t[(n=t.length,Math.random()*n|0)];e.unchoke(),this._rechokeOptimisticWire=e,this._rechokeOptimisticTime=2}}var n;e.filter((e=>e!==this._rechokeOptimisticWire)).forEach((e=>e.choke()))}_hotswap(e,t){const n=e.downloadSpeed();if(n<_.BLOCK_LENGTH)return!1;if(!this._reservations[t])return!1;const i=this._reservations[t];if(!i)return!1;let r,o,s=1/0;for(o=0;o=B||(2*a>n||a>s||(r=t,s=a))}if(!r)return!1;for(o=0;o=(s?Math.min(function(e,t,n){return 1+Math.ceil(t*e.downloadSpeed()/n)}(e,1,r.pieceLength),r.maxWebConns):D(e,1)))return!1;const a=r.pieces[t];let c=s?a.reserveRemaining():a.reserve();if(-1===c&&i&&r._hotswap(e,t)&&(c=s?a.reserveRemaining():a.reserve()),-1===c)return!1;let l=r._reservations[t];l||(l=r._reservations[t]=[]);let p=l.indexOf(null);-1===p&&(p=l.length),l[p]=e;const u=a.chunkOffset(c),d=s?a.chunkLengthRemaining(c):a.chunkLength(c);function f(){n.nextTick((()=>{r._update()}))}return e.request(t,u,d,(function n(i,o){if(r.destroyed)return;if(!r.ready)return r.once("ready",(()=>{n(i,o)}));if(l[p]===e&&(l[p]=null),a!==r.pieces[t])return f();if(i)return r._debug("error getting piece %s (offset: %s length: %s) from %s: %s",t,u,d,`${e.remoteAddress}:${e.remotePort}`,i.message),s?a.cancelRemaining(c):a.cancel(c),void f();if(r._debug("got piece %s (offset: %s length: %s) from %s",t,u,d,`${e.remoteAddress}:${e.remotePort}`),!a.set(c,o,e))return f();const h=a.flush();E(h,(e=>{if(!r.destroyed){if(e===r._hashes[t]){if(!r.pieces[t])return;r._debug("piece verified %s",t),r.pieces[t]=null,r._reservations[t]=null,r.bitfield.set(t,!0),r.store.put(t,h),r.wires.forEach((e=>{e.have(t)})),r._checkDone()&&!r.destroyed&&r.discovery.complete()}else r.pieces[t]=new _(a.length),r.emit("warning",new Error(`Piece ${t} failed verification`));f()}}))})),!0}_checkDone(){if(this.destroyed)return;this.files.forEach((e=>{if(!e.done){for(let t=e._startPiece;t<=e._endPiece;++t)if(!this.bitfield.get(t))return;e.done=!0,e.emit("done"),this._debug("file done: "+e.name)}}));let e=!0;for(let t=0;t{this.load(e,t)}));Array.isArray(e)||(e=[e]),t||(t=q);const n=new h(e),i=new s(this.store,this.pieceLength);w(n,i,(e=>{if(e)return t(e);this._markAllVerified(),this._checkDone(),t(null)}))}createServer(e){if("function"!=typeof O)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const t=new O(this,e);return this._servers.push(t),t}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const e=[].slice.call(arguments);e[0]=`[${this.client?this.client._debugId:"No Client"}] [${this._debugId}] ${e[0]}`,a(...e)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof m.connect||this.destroyed||this.paused||this._numConns>=this.client.maxConns)return;this._debug("drain (%s queued, %s/%s peers)",this._numQueued,this.numPeers,this.client.maxConns);const e=this._queue.shift();if(!e)return;this._debug("%s connect attempt to %s",e.type,e.addr);const t=r(e.addr),n={host:t[0],port:t[1]};"utpOutgoing"===e.type?e.conn=j.connect(n.port,n.host):e.conn=m.connect(n);const i=e.conn;i.once("connect",(()=>{e.onConnect()})),i.once("error",(t=>{e.destroy(t)})),e.startConnectTimeout(),i.on("close",(()=>{if(this.destroyed)return;if(e.retries>=M.length){if(this.client.utp){const t=this._addPeer(e.addr,"tcp");t&&(t.retries=0)}else this._debug("conn %s closed: will not re-add (max %s attempts)",e.addr,M.length);return}const t=M[e.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",e.addr,t,e.retries+1);const n=setTimeout((()=>{if(this.destroyed)return;const t=this._addPeer(e.addr,this.client.utp?"utp":"tcp");t&&(t.retries=e.retries+1)}),t);n.unref&&n.unref()}))}_validAddr(e){let t;try{t=r(e)}catch(e){return!1}const n=t[0],i=t[1];return i>0&&i<65535&&!("127.0.0.1"===n&&i===this.client.torrentPort)}}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../package.json":334,"./file":311,"./peer":312,"./rarity-map":313,"./server":55,_process:187,"addr-to-ip-port":3,bitfield:10,"chunk-store-stream/write":78,debug:316,events:98,fs:56,"fs-chunk-store":141,"immediate-chunk-store":118,multistream:166,net:55,os:55,"parse-torrent":184,path:185,pump:188,"random-iterate":194,"run-parallel":218,"run-parallel-limit":217,"simple-get":222,"simple-sha1":242,speedometer:263,"torrent-discovery":291,"torrent-piece":295,ut_metadata:301,ut_pex:55,"utp-native":55}],315:[function(e,t,n){(function(n){(function(){const i=e("bitfield"),r=e("debug")("webtorrent:webconn"),o=e("simple-get"),s=e("simple-sha1"),a=e("bittorrent-protocol"),c=e("../package.json").version;t.exports=class extends a{constructor(e,t){super(),this.url=e,this.webPeerId=s.sync(e),this._torrent=t,this._init()}_init(){this.setKeepAlive(!0),this.once("handshake",((e,t)=>{if(this.destroyed)return;this.handshake(e,this.webPeerId);const n=this._torrent.pieces.length,r=new i(n);for(let e=0;e<=n;e++)r.set(e,!0);this.bitfield(r)})),this.once("interested",(()=>{r("interested"),this.unchoke()})),this.on("uninterested",(()=>{r("uninterested")})),this.on("choke",(()=>{r("choke")})),this.on("unchoke",(()=>{r("unchoke")})),this.on("bitfield",(()=>{r("bitfield")})),this.on("request",((e,t,n,i)=>{r("request pieceIndex=%d offset=%d length=%d",e,t,n),this.httpRequest(e,t,n,i)}))}httpRequest(e,t,i,s){const a=e*this._torrent.pieceLength+t,l=a+i-1,p=this._torrent.files;let u;if(p.length<=1)u=[{url:this.url,start:a,end:l}];else{const e=p.filter((e=>e.offset<=l&&e.offset+e.length>a));if(e.length<1)return s(new Error("Could not find file corresponnding to web seed range request"));u=e.map((e=>{const t=e.offset+e.length-1;return{url:this.url+("/"===this.url[this.url.length-1]?"":"/")+e.path,fileOffsetInRange:Math.max(e.offset-a,0),start:Math.max(a-e.offset,0),end:Math.min(t,l-e.offset)}}))}let d,f=0,h=!1;u.length>1&&(d=n.alloc(i)),u.forEach((n=>{const a=n.url,l=n.start,p=n.end;r("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",a,e,t,i,l,p);const m={url:a,method:"GET",headers:{"user-agent":`WebTorrent/${c} (https://webtorrent.io)`,range:`bytes=${l}-${p}`}};function g(e,t){if(e.statusCode<200||e.statusCode>=300)return h=!0,s(new Error("Unexpected HTTP status code "+e.statusCode));r("Got data of length %d",t.length),1===u.length?s(null,t):(t.copy(d,n.fileOffsetInRange),++f===u.length&&s(null,d))}o.concat(m,((e,t,n)=>{if(!h)return e?"undefined"==typeof window||a.startsWith(window.location.origin+"/")?(h=!0,s(e)):o.head(a,((t,n)=>{if(!h){if(t)return h=!0,s(t);if(n.statusCode<200||n.statusCode>=300)return h=!0,s(new Error("Unexpected HTTP status code "+n.statusCode));if(n.url===a)return h=!0,s(e);m.url=n.url,o.concat(m,((e,t,n)=>{if(!h)return e?(h=!0,s(e)):void g(t,n)}))}})):void g(t,n)}))}))}destroy(){super.destroy(),this._torrent=null}}}).call(this)}).call(this,e("buffer").Buffer)},{"../package.json":334,bitfield:10,"bittorrent-protocol":11,buffer:60,debug:316,"simple-get":222,"simple-sha1":242}],316:[function(e,t,n){arguments[4][13][0].apply(n,arguments)},{"./common":317,_process:187,dup:13}],317:[function(e,t,n){arguments[4][14][0].apply(n,arguments)},{dup:14,ms:318}],318:[function(e,t,n){arguments[4][15][0].apply(n,arguments)},{dup:15}],319:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{dup:16}],320:[function(e,t,n){arguments[4][17][0].apply(n,arguments)},{"./_stream_readable":322,"./_stream_writable":324,_process:187,dup:17,inherits:119}],321:[function(e,t,n){arguments[4][18][0].apply(n,arguments)},{"./_stream_transform":323,dup:18,inherits:119}],322:[function(e,t,n){arguments[4][19][0].apply(n,arguments)},{"../errors":319,"./_stream_duplex":320,"./internal/streams/async_iterator":325,"./internal/streams/buffer_list":326,"./internal/streams/destroy":327,"./internal/streams/from":329,"./internal/streams/state":331,"./internal/streams/stream":332,_process:187,buffer:60,dup:19,events:98,inherits:119,"string_decoder/":286,util:55}],323:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{"../errors":319,"./_stream_duplex":320,dup:20,inherits:119}],324:[function(e,t,n){arguments[4][21][0].apply(n,arguments)},{"../errors":319,"./_stream_duplex":320,"./internal/streams/destroy":327,"./internal/streams/state":331,"./internal/streams/stream":332,_process:187,buffer:60,dup:21,inherits:119,"util-deprecate":306}],325:[function(e,t,n){arguments[4][22][0].apply(n,arguments)},{"./end-of-stream":328,_process:187,dup:22}],326:[function(e,t,n){arguments[4][23][0].apply(n,arguments)},{buffer:60,dup:23,util:55}],327:[function(e,t,n){arguments[4][24][0].apply(n,arguments)},{_process:187,dup:24}],328:[function(e,t,n){arguments[4][25][0].apply(n,arguments)},{"../../../errors":319,dup:25}],329:[function(e,t,n){arguments[4][26][0].apply(n,arguments)},{dup:26}],330:[function(e,t,n){arguments[4][27][0].apply(n,arguments)},{"../../../errors":319,"./end-of-stream":328,dup:27}],331:[function(e,t,n){arguments[4][28][0].apply(n,arguments)},{"../../../errors":319,dup:28}],332:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29,events:98}],333:[function(e,t,n){arguments[4][30][0].apply(n,arguments)},{"./lib/_stream_duplex.js":320,"./lib/_stream_passthrough.js":321,"./lib/_stream_readable.js":322,"./lib/_stream_transform.js":323,"./lib/_stream_writable.js":324,"./lib/internal/streams/end-of-stream.js":328,"./lib/internal/streams/pipeline.js":330,dup:30}],334:[function(e,t,n){t.exports={version:"0.110.1"}},{}],335:[function(e,t,n){t.exports=function e(t,n){if(t&&n)return e(t)(n);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach((function(e){i[e]=t[e]})),i;function i(){for(var e=new Array(arguments.length),n=0;n1080?(O.setProps({placement:"right"}),R.setProps({placement:"right"}),B.setProps({placement:"right"})):(O.setProps({placement:"top"}),R.setProps({placement:"top"}),B.setProps({placement:"top"}))}function P(e){z();try{console.info("Attempting parse"),p=r(e),D(),p.xs&&(console.info("Magnet includes xs, attempting remote parse"),N(p.xs))}catch(t){console.warn(t),console.info("Attempting remote parse"),N(e)}}function N(e){r.remote(e,(function(e,t){if(e)return console.error(e),void z();d.innerHTML='',f.setContent("Currently loaded information sourced from remotely fetched Torrent file"),p=t,D()}))}function D(){if(console.log(p),x.value=p.infoHash,h.value=p.name?p.name:"",p.created?(g.value=p.created.toISOString().slice(0,19),g.type="datetime-local"):g.type="text",v.value=p.createdBy?"by "+p.createdBy:"",b.value=p.comment?p.comment:"",k.innerHTML="",p.announce&&p.announce.length)for(let e=0;e',i.addEventListener("click",$),t.appendChild(i),k.appendChild(t)}if(E.innerHTML="",p.urlList&&p.urlList.length)for(let e=0;e',i.addEventListener("click",$),t.appendChild(i),E.appendChild(t)}if(T.innerHTML="",p.files&&p.files.length){j.style.display="none";for(let e of p.files){let t=H(a.lookup(e.name));T.appendChild(q(t,e.name,e.length))}T.appendChild(q("folder-tree","",p.length)),I.addEventListener("click",X),I.disabled=!1}else U.torrents.length>0?(j.style.display="none",T.innerHTML=''):(j.style.display="block",T.innerHTML=''),I.removeEventListener("click",X),I.disabled=!0;A.setAttribute("data-clipboard-text",window.location.origin+"#"+r.toMagnetURI(p)),L.setAttribute("data-clipboard-text",r.toMagnetURI(p)),u.style.display="flex",window.location.hash=r.toMagnetURI(p),p.name?document.title="Torrent Parts | "+p.name:document.title="Torrent Parts | Inspect and edit what's in your Torrent file or Magnet link",f.enable()}function q(e,t,n){let i=document.createElement("tr"),r=document.createElement("td");r.innerHTML='',i.appendChild(r);let o=document.createElement("td");o.innerHTML=t,i.appendChild(o);let a=document.createElement("td");return a.innerHTML=s.format(n,{decimalPlaces:1,unitSeparator:" "}),i.appendChild(a),i}function H(e){if(!e)return"file";switch(!0){case e.includes("msword"):case e.includes("wordprocessingml"):case e.includes("opendocument.text"):case e.includes("abiword"):return"file-word";case e.includes("ms-excel"):case e.includes("spreadsheet"):return"file-powerpoint";case e.includes("powerpoint"):case e.includes("presentation"):return"file-powerpoint";case e.includes("7z-"):case e.includes("iso9660"):case e.includes("zip"):case e.includes("octet-stream"):return"file-archive";case e.includes("csv"):return"file-csv";case e.includes("pdf"):return"file-pdf";case e.includes("font"):return"file-contract";case e.includes("text"):case e.includes("subrip"):case e.includes("vtt"):return"file-alt";case e.includes("audio"):return"file-audio";case e.includes("image"):return"file-image";case e.includes("video"):return"file-video";default:return"file"}}function F(e){this.dataset.group?p[this.dataset.group][this.dataset.index]=this.value?this.value:"":p[this.id]=this.value?this.value:"",window.location.hash=r.toMagnetURI(p),Y()}function z(){document.getElementById("magnet").value="",document.getElementById("torrent").value="",u.style.display="none",h.value="",g.value="",v.value="",b.value="",x.value="",k.innerHTML="",E.innerHTML="",U.torrents.forEach((e=>e.destroy())),j.style.display="block",T.innerHTML="",window.location.hash="",A.setAttribute("data-clipboard-text",""),L.setAttribute("data-clipboard-text",""),document.title="Torrent Parts | Inspect and edit what's in your Torrent file or Magnet link",f.disable()}async function W(){y.className="disabled",y.innerHTML="Adding...";try{let e=await fetch("https://newtrackon.com/api/100"),t=await e.text();p.announce=p.announce.concat(t.split("\n\n")),p.announce.push("http://bt1.archive.org:6969/announce"),p.announce.push("http://bt2.archive.org:6969/announce"),p.announce=p.announce.filter(((e,t)=>e&&p.announce.indexOf(e)===t)),Y()}catch(e){console.error(e)}y.innerHTML="Add Known Working Trackers",y.className="",D()}function V(){p[this.dataset.type].unshift(""),D()}function $(){p[this.parentElement.className].splice(this.parentElement.dataset.index,1),D()}function G(e){p[e]=[],Y(),D()}function Y(){p.created=new Date,p.createdBy="Torrent Parts ",p.created?(g.value=p.created.toISOString().slice(0,19),g.type="datetime-local"):g.type="text",v.value=p.createdBy?"by "+p.createdBy:""}function K(){console.info("Attempting fetching files from Webtorrent..."),j.style.display="none",p.announce.push("wss://tracker.webtorrent.io"),p.announce.push("wss://tracker.openwebtorrent.com"),p.announce.push("wss://tracker.btorrent.xyz"),p.announce.push("wss://tracker.fastcast.nz"),p.announce=p.announce.filter(((e,t)=>e&&p.announce.indexOf(e)===t)),U.add(r.toMagnetURI(p),(e=>{p.info=Object.assign({},e.info),p.files=e.files,p.infoBuffer=e.infoBuffer,p.length=e.length,p.lastPieceLength=e.lastPieceLength,Y(),D(),e.destroy()})),D()}function X(){let e=r.toTorrentFile(p);if(null!==e&&navigator.msSaveBlob)return navigator.msSaveBlob(new Blob([e],{type:"application/x-bittorrent"}),p.name+".torrent");let t=document.createElement("a");t.style.display="none";let n=window.URL.createObjectURL(new Blob([e],{type:"application/x-bittorrent"}));t.setAttribute("href",n),t.setAttribute("download",p.name+".torrent"),document.body.appendChild(t),t.click(),window.URL.revokeObjectURL(n),t.remove()}window.addEventListener("resize",M),M(),document.addEventListener("DOMContentLoaded",(function(){document.getElementById("magnet").addEventListener("keyup",(function(e){e.preventDefault(),"Enter"===e.key&&(d.innerHTML='',f.setContent("Currently loaded information sourced from Magnet URL"),P(magnet.value))})),document.getElementById("torrent").addEventListener("change",(function(e){e.preventDefault();try{e.target.files[0].arrayBuffer().then((function(e){d.innerHTML='',f.setContent("Currently loaded information sourced from Torrent file"),P(o.from(e))}))}catch(e){console.error(e)}}));let e=new i("#copyURL");e.on("success",(function(e){console.info(e)})),e.on("failure",(function(e){console.error(e)}));let t=new i("#copyMagnet");t.on("success",(function(e){console.info(e)})),t.on("failure",(function(e){console.error(e)})),h.addEventListener("input",F),h.addEventListener("change",F),h.addEventListener("reset",F),h.addEventListener("paste",F),m.addEventListener("click",z),b.addEventListener("input",F),b.addEventListener("change",F),b.addEventListener("reset",F),b.addEventListener("paste",F),y.addEventListener("click",W),_.addEventListener("click",V),w.addEventListener("click",(()=>G("announce"))),S.addEventListener("click",V),C.addEventListener("click",(()=>G("urlList"))),j.addEventListener("click",K),l("[data-tippy-content]",{theme:"torrent-parts",animation:"shift-away-subtle"}),window.location.hash&&(d.innerHTML='',f.setContent("Currently loaded information sourced from shared torrent.parts link"),P(window.location.hash.split("#")[1]))}))},{Buffer:2,bytes:62,clipboard:79,"mime-types":144,"parse-torrent":184,"tippy.js":289,webtorrent:309}]},{},[337]); \ No newline at end of file +const{EventEmitter:o}=e("events"),s=e("simple-concat"),a=e("create-torrent"),c=e("debug")("webtorrent"),l=e("bittorrent-dht/client"),p=e("load-ip-set"),u=e("run-parallel"),d=e("parse-torrent"),f=e("path"),h=e("simple-peer"),m=e("randombytes"),g=e("speedometer"),v=e("./lib/conn-pool"),b=e("./lib/torrent"),x=e("./package.json").version,y=x.replace(/\d*./g,(e=>("0"+e%100).slice(-2))).slice(0,4),_=`-WW${y}-`;class w extends o{constructor(e={}){super(),"string"==typeof e.peerId?this.peerId=e.peerId:r.isBuffer(e.peerId)?this.peerId=e.peerId.toString("hex"):this.peerId=r.from(_+m(9).toString("base64")).toString("hex"),this.peerIdBuffer=r.from(this.peerId,"hex"),"string"==typeof e.nodeId?this.nodeId=e.nodeId:r.isBuffer(e.nodeId)?this.nodeId=e.nodeId.toString("hex"):this.nodeId=m(20).toString("hex"),this.nodeIdBuffer=r.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=e.torrentPort||0,this.dhtPort=e.dhtPort||0,this.tracker=void 0!==e.tracker?e.tracker:{},this.torrents=[],this.maxConns=Number(e.maxConns)||55,this.utp=!0===e.utp,this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),e.rtcConfig&&(console.warn("WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead"),this.tracker.rtcConfig=e.rtcConfig),e.wrtc&&(console.warn("WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead"),this.tracker.wrtc=e.wrtc),i.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=i.WRTC)),"function"==typeof v?this._connPool=new v(this):n.nextTick((()=>{this._onListening()})),this._downloadSpeed=g(),this._uploadSpeed=g(),!1!==e.dht&&"function"==typeof l?(this.dht=new l(Object.assign({},{nodeId:this.nodeId},e.dht)),this.dht.once("error",(e=>{this._destroy(e)})),this.dht.once("listening",(()=>{const e=this.dht.address();e&&(this.dhtPort=e.port)})),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==e.webSeeds;const t=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof p&&null!=e.blocklist?p(e.blocklist,{headers:{"user-agent":`WebTorrent/${x} (https://webtorrent.io)`}},((e,n)=>{if(e)return this.error("Failed to load blocklist: "+e.message);this.blocked=n,t()})):n.nextTick(t)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const e=this.torrents.filter((e=>1!==e.progress));return e.reduce(((e,t)=>e+t.downloaded),0)/(e.reduce(((e,t)=>e+(t.length||0)),0)||1)}get ratio(){return this.torrents.reduce(((e,t)=>e+t.uploaded),0)/(this.torrents.reduce(((e,t)=>e+t.received),0)||1)}get(e){if(e instanceof b){if(this.torrents.includes(e))return e}else{let t;try{t=d(e)}catch(e){}if(!t)return null;if(!t.infoHash)throw new Error("Invalid torrent identifier");for(const e of this.torrents)if(e.infoHash===t.infoHash)return e}return null}download(e,t,n){return console.warn("WebTorrent: client.download() is deprecated. Use client.add() instead"),this.add(e,t,n)}add(e,t={},n=(()=>{})){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]);const i=()=>{if(!this.destroyed)for(const e of this.torrents)if(e.infoHash===o.infoHash&&e!==o)return void o._destroy(new Error("Cannot add duplicate torrent "+o.infoHash))},r=()=>{this.destroyed||(n(o),this.emit("torrent",o))};this._debug("add"),t=t?Object.assign({},t):{};const o=new b(e,this,t);return this.torrents.push(o),o.once("_infoHash",i),o.once("ready",r),o.once("close",(function e(){o.removeListener("_infoHash",i),o.removeListener("ready",r),o.removeListener("close",e)})),o}seed(e,t,n){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]),this._debug("seed"),(t=t?Object.assign({},t):{}).skipVerify=!0;const i="string"==typeof e;i&&(t.path=f.dirname(e)),t.createdBy||(t.createdBy="WebTorrent/"+y);const r=e=>{this._debug("on seed"),"function"==typeof n&&n(e),e.emit("seed"),this.emit("seed",e)},o=this.add(null,t,(e=>{const t=[t=>{if(i)return t();e.load(c,t)}];this.dht&&t.push((t=>{e.once("dhtAnnounce",t)})),u(t,(t=>{if(!this.destroyed)return t?e._destroy(t):void r(e)}))}));let c;var l;return l=e,"undefined"!=typeof FileList&&l instanceof FileList?e=Array.from(e):Array.isArray(e)||(e=[e]),u(e.map((e=>t=>{!function(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}(e)?t(null,e):s(e,t)})),((e,n)=>{if(!this.destroyed)return e?o._destroy(e):void a.parseInput(n,t,((e,i)=>{if(!this.destroyed){if(e)return o._destroy(e);c=i.map((e=>e.getStream)),a(n,t,((e,t)=>{if(this.destroyed)return;if(e)return o._destroy(e);const n=this.get(t);n?o._destroy(new Error("Cannot add duplicate torrent "+n.infoHash)):o._onTorrentId(t)}))}}))})),o}remove(e,t,n){if("function"==typeof t)return this.remove(e,null,t);this._debug("remove");if(!this.get(e))throw new Error("No torrent with id "+e);this._remove(e,t,n)}_remove(e,t,n){if("function"==typeof t)return this._remove(e,null,t);const i=this.get(e);i&&(this.torrents.splice(this.torrents.indexOf(i),1),i.destroy(t,n))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}destroy(e){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,e)}_destroy(e,t){this._debug("client destroy"),this.destroyed=!0;const n=this.torrents.map((e=>t=>{e.destroy(t)}));this._connPool&&n.push((e=>{this._connPool.destroy(e)})),this.dht&&n.push((e=>{this.dht.destroy(e)})),u(n,t),e&&this.emit("error",e),this.torrents=[],this._connPool=null,this.dht=null}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const e=this._connPool.tcpServer.address();e&&(this.torrentPort=e.port)}this.emit("listening")}_debug(){const e=[].slice.call(arguments);e[0]=`[${this._debugId}] ${e[0]}`,c(...e)}}w.WEBRTC_SUPPORT=h.WEBRTC_SUPPORT,w.VERSION=x,t.exports=w}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./lib/conn-pool":55,"./lib/torrent":314,"./package.json":334,_process:187,"bittorrent-dht/client":55,buffer:60,"create-torrent":80,debug:316,events:98,"load-ip-set":55,"parse-torrent":184,path:185,randombytes:195,"run-parallel":218,"simple-concat":221,"simple-peer":223,speedometer:263}],310:[function(e,t,n){const i=e("debug")("webtorrent:file-stream"),r=e("readable-stream");class o extends r.Readable{constructor(e,t){super(t),this.destroyed=!1,this._torrent=e._torrent;const n=t&&t.start||0,i=t&&t.end&&t.end{if(this._notifying=!1,!this.destroyed){if(i("read %s (length %s) (err %s)",e,n.length,t&&t.message),t)return this._destroy(t);this._offset&&(n=n.slice(this._offset),this._offset=0),this._missing{e.end()})),e}const t=new u(this,e);return this._torrent.select(t._startPiece,t._endPiece,!0,(()=>{t._notify()})),o(t,(()=>{this._destroyed||this._torrent.destroyed||this._torrent.deselect(t._startPiece,t._endPiece,!0)})),t}getBuffer(e){p(this.createReadStream(),this.length,e)}getBlob(e){if("undefined"==typeof window)throw new Error("browser-only method");c(this.createReadStream(),this._getMimeType()).then((t=>e(null,t)),(t=>e(t)))}getBlobURL(e){if("undefined"==typeof window)throw new Error("browser-only method");l(this.createReadStream(),this._getMimeType()).then((t=>e(null,t)),(t=>e(t)))}appendTo(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");a.append(this,e,t,n)}renderTo(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");a.render(this,e,t,n)}_getMimeType(){return a.mime[s.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null}}}).call(this)}).call(this,e("_process"))},{"./file-stream":310,_process:187,"end-of-stream":96,events:98,path:185,"readable-stream":333,"render-media":212,"stream-to-blob":284,"stream-to-blob-url":283,"stream-with-known-length-to-buffer":285}],312:[function(e,t,n){const i=e("unordered-array-remove"),r=e("debug")("webtorrent:peer"),o=e("bittorrent-protocol"),s=e("./webconn");n.createWebRTCPeer=(e,t)=>{const n=new l(e.id,"webrtc");return n.conn=e,n.swarm=t,n.conn.connected?n.onConnect():(n.conn.once("connect",(()=>{n.onConnect()})),n.conn.once("error",(e=>{n.destroy(e)})),n.startConnectTimeout()),n},n.createTCPIncomingPeer=e=>a(e,"tcpIncoming"),n.createUTPIncomingPeer=e=>a(e,"utpIncoming"),n.createTCPOutgoingPeer=(e,t)=>c(e,t,"tcpOutgoing"),n.createUTPOutgoingPeer=(e,t)=>c(e,t,"utpOutgoing");const a=(e,t)=>{const n=`${e.remoteAddress}:${e.remotePort}`,i=new l(n,t);return i.conn=e,i.addr=n,i.onConnect(),i},c=(e,t,n)=>{const i=new l(e,n);return i.addr=e,i.swarm=t,i};n.createWebSeedPeer=(e,t)=>{const n=new l(e,"webSeed");return n.swarm=t,n.conn=new s(e,t),n.onConnect(),n};class l{constructor(e,t){this.id=e,this.type=t,r("new %s Peer %s",t,e),this.addr=null,this.conn=null,this.swarm=null,this.wire=null,this.connected=!1,this.destroyed=!1,this.timeout=null,this.retries=0,this.sentHandshake=!1}onConnect(){if(this.destroyed)return;this.connected=!0,r("Peer %s connected",this.id),clearTimeout(this.connectTimeout);const e=this.conn;e.once("end",(()=>{this.destroy()})),e.once("close",(()=>{this.destroy()})),e.once("finish",(()=>{this.destroy()})),e.once("error",(e=>{this.destroy(e)}));const t=this.wire=new o;t.type=this.type,t.once("end",(()=>{this.destroy()})),t.once("close",(()=>{this.destroy()})),t.once("finish",(()=>{this.destroy()})),t.once("error",(e=>{this.destroy(e)})),t.once("handshake",((e,t)=>{this.onHandshake(e,t)})),this.startHandshakeTimeout(),e.pipe(t).pipe(e),this.swarm&&!this.sentHandshake&&this.handshake()}onHandshake(e,t){if(!this.swarm)return;if(this.destroyed)return;if(this.swarm.destroyed)return this.destroy(new Error("swarm already destroyed"));if(e!==this.swarm.infoHash)return this.destroy(new Error("unexpected handshake info hash for this swarm"));if(t===this.swarm.peerId)return this.destroy(new Error("refusing to connect to ourselves"));r("Peer %s got handshake %s",this.id,e),clearTimeout(this.handshakeTimeout),this.retries=0;let n=this.addr;!n&&this.conn.remoteAddress&&this.conn.remotePort&&(n=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,n),this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const e={dht:!this.swarm.private&&!!this.swarm.client.dht};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,e),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout);const e={webrtc:25e3,tcpOutgoing:5e3,utpOutgoing:5e3};this.connectTimeout=setTimeout((()=>{this.destroy(new Error("connect timeout"))}),e[this.type]),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout((()=>{this.destroy(new Error("handshake timeout"))}),25e3),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(e){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,r("destroy %s %s (error: %s)",this.type,this.id,e&&(e.message||e)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const t=this.swarm,n=this.conn,o=this.wire;this.swarm=null,this.conn=null,this.wire=null,t&&o&&i(t.wires,t.wires.indexOf(o)),n&&(n.on("error",(()=>{})),n.destroy()),o&&o.destroy(),t&&t.removePeer(this.id)}}},{"./webconn":315,"bittorrent-protocol":11,debug:316,"unordered-array-remove":298}],313:[function(e,t,n){t.exports=class{constructor(e){this._torrent=e,this._numPieces=e.pieces.length,this._pieces=new Array(this._numPieces),this._onWire=e=>{this.recalculate(),this._initWire(e)},this._onWireHave=e=>{this._pieces[e]+=1},this._onWireBitfield=()=>{this.recalculate()},this._torrent.wires.forEach((e=>{this._initWire(e)})),this._torrent.on("wire",this._onWire),this.recalculate()}getRarestPiece(e){let t=[],n=1/0;for(let i=0;i{this._cleanupWireEvents(e)})),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(e){e._onClose=()=>{this._cleanupWireEvents(e);for(let t=0;t{this.destroyed||this._onParsedTorrent(t)}))):x.remote(e,((e,t)=>{if(!this.destroyed)return e?this._destroy(e):void this._onParsedTorrent(t)}))}_onParsedTorrent(e){if(!this.destroyed){if(this._processParsedTorrent(e),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));this.path||(this.path=y.join(N,this.infoHash)),this._rechokeIntervalId=setInterval((()=>{this._rechoke()}),1e4),this._rechokeIntervalId.unref&&this._rechokeIntervalId.unref(),this.emit("_infoHash",this.infoHash),this.destroyed||(this.emit("infoHash",this.infoHash),this.destroyed||(this.client.listening?this._onListening():this.client.once("listening",(()=>{this._onListening()}))))}}_processParsedTorrent(e){this._debugId=e.infoHash.toString("hex").substring(0,7),void 0!==this.private&&(e.private=this.private),this.announce&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&i.WEBTORRENT_ANNOUNCE&&!e.private&&(e.announce=e.announce.concat(i.WEBTORRENT_ANNOUNCE)),this.urlList&&(e.urlList=e.urlList.concat(this.urlList)),e.announce=Array.from(new Set(e.announce)),e.urlList=Array.from(new Set(e.urlList)),Object.assign(this,e),this.magnetURI=x.toMagnetURI(e),this.torrentFile=x.toTorrentFile(e)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let e=this.client.tracker;e&&(e=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{const e={uploaded:this.uploaded,downloaded:this.downloaded,left:Math.max(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(e,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(e,this._getAnnounceOpts()),e}})),this.peerAddresses&&this.peerAddresses.forEach((e=>this.addPeer(e))),this.discovery=new c({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:e,port:this.client.torrentPort,userAgent:P}),this.discovery.on("error",(e=>{this._destroy(e)})),this.discovery.on("peer",(e=>{"string"==typeof e&&this.done||this.addPeer(e)})),this.discovery.on("trackerAnnounce",(()=>{this.emit("trackerAnnounce"),0===this.numPeers&&this.emit("noPeers","tracker")})),this.discovery.on("dhtAnnounce",(()=>{this.emit("dhtAnnounce"),0===this.numPeers&&this.emit("noPeers","dht")})),this.discovery.on("warning",(e=>{this.emit("warning",e)}))}_getMetadataFromServer(){const e=this,t=(Array.isArray(this.xs)?this.xs:[this.xs]).map((t=>n=>{!function(t,n){if(0!==t.indexOf("http://")&&0!==t.indexOf("https://"))return e.emit("warning",new Error("skipping non-http xs param: "+t)),n(null);const i={url:t,method:"GET",headers:{"user-agent":P}};let r;try{r=d.concat(i,o)}catch(i){return e.emit("warning",new Error("skipping invalid url xs param: "+t)),n(null)}function o(i,r,o){if(e.destroyed)return n(null);if(e.metadata)return n(null);if(i)return e.emit("warning",new Error("http error from xs param: "+t)),n(null);if(200!==r.statusCode)return e.emit("warning",new Error(`non-200 status code ${r.statusCode} from xs param: ${t}`)),n(null);let s;try{s=x(o)}catch(i){}return s?s.infoHash!==e.infoHash?(e.emit("warning",new Error("got torrent file with incorrect info hash from xs param: "+t)),n(null)):(e._onMetadata(s),void n(null)):(e.emit("warning",new Error("got invalid torrent file from xs param: "+t)),n(null))}e._xsRequests.push(r)}(t,n)}));v(t)}_onMetadata(e){if(this.metadata||this.destroyed)return;let t;if(this._debug("got metadata"),this._xsRequests.forEach((e=>{e.abort()})),this._xsRequests=[],e&&e.infoHash)t=e;else try{t=x(e)}catch(e){return this._destroy(e)}if(this._processParsedTorrent(t),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach((e=>{this.addWebSeed(e)})),this._rarityMap=new I(this),this.store=new f(new this._store(this.pieceLength,{torrent:{infoHash:this.infoHash},files:this.files.map((e=>({path:y.join(this.path,e.path),length:e.length,offset:e.offset}))),length:this.length,name:this.infoHash})),this.files=this.files.map((e=>new A(this,e))),this.so?this.files.forEach(((e,t)=>{this.so.includes(t)?this.files[t].select():this.files[t].deselect()})):0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1),this._hashes=this.pieces,this.pieces=this.pieces.map(((e,t)=>{const n=t===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new _(n)})),this._reservations=this.pieces.map((()=>[])),this.bitfield=new o(this.pieces.length),this.wires.forEach((e=>{e.ut_metadata&&e.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(e)})),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const e=e=>{if(e)return this._destroy(e);this._debug("done verifying"),this._onStore()};this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===u?this.getFileModtimes(((t,n)=>{if(t)return this._destroy(t);this.files.map(((e,t)=>n[t]===this._fileModtimes[t])).every((e=>e))?(this._markAllVerified(),this._onStore()):this._verifyPieces(e)})):this._verifyPieces(e)}}getFileModtimes(e){const t=[];b(this.files.map(((e,n)=>i=>{p.stat(y.join(this.path,e.path),((e,r)=>{if(e&&"ENOENT"!==e.code)return i(e);t[n]=r&&r.mtime.getTime(),i(null)}))})),U,(n=>{this._debug("done getting file modtimes"),e(n,t)}))}_verifyPieces(e){b(this.pieces.map(((e,t)=>e=>{if(this.destroyed)return e(new Error("torrent is destroyed"));this.store.get(t,((i,r)=>this.destroyed?e(new Error("torrent is destroyed")):i?n.nextTick(e,null):void E(r,(n=>{if(this.destroyed)return e(new Error("torrent is destroyed"));if(n===this._hashes[t]){if(!this.pieces[t])return e(null);this._debug("piece verified %s",t),this._markVerified(t)}else this._debug("piece invalid %s",t);e(null)}))))})),U,e)}rescanFiles(e){if(this.destroyed)throw new Error("torrent is destroyed");e||(e=q),this._verifyPieces((t=>{if(t)return this._destroy(t),e(t);this._checkDone(),e(null)}))}_markAllVerified(){for(let e=0;e{e.abort()})),this._rarityMap&&this._rarityMap.destroy();for(const e in this._peers)this.removePeer(e);this.files.forEach((e=>{e instanceof A&&e._destroy()}));const i=this._servers.map((e=>t=>{e.destroy(t)}));this.discovery&&i.push((e=>{this.discovery.destroy(e)})),this.store&&i.push((e=>{t&&t.destroyStore?this.store.destroy(e):this.store.close(e)})),v(i,n),e&&(0===this.listenerCount("error")?this.client.emit("error",e):this.emit("error",e)),this.emit("close"),this.client=null,this.files=[],this.discovery=null,this.store=null,this._rarityMap=null,this._peers=null,this._servers=null,this._xsRequests=null}addPeer(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");if(this.client.blocked){let t;if("string"==typeof e){let n;try{n=r(e)}catch(t){return this._debug("ignoring peer: invalid %s",e),this.emit("invalidPeer",e),!1}t=n[0]}else"string"==typeof e.remoteAddress&&(t=e.remoteAddress);if(t&&this.client.blocked.contains(t))return this._debug("ignoring peer: blocked %s",e),"string"!=typeof e&&e.destroy(),this.emit("blockedPeer",e),!1}const t=!!this._addPeer(e,this.client.utp?"utp":"tcp");return t?this.emit("peer",e):this.emit("invalidPeer",e),t}_addPeer(e,t){if(this.destroyed)return"string"!=typeof e&&e.destroy(),null;if("string"==typeof e&&!this._validAddr(e))return this._debug("ignoring peer: invalid %s",e),null;const n=e&&e.id||e;if(this._peers[n])return this._debug("ignoring peer: duplicate (%s)",n),"string"!=typeof e&&e.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;let i;return this._debug("add peer %s",n),i="string"==typeof e?"utp"===t?L.createUTPOutgoingPeer(e,this):L.createTCPOutgoingPeer(e,this):L.createWebRTCPeer(e,this),this._peers[i.id]=i,this._peersLength+=1,"string"==typeof e&&(this._queue.push(i),this._drain()),i}addWebSeed(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!/^https?:\/\/.+/.test(e))return this.emit("warning",new Error("ignoring invalid web seed: "+e)),void this.emit("invalidPeer",e);if(this._peers[e])return this.emit("warning",new Error("ignoring duplicate web seed: "+e)),void this.emit("invalidPeer",e);this._debug("add web seed %s",e);const t=L.createWebSeedPeer(e,this);this._peers[t.id]=t,this._peersLength+=1,this.emit("peer",e)}_addIncomingPeer(e){return this.destroyed?e.destroy(new Error("torrent is destroyed")):this.paused?e.destroy(new Error("torrent is paused")):(this._debug("add incoming peer %s",e.id),this._peers[e.id]=e,void(this._peersLength+=1))}removePeer(e){const t=e&&e.id||e;(e=this._peers[t])&&(this._debug("removePeer %s",t),delete this._peers[t],this._peersLength-=1,e.destroy(),this._drain())}select(e,t,n,i){if(this.destroyed)throw new Error("torrent is destroyed");if(e<0||tt.priority-e.priority)),this._updateSelections()}deselect(e,t,n){if(this.destroyed)throw new Error("torrent is destroyed");n=Number(n)||0,this._debug("deselect %s-%s (priority %s)",e,t,n);for(let i=0;i{this.destroyed||(this.received+=e,this._downloadSpeed(e),this.client._downloadSpeed(e),this.emit("download",e),this.destroyed||this.client.emit("download",e))})),e.on("upload",(e=>{this.destroyed||(this.uploaded+=e,this._uploadSpeed(e),this.client._uploadSpeed(e),this.emit("upload",e),this.destroyed||this.client.emit("upload",e))})),this.wires.push(e),t){const n=r(t);e.remoteAddress=n[0],e.remotePort=n[1]}this.client.dht&&this.client.dht.listening&&e.on("port",(n=>{if(!this.destroyed&&!this.client.dht.destroyed){if(!e.remoteAddress)return this._debug("ignoring PORT from peer with no address");if(0===n||n>65536)return this._debug("ignoring invalid PORT from peer");this._debug("port: %s (from %s)",n,t),this.client.dht.addNode({host:e.remoteAddress,port:n})}})),e.on("timeout",(()=>{this._debug("wire timeout (%s)",t),e.destroy()})),e.setTimeout(3e4,!0),e.setKeepAlive(!0),e.use(C(this.metadata)),e.ut_metadata.on("warning",(e=>{this._debug("ut_metadata warning: %s",e.message)})),this.metadata||(e.ut_metadata.on("metadata",(e=>{this._debug("got metadata via ut_metadata"),this._onMetadata(e)})),e.ut_metadata.fetch()),"function"!=typeof T||this.private||(e.use(T()),e.ut_pex.on("peer",(e=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",e,t),this.addPeer(e))})),e.ut_pex.on("dropped",(e=>{const n=this._peers[e];n&&!n.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",e,t),this.removePeer(e))})),e.once("close",(()=>{e.ut_pex.reset()}))),this.emit("wire",e,t),this.metadata&&n.nextTick((()=>{this._onWireWithMetadata(e)}))}_onWireWithMetadata(e){let t=null;const n=()=>{this.destroyed||e.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&e.amInterested?e.destroy():(t=setTimeout(n,R),t.unref&&t.unref()))};let i;const r=()=>{if(e.peerPieces.buffer.length===this.bitfield.buffer.length){for(i=0;i{r(),this._update(),this._updateWireInterest(e)})),e.on("have",(()=>{r(),this._update(),this._updateWireInterest(e)})),e.once("interested",(()=>{e.unchoke()})),e.once("close",(()=>{clearTimeout(t)})),e.on("choke",(()=>{clearTimeout(t),t=setTimeout(n,R),t.unref&&t.unref()})),e.on("unchoke",(()=>{clearTimeout(t),this._update()})),e.on("request",((t,n,i,r)=>{if(i>131072)return e.destroy();this.pieces[t]||this.store.get(t,{offset:n,length:i},r)})),e.bitfield(this.bitfield),this._updateWireInterest(e),e.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&e.port(this.client.dht.address().port),"webSeed"!==e.type&&(t=setTimeout(n,R),t.unref&&t.unref()),e.isSeeder=!1,r()}_updateSelections(){this.ready&&!this.destroyed&&(n.nextTick((()=>{this._gcSelections()})),this._updateInterest(),this._update())}_gcSelections(){for(let e=0;ethis._updateWireInterest(e))),e!==this._amInterested&&(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(e){let t=!1;for(let n=0;n=i.from+i.offset;--o)if(e.peerPieces.get(o)&&t._request(e,o,!1))return}}();const n=D(e,.5);if(e.requests.length>=n)return;const i=D(e,1);function r(t,n,i,r){return o=>o>=t&&o<=n&&!(o in i)&&e.peerPieces.get(o)&&(!r||r(o))}function o(e){let n=e;for(let i=e;i=i)return!0;const s=function(){const n=e.downloadSpeed()||1;if(n>B)return()=>!0;const i=Math.max(1,e.requests.length)*_.BLOCK_LENGTH/n;let r=10,o=0;return e=>{if(!r||t.bitfield.get(e))return!0;let s=t.pieces[e].missing;for(;o0))return r--,!1}return!0}}();for(let a=0;a({wire:e,random:Math.random()}))).sort(((e,t)=>{const n=e.wire,i=t.wire;return n.downloadSpeed()!==i.downloadSpeed()?n.downloadSpeed()-i.downloadSpeed():n.uploadSpeed()!==i.uploadSpeed()?n.uploadSpeed()-i.uploadSpeed():n.amChoking!==i.amChoking?n.amChoking?-1:1:e.random-t.random})).map((e=>e.wire));this._rechokeOptimisticTime<=0?this._rechokeOptimisticWire=null:this._rechokeOptimisticTime-=1;let t=0;for(;e.length>0&&t0){const t=e.filter((e=>e.peerInterested));if(t.length>0){const e=t[(n=t.length,Math.random()*n|0)];e.unchoke(),this._rechokeOptimisticWire=e,this._rechokeOptimisticTime=2}}var n;e.filter((e=>e!==this._rechokeOptimisticWire)).forEach((e=>e.choke()))}_hotswap(e,t){const n=e.downloadSpeed();if(n<_.BLOCK_LENGTH)return!1;if(!this._reservations[t])return!1;const i=this._reservations[t];if(!i)return!1;let r,o,s=1/0;for(o=0;o=B||(2*a>n||a>s||(r=t,s=a))}if(!r)return!1;for(o=0;o=(s?Math.min(function(e,t,n){return 1+Math.ceil(t*e.downloadSpeed()/n)}(e,1,r.pieceLength),r.maxWebConns):D(e,1)))return!1;const a=r.pieces[t];let c=s?a.reserveRemaining():a.reserve();if(-1===c&&i&&r._hotswap(e,t)&&(c=s?a.reserveRemaining():a.reserve()),-1===c)return!1;let l=r._reservations[t];l||(l=r._reservations[t]=[]);let p=l.indexOf(null);-1===p&&(p=l.length),l[p]=e;const u=a.chunkOffset(c),d=s?a.chunkLengthRemaining(c):a.chunkLength(c);function f(){n.nextTick((()=>{r._update()}))}return e.request(t,u,d,(function n(i,o){if(r.destroyed)return;if(!r.ready)return r.once("ready",(()=>{n(i,o)}));if(l[p]===e&&(l[p]=null),a!==r.pieces[t])return f();if(i)return r._debug("error getting piece %s (offset: %s length: %s) from %s: %s",t,u,d,`${e.remoteAddress}:${e.remotePort}`,i.message),s?a.cancelRemaining(c):a.cancel(c),void f();if(r._debug("got piece %s (offset: %s length: %s) from %s",t,u,d,`${e.remoteAddress}:${e.remotePort}`),!a.set(c,o,e))return f();const h=a.flush();E(h,(e=>{if(!r.destroyed){if(e===r._hashes[t]){if(!r.pieces[t])return;r._debug("piece verified %s",t),r.pieces[t]=null,r._reservations[t]=null,r.bitfield.set(t,!0),r.store.put(t,h),r.wires.forEach((e=>{e.have(t)})),r._checkDone()&&!r.destroyed&&r.discovery.complete()}else r.pieces[t]=new _(a.length),r.emit("warning",new Error(`Piece ${t} failed verification`));f()}}))})),!0}_checkDone(){if(this.destroyed)return;this.files.forEach((e=>{if(!e.done){for(let t=e._startPiece;t<=e._endPiece;++t)if(!this.bitfield.get(t))return;e.done=!0,e.emit("done"),this._debug("file done: "+e.name)}}));let e=!0;for(let t=0;t{this.load(e,t)}));Array.isArray(e)||(e=[e]),t||(t=q);const n=new h(e),i=new s(this.store,this.pieceLength);w(n,i,(e=>{if(e)return t(e);this._markAllVerified(),this._checkDone(),t(null)}))}createServer(e){if("function"!=typeof O)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const t=new O(this,e);return this._servers.push(t),t}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const e=[].slice.call(arguments);e[0]=`[${this.client?this.client._debugId:"No Client"}] [${this._debugId}] ${e[0]}`,a(...e)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof m.connect||this.destroyed||this.paused||this._numConns>=this.client.maxConns)return;this._debug("drain (%s queued, %s/%s peers)",this._numQueued,this.numPeers,this.client.maxConns);const e=this._queue.shift();if(!e)return;this._debug("%s connect attempt to %s",e.type,e.addr);const t=r(e.addr),n={host:t[0],port:t[1]};"utpOutgoing"===e.type?e.conn=j.connect(n.port,n.host):e.conn=m.connect(n);const i=e.conn;i.once("connect",(()=>{e.onConnect()})),i.once("error",(t=>{e.destroy(t)})),e.startConnectTimeout(),i.on("close",(()=>{if(this.destroyed)return;if(e.retries>=M.length){if(this.client.utp){const t=this._addPeer(e.addr,"tcp");t&&(t.retries=0)}else this._debug("conn %s closed: will not re-add (max %s attempts)",e.addr,M.length);return}const t=M[e.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",e.addr,t,e.retries+1);const n=setTimeout((()=>{if(this.destroyed)return;const t=this._addPeer(e.addr,this.client.utp?"utp":"tcp");t&&(t.retries=e.retries+1)}),t);n.unref&&n.unref()}))}_validAddr(e){let t;try{t=r(e)}catch(e){return!1}const n=t[0],i=t[1];return i>0&&i<65535&&!("127.0.0.1"===n&&i===this.client.torrentPort)}}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../package.json":334,"./file":311,"./peer":312,"./rarity-map":313,"./server":55,_process:187,"addr-to-ip-port":3,bitfield:10,"chunk-store-stream/write":78,debug:316,events:98,fs:56,"fs-chunk-store":141,"immediate-chunk-store":118,multistream:166,net:55,os:55,"parse-torrent":184,path:185,pump:188,"random-iterate":194,"run-parallel":218,"run-parallel-limit":217,"simple-get":222,"simple-sha1":242,speedometer:263,"torrent-discovery":291,"torrent-piece":295,ut_metadata:301,ut_pex:55,"utp-native":55}],315:[function(e,t,n){(function(n){(function(){const i=e("bitfield"),r=e("debug")("webtorrent:webconn"),o=e("simple-get"),s=e("simple-sha1"),a=e("bittorrent-protocol"),c=e("../package.json").version;t.exports=class extends a{constructor(e,t){super(),this.url=e,this.webPeerId=s.sync(e),this._torrent=t,this._init()}_init(){this.setKeepAlive(!0),this.once("handshake",((e,t)=>{if(this.destroyed)return;this.handshake(e,this.webPeerId);const n=this._torrent.pieces.length,r=new i(n);for(let e=0;e<=n;e++)r.set(e,!0);this.bitfield(r)})),this.once("interested",(()=>{r("interested"),this.unchoke()})),this.on("uninterested",(()=>{r("uninterested")})),this.on("choke",(()=>{r("choke")})),this.on("unchoke",(()=>{r("unchoke")})),this.on("bitfield",(()=>{r("bitfield")})),this.on("request",((e,t,n,i)=>{r("request pieceIndex=%d offset=%d length=%d",e,t,n),this.httpRequest(e,t,n,i)}))}httpRequest(e,t,i,s){const a=e*this._torrent.pieceLength+t,l=a+i-1,p=this._torrent.files;let u;if(p.length<=1)u=[{url:this.url,start:a,end:l}];else{const e=p.filter((e=>e.offset<=l&&e.offset+e.length>a));if(e.length<1)return s(new Error("Could not find file corresponnding to web seed range request"));u=e.map((e=>{const t=e.offset+e.length-1;return{url:this.url+("/"===this.url[this.url.length-1]?"":"/")+e.path,fileOffsetInRange:Math.max(e.offset-a,0),start:Math.max(a-e.offset,0),end:Math.min(t,l-e.offset)}}))}let d,f=0,h=!1;u.length>1&&(d=n.alloc(i)),u.forEach((n=>{const a=n.url,l=n.start,p=n.end;r("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",a,e,t,i,l,p);const m={url:a,method:"GET",headers:{"user-agent":`WebTorrent/${c} (https://webtorrent.io)`,range:`bytes=${l}-${p}`}};function g(e,t){if(e.statusCode<200||e.statusCode>=300)return h=!0,s(new Error("Unexpected HTTP status code "+e.statusCode));r("Got data of length %d",t.length),1===u.length?s(null,t):(t.copy(d,n.fileOffsetInRange),++f===u.length&&s(null,d))}o.concat(m,((e,t,n)=>{if(!h)return e?"undefined"==typeof window||a.startsWith(window.location.origin+"/")?(h=!0,s(e)):o.head(a,((t,n)=>{if(!h){if(t)return h=!0,s(t);if(n.statusCode<200||n.statusCode>=300)return h=!0,s(new Error("Unexpected HTTP status code "+n.statusCode));if(n.url===a)return h=!0,s(e);m.url=n.url,o.concat(m,((e,t,n)=>{if(!h)return e?(h=!0,s(e)):void g(t,n)}))}})):void g(t,n)}))}))}destroy(){super.destroy(),this._torrent=null}}}).call(this)}).call(this,e("buffer").Buffer)},{"../package.json":334,bitfield:10,"bittorrent-protocol":11,buffer:60,debug:316,"simple-get":222,"simple-sha1":242}],316:[function(e,t,n){arguments[4][13][0].apply(n,arguments)},{"./common":317,_process:187,dup:13}],317:[function(e,t,n){arguments[4][14][0].apply(n,arguments)},{dup:14,ms:318}],318:[function(e,t,n){arguments[4][15][0].apply(n,arguments)},{dup:15}],319:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{dup:16}],320:[function(e,t,n){arguments[4][17][0].apply(n,arguments)},{"./_stream_readable":322,"./_stream_writable":324,_process:187,dup:17,inherits:119}],321:[function(e,t,n){arguments[4][18][0].apply(n,arguments)},{"./_stream_transform":323,dup:18,inherits:119}],322:[function(e,t,n){arguments[4][19][0].apply(n,arguments)},{"../errors":319,"./_stream_duplex":320,"./internal/streams/async_iterator":325,"./internal/streams/buffer_list":326,"./internal/streams/destroy":327,"./internal/streams/from":329,"./internal/streams/state":331,"./internal/streams/stream":332,_process:187,buffer:60,dup:19,events:98,inherits:119,"string_decoder/":286,util:55}],323:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{"../errors":319,"./_stream_duplex":320,dup:20,inherits:119}],324:[function(e,t,n){arguments[4][21][0].apply(n,arguments)},{"../errors":319,"./_stream_duplex":320,"./internal/streams/destroy":327,"./internal/streams/state":331,"./internal/streams/stream":332,_process:187,buffer:60,dup:21,inherits:119,"util-deprecate":306}],325:[function(e,t,n){arguments[4][22][0].apply(n,arguments)},{"./end-of-stream":328,_process:187,dup:22}],326:[function(e,t,n){arguments[4][23][0].apply(n,arguments)},{buffer:60,dup:23,util:55}],327:[function(e,t,n){arguments[4][24][0].apply(n,arguments)},{_process:187,dup:24}],328:[function(e,t,n){arguments[4][25][0].apply(n,arguments)},{"../../../errors":319,dup:25}],329:[function(e,t,n){arguments[4][26][0].apply(n,arguments)},{dup:26}],330:[function(e,t,n){arguments[4][27][0].apply(n,arguments)},{"../../../errors":319,"./end-of-stream":328,dup:27}],331:[function(e,t,n){arguments[4][28][0].apply(n,arguments)},{"../../../errors":319,dup:28}],332:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29,events:98}],333:[function(e,t,n){arguments[4][30][0].apply(n,arguments)},{"./lib/_stream_duplex.js":320,"./lib/_stream_passthrough.js":321,"./lib/_stream_readable.js":322,"./lib/_stream_transform.js":323,"./lib/_stream_writable.js":324,"./lib/internal/streams/end-of-stream.js":328,"./lib/internal/streams/pipeline.js":330,dup:30}],334:[function(e,t,n){t.exports={version:"0.110.1"}},{}],335:[function(e,t,n){t.exports=function e(t,n){if(t&&n)return e(t)(n);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach((function(e){i[e]=t[e]})),i;function i(){for(var e=new Array(arguments.length),n=0;n1080?(O.setProps({placement:"right"}),R.setProps({placement:"right"}),B.setProps({placement:"right"})):(O.setProps({placement:"top"}),R.setProps({placement:"top"}),B.setProps({placement:"top"}))}function P(e){z();try{console.info("Attempting parse"),p=r(e),D(),p.xs&&(console.info("Magnet includes xs, attempting remote parse"),N(p.xs))}catch(t){console.warn(t),console.info("Attempting remote parse"),N(e)}}function N(e){r.remote(e,(function(e,t){if(e)return console.error(e),void z();d.innerHTML='',f.setContent("Currently loaded information sourced from remotely fetched Torrent file"),p=t,D()}))}function D(){if(console.log(p),x.value=p.infoHash,h.value=p.name?p.name:"",p.created?(g.value=p.created.toISOString().slice(0,19),g.type="datetime-local"):g.type="text",v.value=p.createdBy?"by "+p.createdBy:"",b.value=p.comment?p.comment:"",k.innerHTML="",p.announce&&p.announce.length)for(let e=0;e',i.addEventListener("click",$),t.appendChild(i),k.appendChild(t)}if(E.innerHTML="",p.urlList&&p.urlList.length)for(let e=0;e',i.addEventListener("click",$),t.appendChild(i),E.appendChild(t)}if(T.innerHTML="",p.files&&p.files.length){j.style.display="none";for(let e of p.files){let t=H(a.lookup(e.name));T.appendChild(q(t,e.name,e.length))}T.appendChild(q("folder-tree","",p.length)),I.addEventListener("click",X),I.disabled=!1}else U.torrents.length>0?(j.style.display="none",T.innerHTML=''):(j.style.display="block",T.innerHTML=''),I.removeEventListener("click",X),I.disabled=!0;A.setAttribute("data-clipboard-text",window.location.origin+"#"+r.toMagnetURI(p)),L.setAttribute("data-clipboard-text",r.toMagnetURI(p)),u.style.display="flex",window.location.hash=r.toMagnetURI(p),p.name?document.title="Torrent Parts | "+p.name:document.title="Torrent Parts | Inspect and edit what's in your Torrent file or Magnet link",f.enable()}function q(e,t,n){let i=document.createElement("tr"),r=document.createElement("td");r.innerHTML='',i.appendChild(r);let o=document.createElement("td");o.innerHTML=t,i.appendChild(o);let a=document.createElement("td");return a.innerHTML=s.format(n,{decimalPlaces:1,unitSeparator:" "}),i.appendChild(a),i}function H(e){if(!e)return"file";switch(!0){case e.includes("msword"):case e.includes("wordprocessingml"):case e.includes("opendocument.text"):case e.includes("abiword"):return"file-word";case e.includes("ms-excel"):case e.includes("spreadsheet"):return"file-powerpoint";case e.includes("powerpoint"):case e.includes("presentation"):return"file-powerpoint";case e.includes("7z-"):case e.includes("iso9660"):case e.includes("zip"):case e.includes("octet-stream"):return"file-archive";case e.includes("csv"):return"file-csv";case e.includes("pdf"):return"file-pdf";case e.includes("font"):return"file-contract";case e.includes("text"):case e.includes("subrip"):case e.includes("vtt"):return"file-alt";case e.includes("audio"):return"file-audio";case e.includes("image"):return"file-image";case e.includes("video"):return"file-video";default:return"file"}}function F(e){this.dataset.group?p[this.dataset.group][this.dataset.index]=this.value?this.value:"":p[this.id]=this.value?this.value:"",window.location.hash=r.toMagnetURI(p),Y()}function z(){document.getElementById("magnet").value="",document.getElementById("torrent").value="",u.style.display="none",h.value="",g.value="",v.value="",b.value="",x.value="",k.innerHTML="",E.innerHTML="",U.torrents.forEach((e=>e.destroy())),j.style.display="block",T.innerHTML="",window.location.hash="",A.setAttribute("data-clipboard-text",""),L.setAttribute("data-clipboard-text",""),document.title="Torrent Parts | Inspect and edit what's in your Torrent file or Magnet link",f.disable()}async function W(){y.className="disabled",y.innerHTML="Adding...";try{let e=await fetch("https://newtrackon.com/api/100"),t=await e.text();p.announce=p.announce.concat(t.split("\n\n")),p.announce.push("http://bt1.archive.org:6969/announce"),p.announce.push("http://bt2.archive.org:6969/announce"),p.announce=p.announce.filter(((e,t)=>e&&p.announce.indexOf(e)===t)),Y()}catch(e){console.error(e)}y.innerHTML="Add Known Working Trackers",y.className="",D()}function V(){p[this.dataset.type].unshift(""),D()}function $(){p[this.parentElement.className].splice(this.parentElement.dataset.index,1),D()}function G(e){p[e]=[],Y(),D()}function Y(){p.created=new Date,p.createdBy="Torrent Parts ",p.created?(g.value=p.created.toISOString().slice(0,19),g.type="datetime-local"):g.type="text",v.value=p.createdBy?"by "+p.createdBy:""}function K(){console.info("Attempting fetching files from Webtorrent..."),j.style.display="none",p.announce.push("wss://tracker.webtorrent.io"),p.announce.push("wss://tracker.openwebtorrent.com"),p.announce.push("wss://tracker.btorrent.xyz"),p.announce.push("wss://tracker.fastcast.nz"),p.announce=p.announce.filter(((e,t)=>e&&p.announce.indexOf(e)===t)),U.add(r.toMagnetURI(p),(e=>{p.info=Object.assign({},e.info),p.files=e.files,p.infoBuffer=e.infoBuffer,p.length=e.length,p.lastPieceLength=e.lastPieceLength,Y(),D(),e.destroy()})),D()}function X(){let e=r.toTorrentFile(p);if(null!==e&&navigator.msSaveBlob)return navigator.msSaveBlob(new Blob([e],{type:"application/x-bittorrent"}),p.name+".torrent");let t=document.createElement("a");t.style.display="none";let n=window.URL.createObjectURL(new Blob([e],{type:"application/x-bittorrent"}));t.setAttribute("href",n),t.setAttribute("download",p.name+".torrent"),document.body.appendChild(t),t.click(),window.URL.revokeObjectURL(n),t.remove()}window.addEventListener("resize",M),M(),document.addEventListener("DOMContentLoaded",(function(){document.getElementById("magnet").addEventListener("keyup",(function(e){e.preventDefault(),"Enter"===e.key&&(d.innerHTML='',f.setContent("Currently loaded information sourced from Magnet URL"),P(magnet.value))})),document.getElementById("torrent").addEventListener("change",(function(e){e.preventDefault();try{e.target.files[0].arrayBuffer().then((function(e){d.innerHTML='',f.setContent("Currently loaded information sourced from Torrent file"),P(o.from(e))}))}catch(e){console.error(e)}}));let e=new i("#copyURL");e.on("success",(function(e){console.info(e)})),e.on("failure",(function(e){console.error(e)}));let t=new i("#copyMagnet");t.on("success",(function(e){console.info(e)})),t.on("failure",(function(e){console.error(e)})),h.addEventListener("input",F),h.addEventListener("change",F),h.addEventListener("reset",F),h.addEventListener("paste",F),m.addEventListener("click",z),b.addEventListener("input",F),b.addEventListener("change",F),b.addEventListener("reset",F),b.addEventListener("paste",F),y.addEventListener("click",W),_.addEventListener("click",V),w.addEventListener("click",(()=>G("announce"))),S.addEventListener("click",V),C.addEventListener("click",(()=>G("urlList"))),j.addEventListener("click",K),l("[data-tippy-content]",{theme:"torrent-parts",animation:"shift-away-subtle"}),f.disable(),window.location.hash&&(d.innerHTML='',f.setContent("Currently loaded information sourced from shared torrent.parts link"),P(window.location.hash.split("#")[1]))}))},{Buffer:2,bytes:62,clipboard:79,"mime-types":144,"parse-torrent":184,"tippy.js":289,webtorrent:309}]},{},[337]); \ No newline at end of file diff --git a/index.html b/index.html index 2e50c86..b310c9e 100644 --- a/index.html +++ b/index.html @@ -4,7 +4,7 @@ - + @@ -35,7 +35,7 @@ Torrent Parts | Inspect and edit what's in your Torrent file or Magnet link - + @@ -52,18 +52,18 @@
-

TorrentParts

- Star +

TorrentParts

+ Star
-
@@ -88,10 +88,10 @@
-
@@ -100,10 +100,10 @@
-
@@ -112,10 +112,10 @@
-
@@ -127,10 +127,10 @@
-
@@ -139,10 +139,10 @@
-
@@ -156,10 +156,10 @@
-
@@ -172,10 +172,10 @@
-
diff --git a/parse.js b/parse.js index 0742ed8..38f5ae0 100644 --- a/parse.js +++ b/parse.js @@ -108,6 +108,7 @@ function start() { getFiles.addEventListener('click', getFilesFromPeers); tippy('[data-tippy-content]', {"theme": "torrent-parts", "animation": "shift-away-subtle"}); // all element-defined tooltips + source.disable(); if (window.location.hash) { originalSourceIcon.innerHTML = ''; diff --git a/style.css b/style.css index c764415..37f77b0 100644 --- a/style.css +++ b/style.css @@ -1,6 +1,17 @@ /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */ html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none} +.sr-only { + border: 0; + clip: rect(0 0 0 0); + height: 1px; + margin: -1px; + overflow: hidden; + padding: 0; + position: absolute; + width: 1px; +} + :root { --gradient: linear-gradient(180deg, #152332, #24384D); --dark-blue: #102030;