/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/webtorrent@2.8.5/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
/*! webtorrent. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */
import EventEmitter from"events";import path from"path";import createTorrent,{parseInput}from"create-torrent";import debugFactory from"debug";import{Client as DHT}from"bittorrent-dht";import loadIPSet from"load-ip-set";import parallel from"run-parallel";import parseTorrent from"parse-torrent";import Peer from"@thaunknown/simple-peer/lite.js";import queueMicrotask from"queue-microtask";import{hash,hex2arr,arr2hex,arr2base,text2arr,randomBytes,concat}from"uint8-util";import throughput from"throughput";import{ThrottleGroup}from"speed-limiter";import NatAPI from"@silentbot1/nat-api";import ConnPool from"./lib/conn-pool.js";import Torrent from"./lib/torrent.js";import{NodeServer,BrowserServer}from"./lib/server.js";import VERSION from"./version.cjs";const debug=debugFactory("webtorrent"),VERSION_STR=VERSION.replace(/\d*./g,(t=>("0"+t%100).slice(-2))).slice(0,4),VERSION_PREFIX=`-WW${VERSION_STR}-`;export default class WebTorrent extends EventEmitter{constructor(t={}){super(),"string"==typeof t.peerId?this.peerId=t.peerId:ArrayBuffer.isView(t.peerId)?this.peerId=arr2hex(t.peerId):this.peerId=arr2hex(text2arr(VERSION_PREFIX+arr2base(randomBytes(9)))),this.peerIdBuffer=hex2arr(this.peerId),"string"==typeof t.nodeId?this.nodeId=t.nodeId:ArrayBuffer.isView(t.nodeId)?this.nodeId=arr2hex(t.nodeId):this.nodeId=arr2hex(randomBytes(20)),this.nodeIdBuffer=hex2arr(this.nodeId),this._debugId=this.peerId.substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=t.torrentPort||0,this.dhtPort=t.dhtPort||0,this.tracker=void 0!==t.tracker?t.tracker:{},this.lsd=!1!==t.lsd,this.utPex=!1!==t.utPex,this.natUpnp=t.natUpnp??!0,this.natPmp=t.natPmp??!0,this.torrents=[],this.maxConns=Number(t.maxConns)||55,this.utp=WebTorrent.UTP_SUPPORT&&!1!==t.utp,this.seedOutgoingConnections=t.seedOutgoingConnections??!0,this._downloadLimit=Math.max("number"==typeof t.downloadLimit?t.downloadLimit:-1,-1),this._uploadLimit=Math.max("number"==typeof t.uploadLimit?t.uploadLimit:-1,-1),(this.natUpnp||this.natPmp)&&"function"==typeof NatAPI&&(this.natTraversal=new NatAPI({enableUPNP:this.natUpnp,enablePMP:this.natPmp,upnpPermanentFallback:"permanent"===t.natUpnp})),!0===t.secure&&import("./lib/peer.js").then((({enableSecure:t})=>t())),this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.throttleGroups={down:new ThrottleGroup({rate:Math.max(this._downloadLimit,0),enabled:this._downloadLimit>=0}),up:new ThrottleGroup({rate:Math.max(this._uploadLimit,0),enabled:this._uploadLimit>=0})},this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),globalThis.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=globalThis.WRTC)),"function"==typeof ConnPool?this._connPool=new ConnPool(this):queueMicrotask((()=>{this._onListening()})),this._downloadSpeed=throughput(),this._uploadSpeed=throughput(),!1!==t.dht&&"function"==typeof DHT?(this.dht=new DHT(Object.assign({},{nodeId:this.nodeId},t.dht)),this.dht.once("error",(t=>{this._destroy(t)})),this.dht.once("listening",(()=>{const t=this.dht.address();t&&(this.dhtPort=t.port,this.natTraversal&&this.natTraversal.map({publicPort:this.dhtPort,privatePort:this.dhtPort,protocol:"udp",description:"WebTorrent DHT"}).catch((t=>{debug("error mapping DHT port via UPnP/PMP: %o",t)})))})),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==t.webSeeds;const e=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof loadIPSet&&null!=t.blocklist?loadIPSet(t.blocklist,{headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`}},((t,r)=>{if(t)return console.error(`Failed to load blocklist: ${t.message}`);this.blocked=r,e()})):queueMicrotask(e)}createServer(t,e){if(this.destroyed)throw new Error("torrent is destroyed");if(this._server)throw new Error("server already created");if("undefined"!=typeof window&&"node"!==e||"browser"===e){if(!(t?.controller instanceof ServiceWorkerRegistration))throw new Error("Invalid worker registration");if("activated"!==t.controller.active.state)throw new Error("Worker isn't activated");return this._server=new BrowserServer(this,t),this._server}return this._server=new NodeServer(this,t),this._server}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const t=this.torrents.filter((t=>1!==t.progress));return t.reduce(((t,e)=>t+e.downloaded),0)/(t.reduce(((t,e)=>t+(e.length||0)),0)||1)}get ratio(){return this.torrents.reduce(((t,e)=>t+e.uploaded),0)/(this.torrents.reduce(((t,e)=>t+e.received),0)||1)}async get(t){if(t instanceof Torrent){if(this.torrents.includes(t))return t}else{const e=this.torrents;let r;try{r=await parseTorrent(t)}catch(t){}if(!r)return null;if(!r.infoHash)throw new Error("Invalid torrent identifier");for(const t of e)if(t.infoHash===r.infoHash)return t}return null}add(t,e={},r=()=>{}){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof e&&([e,r]=[{},e]);const o=()=>{if(!this.destroyed)for(const t of this.torrents)if(t.infoHash===i.infoHash&&t!==i)return i._destroy(new Error(`Cannot add duplicate torrent ${i.infoHash}`)),void r(t)},s=()=>{this.destroyed||(r(i),this.emit("torrent",i))};this._debug("add"),e=e?Object.assign({},e):{};const i=new Torrent(t,this,e);return this.torrents.push(i),i.once("_infoHash",o),i.once("ready",s),i.once("close",(function t(){i.removeListener("_infoHash",o),i.removeListener("ready",s),i.removeListener("close",t)})),this.emit("add",i),i}seed(t,e,r){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof e&&([e,r]=[{},e]),this._debug("seed"),(e=e?Object.assign({},e):{}).skipVerify=!0;const o="string"==typeof t;o&&(e.path=path.dirname(t)),e.createdBy||(e.createdBy=`WebTorrent/${VERSION_STR}`);const s=t=>{this._debug("on seed"),"function"==typeof r&&r(t),t.emit("seed"),this.emit("seed",t)},i=this.add(null,e,(t=>{const r=[r=>{if(o||e.preloadedStore)return r();t.load(n,r)}];this.dht&&r.push((e=>{t.once("dhtAnnounce",e)})),parallel(r,(e=>{if(!this.destroyed)return e?t._destroy(e):void s(t)}))}));let n;return isFileList(t)?t=Array.from(t):Array.isArray(t)||(t=[t]),parallel(t.map((t=>async r=>{if(!e.preloadedStore&&isReadable(t)){const e=[];try{for await(const r of t)e.push(r)}catch(t){return r(t)}const o=concat(e);o.name=t.name,r(null,o)}else r(null,t)})),((t,o)=>{if(!this.destroyed)return t?i._destroy(t):void parseInput(o,e,((t,s)=>{if(!this.destroyed){if(t)return i._destroy(t);n=s.map((t=>t.getStream)),createTorrent(o,e,(async(t,e)=>{if(this.destroyed)return;if(t)return i._destroy(t);const o=await this.get(e);o?(console.warn("A torrent with the same id is already being seeded"),i._destroy(),"function"==typeof r&&r(o)):i._onTorrentId(e)}))}}))})),i}async remove(t,e,r){if("function"==typeof e)return this.remove(t,null,e);this._debug("remove");const o=await this.get(t);if(!o)throw new Error(`No torrent with id ${t}`);this._remove(o,e,r)}_remove(t,e,r){if(!t)return;if("function"==typeof e)return this._remove(t,null,e);const o=this.torrents.indexOf(t);-1!==o&&(this.torrents.splice(o,1),t.destroy(e,r),this.dht&&this.dht._tables.remove(t.infoHash),this.emit("remove",t))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}throttleDownload(t){return t=Number(t),!(isNaN(t)||!isFinite(t)||t<-1)&&(this._downloadLimit=t,this._downloadLimit<0?this.throttleGroups.down.setEnabled(!1):(this.throttleGroups.down.setEnabled(!0),void this.throttleGroups.down.setRate(this._downloadLimit)))}throttleUpload(t){return t=Number(t),!(isNaN(t)||!isFinite(t)||t<-1)&&(this._uploadLimit=t,this._uploadLimit<0?this.throttleGroups.up.setEnabled(!1):(this.throttleGroups.up.setEnabled(!0),void this.throttleGroups.up.setRate(this._uploadLimit)))}destroy(t){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,t)}_destroy(t,e){this._debug("client destroy"),this.destroyed=!0;const r=this.torrents.map((t=>e=>{t.destroy(e)}));this._connPool&&r.push((t=>{this._connPool.destroy(t)})),this.dht&&r.push((t=>{this.dht.destroy(t)})),this._server&&r.push((t=>{this._server.destroy(t)})),this.natTraversal&&r.push((t=>{this.natTraversal.destroy().then((()=>t()))})),parallel(r,e),t&&this.emit("error",t),this.torrents=[],this._connPool=null,this.dht=null,this.throttleGroups.down.destroy(),this.throttleGroups.up.destroy()}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const t=this._connPool.tcpServer.address();t&&(this.torrentPort=t.port,this.natTraversal&&this.natTraversal.map({publicPort:this.torrentPort,privatePort:this.torrentPort,protocol:this.utp?null:"tcp",description:"WebTorrent Torrent"}).catch((t=>{debug("error mapping WebTorrent port via UPnP/PMP: %o",t)})))}this.emit("listening")}_debug(){const t=[].slice.call(arguments);t[0]=`[${this._debugId}] ${t[0]}`,debug(...t)}async _getByHash(t){for(const e of this.torrents)if(e.infoHashHash||(e.infoHashHash=await hash(hex2arr("72657132"+e.infoHash),"hex")),t===e.infoHashHash)return e;return null}}function isReadable(t){return"object"==typeof t&&null!=t&&"function"==typeof t.pipe}function isFileList(t){return"undefined"!=typeof FileList&&t instanceof FileList}WebTorrent.WEBRTC_SUPPORT=Peer.WEBRTC_SUPPORT,WebTorrent.UTP_SUPPORT=ConnPool.UTP_SUPPORT,WebTorrent.VERSION=VERSION;
//# sourceMappingURL=/sm/ace68c8a6cb7ef77354fea76bd5a414160eae1694a6bdf0c5c19a606b9566a5a.map