@transai/connector-runner-mqtt 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,13 @@
1
+ ## 0.24.0 (2026-04-13)
2
+
3
+ ### 🧱 Updated Dependencies
4
+
5
+ - Updated @transai/connector-runtime-sdk to 0.13.0
6
+
7
+ ## 0.23.0 (2026-04-10)
8
+
9
+ This was a version bump only for connector-runner-mqtt to align it with other projects, there were no code changes.
10
+
1
11
  ## 0.22.0 (2026-04-09)
2
12
 
3
13
  This was a version bump only for connector-runner-mqtt to align it with other projects, there were no code changes.
package/index.cjs CHANGED
@@ -130,7 +130,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
130
130
  `+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
131
131
  `)+`\r
132
132
  \r
133
- `+r)}function Bs(t,e,r,n,i,a){if(t.listenerCount("wsClientError")){let s=new Error(i);Error.captureStackTrace(s,Bs),t.emit("wsClientError",s,r,e)}else zc(r,n,i,a)}});var F7=p((uLe,B7)=>{"use strict";var Fi=Lh();Fi.createWebSocketStream=O7();Fi.Server=k7();Fi.Receiver=YT();Fi.Sender=WT();Fi.WebSocket=Fi;Fi.WebSocketServer=Fi.Server;B7.exports=Fi});var kh=p($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.BufferedDuplex=void 0;$c.writev=q7;var fye=Sa(),U7=require("buffer");function q7(t,e){let r=new Array(t.length);for(let n=0;n<t.length;n++)typeof t[n].chunk=="string"?r[n]=U7.Buffer.from(t[n].chunk,"utf8"):r[n]=t[n].chunk;this._write(U7.Buffer.concat(r),"binary",e)}var JT=class extends fye.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(e,r,n){super({objectMode:!0}),this.proxy=r,this.socket=n,this.writeQueue=[],e.objectMode||(this._writev=q7.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",i=>{!this.destroyed&&this.readable&&this.push(i)})}_read(e){this.proxy.read(e)}_write(e,r,n){this.isSocketOpen?this.writeToProxy(e,r,n):this.writeQueue.push({chunk:e,encoding:r,cb:n})}_final(e){this.writeQueue=[],this.proxy.end(e)}_destroy(e,r){this.writeQueue=[],this.proxy.destroy(),r(e)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(e,r,n){this.proxy.write(e,r)===!1?this.proxy.once("drain",n):n()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:e,encoding:r,cb:n}=this.writeQueue.shift();this.writeToProxy(e,r,n)}}};$c.BufferedDuplex=JT});var Kc=p(wa=>{"use strict";var tC=wa&&wa.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(wa,"__esModule",{value:!0});wa.streamBuilder=wa.browserStreamBuilder=void 0;var Bh=require("buffer"),G7=tC(F7()),_ye=tC(Tn()),pye=Sa(),hye=tC(kc()),eC=kh(),Na=(0,_ye.default)("mqttjs:ws"),mye=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function Y7(t,e){let r=`${t.protocol}://${t.hostname}:${t.port}${t.path}`;return typeof t.transformWsUrl=="function"&&(r=t.transformWsUrl(r,t,e)),r}function H7(t){let e=t;return t.port||(t.protocol==="wss"?e.port=443:e.port=80),t.path||(e.path="/"),t.wsOptions||(e.wsOptions={}),!hye.default&&!t.forceNativeWebSocket&&t.protocol==="wss"&&mye.forEach(r=>{Object.prototype.hasOwnProperty.call(t,r)&&!Object.prototype.hasOwnProperty.call(t.wsOptions,r)&&(e.wsOptions[r]=t[r])}),e}function gye(t){let e=H7(t);if(e.hostname||(e.hostname=e.host),!e.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let r=new URL(document.URL);e.hostname=r.hostname,e.port||(e.port=Number(r.port))}return e.objectMode===void 0&&(e.objectMode=!(e.binary===!0||e.binary===void 0)),e}function Eye(t,e,r){Na("createWebSocket"),Na(`protocol: ${r.protocolId} ${r.protocolVersion}`);let n=r.protocolId==="MQIsdp"&&r.protocolVersion===3?"mqttv3.1":"mqtt";Na(`creating new Websocket for url: ${e} and protocol: ${n}`);let i;return r.createWebsocket?i=r.createWebsocket(e,[n],r):i=new G7.default(e,[n],r.wsOptions),i}function Sye(t,e){let r=e.protocolId==="MQIsdp"&&e.protocolVersion===3?"mqttv3.1":"mqtt",n=Y7(e,t),i;return e.createWebsocket?i=e.createWebsocket(n,[r],e):i=new WebSocket(n,[r]),i.binaryType="arraybuffer",i}var bye=(t,e)=>{Na("streamBuilder");let r=H7(e);r.hostname=r.hostname||r.host||"localhost";let n=Y7(r,t),i=Eye(t,n,r),a=G7.default.createWebSocketStream(i,r.wsOptions);return a.url=n,i.on("close",()=>{a.destroy()}),a};wa.streamBuilder=bye;var vye=(t,e)=>{Na("browserStreamBuilder");let r,i=gye(e).browserBufferSize||1024*512,a=e.browserBufferTimeout||1e3,s=!e.objectMode,o=Sye(t,e),l=_(e,b,T);e.objectMode||(l._writev=eC.writev.bind(l)),l.on("close",()=>{o.close()});let c=typeof o.addEventListener<"u";o.readyState===o.OPEN?(r=l,r.socket=o):(r=new eC.BufferedDuplex(e,l,o),c?o.addEventListener("open",d):o.onopen=d),c?(o.addEventListener("close",m),o.addEventListener("error",S),o.addEventListener("message",E)):(o.onclose=m,o.onerror=S,o.onmessage=E);function _(y,C,O){let A=new pye.Transform({objectMode:y.objectMode});return A._write=C,A._flush=O,A}function d(){Na("WebSocket onOpen"),r instanceof eC.BufferedDuplex&&r.socketReady()}function m(y){Na("WebSocket onClose",y),r.end(),r.destroy()}function S(y){Na("WebSocket onError",y);let C=new Error("WebSocket error");C.event=y,r.destroy(C)}async function E(y){if(!l||!l.readable||!l.writable)return;let{data:C}=y;C instanceof ArrayBuffer?C=Bh.Buffer.from(C):C instanceof Blob?C=Bh.Buffer.from(await new Response(C).arrayBuffer()):C=Bh.Buffer.from(C,"utf8"),l.push(C)}function b(y,C,O){if(o.bufferedAmount>i){setTimeout(b,a,y,C,O);return}s&&typeof y=="string"&&(y=Bh.Buffer.from(y,"utf8"));try{o.send(y)}catch(A){return O(A)}O()}function T(y){o.close(),y()}return r};wa.browserStreamBuilder=vye});var $7=p(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});var V7=require("buffer"),Fs={INVALID_ENCODING:"Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",INVALID_SMARTBUFFER_SIZE:"Invalid size provided. Size must be a valid integer greater than zero.",INVALID_SMARTBUFFER_BUFFER:"Invalid Buffer provided in SmartBufferOptions.",INVALID_SMARTBUFFER_OBJECT:"Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",INVALID_OFFSET:"An invalid offset value was provided.",INVALID_OFFSET_NON_NUMBER:"An invalid offset value was provided. A numeric value is required.",INVALID_LENGTH:"An invalid length value was provided.",INVALID_LENGTH_NON_NUMBER:"An invalid length value was provived. A numeric value is required.",INVALID_TARGET_OFFSET:"Target offset is beyond the bounds of the internal SmartBuffer data.",INVALID_TARGET_LENGTH:"Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",INVALID_READ_BEYOND_BOUNDS:"Attempted to read beyond the bounds of the managed data.",INVALID_WRITE_BEYOND_BOUNDS:"Attempted to write beyond the bounds of the managed data."};Ui.ERRORS=Fs;function yye(t){if(!V7.Buffer.isEncoding(t))throw new Error(Fs.INVALID_ENCODING)}Ui.checkEncoding=yye;function W7(t){return typeof t=="number"&&isFinite(t)&&Rye(t)}Ui.isFiniteInteger=W7;function z7(t,e){if(typeof t=="number"){if(!W7(t)||t<0)throw new Error(e?Fs.INVALID_OFFSET:Fs.INVALID_LENGTH)}else throw new Error(e?Fs.INVALID_OFFSET_NON_NUMBER:Fs.INVALID_LENGTH_NON_NUMBER)}function Tye(t){z7(t,!1)}Ui.checkLengthValue=Tye;function Cye(t){z7(t,!0)}Ui.checkOffsetValue=Cye;function Aye(t,e){if(t<0||t>e.length)throw new Error(Fs.INVALID_TARGET_OFFSET)}Ui.checkTargetOffset=Aye;function Rye(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t}function Oye(t){if(typeof BigInt>"u")throw new Error("Platform does not support JS BigInt type.");if(typeof V7.Buffer.prototype[t]>"u")throw new Error(`Platform does not support Buffer.prototype.${t}.`)}Ui.bigIntAndBufferInt64Check=Oye});var Q7=p(nC=>{"use strict";Object.defineProperty(nC,"__esModule",{value:!0});var Te=$7(),K7=4096,Nye="utf8",rC=class t{constructor(e){if(this.length=0,this._encoding=Nye,this._writeOffset=0,this._readOffset=0,t.isSmartBufferOptions(e))if(e.encoding&&(Te.checkEncoding(e.encoding),this._encoding=e.encoding),e.size)if(Te.isFiniteInteger(e.size)&&e.size>0)this._buff=Buffer.allocUnsafe(e.size);else throw new Error(Te.ERRORS.INVALID_SMARTBUFFER_SIZE);else if(e.buff)if(Buffer.isBuffer(e.buff))this._buff=e.buff,this.length=e.buff.length;else throw new Error(Te.ERRORS.INVALID_SMARTBUFFER_BUFFER);else this._buff=Buffer.allocUnsafe(K7);else{if(typeof e<"u")throw new Error(Te.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(K7)}}static fromSize(e,r){return new this({size:e,encoding:r})}static fromBuffer(e,r){return new this({buff:e,encoding:r})}static fromOptions(e){return new this(e)}static isSmartBufferOptions(e){let r=e;return r&&(r.encoding!==void 0||r.size!==void 0||r.buff!==void 0)}readInt8(e){return this._readNumberValue(Buffer.prototype.readInt8,1,e)}readInt16BE(e){return this._readNumberValue(Buffer.prototype.readInt16BE,2,e)}readInt16LE(e){return this._readNumberValue(Buffer.prototype.readInt16LE,2,e)}readInt32BE(e){return this._readNumberValue(Buffer.prototype.readInt32BE,4,e)}readInt32LE(e){return this._readNumberValue(Buffer.prototype.readInt32LE,4,e)}readBigInt64BE(e){return Te.bigIntAndBufferInt64Check("readBigInt64BE"),this._readNumberValue(Buffer.prototype.readBigInt64BE,8,e)}readBigInt64LE(e){return Te.bigIntAndBufferInt64Check("readBigInt64LE"),this._readNumberValue(Buffer.prototype.readBigInt64LE,8,e)}writeInt8(e,r){return this._writeNumberValue(Buffer.prototype.writeInt8,1,e,r),this}insertInt8(e,r){return this._insertNumberValue(Buffer.prototype.writeInt8,1,e,r)}writeInt16BE(e,r){return this._writeNumberValue(Buffer.prototype.writeInt16BE,2,e,r)}insertInt16BE(e,r){return this._insertNumberValue(Buffer.prototype.writeInt16BE,2,e,r)}writeInt16LE(e,r){return this._writeNumberValue(Buffer.prototype.writeInt16LE,2,e,r)}insertInt16LE(e,r){return this._insertNumberValue(Buffer.prototype.writeInt16LE,2,e,r)}writeInt32BE(e,r){return this._writeNumberValue(Buffer.prototype.writeInt32BE,4,e,r)}insertInt32BE(e,r){return this._insertNumberValue(Buffer.prototype.writeInt32BE,4,e,r)}writeInt32LE(e,r){return this._writeNumberValue(Buffer.prototype.writeInt32LE,4,e,r)}insertInt32LE(e,r){return this._insertNumberValue(Buffer.prototype.writeInt32LE,4,e,r)}writeBigInt64BE(e,r){return Te.bigIntAndBufferInt64Check("writeBigInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigInt64BE,8,e,r)}insertBigInt64BE(e,r){return Te.bigIntAndBufferInt64Check("writeBigInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigInt64BE,8,e,r)}writeBigInt64LE(e,r){return Te.bigIntAndBufferInt64Check("writeBigInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigInt64LE,8,e,r)}insertBigInt64LE(e,r){return Te.bigIntAndBufferInt64Check("writeBigInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigInt64LE,8,e,r)}readUInt8(e){return this._readNumberValue(Buffer.prototype.readUInt8,1,e)}readUInt16BE(e){return this._readNumberValue(Buffer.prototype.readUInt16BE,2,e)}readUInt16LE(e){return this._readNumberValue(Buffer.prototype.readUInt16LE,2,e)}readUInt32BE(e){return this._readNumberValue(Buffer.prototype.readUInt32BE,4,e)}readUInt32LE(e){return this._readNumberValue(Buffer.prototype.readUInt32LE,4,e)}readBigUInt64BE(e){return Te.bigIntAndBufferInt64Check("readBigUInt64BE"),this._readNumberValue(Buffer.prototype.readBigUInt64BE,8,e)}readBigUInt64LE(e){return Te.bigIntAndBufferInt64Check("readBigUInt64LE"),this._readNumberValue(Buffer.prototype.readBigUInt64LE,8,e)}writeUInt8(e,r){return this._writeNumberValue(Buffer.prototype.writeUInt8,1,e,r)}insertUInt8(e,r){return this._insertNumberValue(Buffer.prototype.writeUInt8,1,e,r)}writeUInt16BE(e,r){return this._writeNumberValue(Buffer.prototype.writeUInt16BE,2,e,r)}insertUInt16BE(e,r){return this._insertNumberValue(Buffer.prototype.writeUInt16BE,2,e,r)}writeUInt16LE(e,r){return this._writeNumberValue(Buffer.prototype.writeUInt16LE,2,e,r)}insertUInt16LE(e,r){return this._insertNumberValue(Buffer.prototype.writeUInt16LE,2,e,r)}writeUInt32BE(e,r){return this._writeNumberValue(Buffer.prototype.writeUInt32BE,4,e,r)}insertUInt32BE(e,r){return this._insertNumberValue(Buffer.prototype.writeUInt32BE,4,e,r)}writeUInt32LE(e,r){return this._writeNumberValue(Buffer.prototype.writeUInt32LE,4,e,r)}insertUInt32LE(e,r){return this._insertNumberValue(Buffer.prototype.writeUInt32LE,4,e,r)}writeBigUInt64BE(e,r){return Te.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64BE,8,e,r)}insertBigUInt64BE(e,r){return Te.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64BE,8,e,r)}writeBigUInt64LE(e,r){return Te.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64LE,8,e,r)}insertBigUInt64LE(e,r){return Te.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64LE,8,e,r)}readFloatBE(e){return this._readNumberValue(Buffer.prototype.readFloatBE,4,e)}readFloatLE(e){return this._readNumberValue(Buffer.prototype.readFloatLE,4,e)}writeFloatBE(e,r){return this._writeNumberValue(Buffer.prototype.writeFloatBE,4,e,r)}insertFloatBE(e,r){return this._insertNumberValue(Buffer.prototype.writeFloatBE,4,e,r)}writeFloatLE(e,r){return this._writeNumberValue(Buffer.prototype.writeFloatLE,4,e,r)}insertFloatLE(e,r){return this._insertNumberValue(Buffer.prototype.writeFloatLE,4,e,r)}readDoubleBE(e){return this._readNumberValue(Buffer.prototype.readDoubleBE,8,e)}readDoubleLE(e){return this._readNumberValue(Buffer.prototype.readDoubleLE,8,e)}writeDoubleBE(e,r){return this._writeNumberValue(Buffer.prototype.writeDoubleBE,8,e,r)}insertDoubleBE(e,r){return this._insertNumberValue(Buffer.prototype.writeDoubleBE,8,e,r)}writeDoubleLE(e,r){return this._writeNumberValue(Buffer.prototype.writeDoubleLE,8,e,r)}insertDoubleLE(e,r){return this._insertNumberValue(Buffer.prototype.writeDoubleLE,8,e,r)}readString(e,r){let n;typeof e=="number"?(Te.checkLengthValue(e),n=Math.min(e,this.length-this._readOffset)):(r=e,n=this.length-this._readOffset),typeof r<"u"&&Te.checkEncoding(r);let i=this._buff.slice(this._readOffset,this._readOffset+n).toString(r||this._encoding);return this._readOffset+=n,i}insertString(e,r,n){return Te.checkOffsetValue(r),this._handleString(e,!0,r,n)}writeString(e,r,n){return this._handleString(e,!1,r,n)}readStringNT(e){typeof e<"u"&&Te.checkEncoding(e);let r=this.length;for(let i=this._readOffset;i<this.length;i++)if(this._buff[i]===0){r=i;break}let n=this._buff.slice(this._readOffset,r);return this._readOffset=r+1,n.toString(e||this._encoding)}insertStringNT(e,r,n){return Te.checkOffsetValue(r),this.insertString(e,r,n),this.insertUInt8(0,r+e.length),this}writeStringNT(e,r,n){return this.writeString(e,r,n),this.writeUInt8(0,typeof r=="number"?r+e.length:this.writeOffset),this}readBuffer(e){typeof e<"u"&&Te.checkLengthValue(e);let r=typeof e=="number"?e:this.length,n=Math.min(this.length,this._readOffset+r),i=this._buff.slice(this._readOffset,n);return this._readOffset=n,i}insertBuffer(e,r){return Te.checkOffsetValue(r),this._handleBuffer(e,!0,r)}writeBuffer(e,r){return this._handleBuffer(e,!1,r)}readBufferNT(){let e=this.length;for(let n=this._readOffset;n<this.length;n++)if(this._buff[n]===0){e=n;break}let r=this._buff.slice(this._readOffset,e);return this._readOffset=e+1,r}insertBufferNT(e,r){return Te.checkOffsetValue(r),this.insertBuffer(e,r),this.insertUInt8(0,r+e.length),this}writeBufferNT(e,r){return typeof r<"u"&&Te.checkOffsetValue(r),this.writeBuffer(e,r),this.writeUInt8(0,typeof r=="number"?r+e.length:this._writeOffset),this}clear(){return this._writeOffset=0,this._readOffset=0,this.length=0,this}remaining(){return this.length-this._readOffset}get readOffset(){return this._readOffset}set readOffset(e){Te.checkOffsetValue(e),Te.checkTargetOffset(e,this),this._readOffset=e}get writeOffset(){return this._writeOffset}set writeOffset(e){Te.checkOffsetValue(e),Te.checkTargetOffset(e,this),this._writeOffset=e}get encoding(){return this._encoding}set encoding(e){Te.checkEncoding(e),this._encoding=e}get internalBuffer(){return this._buff}toBuffer(){return this._buff.slice(0,this.length)}toString(e){let r=typeof e=="string"?e:this._encoding;return Te.checkEncoding(r),this._buff.toString(r,0,this.length)}destroy(){return this.clear(),this}_handleString(e,r,n,i){let a=this._writeOffset,s=this._encoding;typeof n=="number"?a=n:typeof n=="string"&&(Te.checkEncoding(n),s=n),typeof i=="string"&&(Te.checkEncoding(i),s=i);let o=Buffer.byteLength(e,s);return r?this.ensureInsertable(o,a):this._ensureWriteable(o,a),this._buff.write(e,a,o,s),r?this._writeOffset+=o:typeof n=="number"?this._writeOffset=Math.max(this._writeOffset,a+o):this._writeOffset+=o,this}_handleBuffer(e,r,n){let i=typeof n=="number"?n:this._writeOffset;return r?this.ensureInsertable(e.length,i):this._ensureWriteable(e.length,i),e.copy(this._buff,i),r?this._writeOffset+=e.length:typeof n=="number"?this._writeOffset=Math.max(this._writeOffset,i+e.length):this._writeOffset+=e.length,this}ensureReadable(e,r){let n=this._readOffset;if(typeof r<"u"&&(Te.checkOffsetValue(r),n=r),n<0||n+e>this.length)throw new Error(Te.ERRORS.INVALID_READ_BEYOND_BOUNDS)}ensureInsertable(e,r){Te.checkOffsetValue(r),this._ensureCapacity(this.length+e),r<this.length&&this._buff.copy(this._buff,r+e,r,this._buff.length),r+e>this.length?this.length=r+e:this.length+=e}_ensureWriteable(e,r){let n=typeof r=="number"?r:this._writeOffset;this._ensureCapacity(n+e),n+e>this.length&&(this.length=n+e)}_ensureCapacity(e){let r=this._buff.length;if(e>r){let n=this._buff,i=r*3/2+1;i<e&&(i=e),this._buff=Buffer.allocUnsafe(i),n.copy(this._buff,0,0,r)}}_readNumberValue(e,r,n){this.ensureReadable(r,n);let i=e.call(this._buff,typeof n=="number"?n:this._readOffset);return typeof n>"u"&&(this._readOffset+=r),i}_insertNumberValue(e,r,n,i){return Te.checkOffsetValue(i),this.ensureInsertable(r,i),e.call(this._buff,n,i),this._writeOffset+=r,this}_writeNumberValue(e,r,n,i){if(typeof i=="number"){if(i<0)throw new Error(Te.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);Te.checkOffsetValue(i)}let a=typeof i=="number"?i:this._writeOffset;return this._ensureWriteable(r,a),e.call(this._buff,n,a),typeof i=="number"?this._writeOffset=Math.max(this._writeOffset,a+r):this._writeOffset+=r,this}};nC.SmartBuffer=rC});var iC=p(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.SOCKS5_NO_ACCEPTABLE_AUTH=it.SOCKS5_CUSTOM_AUTH_END=it.SOCKS5_CUSTOM_AUTH_START=it.SOCKS_INCOMING_PACKET_SIZES=it.SocksClientState=it.Socks5Response=it.Socks5HostType=it.Socks5Auth=it.Socks4Response=it.SocksCommand=it.ERRORS=it.DEFAULT_TIMEOUT=void 0;var wye=3e4;it.DEFAULT_TIMEOUT=wye;var Iye={InvalidSocksCommand:"An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",InvalidSocksCommandForOperation:"An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",InvalidSocksCommandChain:"An invalid SOCKS command was provided. Chaining currently only supports the connect command.",InvalidSocksClientOptionsDestination:"An invalid destination host was provided.",InvalidSocksClientOptionsExistingSocket:"An invalid existing socket was provided. This should be an instance of stream.Duplex.",InvalidSocksClientOptionsProxy:"Invalid SOCKS proxy details were provided.",InvalidSocksClientOptionsTimeout:"An invalid timeout value was provided. Please enter a value above 0 (in ms).",InvalidSocksClientOptionsProxiesLength:"At least two socks proxies must be provided for chaining.",InvalidSocksClientOptionsCustomAuthRange:"Custom auth must be a value between 0x80 and 0xFE.",InvalidSocksClientOptionsCustomAuthOptions:"When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",NegotiationError:"Negotiation error",SocketClosed:"Socket closed",ProxyConnectionTimedOut:"Proxy connection timed out",InternalError:"SocksClient internal error (this should not happen)",InvalidSocks4HandshakeResponse:"Received invalid Socks4 handshake response",Socks4ProxyRejectedConnection:"Socks4 Proxy rejected connection",InvalidSocks4IncomingConnectionResponse:"Socks4 invalid incoming connection response",Socks4ProxyRejectedIncomingBoundConnection:"Socks4 Proxy rejected incoming bound connection",InvalidSocks5InitialHandshakeResponse:"Received invalid Socks5 initial handshake response",InvalidSocks5IntiailHandshakeSocksVersion:"Received invalid Socks5 initial handshake (invalid socks version)",InvalidSocks5InitialHandshakeNoAcceptedAuthType:"Received invalid Socks5 initial handshake (no accepted authentication type)",InvalidSocks5InitialHandshakeUnknownAuthType:"Received invalid Socks5 initial handshake (unknown authentication type)",Socks5AuthenticationFailed:"Socks5 Authentication failed",InvalidSocks5FinalHandshake:"Received invalid Socks5 final handshake response",InvalidSocks5FinalHandshakeRejected:"Socks5 proxy rejected connection",InvalidSocks5IncomingConnectionResponse:"Received invalid Socks5 incoming connection response",Socks5ProxyRejectedIncomingBoundConnection:"Socks5 Proxy rejected incoming bound connection"};it.ERRORS=Iye;var Dye={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:t=>t+7,Socks4Response:8};it.SOCKS_INCOMING_PACKET_SIZES=Dye;var j7;(function(t){t[t.connect=1]="connect",t[t.bind=2]="bind",t[t.associate=3]="associate"})(j7||(it.SocksCommand=j7={}));var X7;(function(t){t[t.Granted=90]="Granted",t[t.Failed=91]="Failed",t[t.Rejected=92]="Rejected",t[t.RejectedIdent=93]="RejectedIdent"})(X7||(it.Socks4Response=X7={}));var Z7;(function(t){t[t.NoAuth=0]="NoAuth",t[t.GSSApi=1]="GSSApi",t[t.UserPass=2]="UserPass"})(Z7||(it.Socks5Auth=Z7={}));var xye=128;it.SOCKS5_CUSTOM_AUTH_START=xye;var Mye=254;it.SOCKS5_CUSTOM_AUTH_END=Mye;var Lye=255;it.SOCKS5_NO_ACCEPTABLE_AUTH=Lye;var J7;(function(t){t[t.Granted=0]="Granted",t[t.Failure=1]="Failure",t[t.NotAllowed=2]="NotAllowed",t[t.NetworkUnreachable=3]="NetworkUnreachable",t[t.HostUnreachable=4]="HostUnreachable",t[t.ConnectionRefused=5]="ConnectionRefused",t[t.TTLExpired=6]="TTLExpired",t[t.CommandNotSupported=7]="CommandNotSupported",t[t.AddressNotSupported=8]="AddressNotSupported"})(J7||(it.Socks5Response=J7={}));var eW;(function(t){t[t.IPv4=1]="IPv4",t[t.Hostname=3]="Hostname",t[t.IPv6=4]="IPv6"})(eW||(it.Socks5HostType=eW={}));var tW;(function(t){t[t.Created=0]="Created",t[t.Connecting=1]="Connecting",t[t.Connected=2]="Connected",t[t.SentInitialHandshake=3]="SentInitialHandshake",t[t.ReceivedInitialHandshakeResponse=4]="ReceivedInitialHandshakeResponse",t[t.SentAuthentication=5]="SentAuthentication",t[t.ReceivedAuthenticationResponse=6]="ReceivedAuthenticationResponse",t[t.SentFinalHandshake=7]="SentFinalHandshake",t[t.ReceivedFinalResponse=8]="ReceivedFinalResponse",t[t.BoundWaitingForConnection=9]="BoundWaitingForConnection",t[t.Established=10]="Established",t[t.Disconnected=11]="Disconnected",t[t.Error=99]="Error"})(tW||(it.SocksClientState=tW={}))});var sC=p(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});bl.shuffleArray=bl.SocksClientError=void 0;var aC=class extends Error{constructor(e,r){super(e),this.options=r}};bl.SocksClientError=aC;function Pye(t){for(let e=t.length-1;e>0;e--){let r=Math.floor(Math.random()*(e+1));[t[e],t[r]]=[t[r],t[e]]}}bl.shuffleArray=Pye});var Fh=p(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.isInSubnet=kye;Us.isCorrect=Bye;Us.numberToPaddedHex=rW;Us.stringToPaddedHex=Fye;Us.testBit=Uye;function kye(t){return this.subnetMask<t.subnetMask?!1:this.mask(t.subnetMask)===t.mask()}function Bye(t){return function(){return this.addressMinusSuffix!==this.correctForm()?!1:this.subnetMask===t&&!this.parsedSubnet?!0:this.parsedSubnet===String(this.subnetMask)}}function rW(t){return t.toString(16).padStart(2,"0")}function Fye(t){return rW(parseInt(t,10))}function Uye(t,e){let{length:r}=t;if(e>r)return!1;let n=r-e;return t.substring(n,n+1)==="1"}});var oC=p(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.RE_SUBNET_STRING=ri.RE_ADDRESS=ri.GROUPS=ri.BITS=void 0;ri.BITS=32;ri.GROUPS=4;ri.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;ri.RE_SUBNET_STRING=/\/\d{1,2}$/});var qh=p(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});Uh.AddressError=void 0;var lC=class extends Error{constructor(e,r){super(e),this.name="AddressError",this.parseMessage=r}};Uh.AddressError=lC});var cC=p(ni=>{"use strict";var qye=ni&&ni.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Gye=ni&&ni.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),nW=ni&&ni.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&qye(e,t,r);return Gye(e,t),e};Object.defineProperty(ni,"__esModule",{value:!0});ni.Address4=void 0;var vl=nW(Fh()),wn=nW(oC()),Qc=qh(),uC=class t{constructor(e){this.groups=wn.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=vl.isCorrect(wn.BITS),this.isInSubnet=vl.isInSubnet,this.address=e;let r=wn.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>wn.BITS)throw new Qc.AddressError("Invalid subnet mask.");e=e.replace(wn.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new t(e),!0}catch{return!1}}parse(e){let r=e.split(".");if(!e.match(wn.RE_ADDRESS))throw new Qc.AddressError("Invalid IPv4 address.");return r}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromHex(e){let r=e.replace(/:/g,"").padStart(8,"0"),n=[],i;for(i=0;i<8;i+=2){let a=r.slice(i,i+2);n.push(parseInt(a,16))}return new t(n.join("."))}static fromInteger(e){return t.fromHex(e.toString(16))}static fromArpa(e){let n=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new t(n)}toHex(){return this.parsedAddress.map(e=>vl.stringToPaddedHex(e)).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],r;for(r=0;r<wn.GROUPS;r+=2)e.push(`${vl.stringToPaddedHex(this.parsedAddress[r])}${vl.stringToPaddedHex(this.parsedAddress[r+1])}`);return e.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>vl.stringToPaddedHex(e)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(wn.BITS-this.subnetMask)}`)}startAddress(){return t.fromBigInt(this._startAddress())}startAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(wn.BITS-this.subnetMask)}`)}endAddress(){return t.fromBigInt(this._endAddress())}endAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._endAddress()-e)}static fromBigInt(e){return t.fromHex(e.toString(16))}static fromByteArray(e){if(e.length!==4)throw new Qc.AddressError("IPv4 addresses require exactly 4 bytes");for(let r=0;r<e.length;r++)if(!Number.isInteger(e[r])||e[r]<0||e[r]>255)throw new Qc.AddressError("All bytes must be integers between 0 and 255");return this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(e){if(e.length!==4)throw new Qc.AddressError("IPv4 addresses require exactly 4 bytes");let r=e.join(".");return new t(r)}mask(e){return e===void 0&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,r){return this.binaryZeroPad().slice(e,r)}reverseForm(e){e||(e={});let r=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?r:`${r}.in-addr.arpa.`}isMulticast(){return this.isInSubnet(new t("224.0.0.0/4"))}binaryZeroPad(){return this.bigInt().toString(2).padStart(wn.BITS,"0")}groupForV6(){let e=this.parsedAddress;return this.address.replace(wn.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(".")}</span>`)}};ni.Address4=uC});var dC=p(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.RE_URL_WITH_PORT=Nt.RE_URL=Nt.RE_ZONE_STRING=Nt.RE_SUBNET_STRING=Nt.RE_BAD_ADDRESS=Nt.RE_BAD_CHARACTERS=Nt.TYPES=Nt.SCOPES=Nt.GROUPS=Nt.BITS=void 0;Nt.BITS=128;Nt.GROUPS=8;Nt.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};Nt.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"};Nt.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;Nt.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;Nt.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;Nt.RE_ZONE_STRING=/%.*$/;Nt.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/;Nt.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/});var fC=p(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});yl.spanAllZeroes=iW;yl.spanAll=Yye;yl.spanLeadingZeroes=Hye;yl.simpleGroup=Vye;function iW(t){return t.replace(/(0+)/g,'<span class="zero">$1</span>')}function Yye(t,e=0){return t.split("").map((n,i)=>`<span class="digit value-${n} position-${i+e}">${iW(n)}</span>`).join("")}function aW(t){return t.replace(/^(0+)/,'<span class="zero">$1</span>')}function Hye(t){return t.split(":").map(r=>aW(r)).join(":")}function Vye(t,e=0){return t.split(":").map((n,i)=>/group-v4/.test(n)?n:`<span class="hover-group group-${i+e}">${aW(n)}</span>`)}});var sW=p(Ir=>{"use strict";var Wye=Ir&&Ir.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),zye=Ir&&Ir.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),$ye=Ir&&Ir.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Wye(e,t,r);return zye(e,t),e};Object.defineProperty(Ir,"__esModule",{value:!0});Ir.ADDRESS_BOUNDARY=void 0;Ir.groupPossibilities=Yh;Ir.padGroup=Gh;Ir.simpleRegularExpression=Qye;Ir.possibleElisions=jye;var Kye=$ye(dC());function Yh(t){return`(${t.join("|")})`}function Gh(t){return t.length<4?`0{0,${4-t.length}}${t}`:t}Ir.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function Qye(t){let e=[];t.forEach((n,i)=>{parseInt(n,16)===0&&e.push(i)});let r=e.map(n=>t.map((i,a)=>{if(a===n){let s=a===0||a===Kye.GROUPS-1?":":"";return Yh([Gh(i),s])}return Gh(i)}).join(":"));return r.push(t.map(Gh).join(":")),Yh(r)}function jye(t,e,r){let n=e?"":":",i=r?"":":",a=[];!e&&!r&&a.push("::"),e&&r&&a.push(""),(r&&!e||!r&&e)&&a.push(":"),a.push(`${n}(:0{1,4}){1,${t-1}}`),a.push(`(0{1,4}:){1,${t-1}}${i}`),a.push(`(0{1,4}:){${t-1}}0{1,4}`);for(let s=1;s<t-1;s++)for(let o=1;o<t-s;o++)a.push(`(0{1,4}:){${o}}:(0{1,4}:){${t-o-s-1}}0{1,4}`);return Yh(a)}});var cW=p(ii=>{"use strict";var Xye=ii&&ii.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Zye=ii&&ii.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Wh=ii&&ii.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Xye(e,t,r);return Zye(e,t),e};Object.defineProperty(ii,"__esModule",{value:!0});ii.Address6=void 0;var oW=Wh(Fh()),_C=Wh(oC()),at=Wh(dC()),pC=Wh(fC()),qs=cC(),Gs=sW(),qi=qh(),Hh=Fh();function Vh(t){if(!t)throw new Error("Assertion failed.")}function Jye(t){let e=/(\d+)(\d{3})/;for(;e.test(t);)t=t.replace(e,"$1,$2");return t}function eTe(t){return t=t.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2'),t=t.replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2'),t}function tTe(t,e){let r=[],n=[],i;for(i=0;i<t.length;i++)i<e[0]?r.push(t[i]):i>e[1]&&n.push(t[i]);return r.concat(["compact"]).concat(n)}function lW(t){return parseInt(t,16).toString(16).padStart(4,"0")}function uW(t){return t&255}var hC=class t{constructor(e,r){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=oW.isInSubnet,this.isCorrect=oW.isCorrect(at.BITS),r===void 0?this.groups=at.GROUPS:this.groups=r,this.address=e;let n=at.RE_SUBNET_STRING.exec(e);if(n){if(this.parsedSubnet=n[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>at.BITS)throw new qi.AddressError("Invalid subnet mask.");e=e.replace(at.RE_SUBNET_STRING,"")}else if(/\//.test(e))throw new qi.AddressError("Invalid subnet mask.");let i=at.RE_ZONE_STRING.exec(e);i&&(this.zone=i[0],e=e.replace(at.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new t(e),!0}catch{return!1}}static fromBigInt(e){let r=e.toString(16).padStart(32,"0"),n=[],i;for(i=0;i<at.GROUPS;i++)n.push(r.slice(i*4,(i+1)*4));return new t(n.join(":"))}static fromURL(e){let r,n=null,i;if(e.indexOf("[")!==-1&&e.indexOf("]:")!==-1){if(i=at.RE_URL_WITH_PORT.exec(e),i===null)return{error:"failed to parse address with port",address:null,port:null};r=i[1],n=i[2]}else if(e.indexOf("/")!==-1){if(e=e.replace(/^[a-z0-9]+:\/\//,""),i=at.RE_URL.exec(e),i===null)return{error:"failed to parse address from URL",address:null,port:null};r=i[1]}else r=e;return n?(n=parseInt(n,10),(n<0||n>65536)&&(n=null)):n=null,{address:new t(r),port:n}}static fromAddress4(e){let r=new qs.Address4(e),n=at.BITS-(_C.BITS-r.subnetMask);return new t(`::ffff:${r.correctForm()}/${n}`)}static fromArpa(e){let r=e.replace(/(\.ip6\.arpa)?\.$/,""),n=7;if(r.length!==63)throw new qi.AddressError("Invalid 'ip6.arpa' form.");let i=r.split(".").reverse();for(let a=n;a>0;a--){let s=a*4;i.splice(s,0,":")}return r=i.join(""),new t(r)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){let r=at.BITS-this.subnetMask,n=Math.abs(e-at.BITS),i=r-n;return i<0?"0":Jye((BigInt("2")**BigInt(i)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(at.BITS-this.subnetMask)}`)}startAddress(){return t.fromBigInt(this._startAddress())}startAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(at.BITS-this.subnetMask)}`)}endAddress(){return t.fromBigInt(this._endAddress())}endAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._endAddress()-e)}getScope(){let e=at.SCOPES[parseInt(this.getBits(12,16).toString(10),10)];return this.getType()==="Global unicast"&&e!=="Link local"&&(e="Global"),e||"Unknown"}getType(){for(let e of Object.keys(at.TYPES))if(this.isInSubnet(new t(e)))return at.TYPES[e];return"Global unicast"}getBits(e,r){return BigInt(`0b${this.getBitsBase2(e,r)}`)}getBitsBase2(e,r){return this.binaryZeroPad().slice(e,r)}getBitsBase16(e,r){let n=r-e;if(n%4!==0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,r).toString(16).padStart(n/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,at.BITS)}reverseForm(e){e||(e={});let r=Math.floor(this.subnetMask/4),n=this.canonicalForm().replace(/:/g,"").split("").slice(0,r).reverse().join(".");return r>0?e.omitSuffix?n:`${n}.ip6.arpa.`:e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,r=[],n=0,i=[];for(e=0;e<this.parsedAddress.length;e++){let o=parseInt(this.parsedAddress[e],16);o===0&&n++,o!==0&&n>0&&(n>1&&i.push([e-n,e-1]),n=0)}n>1&&i.push([this.parsedAddress.length-n,this.parsedAddress.length-1]);let a=i.map(o=>o[1]-o[0]+1);if(i.length>0){let o=a.indexOf(Math.max(...a));r=tTe(this.parsedAddress,i[o])}else r=this.parsedAddress;for(e=0;e<r.length;e++)r[e]!=="compact"&&(r[e]=parseInt(r[e],16).toString(16));let s=r.join(":");return s=s.replace(/^compact$/,"::"),s=s.replace(/(^compact)|(compact$)/,":"),s=s.replace(/compact/,""),s}binaryZeroPad(){return this.bigInt().toString(2).padStart(at.BITS,"0")}parse4in6(e){let r=e.split(":"),i=r.slice(-1)[0].match(_C.RE_ADDRESS);if(i){this.parsedAddress4=i[0],this.address4=new qs.Address4(this.parsedAddress4);for(let a=0;a<this.address4.groups;a++)if(/^0[0-9]+/.test(this.address4.parsedAddress[a]))throw new qi.AddressError("IPv4 addresses can't have leading zeroes.",e.replace(_C.RE_ADDRESS,this.address4.parsedAddress.map(eTe).join(".")));this.v4=!0,r[r.length-1]=this.address4.toGroup6(),e=r.join(":")}return e}parse(e){e=this.parse4in6(e);let r=e.match(at.RE_BAD_CHARACTERS);if(r)throw new qi.AddressError(`Bad character${r.length>1?"s":""} detected in address: ${r.join("")}`,e.replace(at.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let n=e.match(at.RE_BAD_ADDRESS);if(n)throw new qi.AddressError(`Address failed regex: ${n.join("")}`,e.replace(at.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let i=[],a=e.split("::");if(a.length===2){let s=a[0].split(":"),o=a[1].split(":");s.length===1&&s[0]===""&&(s=[]),o.length===1&&o[0]===""&&(o=[]);let l=this.groups-(s.length+o.length);if(!l)throw new qi.AddressError("Error parsing groups");this.elidedGroups=l,this.elisionBegin=s.length,this.elisionEnd=s.length+this.elidedGroups,i=i.concat(s);for(let c=0;c<l;c++)i.push("0");i=i.concat(o)}else if(a.length===1)i=e.split(":"),this.elidedGroups=0;else throw new qi.AddressError("Too many :: groups found");if(i=i.map(s=>parseInt(s,16).toString(16)),i.length!==this.groups)throw new qi.AddressError("Incorrect number of groups found");return i}canonicalForm(){return this.parsedAddress.map(lW).join(":")}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(lW).join("")}`)}to4(){let e=this.binaryZeroPad().split("");return qs.Address4.fromHex(BigInt(`0b${e.slice(96,128).join("")}`).toString(16))}to4in6(){let e=this.to4(),n=new t(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),i="";return/:$/.test(n)||(i=":"),n+i+e.address}inspectTeredo(){let e=this.getBitsBase16(0,32),n=(this.getBits(80,96)^BigInt("0xffff")).toString(),i=qs.Address4.fromHex(this.getBitsBase16(32,64)),a=this.getBits(96,128),s=qs.Address4.fromHex((a^BigInt("0xffffffff")).toString(16)),o=this.getBitsBase2(64,80),l=(0,Hh.testBit)(o,15),c=(0,Hh.testBit)(o,14),_=(0,Hh.testBit)(o,8),d=(0,Hh.testBit)(o,9),m=BigInt(`0b${o.slice(2,6)+o.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:i.address,client4:s.address,flags:o,coneNat:l,microsoft:{reserved:c,universalLocal:d,groupIndividual:_,nonce:m},udpPort:n}}inspect6to4(){let e=this.getBitsBase16(0,16),r=qs.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:r.address}}to6to4(){if(!this.is4())return null;let e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new t(e)}toByteArray(){let e=this.bigInt().toString(16),n=`${"0".repeat(e.length%2)}${e}`,i=[];for(let a=0,s=n.length;a<s;a+=2)i.push(parseInt(n.substring(a,a+2),16));return i}toUnsignedByteArray(){return this.toByteArray().map(uW)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(uW))}static fromUnsignedByteArray(e){let r=BigInt("256"),n=BigInt("0"),i=BigInt("1");for(let a=e.length-1;a>=0;a--)n+=i*BigInt(e[a].toString(10)),i*=r;return t.fromBigInt(n)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){return this.getBitsBase2(0,64)==="1111111010000000000000000000000000000000000000000000000000000000"}isMulticast(){return this.getType()==="Multicast"}is4(){return this.v4}isTeredo(){return this.isInSubnet(new t("2001::/32"))}is6to4(){return this.isInSubnet(new t("2002::/16"))}isLoopback(){return this.getType()==="Loopback"}href(e){return e===void 0?e="":e=`:${e}`,`http://[${this.correctForm()}]${e}/`}link(e){e||(e={}),e.className===void 0&&(e.className=""),e.prefix===void 0&&(e.prefix="/#address="),e.v4===void 0&&(e.v4=!1);let r=this.correctForm;e.v4&&(r=this.to4in6);let n=r.call(this);return e.className?`<a href="${e.prefix}${n}" class="${e.className}">${n}</a>`:`<a href="${e.prefix}${n}">${n}</a>`}group(){if(this.elidedGroups===0)return pC.simpleGroup(this.address).join(":");Vh(typeof this.elidedGroups=="number"),Vh(typeof this.elisionBegin=="number");let e=[],[r,n]=this.address.split("::");r.length?e.push(...pC.simpleGroup(r)):e.push("");let i=["hover-group"];for(let a=this.elisionBegin;a<this.elisionBegin+this.elidedGroups;a++)i.push(`group-${a}`);return e.push(`<span class="${i.join(" ")}"></span>`),n.length?e.push(...pC.simpleGroup(n,this.elisionEnd)):e.push(""),this.is4()&&(Vh(this.address4 instanceof qs.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let r=[],n=new t(this.correctForm());if(n.elidedGroups===0)r.push((0,Gs.simpleRegularExpression)(n.parsedAddress));else if(n.elidedGroups===at.GROUPS)r.push((0,Gs.possibleElisions)(at.GROUPS));else{let i=n.address.split("::");i[0].length&&r.push((0,Gs.simpleRegularExpression)(i[0].split(":"))),Vh(typeof n.elidedGroups=="number"),r.push((0,Gs.possibleElisions)(n.elidedGroups,i[0].length!==0,i[1].length!==0)),i[1].length&&r.push((0,Gs.simpleRegularExpression)(i[1].split(":"))),r=[r.join(":")]}return e||(r=["(?=^|",Gs.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...r,")(?=[^\\w\\:]|",Gs.ADDRESS_BOUNDARY,"|$)"]),r.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}};ii.Address6=hC});var mC=p(dr=>{"use strict";var rTe=dr&&dr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),nTe=dr&&dr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),iTe=dr&&dr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rTe(e,t,r);return nTe(e,t),e};Object.defineProperty(dr,"__esModule",{value:!0});dr.v6=dr.AddressError=dr.Address6=dr.Address4=void 0;var aTe=cC();Object.defineProperty(dr,"Address4",{enumerable:!0,get:function(){return aTe.Address4}});var sTe=cW();Object.defineProperty(dr,"Address6",{enumerable:!0,get:function(){return sTe.Address6}});var oTe=qh();Object.defineProperty(dr,"AddressError",{enumerable:!0,get:function(){return oTe.AddressError}});var lTe=iTe(fC());dr.v6={helpers:lTe}});var mW=p(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.ipToBuffer=nn.int32ToIpv4=nn.ipv4ToInt32=nn.validateSocksClientChainOptions=nn.validateSocksClientOptions=void 0;var yr=sC(),Jt=iC(),uTe=require("stream"),gC=mC(),dW=require("net");function cTe(t,e=["connect","bind","associate"]){if(!Jt.SocksCommand[t.command])throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksCommand,t);if(e.indexOf(t.command)===-1)throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksCommandForOperation,t);if(!_W(t.destination))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsDestination,t);if(!pW(t.proxy))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsProxy,t);if(fW(t.proxy,t),t.timeout&&!hW(t.timeout))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsTimeout,t);if(t.existing_socket&&!(t.existing_socket instanceof uTe.Duplex))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsExistingSocket,t)}nn.validateSocksClientOptions=cTe;function dTe(t){if(t.command!=="connect")throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksCommandChain,t);if(!_W(t.destination))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsDestination,t);if(!(t.proxies&&Array.isArray(t.proxies)&&t.proxies.length>=2))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsProxiesLength,t);if(t.proxies.forEach(e=>{if(!pW(e))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsProxy,t);fW(e,t)}),t.timeout&&!hW(t.timeout))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsTimeout,t)}nn.validateSocksClientChainOptions=dTe;function fW(t,e){if(t.custom_auth_method!==void 0){if(t.custom_auth_method<Jt.SOCKS5_CUSTOM_AUTH_START||t.custom_auth_method>Jt.SOCKS5_CUSTOM_AUTH_END)throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsCustomAuthRange,e);if(t.custom_auth_request_handler===void 0||typeof t.custom_auth_request_handler!="function")throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,e);if(t.custom_auth_response_size===void 0)throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,e);if(t.custom_auth_response_handler===void 0||typeof t.custom_auth_response_handler!="function")throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,e)}}function _W(t){return t&&typeof t.host=="string"&&Buffer.byteLength(t.host)<256&&typeof t.port=="number"&&t.port>=0&&t.port<=65535}function pW(t){return t&&(typeof t.host=="string"||typeof t.ipaddress=="string")&&typeof t.port=="number"&&t.port>=0&&t.port<=65535&&(t.type===4||t.type===5)}function hW(t){return typeof t=="number"&&t>0}function fTe(t){return new gC.Address4(t).toArray().reduce((r,n)=>(r<<8)+n,0)>>>0}nn.ipv4ToInt32=fTe;function _Te(t){let e=t>>>24&255,r=t>>>16&255,n=t>>>8&255,i=t&255;return[e,r,n,i].join(".")}nn.int32ToIpv4=_Te;function pTe(t){if(dW.isIPv4(t)){let e=new gC.Address4(t);return Buffer.from(e.toArray())}else if(dW.isIPv6(t)){let e=new gC.Address6(t);return Buffer.from(e.canonicalForm().split(":").map(r=>r.padStart(4,"0")).join(""),"hex")}else throw new Error("Invalid IP address format")}nn.ipToBuffer=pTe});var gW=p(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});zh.ReceiveBuffer=void 0;var EC=class{constructor(e=4096){this.buffer=Buffer.allocUnsafe(e),this.offset=0,this.originalSize=e}get length(){return this.offset}append(e){if(!Buffer.isBuffer(e))throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer.");if(this.offset+e.length>=this.buffer.length){let r=this.buffer;this.buffer=Buffer.allocUnsafe(Math.max(this.buffer.length+this.originalSize,this.buffer.length+e.length)),r.copy(this.buffer)}return e.copy(this.buffer,this.offset),this.offset+=e.length}peek(e){if(e>this.offset)throw new Error("Attempted to read beyond the bounds of the managed internal data.");return this.buffer.slice(0,e)}get(e){if(e>this.offset)throw new Error("Attempted to read beyond the bounds of the managed internal data.");let r=Buffer.allocUnsafe(e);return this.buffer.slice(0,e).copy(r),this.buffer.copyWithin(0,e,e+this.offset-e),this.offset-=e,r}};zh.ReceiveBuffer=EC});var EW=p(Ia=>{"use strict";var Tl=Ia&&Ia.__awaiter||function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(_){try{c(n.next(_))}catch(d){s(d)}}function l(_){try{c(n.throw(_))}catch(d){s(d)}}function c(_){_.done?a(_.value):i(_.value).then(o,l)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Ia,"__esModule",{value:!0});Ia.SocksClientError=Ia.SocksClient=void 0;var hTe=require("events"),Cl=require("net"),Dr=Q7(),U=iC(),Fr=mW(),mTe=gW(),bC=sC();Object.defineProperty(Ia,"SocksClientError",{enumerable:!0,get:function(){return bC.SocksClientError}});var SC=mC(),vC=class t extends hTe.EventEmitter{constructor(e){super(),this.options=Object.assign({},e),(0,Fr.validateSocksClientOptions)(e),this.setState(U.SocksClientState.Created)}static createConnection(e,r){return new Promise((n,i)=>{try{(0,Fr.validateSocksClientOptions)(e,["connect"])}catch(s){return typeof r=="function"?(r(s),n(s)):i(s)}let a=new t(e);a.connect(e.existing_socket),a.once("established",s=>{a.removeAllListeners(),typeof r=="function"&&r(null,s),n(s)}),a.once("error",s=>{a.removeAllListeners(),typeof r=="function"?(r(s),n(s)):i(s)})})}static createConnectionChain(e,r){return new Promise((n,i)=>Tl(this,void 0,void 0,function*(){try{(0,Fr.validateSocksClientChainOptions)(e)}catch(a){return typeof r=="function"?(r(a),n(a)):i(a)}e.randomizeChain&&(0,bC.shuffleArray)(e.proxies);try{let a;for(let s=0;s<e.proxies.length;s++){let o=e.proxies[s],l=s===e.proxies.length-1?e.destination:{host:e.proxies[s+1].host||e.proxies[s+1].ipaddress,port:e.proxies[s+1].port},c=yield t.createConnection({command:"connect",proxy:o,destination:l,existing_socket:a});a=a||c.socket}typeof r=="function"?(r(null,{socket:a}),n({socket:a})):n({socket:a})}catch(a){typeof r=="function"?(r(a),n(a)):i(a)}}))}static createUDPFrame(e){let r=new Dr.SmartBuffer;return r.writeUInt16BE(0),r.writeUInt8(e.frameNumber||0),Cl.isIPv4(e.remoteHost.host)?(r.writeUInt8(U.Socks5HostType.IPv4),r.writeUInt32BE((0,Fr.ipv4ToInt32)(e.remoteHost.host))):Cl.isIPv6(e.remoteHost.host)?(r.writeUInt8(U.Socks5HostType.IPv6),r.writeBuffer((0,Fr.ipToBuffer)(e.remoteHost.host))):(r.writeUInt8(U.Socks5HostType.Hostname),r.writeUInt8(Buffer.byteLength(e.remoteHost.host)),r.writeString(e.remoteHost.host)),r.writeUInt16BE(e.remoteHost.port),r.writeBuffer(e.data),r.toBuffer()}static parseUDPFrame(e){let r=Dr.SmartBuffer.fromBuffer(e);r.readOffset=2;let n=r.readUInt8(),i=r.readUInt8(),a;i===U.Socks5HostType.IPv4?a=(0,Fr.int32ToIpv4)(r.readUInt32BE()):i===U.Socks5HostType.IPv6?a=SC.Address6.fromByteArray(Array.from(r.readBuffer(16))).canonicalForm():a=r.readString(r.readUInt8());let s=r.readUInt16BE();return{frameNumber:n,remoteHost:{host:a,port:s},data:r.readBuffer()}}setState(e){this.state!==U.SocksClientState.Error&&(this.state=e)}connect(e){this.onDataReceived=n=>this.onDataReceivedHandler(n),this.onClose=()=>this.onCloseHandler(),this.onError=n=>this.onErrorHandler(n),this.onConnect=()=>this.onConnectHandler();let r=setTimeout(()=>this.onEstablishedTimeout(),this.options.timeout||U.DEFAULT_TIMEOUT);r.unref&&typeof r.unref=="function"&&r.unref(),e?this.socket=e:this.socket=new Cl.Socket,this.socket.once("close",this.onClose),this.socket.once("error",this.onError),this.socket.once("connect",this.onConnect),this.socket.on("data",this.onDataReceived),this.setState(U.SocksClientState.Connecting),this.receiveBuffer=new mTe.ReceiveBuffer,e?this.socket.emit("connect"):(this.socket.connect(this.getSocketOptions()),this.options.set_tcp_nodelay!==void 0&&this.options.set_tcp_nodelay!==null&&this.socket.setNoDelay(!!this.options.set_tcp_nodelay)),this.prependOnceListener("established",n=>{setImmediate(()=>{if(this.receiveBuffer.length>0){let i=this.receiveBuffer.get(this.receiveBuffer.length);n.socket.emit("data",i)}n.socket.resume()})})}getSocketOptions(){return Object.assign(Object.assign({},this.options.socket_options),{host:this.options.proxy.host||this.options.proxy.ipaddress,port:this.options.proxy.port})}onEstablishedTimeout(){this.state!==U.SocksClientState.Established&&this.state!==U.SocksClientState.BoundWaitingForConnection&&this.closeSocket(U.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){this.setState(U.SocksClientState.Connected),this.options.proxy.type===4?this.sendSocks4InitialHandshake():this.sendSocks5InitialHandshake(),this.setState(U.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(e){this.receiveBuffer.append(e),this.processData()}processData(){for(;this.state!==U.SocksClientState.Established&&this.state!==U.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize;)if(this.state===U.SocksClientState.SentInitialHandshake)this.options.proxy.type===4?this.handleSocks4FinalHandshakeResponse():this.handleInitialSocks5HandshakeResponse();else if(this.state===U.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===U.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else if(this.state===U.SocksClientState.BoundWaitingForConnection)this.options.proxy.type===4?this.handleSocks4IncomingConnectionResponse():this.handleSocks5IncomingConnectionResponse();else{this.closeSocket(U.ERRORS.InternalError);break}}onCloseHandler(){this.closeSocket(U.ERRORS.SocketClosed)}onErrorHandler(e){this.closeSocket(e.message)}removeInternalSocketHandlers(){this.socket.pause(),this.socket.removeListener("data",this.onDataReceived),this.socket.removeListener("close",this.onClose),this.socket.removeListener("error",this.onError),this.socket.removeListener("connect",this.onConnect)}closeSocket(e){this.state!==U.SocksClientState.Error&&(this.setState(U.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new bC.SocksClientError(e,this.options)))}sendSocks4InitialHandshake(){let e=this.options.proxy.userId||"",r=new Dr.SmartBuffer;r.writeUInt8(4),r.writeUInt8(U.SocksCommand[this.options.command]),r.writeUInt16BE(this.options.destination.port),Cl.isIPv4(this.options.destination.host)?(r.writeBuffer((0,Fr.ipToBuffer)(this.options.destination.host)),r.writeStringNT(e)):(r.writeUInt8(0),r.writeUInt8(0),r.writeUInt8(0),r.writeUInt8(1),r.writeStringNT(e),r.writeStringNT(this.options.destination.host)),this.nextRequiredPacketBufferSize=U.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write(r.toBuffer())}handleSocks4FinalHandshakeResponse(){let e=this.receiveBuffer.get(8);if(e[1]!==U.Socks4Response.Granted)this.closeSocket(`${U.ERRORS.Socks4ProxyRejectedConnection} - (${U.Socks4Response[e[1]]})`);else if(U.SocksCommand[this.options.command]===U.SocksCommand.bind){let r=Dr.SmartBuffer.fromBuffer(e);r.readOffset=2;let n={port:r.readUInt16BE(),host:(0,Fr.int32ToIpv4)(r.readUInt32BE())};n.host==="0.0.0.0"&&(n.host=this.options.proxy.ipaddress),this.setState(U.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost:n,socket:this.socket})}else this.setState(U.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){let e=this.receiveBuffer.get(8);if(e[1]!==U.Socks4Response.Granted)this.closeSocket(`${U.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${U.Socks4Response[e[1]]})`);else{let r=Dr.SmartBuffer.fromBuffer(e);r.readOffset=2;let n={port:r.readUInt16BE(),host:(0,Fr.int32ToIpv4)(r.readUInt32BE())};this.setState(U.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:n,socket:this.socket})}}sendSocks5InitialHandshake(){let e=new Dr.SmartBuffer,r=[U.Socks5Auth.NoAuth];(this.options.proxy.userId||this.options.proxy.password)&&r.push(U.Socks5Auth.UserPass),this.options.proxy.custom_auth_method!==void 0&&r.push(this.options.proxy.custom_auth_method),e.writeUInt8(5),e.writeUInt8(r.length);for(let n of r)e.writeUInt8(n);this.nextRequiredPacketBufferSize=U.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(e.toBuffer()),this.setState(U.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){let e=this.receiveBuffer.get(2);e[0]!==5?this.closeSocket(U.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion):e[1]===U.SOCKS5_NO_ACCEPTABLE_AUTH?this.closeSocket(U.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType):e[1]===U.Socks5Auth.NoAuth?(this.socks5ChosenAuthType=U.Socks5Auth.NoAuth,this.sendSocks5CommandRequest()):e[1]===U.Socks5Auth.UserPass?(this.socks5ChosenAuthType=U.Socks5Auth.UserPass,this.sendSocks5UserPassAuthentication()):e[1]===this.options.proxy.custom_auth_method?(this.socks5ChosenAuthType=this.options.proxy.custom_auth_method,this.sendSocks5CustomAuthentication()):this.closeSocket(U.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType)}sendSocks5UserPassAuthentication(){let e=this.options.proxy.userId||"",r=this.options.proxy.password||"",n=new Dr.SmartBuffer;n.writeUInt8(1),n.writeUInt8(Buffer.byteLength(e)),n.writeString(e),n.writeUInt8(Buffer.byteLength(r)),n.writeString(r),this.nextRequiredPacketBufferSize=U.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(n.toBuffer()),this.setState(U.SocksClientState.SentAuthentication)}sendSocks5CustomAuthentication(){return Tl(this,void 0,void 0,function*(){this.nextRequiredPacketBufferSize=this.options.proxy.custom_auth_response_size,this.socket.write(yield this.options.proxy.custom_auth_request_handler()),this.setState(U.SocksClientState.SentAuthentication)})}handleSocks5CustomAuthHandshakeResponse(e){return Tl(this,void 0,void 0,function*(){return yield this.options.proxy.custom_auth_response_handler(e)})}handleSocks5AuthenticationNoAuthHandshakeResponse(e){return Tl(this,void 0,void 0,function*(){return e[1]===0})}handleSocks5AuthenticationUserPassHandshakeResponse(e){return Tl(this,void 0,void 0,function*(){return e[1]===0})}handleInitialSocks5AuthenticationHandshakeResponse(){return Tl(this,void 0,void 0,function*(){this.setState(U.SocksClientState.ReceivedAuthenticationResponse);let e=!1;this.socks5ChosenAuthType===U.Socks5Auth.NoAuth?e=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2)):this.socks5ChosenAuthType===U.Socks5Auth.UserPass?e=yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2)):this.socks5ChosenAuthType===this.options.proxy.custom_auth_method&&(e=yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size))),e?this.sendSocks5CommandRequest():this.closeSocket(U.ERRORS.Socks5AuthenticationFailed)})}sendSocks5CommandRequest(){let e=new Dr.SmartBuffer;e.writeUInt8(5),e.writeUInt8(U.SocksCommand[this.options.command]),e.writeUInt8(0),Cl.isIPv4(this.options.destination.host)?(e.writeUInt8(U.Socks5HostType.IPv4),e.writeBuffer((0,Fr.ipToBuffer)(this.options.destination.host))):Cl.isIPv6(this.options.destination.host)?(e.writeUInt8(U.Socks5HostType.IPv6),e.writeBuffer((0,Fr.ipToBuffer)(this.options.destination.host))):(e.writeUInt8(U.Socks5HostType.Hostname),e.writeUInt8(this.options.destination.host.length),e.writeString(this.options.destination.host)),e.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(e.toBuffer()),this.setState(U.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){let e=this.receiveBuffer.peek(5);if(e[0]!==5||e[1]!==U.Socks5Response.Granted)this.closeSocket(`${U.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${U.Socks5Response[e[1]]}`);else{let r=e[3],n,i;if(r===U.Socks5HostType.IPv4){let a=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<a){this.nextRequiredPacketBufferSize=a;return}i=Dr.SmartBuffer.fromBuffer(this.receiveBuffer.get(a).slice(4)),n={host:(0,Fr.int32ToIpv4)(i.readUInt32BE()),port:i.readUInt16BE()},n.host==="0.0.0.0"&&(n.host=this.options.proxy.ipaddress)}else if(r===U.Socks5HostType.Hostname){let a=e[4],s=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(a);if(this.receiveBuffer.length<s){this.nextRequiredPacketBufferSize=s;return}i=Dr.SmartBuffer.fromBuffer(this.receiveBuffer.get(s).slice(5)),n={host:i.readString(a),port:i.readUInt16BE()}}else if(r===U.Socks5HostType.IPv6){let a=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<a){this.nextRequiredPacketBufferSize=a;return}i=Dr.SmartBuffer.fromBuffer(this.receiveBuffer.get(a).slice(4)),n={host:SC.Address6.fromByteArray(Array.from(i.readBuffer(16))).canonicalForm(),port:i.readUInt16BE()}}this.setState(U.SocksClientState.ReceivedFinalResponse),U.SocksCommand[this.options.command]===U.SocksCommand.connect?(this.setState(U.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:n,socket:this.socket})):U.SocksCommand[this.options.command]===U.SocksCommand.bind?(this.setState(U.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost:n,socket:this.socket})):U.SocksCommand[this.options.command]===U.SocksCommand.associate&&(this.setState(U.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:n,socket:this.socket}))}}handleSocks5IncomingConnectionResponse(){let e=this.receiveBuffer.peek(5);if(e[0]!==5||e[1]!==U.Socks5Response.Granted)this.closeSocket(`${U.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${U.Socks5Response[e[1]]}`);else{let r=e[3],n,i;if(r===U.Socks5HostType.IPv4){let a=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<a){this.nextRequiredPacketBufferSize=a;return}i=Dr.SmartBuffer.fromBuffer(this.receiveBuffer.get(a).slice(4)),n={host:(0,Fr.int32ToIpv4)(i.readUInt32BE()),port:i.readUInt16BE()},n.host==="0.0.0.0"&&(n.host=this.options.proxy.ipaddress)}else if(r===U.Socks5HostType.Hostname){let a=e[4],s=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(a);if(this.receiveBuffer.length<s){this.nextRequiredPacketBufferSize=s;return}i=Dr.SmartBuffer.fromBuffer(this.receiveBuffer.get(s).slice(5)),n={host:i.readString(a),port:i.readUInt16BE()}}else if(r===U.Socks5HostType.IPv6){let a=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<a){this.nextRequiredPacketBufferSize=a;return}i=Dr.SmartBuffer.fromBuffer(this.receiveBuffer.get(a).slice(4)),n={host:SC.Address6.fromByteArray(Array.from(i.readBuffer(16))).canonicalForm(),port:i.readUInt16BE()}}this.setState(U.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:n,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}};Ia.SocksClient=vC});var SW=p(Ys=>{"use strict";var gTe=Ys&&Ys.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),ETe=Ys&&Ys.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&gTe(e,t,r)};Object.defineProperty(Ys,"__esModule",{value:!0});ETe(EW(),Ys)});var CC=p(In=>{"use strict";var STe=In&&In.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),bTe=In&&In.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),vTe=In&&In.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&STe(r,e,n[i]);return bTe(r,e),r}})(),bW=In&&In.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(In,"__esModule",{value:!0});In.default=ITe;var yTe=bW(Tn()),TTe=require("stream"),CTe=SW(),ATe=vTe(require("dns")),RTe=require("util"),yC=bW(require("assert")),Gi=(0,yTe.default)("mqttjs:socks"),TC=class extends TTe.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1}),this.cork()}_start(e){if(Gi("proxy stream started"),(0,yC.default)(!this._socket),this.destroyed){e.destroy(this.errored);return}this._socket=e,this._flowing||e.pause(),e.on("data",this._onData),e.on("end",this._onEnd),e.on("error",this._onError),e.on("close",this._onClose),e.emit("connect"),this.uncork()}_write(e,r,n){(0,yC.default)(this._socket),this._socket.write(e,n)}_read(e){this._flowing=!0,this._socket?.resume?.()}_destroy(e,r){this._socket?.destroy?.(e),r(e)}_onData=e=>{(0,yC.default)(this._socket),this._flowing=this.push(e),this._flowing||this._socket.pause()};_onEnd=()=>{Gi("proxy stream received EOF"),this.push(null)};_onClose=()=>{Gi("proxy stream closed"),this.destroy()};_onError=e=>{Gi("proxy stream died with error %s",e),this.destroy(e)}};function $h(t){try{return t.code===void 0&&(t.code="SOCKS"),t}catch{return t}}function OTe(t){switch(t){case"socks5h:":return[5,!0];case"socks4a:":return[4,!0];case"socks5:":return[5,!1];case"socks4:":return[4,!1];default:return[void 0,!1]}}function NTe(t){let e=new URL(t);if(e.pathname||e.hash||e.search)throw $h(new Error("bad SOCKS URL"));let[r,n]=OTe(e.protocol);if(!r)throw $h(new Error("bad SOCKS URL: invalid protocol"));let i=parseInt(e.port,10);if(Number.isNaN(i))throw $h(new Error("bad SOCKS URL: invalid port"));return[{host:e.hostname,port:i,type:r},n]}async function wTe(t,e,r,n,i={}){let a=i.lookup??(0,RTe.promisify)(ATe.lookup),[s,o]=NTe(r);o||(Gi("resolving %s locally",t),t=(await a(t,{family:s.type===4?4:0})).address),Gi("establishing SOCKS%d connection to %s:%d via %s:%d",s.type,t,e,s.host,s.port);let l=new CTe.SocksClient({command:"connect",destination:{host:t,port:e},proxy:{...s},timeout:i.timeout});l.connect(),l.on("established",({socket:c})=>n._start(c)),l.on("error",c=>{Gi("SOCKS failed: %s",c),n.destroy($h(c))})}function ITe(t,e,r,n){Gi("SOCKS connection to %s:%d via %s",t,e,r);let i=new TC;return wTe(t,e,r,i,n).catch(a=>{Gi("SOCKS failed: %s",a),i.destroy(a)}),i}});var RC=p(jc=>{"use strict";var AC=jc&&jc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(jc,"__esModule",{value:!0});var DTe=AC(require("net")),xTe=AC(Tn()),MTe=AC(CC()),LTe=(0,xTe.default)("mqttjs:tcp"),PTe=(t,e)=>{if(e.port=e.port||1883,e.hostname=e.hostname||e.host||"localhost",e.socksProxy)return(0,MTe.default)(e.hostname,e.port,e.socksProxy,{timeout:e.socksTimeout});let{port:r,path:n}=e,i=e.hostname;return LTe("port %d and host %s",r,i),DTe.default.createConnection({port:r,host:i,path:n})};jc.default=PTe});var NC=p(Xc=>{"use strict";var OC=Xc&&Xc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Xc,"__esModule",{value:!0});var vW=require("tls"),kTe=OC(require("net")),BTe=OC(Tn()),FTe=OC(CC()),UTe=(0,BTe.default)("mqttjs:tls");function qTe(t){let{host:e,port:r,socksProxy:n,...i}=t;if(n!==void 0){let a=(0,FTe.default)(e,r,n,{timeout:t.socksTimeout});return(0,vW.connect)({...i,socket:a})}return(0,vW.connect)(t)}var GTe=(t,e)=>{e.port=e.port||8883,e.host=e.hostname||e.host||"localhost",kTe.default.isIP(e.host)===0&&(e.servername=e.host),e.rejectUnauthorized=e.rejectUnauthorized!==!1,delete e.path,UTe("port %d host %s rejectUnauthorized %b",e.port,e.host,e.rejectUnauthorized);let r=qTe(e);r.on("secureConnect",()=>{e.rejectUnauthorized&&!r.authorized?r.emit("error",new Error("TLS not authorized")):r.removeListener("error",n)});function n(i){e.rejectUnauthorized&&t.emit("error",i),r.end()}return r.on("error",n),r};Xc.default=GTe});var DC=p(IC=>{"use strict";Object.defineProperty(IC,"__esModule",{value:!0});var yW=require("buffer"),YTe=Sa(),HTe=kh(),ai,wC,Ur;function VTe(){let t=new YTe.Transform;return t._write=(e,r,n)=>{ai.send({data:e.buffer,success(){n()},fail(i){n(new Error(i))}})},t._flush=e=>{ai.close({success(){e()}})},t}function WTe(t){t.hostname||(t.hostname="localhost"),t.path||(t.path="/"),t.wsOptions||(t.wsOptions={})}function zTe(t,e){let r=t.protocol==="wxs"?"wss":"ws",n=`${r}://${t.hostname}${t.path}`;return t.port&&t.port!==80&&t.port!==443&&(n=`${r}://${t.hostname}:${t.port}${t.path}`),typeof t.transformWsUrl=="function"&&(n=t.transformWsUrl(n,t,e)),n}function $Te(){ai.onOpen(()=>{Ur.socketReady()}),ai.onMessage(t=>{let{data:e}=t;e instanceof ArrayBuffer?e=yW.Buffer.from(e):e=yW.Buffer.from(e,"utf8"),wC.push(e)}),ai.onClose(()=>{Ur.emit("close"),Ur.end(),Ur.destroy()}),ai.onError(t=>{let e=new Error(t.errMsg);Ur.destroy(e)})}var KTe=(t,e)=>{if(e.hostname=e.hostname||e.host,!e.hostname)throw new Error("Could not determine host. Specify host manually.");let r=e.protocolId==="MQIsdp"&&e.protocolVersion===3?"mqttv3.1":"mqtt";WTe(e);let n=zTe(e,t);ai=wx.connectSocket({url:n,protocols:[r]}),wC=VTe(),Ur=new HTe.BufferedDuplex(e,wC,ai),Ur._destroy=(a,s)=>{ai.close({success(){s&&s(a)}})};let i=Ur.destroy;return Ur.destroy=(a,s)=>(Ur.destroy=i,setTimeout(()=>{ai.close({fail(){Ur._destroy(a,s)}})},0),Ur),$Te(),Ur};IC.default=KTe});var LC=p(MC=>{"use strict";Object.defineProperty(MC,"__esModule",{value:!0});var xC=require("buffer"),QTe=Sa(),jTe=kh(),Yi,Zc,Al,TW=!1;function XTe(){let t=new QTe.Transform;return t._write=(e,r,n)=>{Yi.sendSocketMessage({data:e.buffer,success(){n()},fail(){n(new Error)}})},t._flush=e=>{Yi.closeSocket({success(){e()}})},t}function ZTe(t){t.hostname||(t.hostname="localhost"),t.path||(t.path="/"),t.wsOptions||(t.wsOptions={})}function JTe(t,e){let r=t.protocol==="alis"?"wss":"ws",n=`${r}://${t.hostname}${t.path}`;return t.port&&t.port!==80&&t.port!==443&&(n=`${r}://${t.hostname}:${t.port}${t.path}`),typeof t.transformWsUrl=="function"&&(n=t.transformWsUrl(n,t,e)),n}function eCe(){TW||(TW=!0,Yi.onSocketOpen(()=>{Al.socketReady()}),Yi.onSocketMessage(t=>{if(typeof t.data=="string"){let e=xC.Buffer.from(t.data,"base64");Zc.push(e)}else{let e=new FileReader;e.addEventListener("load",()=>{if(e.result instanceof ArrayBuffer){Zc.push(xC.Buffer.from(e.result));return}Zc.push(xC.Buffer.from(e.result,"utf-8"))}),e.readAsArrayBuffer(t.data)}}),Yi.onSocketClose(()=>{Al.end(),Al.destroy()}),Yi.onSocketError(t=>{Al.destroy(t)}))}var tCe=(t,e)=>{if(e.hostname=e.hostname||e.host,!e.hostname)throw new Error("Could not determine host. Specify host manually.");let r=e.protocolId==="MQIsdp"&&e.protocolVersion===3?"mqttv3.1":"mqtt";ZTe(e);let n=JTe(e,t);return Yi=e.my,Yi.connectSocket({url:n,protocols:r}),Zc=XTe(),Al=new jTe.BufferedDuplex(e,Zc,Yi),eCe(),Al};MC.default=tCe});var OW=p(Rl=>{"use strict";var Kh=Rl&&Rl.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Rl,"__esModule",{value:!0});Rl.connectAsync=sCe;var rCe=Kh(Tn()),nCe=Kh(require("url")),iCe=Kh(yh()),CW=Kh(kc());typeof process?.nextTick!="function"&&(process.nextTick=setImmediate);var AW=(0,rCe.default)("mqttjs"),Vt=null;function aCe(t){let e;if(t.auth)if(e=t.auth.match(/^(.+):(.+)$/),e){let[,r,n]=e;t.username=r,t.password=n}else t.username=t.auth}function RW(t,e){if(AW("connecting to an MQTT broker..."),typeof t=="object"&&!e&&(e=t,t=""),e=e||{},t&&typeof t=="string"){let i=nCe.default.parse(t,!0),a={};if(i.port!=null&&(a.port=Number(i.port)),a.host=i.hostname,a.query=i.query,a.auth=i.auth,a.protocol=i.protocol,a.path=i.path,e={...a,...e},!e.protocol)throw new Error("Missing protocol");e.protocol=e.protocol.replace(/:$/,"")}if(e.unixSocket=e.unixSocket||e.protocol?.includes("+unix"),e.unixSocket?e.protocol=e.protocol.replace("+unix",""):!e.protocol?.startsWith("ws")&&!e.protocol?.startsWith("wx")&&delete e.path,aCe(e),e.query&&typeof e.query.clientId=="string"&&(e.clientId=e.query.clientId),CW.default||e.unixSocket?e.socksProxy=void 0:e.socksProxy===void 0&&typeof process<"u"&&(e.socksProxy=process.env.MQTTJS_SOCKS_PROXY),e.cert&&e.key)if(e.protocol){if(["mqtts","wss","wxs","alis"].indexOf(e.protocol)===-1)switch(e.protocol){case"mqtt":e.protocol="mqtts";break;case"ws":e.protocol="wss";break;case"wx":e.protocol="wxs";break;case"ali":e.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${e.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(Vt||(Vt={},!CW.default&&!e.forceNativeWebSocket?(Vt.ws=Kc().streamBuilder,Vt.wss=Kc().streamBuilder,Vt.mqtt=RC().default,Vt.tcp=RC().default,Vt.ssl=NC().default,Vt.tls=Vt.ssl,Vt.mqtts=NC().default):(Vt.ws=Kc().browserStreamBuilder,Vt.wss=Kc().browserStreamBuilder,Vt.wx=DC().default,Vt.wxs=DC().default,Vt.ali=LC().default,Vt.alis=LC().default)),!Vt[e.protocol]){let i=["mqtts","wss"].indexOf(e.protocol)!==-1;e.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((a,s)=>i&&s%2===0?!1:typeof Vt[a]=="function")[0]}if(e.clean===!1&&!e.clientId)throw new Error("Missing clientId for unclean clients");e.protocol&&(e.defaultProtocol=e.protocol);function r(i){return e.servers&&((!i._reconnectCount||i._reconnectCount===e.servers.length)&&(i._reconnectCount=0),e.host=e.servers[i._reconnectCount].host,e.port=e.servers[i._reconnectCount].port,e.protocol=e.servers[i._reconnectCount].protocol?e.servers[i._reconnectCount].protocol:e.defaultProtocol,e.hostname=e.host,i._reconnectCount++),AW("calling streambuilder for",e.protocol),Vt[e.protocol](i,e)}let n=new iCe.default(r,e);return n.on("error",()=>{}),n}function sCe(t,e,r=!0){return new Promise((n,i)=>{let a=RW(t,e),s={connect:l=>{o(),n(a)},end:()=>{o(),n(a)},error:l=>{o(),a.end(),i(l)}};r===!1&&(s.close=()=>{s.error(new Error("Couldn't connect to server"))});function o(){Object.keys(s).forEach(l=>{a.off(l,s[l])})}Object.keys(s).forEach(l=>{a.on(l,s[l])})})}Rl.default=RW});var PC=p(He=>{"use strict";var NW=He&&He.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),oCe=He&&He.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),lCe=He&&He.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&NW(r,e,n[i]);return oCe(r,e),r}})(),wW=He&&He.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&NW(e,t,r)},Jc=He&&He.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(He,"__esModule",{value:!0});He.ReasonCodes=He.KeepaliveManager=He.UniqueMessageIdProvider=He.DefaultMessageIdProvider=He.Store=He.MqttClient=He.connectAsync=He.connect=He.Client=void 0;var IW=Jc(yh());He.MqttClient=IW.default;var uCe=Jc(dT());He.DefaultMessageIdProvider=uCe.default;var cCe=Jc(xV());He.UniqueMessageIdProvider=cCe.default;var dCe=Jc(Cy());He.Store=dCe.default;var DW=lCe(OW());He.connect=DW.default;Object.defineProperty(He,"connectAsync",{enumerable:!0,get:function(){return DW.connectAsync}});var fCe=Jc(RT());He.KeepaliveManager=fCe.default;He.Client=IW.default;wW(yh(),He);wW(As(),He);var _Ce=pc();Object.defineProperty(He,"ReasonCodes",{enumerable:!0,get:function(){return _Ce.ReasonCodes}})});var MW=p(an=>{"use strict";var xW=an&&an.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),pCe=an&&an.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),hCe=an&&an.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&xW(r,e,n[i]);return pCe(r,e),r}})(),mCe=an&&an.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&xW(e,t,r)};Object.defineProperty(an,"__esModule",{value:!0});var gCe=hCe(PC());an.default=gCe;mCe(PC(),an)});var SCe={};UK(SCe,{ConnectorRunnerMqtt:()=>kC});module.exports=qK(SCe);var kl=Zs(require("node:process")),Rd=class{#e="connector-runtime";#r;constructor(e,r){this.#r=r,kl.default.on?kl.default.on("message",n=>{n.cmd===this.#e&&r.logger.verbose(`${kl.default.pid} Received message from parent process:`,n)}):r.logger.warn("IPC channel is not available. process.on is undefined."),kl.default.send||r.logger.warn("IPC channel is not available. process.send is undefined."),e.actions?.forEach(n=>{if(n.config.templates===void 0)return;let i={};Object.entries(n.config.templates).forEach(([a,s])=>{try{i[a]=r.templating.compile(s)}catch(o){r.logger.error(`Error compiling template ${a} for action ${n.identifier}`,o)}}),n.config.parsedTemplates=i})}init=()=>Promise.resolve();start=()=>Promise.resolve();stop=()=>Promise.resolve();set callbackFunction(e){this.connectorSDK.receiver.registerCallback(this.#o(e))}get connectorSDK(){return this.#r}#o(e){return async r=>{let n=await this.#r.receiver.getActionConfig(r);return n?e(r,n):this.#r.receiver.responses.badRequest("Action not found")(r)}}};var Qh=Zs(cf()),kW=Zs(n3());var En=Zs(require("node:process")),Er=Zs(m4()),g4=(a=>(a.error="error",a.warn="warn",a.info="info",a.http="http",a.debug="debug",a))(g4||{}),ap=class t{static instance;logger;#e;constructor(e="default",r="info"){this.logger=Er.default.createLogger({level:r,format:Er.default.format.combine(Er.default.format.label({label:e}),Er.default.format.timestamp(),Er.default.format.json(),Er.default.format.errors({stack:!0}))});let n=!1;(En.default.env.NODE_ENV!=="production"||En.default.env.LOG_TO_CONSOLE==="true")&&(n=!0,this.logger.add(new Er.default.transports.Console({format:Er.default.format.printf(({label:i,level:a,message:s})=>{let o=new Date().toLocaleString();return`[${i}] ${En.default.pid} - ${o} ${a}: ${s}`})}))),En.default.env.LOG_TO_FILE==="true"&&(n=!0,this.logger.add(new Er.default.transports.File({filename:"error.log",level:"error"})),this.logger.add(new Er.default.transports.File({filename:"combined.log"}))),n||this.logger.add(new Er.default.transports.Console({format:Er.default.format.printf(({label:i,level:a,message:s})=>`[${i}] ${a}: ${s}`)}))}static getInstance(e,r){return t.instance||(t.instance=new t(e??"default",t.#o(r))),t.instance}setDatadogTransport(e){let r=e?.apiKey??En.default.env.DATADOG_API_KEY;if(!r)return this.debug("DATADOG_API_KEY is not set, cannot add Datadog transport"),this;let n=new URLSearchParams({"dd-api-key":r,ddsource:e?.source??En.default.env.DD_SOURCE??"nodejs",service:e?.service??En.default.env.DD_SERVICE??"unknown",env:e?.env??En.default.env.DD_ENV??"prod"});e?.tags&&n.append("ddtags",Object.entries(e.tags).map(([a,s])=>`${a}:${s}`).join(","));let i={host:`http-intake.logs.${En.default.env.DD_SITE??"datadoghq.eu"}`,path:`/api/v2/logs?${n.toString()}`,ssl:!0,batch:!0,format:Er.default.format.json(),level:"info"};return this.#e&&this.logger.remove(this.#e),this.#e=new Er.default.transports.Http(i),this.logger.add(this.#e),this}info(...e){this.#r(this.logger.info,...e)}static info(...e){this.getInstance().info(...e)}debug(...e){this.#r(this.logger.debug,...e)}static debug(...e){this.getInstance().debug(...e)}error(...e){this.#r(this.logger.error,...e)}static error(...e){this.getInstance().error(...e)}warn(...e){this.#r(this.logger.warn,...e)}static warn(...e){this.getInstance().warn(...e)}verbose(...e){this.#r(this.logger.verbose,...e)}static verbose(...e){this.getInstance().verbose(...e)}#r(e,...r){try{let n=r.map(i=>typeof i=="object"?JSON.stringify(i):String(i));e(n.join(" "),...r)}catch(n){console.error("unknown error in log, function",n)}}static#o=e=>{if(e!==void 0)return e;let r=En.default.env.LOG_LEVEL||"info",i=!Object.values(g4).includes(r);return i&&(r="info"),i&&console.error(`Invalid log level: ${r} only allow; 'error', 'warn', 'info', 'debug', 'trace'. Using info as default.`),r}};var PW=Zs(MW());function LW(t,e){let r=e.find(n=>n.topic===t);if(r)return r.collection;for(let n of e)if(ECe(t,n.topic))return n.collection}function ECe(t,e){if(t===e)return!0;let r=t.split("/"),n=e.split("/"),i=n.indexOf("#");if(i!==-1){if(i!==n.length-1)return!1;for(let a=0;a<i;a++)if(a>=r.length||n[a]!=="+"&&n[a]!==r[a])return!1;return!0}if(r.length!==n.length)return!1;for(let a=0;a<n.length;a++)if(n[a]!=="+"&&n[a]!==r[a])return!1;return!0}var ed=class{#e;#r;#o;#l;get brokerUrl(){return this.#e.brokerUrl}constructor(e,r){this.#l=ap.getInstance(),this.#e=e,this.#o=r,this.#r=(0,PW.connect)(this.#e.brokerUrl,{clientId:this.#e.clientId,username:this.#e.username,password:this.#e.password,rejectUnauthorized:!1}),this.#r.on("connect",()=>{this.#l.info("Connected to MQTT broker"),this.#e.topic&&this.#r?.subscribe(this.#e.topic),this.#e.topics&&this.#e.topics.forEach(n=>{this.#r?.subscribe(n.topic)})}),this.#r.on("error",n=>{this.#l.error("MQTT connection error:",n)}),this.#r.on("message",async(n,i)=>{let a=i.toString().replace(/\u0000+$/,"");this.#l.debug(`Received message from MQTT broker with topic ${n}: ${a.trim().replace(/\s+/g," ").slice(0,100)}`);let s;try{s=JSON.parse(a)}catch(l){this.#l.error(`Error parsing message ${a}:`,l),s={body:a}}let o=LW(n,this.#e.topics||[]);!o&&this.#e.topics&&this.#l.warn(`No corresponding collection found for topic ${n}. Using topic as collection.`),await this.#o.sender.metricsLegacy([s],{collection:o??n},{},o)})}async stop(){if(this.#r?.removeAllListeners(),this.#e.topic&&await this.#r?.unsubscribeAsync(this.#e.topic),this.#e.topics)for(let e of this.#e.topics)await this.#r?.unsubscribeAsync(e.topic);await this.#r?.endAsync()}async publish(e,r){this.#r?.publish(e,r)}};var kC=class extends Rd{CONNECTOR_INSTANCE="XOD_CONNECTOR_MQTT_SOURCE_CONFIG";#e;constructor(e,r){super(e,r),(0,kW.default)()}init=async()=>{let e=await this.connectorSDK.config;if(e.servers!==void 0){let n=e;this.#e=n.servers.map(i=>new ed(i,this.connectorSDK))}else{let n=e;this.#e=[new ed(n,this.connectorSDK)]}this.callbackFunction=this.callbackFunctionChain};#r(e){return async(r,n)=>{console.log(n.config);let i={};Object.keys(n.config).forEach(_=>{try{let d=n.config[_],m=Qh.default.compile(d);i[_]=m}catch(d){this.connectorSDK.logger.error(`Error compiling template ${_} for action ${n.identifier}`),d instanceof Qh.Exception&&this.connectorSDK.logger.error(d.message)}});let s=i.payload({inputs:r.payload}).trim(),o=i.topic({inputs:r.payload}).trim(),l=i.servers?JSON.parse(i.servers({inputs:r.payload}).trim()):void 0,c=l?this.#e?.filter(_=>l.includes(_.brokerUrl)):this.#e;if(!c||c.length===0){let _=`[MQTT] No MQTT client available for the specified servers: ${l?.join(", ")}`;return this.connectorSDK.logger.warn(_),this.connectorSDK.receiver.responses.badRequest(_)(r)}return c.forEach(_=>{_.publish(o,typeof s=="string"?s:JSON.stringify(s)),this.connectorSDK.logger.info(`Published message to MQTT broker ${_.brokerUrl} on topic ${o}`)}),e(r)}}get callbackFunctionChain(){return this.#r(this.connectorSDK.receiver.emitEventType(this.connectorSDK.receiver.responses.ok()))}stop=async()=>{this.#e?.forEach(e=>e.stop())}};0&&(module.exports={ConnectorRunnerMqtt});
133
+ `+r)}function Bs(t,e,r,n,i,a){if(t.listenerCount("wsClientError")){let s=new Error(i);Error.captureStackTrace(s,Bs),t.emit("wsClientError",s,r,e)}else zc(r,n,i,a)}});var F7=p((uLe,B7)=>{"use strict";var Fi=Lh();Fi.createWebSocketStream=O7();Fi.Server=k7();Fi.Receiver=YT();Fi.Sender=WT();Fi.WebSocket=Fi;Fi.WebSocketServer=Fi.Server;B7.exports=Fi});var kh=p($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.BufferedDuplex=void 0;$c.writev=q7;var fye=Sa(),U7=require("buffer");function q7(t,e){let r=new Array(t.length);for(let n=0;n<t.length;n++)typeof t[n].chunk=="string"?r[n]=U7.Buffer.from(t[n].chunk,"utf8"):r[n]=t[n].chunk;this._write(U7.Buffer.concat(r),"binary",e)}var JT=class extends fye.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(e,r,n){super({objectMode:!0}),this.proxy=r,this.socket=n,this.writeQueue=[],e.objectMode||(this._writev=q7.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",i=>{!this.destroyed&&this.readable&&this.push(i)})}_read(e){this.proxy.read(e)}_write(e,r,n){this.isSocketOpen?this.writeToProxy(e,r,n):this.writeQueue.push({chunk:e,encoding:r,cb:n})}_final(e){this.writeQueue=[],this.proxy.end(e)}_destroy(e,r){this.writeQueue=[],this.proxy.destroy(),r(e)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(e,r,n){this.proxy.write(e,r)===!1?this.proxy.once("drain",n):n()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:e,encoding:r,cb:n}=this.writeQueue.shift();this.writeToProxy(e,r,n)}}};$c.BufferedDuplex=JT});var Kc=p(wa=>{"use strict";var tC=wa&&wa.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(wa,"__esModule",{value:!0});wa.streamBuilder=wa.browserStreamBuilder=void 0;var Bh=require("buffer"),G7=tC(F7()),_ye=tC(Tn()),pye=Sa(),hye=tC(kc()),eC=kh(),Na=(0,_ye.default)("mqttjs:ws"),mye=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function Y7(t,e){let r=`${t.protocol}://${t.hostname}:${t.port}${t.path}`;return typeof t.transformWsUrl=="function"&&(r=t.transformWsUrl(r,t,e)),r}function H7(t){let e=t;return t.port||(t.protocol==="wss"?e.port=443:e.port=80),t.path||(e.path="/"),t.wsOptions||(e.wsOptions={}),!hye.default&&!t.forceNativeWebSocket&&t.protocol==="wss"&&mye.forEach(r=>{Object.prototype.hasOwnProperty.call(t,r)&&!Object.prototype.hasOwnProperty.call(t.wsOptions,r)&&(e.wsOptions[r]=t[r])}),e}function gye(t){let e=H7(t);if(e.hostname||(e.hostname=e.host),!e.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let r=new URL(document.URL);e.hostname=r.hostname,e.port||(e.port=Number(r.port))}return e.objectMode===void 0&&(e.objectMode=!(e.binary===!0||e.binary===void 0)),e}function Eye(t,e,r){Na("createWebSocket"),Na(`protocol: ${r.protocolId} ${r.protocolVersion}`);let n=r.protocolId==="MQIsdp"&&r.protocolVersion===3?"mqttv3.1":"mqtt";Na(`creating new Websocket for url: ${e} and protocol: ${n}`);let i;return r.createWebsocket?i=r.createWebsocket(e,[n],r):i=new G7.default(e,[n],r.wsOptions),i}function Sye(t,e){let r=e.protocolId==="MQIsdp"&&e.protocolVersion===3?"mqttv3.1":"mqtt",n=Y7(e,t),i;return e.createWebsocket?i=e.createWebsocket(n,[r],e):i=new WebSocket(n,[r]),i.binaryType="arraybuffer",i}var bye=(t,e)=>{Na("streamBuilder");let r=H7(e);r.hostname=r.hostname||r.host||"localhost";let n=Y7(r,t),i=Eye(t,n,r),a=G7.default.createWebSocketStream(i,r.wsOptions);return a.url=n,i.on("close",()=>{a.destroy()}),a};wa.streamBuilder=bye;var vye=(t,e)=>{Na("browserStreamBuilder");let r,i=gye(e).browserBufferSize||1024*512,a=e.browserBufferTimeout||1e3,s=!e.objectMode,o=Sye(t,e),l=_(e,b,T);e.objectMode||(l._writev=eC.writev.bind(l)),l.on("close",()=>{o.close()});let c=typeof o.addEventListener<"u";o.readyState===o.OPEN?(r=l,r.socket=o):(r=new eC.BufferedDuplex(e,l,o),c?o.addEventListener("open",d):o.onopen=d),c?(o.addEventListener("close",m),o.addEventListener("error",S),o.addEventListener("message",E)):(o.onclose=m,o.onerror=S,o.onmessage=E);function _(y,C,O){let A=new pye.Transform({objectMode:y.objectMode});return A._write=C,A._flush=O,A}function d(){Na("WebSocket onOpen"),r instanceof eC.BufferedDuplex&&r.socketReady()}function m(y){Na("WebSocket onClose",y),r.end(),r.destroy()}function S(y){Na("WebSocket onError",y);let C=new Error("WebSocket error");C.event=y,r.destroy(C)}async function E(y){if(!l||!l.readable||!l.writable)return;let{data:C}=y;C instanceof ArrayBuffer?C=Bh.Buffer.from(C):C instanceof Blob?C=Bh.Buffer.from(await new Response(C).arrayBuffer()):C=Bh.Buffer.from(C,"utf8"),l.push(C)}function b(y,C,O){if(o.bufferedAmount>i){setTimeout(b,a,y,C,O);return}s&&typeof y=="string"&&(y=Bh.Buffer.from(y,"utf8"));try{o.send(y)}catch(A){return O(A)}O()}function T(y){o.close(),y()}return r};wa.browserStreamBuilder=vye});var $7=p(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});var V7=require("buffer"),Fs={INVALID_ENCODING:"Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",INVALID_SMARTBUFFER_SIZE:"Invalid size provided. Size must be a valid integer greater than zero.",INVALID_SMARTBUFFER_BUFFER:"Invalid Buffer provided in SmartBufferOptions.",INVALID_SMARTBUFFER_OBJECT:"Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",INVALID_OFFSET:"An invalid offset value was provided.",INVALID_OFFSET_NON_NUMBER:"An invalid offset value was provided. A numeric value is required.",INVALID_LENGTH:"An invalid length value was provided.",INVALID_LENGTH_NON_NUMBER:"An invalid length value was provived. A numeric value is required.",INVALID_TARGET_OFFSET:"Target offset is beyond the bounds of the internal SmartBuffer data.",INVALID_TARGET_LENGTH:"Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",INVALID_READ_BEYOND_BOUNDS:"Attempted to read beyond the bounds of the managed data.",INVALID_WRITE_BEYOND_BOUNDS:"Attempted to write beyond the bounds of the managed data."};Ui.ERRORS=Fs;function yye(t){if(!V7.Buffer.isEncoding(t))throw new Error(Fs.INVALID_ENCODING)}Ui.checkEncoding=yye;function W7(t){return typeof t=="number"&&isFinite(t)&&Rye(t)}Ui.isFiniteInteger=W7;function z7(t,e){if(typeof t=="number"){if(!W7(t)||t<0)throw new Error(e?Fs.INVALID_OFFSET:Fs.INVALID_LENGTH)}else throw new Error(e?Fs.INVALID_OFFSET_NON_NUMBER:Fs.INVALID_LENGTH_NON_NUMBER)}function Tye(t){z7(t,!1)}Ui.checkLengthValue=Tye;function Cye(t){z7(t,!0)}Ui.checkOffsetValue=Cye;function Aye(t,e){if(t<0||t>e.length)throw new Error(Fs.INVALID_TARGET_OFFSET)}Ui.checkTargetOffset=Aye;function Rye(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t}function Oye(t){if(typeof BigInt>"u")throw new Error("Platform does not support JS BigInt type.");if(typeof V7.Buffer.prototype[t]>"u")throw new Error(`Platform does not support Buffer.prototype.${t}.`)}Ui.bigIntAndBufferInt64Check=Oye});var Q7=p(nC=>{"use strict";Object.defineProperty(nC,"__esModule",{value:!0});var Te=$7(),K7=4096,Nye="utf8",rC=class t{constructor(e){if(this.length=0,this._encoding=Nye,this._writeOffset=0,this._readOffset=0,t.isSmartBufferOptions(e))if(e.encoding&&(Te.checkEncoding(e.encoding),this._encoding=e.encoding),e.size)if(Te.isFiniteInteger(e.size)&&e.size>0)this._buff=Buffer.allocUnsafe(e.size);else throw new Error(Te.ERRORS.INVALID_SMARTBUFFER_SIZE);else if(e.buff)if(Buffer.isBuffer(e.buff))this._buff=e.buff,this.length=e.buff.length;else throw new Error(Te.ERRORS.INVALID_SMARTBUFFER_BUFFER);else this._buff=Buffer.allocUnsafe(K7);else{if(typeof e<"u")throw new Error(Te.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(K7)}}static fromSize(e,r){return new this({size:e,encoding:r})}static fromBuffer(e,r){return new this({buff:e,encoding:r})}static fromOptions(e){return new this(e)}static isSmartBufferOptions(e){let r=e;return r&&(r.encoding!==void 0||r.size!==void 0||r.buff!==void 0)}readInt8(e){return this._readNumberValue(Buffer.prototype.readInt8,1,e)}readInt16BE(e){return this._readNumberValue(Buffer.prototype.readInt16BE,2,e)}readInt16LE(e){return this._readNumberValue(Buffer.prototype.readInt16LE,2,e)}readInt32BE(e){return this._readNumberValue(Buffer.prototype.readInt32BE,4,e)}readInt32LE(e){return this._readNumberValue(Buffer.prototype.readInt32LE,4,e)}readBigInt64BE(e){return Te.bigIntAndBufferInt64Check("readBigInt64BE"),this._readNumberValue(Buffer.prototype.readBigInt64BE,8,e)}readBigInt64LE(e){return Te.bigIntAndBufferInt64Check("readBigInt64LE"),this._readNumberValue(Buffer.prototype.readBigInt64LE,8,e)}writeInt8(e,r){return this._writeNumberValue(Buffer.prototype.writeInt8,1,e,r),this}insertInt8(e,r){return this._insertNumberValue(Buffer.prototype.writeInt8,1,e,r)}writeInt16BE(e,r){return this._writeNumberValue(Buffer.prototype.writeInt16BE,2,e,r)}insertInt16BE(e,r){return this._insertNumberValue(Buffer.prototype.writeInt16BE,2,e,r)}writeInt16LE(e,r){return this._writeNumberValue(Buffer.prototype.writeInt16LE,2,e,r)}insertInt16LE(e,r){return this._insertNumberValue(Buffer.prototype.writeInt16LE,2,e,r)}writeInt32BE(e,r){return this._writeNumberValue(Buffer.prototype.writeInt32BE,4,e,r)}insertInt32BE(e,r){return this._insertNumberValue(Buffer.prototype.writeInt32BE,4,e,r)}writeInt32LE(e,r){return this._writeNumberValue(Buffer.prototype.writeInt32LE,4,e,r)}insertInt32LE(e,r){return this._insertNumberValue(Buffer.prototype.writeInt32LE,4,e,r)}writeBigInt64BE(e,r){return Te.bigIntAndBufferInt64Check("writeBigInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigInt64BE,8,e,r)}insertBigInt64BE(e,r){return Te.bigIntAndBufferInt64Check("writeBigInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigInt64BE,8,e,r)}writeBigInt64LE(e,r){return Te.bigIntAndBufferInt64Check("writeBigInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigInt64LE,8,e,r)}insertBigInt64LE(e,r){return Te.bigIntAndBufferInt64Check("writeBigInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigInt64LE,8,e,r)}readUInt8(e){return this._readNumberValue(Buffer.prototype.readUInt8,1,e)}readUInt16BE(e){return this._readNumberValue(Buffer.prototype.readUInt16BE,2,e)}readUInt16LE(e){return this._readNumberValue(Buffer.prototype.readUInt16LE,2,e)}readUInt32BE(e){return this._readNumberValue(Buffer.prototype.readUInt32BE,4,e)}readUInt32LE(e){return this._readNumberValue(Buffer.prototype.readUInt32LE,4,e)}readBigUInt64BE(e){return Te.bigIntAndBufferInt64Check("readBigUInt64BE"),this._readNumberValue(Buffer.prototype.readBigUInt64BE,8,e)}readBigUInt64LE(e){return Te.bigIntAndBufferInt64Check("readBigUInt64LE"),this._readNumberValue(Buffer.prototype.readBigUInt64LE,8,e)}writeUInt8(e,r){return this._writeNumberValue(Buffer.prototype.writeUInt8,1,e,r)}insertUInt8(e,r){return this._insertNumberValue(Buffer.prototype.writeUInt8,1,e,r)}writeUInt16BE(e,r){return this._writeNumberValue(Buffer.prototype.writeUInt16BE,2,e,r)}insertUInt16BE(e,r){return this._insertNumberValue(Buffer.prototype.writeUInt16BE,2,e,r)}writeUInt16LE(e,r){return this._writeNumberValue(Buffer.prototype.writeUInt16LE,2,e,r)}insertUInt16LE(e,r){return this._insertNumberValue(Buffer.prototype.writeUInt16LE,2,e,r)}writeUInt32BE(e,r){return this._writeNumberValue(Buffer.prototype.writeUInt32BE,4,e,r)}insertUInt32BE(e,r){return this._insertNumberValue(Buffer.prototype.writeUInt32BE,4,e,r)}writeUInt32LE(e,r){return this._writeNumberValue(Buffer.prototype.writeUInt32LE,4,e,r)}insertUInt32LE(e,r){return this._insertNumberValue(Buffer.prototype.writeUInt32LE,4,e,r)}writeBigUInt64BE(e,r){return Te.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64BE,8,e,r)}insertBigUInt64BE(e,r){return Te.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64BE,8,e,r)}writeBigUInt64LE(e,r){return Te.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64LE,8,e,r)}insertBigUInt64LE(e,r){return Te.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64LE,8,e,r)}readFloatBE(e){return this._readNumberValue(Buffer.prototype.readFloatBE,4,e)}readFloatLE(e){return this._readNumberValue(Buffer.prototype.readFloatLE,4,e)}writeFloatBE(e,r){return this._writeNumberValue(Buffer.prototype.writeFloatBE,4,e,r)}insertFloatBE(e,r){return this._insertNumberValue(Buffer.prototype.writeFloatBE,4,e,r)}writeFloatLE(e,r){return this._writeNumberValue(Buffer.prototype.writeFloatLE,4,e,r)}insertFloatLE(e,r){return this._insertNumberValue(Buffer.prototype.writeFloatLE,4,e,r)}readDoubleBE(e){return this._readNumberValue(Buffer.prototype.readDoubleBE,8,e)}readDoubleLE(e){return this._readNumberValue(Buffer.prototype.readDoubleLE,8,e)}writeDoubleBE(e,r){return this._writeNumberValue(Buffer.prototype.writeDoubleBE,8,e,r)}insertDoubleBE(e,r){return this._insertNumberValue(Buffer.prototype.writeDoubleBE,8,e,r)}writeDoubleLE(e,r){return this._writeNumberValue(Buffer.prototype.writeDoubleLE,8,e,r)}insertDoubleLE(e,r){return this._insertNumberValue(Buffer.prototype.writeDoubleLE,8,e,r)}readString(e,r){let n;typeof e=="number"?(Te.checkLengthValue(e),n=Math.min(e,this.length-this._readOffset)):(r=e,n=this.length-this._readOffset),typeof r<"u"&&Te.checkEncoding(r);let i=this._buff.slice(this._readOffset,this._readOffset+n).toString(r||this._encoding);return this._readOffset+=n,i}insertString(e,r,n){return Te.checkOffsetValue(r),this._handleString(e,!0,r,n)}writeString(e,r,n){return this._handleString(e,!1,r,n)}readStringNT(e){typeof e<"u"&&Te.checkEncoding(e);let r=this.length;for(let i=this._readOffset;i<this.length;i++)if(this._buff[i]===0){r=i;break}let n=this._buff.slice(this._readOffset,r);return this._readOffset=r+1,n.toString(e||this._encoding)}insertStringNT(e,r,n){return Te.checkOffsetValue(r),this.insertString(e,r,n),this.insertUInt8(0,r+e.length),this}writeStringNT(e,r,n){return this.writeString(e,r,n),this.writeUInt8(0,typeof r=="number"?r+e.length:this.writeOffset),this}readBuffer(e){typeof e<"u"&&Te.checkLengthValue(e);let r=typeof e=="number"?e:this.length,n=Math.min(this.length,this._readOffset+r),i=this._buff.slice(this._readOffset,n);return this._readOffset=n,i}insertBuffer(e,r){return Te.checkOffsetValue(r),this._handleBuffer(e,!0,r)}writeBuffer(e,r){return this._handleBuffer(e,!1,r)}readBufferNT(){let e=this.length;for(let n=this._readOffset;n<this.length;n++)if(this._buff[n]===0){e=n;break}let r=this._buff.slice(this._readOffset,e);return this._readOffset=e+1,r}insertBufferNT(e,r){return Te.checkOffsetValue(r),this.insertBuffer(e,r),this.insertUInt8(0,r+e.length),this}writeBufferNT(e,r){return typeof r<"u"&&Te.checkOffsetValue(r),this.writeBuffer(e,r),this.writeUInt8(0,typeof r=="number"?r+e.length:this._writeOffset),this}clear(){return this._writeOffset=0,this._readOffset=0,this.length=0,this}remaining(){return this.length-this._readOffset}get readOffset(){return this._readOffset}set readOffset(e){Te.checkOffsetValue(e),Te.checkTargetOffset(e,this),this._readOffset=e}get writeOffset(){return this._writeOffset}set writeOffset(e){Te.checkOffsetValue(e),Te.checkTargetOffset(e,this),this._writeOffset=e}get encoding(){return this._encoding}set encoding(e){Te.checkEncoding(e),this._encoding=e}get internalBuffer(){return this._buff}toBuffer(){return this._buff.slice(0,this.length)}toString(e){let r=typeof e=="string"?e:this._encoding;return Te.checkEncoding(r),this._buff.toString(r,0,this.length)}destroy(){return this.clear(),this}_handleString(e,r,n,i){let a=this._writeOffset,s=this._encoding;typeof n=="number"?a=n:typeof n=="string"&&(Te.checkEncoding(n),s=n),typeof i=="string"&&(Te.checkEncoding(i),s=i);let o=Buffer.byteLength(e,s);return r?this.ensureInsertable(o,a):this._ensureWriteable(o,a),this._buff.write(e,a,o,s),r?this._writeOffset+=o:typeof n=="number"?this._writeOffset=Math.max(this._writeOffset,a+o):this._writeOffset+=o,this}_handleBuffer(e,r,n){let i=typeof n=="number"?n:this._writeOffset;return r?this.ensureInsertable(e.length,i):this._ensureWriteable(e.length,i),e.copy(this._buff,i),r?this._writeOffset+=e.length:typeof n=="number"?this._writeOffset=Math.max(this._writeOffset,i+e.length):this._writeOffset+=e.length,this}ensureReadable(e,r){let n=this._readOffset;if(typeof r<"u"&&(Te.checkOffsetValue(r),n=r),n<0||n+e>this.length)throw new Error(Te.ERRORS.INVALID_READ_BEYOND_BOUNDS)}ensureInsertable(e,r){Te.checkOffsetValue(r),this._ensureCapacity(this.length+e),r<this.length&&this._buff.copy(this._buff,r+e,r,this._buff.length),r+e>this.length?this.length=r+e:this.length+=e}_ensureWriteable(e,r){let n=typeof r=="number"?r:this._writeOffset;this._ensureCapacity(n+e),n+e>this.length&&(this.length=n+e)}_ensureCapacity(e){let r=this._buff.length;if(e>r){let n=this._buff,i=r*3/2+1;i<e&&(i=e),this._buff=Buffer.allocUnsafe(i),n.copy(this._buff,0,0,r)}}_readNumberValue(e,r,n){this.ensureReadable(r,n);let i=e.call(this._buff,typeof n=="number"?n:this._readOffset);return typeof n>"u"&&(this._readOffset+=r),i}_insertNumberValue(e,r,n,i){return Te.checkOffsetValue(i),this.ensureInsertable(r,i),e.call(this._buff,n,i),this._writeOffset+=r,this}_writeNumberValue(e,r,n,i){if(typeof i=="number"){if(i<0)throw new Error(Te.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);Te.checkOffsetValue(i)}let a=typeof i=="number"?i:this._writeOffset;return this._ensureWriteable(r,a),e.call(this._buff,n,a),typeof i=="number"?this._writeOffset=Math.max(this._writeOffset,a+r):this._writeOffset+=r,this}};nC.SmartBuffer=rC});var iC=p(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.SOCKS5_NO_ACCEPTABLE_AUTH=it.SOCKS5_CUSTOM_AUTH_END=it.SOCKS5_CUSTOM_AUTH_START=it.SOCKS_INCOMING_PACKET_SIZES=it.SocksClientState=it.Socks5Response=it.Socks5HostType=it.Socks5Auth=it.Socks4Response=it.SocksCommand=it.ERRORS=it.DEFAULT_TIMEOUT=void 0;var wye=3e4;it.DEFAULT_TIMEOUT=wye;var Iye={InvalidSocksCommand:"An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",InvalidSocksCommandForOperation:"An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",InvalidSocksCommandChain:"An invalid SOCKS command was provided. Chaining currently only supports the connect command.",InvalidSocksClientOptionsDestination:"An invalid destination host was provided.",InvalidSocksClientOptionsExistingSocket:"An invalid existing socket was provided. This should be an instance of stream.Duplex.",InvalidSocksClientOptionsProxy:"Invalid SOCKS proxy details were provided.",InvalidSocksClientOptionsTimeout:"An invalid timeout value was provided. Please enter a value above 0 (in ms).",InvalidSocksClientOptionsProxiesLength:"At least two socks proxies must be provided for chaining.",InvalidSocksClientOptionsCustomAuthRange:"Custom auth must be a value between 0x80 and 0xFE.",InvalidSocksClientOptionsCustomAuthOptions:"When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",NegotiationError:"Negotiation error",SocketClosed:"Socket closed",ProxyConnectionTimedOut:"Proxy connection timed out",InternalError:"SocksClient internal error (this should not happen)",InvalidSocks4HandshakeResponse:"Received invalid Socks4 handshake response",Socks4ProxyRejectedConnection:"Socks4 Proxy rejected connection",InvalidSocks4IncomingConnectionResponse:"Socks4 invalid incoming connection response",Socks4ProxyRejectedIncomingBoundConnection:"Socks4 Proxy rejected incoming bound connection",InvalidSocks5InitialHandshakeResponse:"Received invalid Socks5 initial handshake response",InvalidSocks5IntiailHandshakeSocksVersion:"Received invalid Socks5 initial handshake (invalid socks version)",InvalidSocks5InitialHandshakeNoAcceptedAuthType:"Received invalid Socks5 initial handshake (no accepted authentication type)",InvalidSocks5InitialHandshakeUnknownAuthType:"Received invalid Socks5 initial handshake (unknown authentication type)",Socks5AuthenticationFailed:"Socks5 Authentication failed",InvalidSocks5FinalHandshake:"Received invalid Socks5 final handshake response",InvalidSocks5FinalHandshakeRejected:"Socks5 proxy rejected connection",InvalidSocks5IncomingConnectionResponse:"Received invalid Socks5 incoming connection response",Socks5ProxyRejectedIncomingBoundConnection:"Socks5 Proxy rejected incoming bound connection"};it.ERRORS=Iye;var Dye={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:t=>t+7,Socks4Response:8};it.SOCKS_INCOMING_PACKET_SIZES=Dye;var j7;(function(t){t[t.connect=1]="connect",t[t.bind=2]="bind",t[t.associate=3]="associate"})(j7||(it.SocksCommand=j7={}));var X7;(function(t){t[t.Granted=90]="Granted",t[t.Failed=91]="Failed",t[t.Rejected=92]="Rejected",t[t.RejectedIdent=93]="RejectedIdent"})(X7||(it.Socks4Response=X7={}));var Z7;(function(t){t[t.NoAuth=0]="NoAuth",t[t.GSSApi=1]="GSSApi",t[t.UserPass=2]="UserPass"})(Z7||(it.Socks5Auth=Z7={}));var xye=128;it.SOCKS5_CUSTOM_AUTH_START=xye;var Mye=254;it.SOCKS5_CUSTOM_AUTH_END=Mye;var Lye=255;it.SOCKS5_NO_ACCEPTABLE_AUTH=Lye;var J7;(function(t){t[t.Granted=0]="Granted",t[t.Failure=1]="Failure",t[t.NotAllowed=2]="NotAllowed",t[t.NetworkUnreachable=3]="NetworkUnreachable",t[t.HostUnreachable=4]="HostUnreachable",t[t.ConnectionRefused=5]="ConnectionRefused",t[t.TTLExpired=6]="TTLExpired",t[t.CommandNotSupported=7]="CommandNotSupported",t[t.AddressNotSupported=8]="AddressNotSupported"})(J7||(it.Socks5Response=J7={}));var eW;(function(t){t[t.IPv4=1]="IPv4",t[t.Hostname=3]="Hostname",t[t.IPv6=4]="IPv6"})(eW||(it.Socks5HostType=eW={}));var tW;(function(t){t[t.Created=0]="Created",t[t.Connecting=1]="Connecting",t[t.Connected=2]="Connected",t[t.SentInitialHandshake=3]="SentInitialHandshake",t[t.ReceivedInitialHandshakeResponse=4]="ReceivedInitialHandshakeResponse",t[t.SentAuthentication=5]="SentAuthentication",t[t.ReceivedAuthenticationResponse=6]="ReceivedAuthenticationResponse",t[t.SentFinalHandshake=7]="SentFinalHandshake",t[t.ReceivedFinalResponse=8]="ReceivedFinalResponse",t[t.BoundWaitingForConnection=9]="BoundWaitingForConnection",t[t.Established=10]="Established",t[t.Disconnected=11]="Disconnected",t[t.Error=99]="Error"})(tW||(it.SocksClientState=tW={}))});var sC=p(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});bl.shuffleArray=bl.SocksClientError=void 0;var aC=class extends Error{constructor(e,r){super(e),this.options=r}};bl.SocksClientError=aC;function Pye(t){for(let e=t.length-1;e>0;e--){let r=Math.floor(Math.random()*(e+1));[t[e],t[r]]=[t[r],t[e]]}}bl.shuffleArray=Pye});var Fh=p(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.isInSubnet=kye;Us.isCorrect=Bye;Us.numberToPaddedHex=rW;Us.stringToPaddedHex=Fye;Us.testBit=Uye;function kye(t){return this.subnetMask<t.subnetMask?!1:this.mask(t.subnetMask)===t.mask()}function Bye(t){return function(){return this.addressMinusSuffix!==this.correctForm()?!1:this.subnetMask===t&&!this.parsedSubnet?!0:this.parsedSubnet===String(this.subnetMask)}}function rW(t){return t.toString(16).padStart(2,"0")}function Fye(t){return rW(parseInt(t,10))}function Uye(t,e){let{length:r}=t;if(e>r)return!1;let n=r-e;return t.substring(n,n+1)==="1"}});var oC=p(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.RE_SUBNET_STRING=ri.RE_ADDRESS=ri.GROUPS=ri.BITS=void 0;ri.BITS=32;ri.GROUPS=4;ri.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;ri.RE_SUBNET_STRING=/\/\d{1,2}$/});var qh=p(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});Uh.AddressError=void 0;var lC=class extends Error{constructor(e,r){super(e),this.name="AddressError",this.parseMessage=r}};Uh.AddressError=lC});var cC=p(ni=>{"use strict";var qye=ni&&ni.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Gye=ni&&ni.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),nW=ni&&ni.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&qye(e,t,r);return Gye(e,t),e};Object.defineProperty(ni,"__esModule",{value:!0});ni.Address4=void 0;var vl=nW(Fh()),wn=nW(oC()),Qc=qh(),uC=class t{constructor(e){this.groups=wn.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=vl.isCorrect(wn.BITS),this.isInSubnet=vl.isInSubnet,this.address=e;let r=wn.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>wn.BITS)throw new Qc.AddressError("Invalid subnet mask.");e=e.replace(wn.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new t(e),!0}catch{return!1}}parse(e){let r=e.split(".");if(!e.match(wn.RE_ADDRESS))throw new Qc.AddressError("Invalid IPv4 address.");return r}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromHex(e){let r=e.replace(/:/g,"").padStart(8,"0"),n=[],i;for(i=0;i<8;i+=2){let a=r.slice(i,i+2);n.push(parseInt(a,16))}return new t(n.join("."))}static fromInteger(e){return t.fromHex(e.toString(16))}static fromArpa(e){let n=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new t(n)}toHex(){return this.parsedAddress.map(e=>vl.stringToPaddedHex(e)).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],r;for(r=0;r<wn.GROUPS;r+=2)e.push(`${vl.stringToPaddedHex(this.parsedAddress[r])}${vl.stringToPaddedHex(this.parsedAddress[r+1])}`);return e.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>vl.stringToPaddedHex(e)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(wn.BITS-this.subnetMask)}`)}startAddress(){return t.fromBigInt(this._startAddress())}startAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(wn.BITS-this.subnetMask)}`)}endAddress(){return t.fromBigInt(this._endAddress())}endAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._endAddress()-e)}static fromBigInt(e){return t.fromHex(e.toString(16))}static fromByteArray(e){if(e.length!==4)throw new Qc.AddressError("IPv4 addresses require exactly 4 bytes");for(let r=0;r<e.length;r++)if(!Number.isInteger(e[r])||e[r]<0||e[r]>255)throw new Qc.AddressError("All bytes must be integers between 0 and 255");return this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(e){if(e.length!==4)throw new Qc.AddressError("IPv4 addresses require exactly 4 bytes");let r=e.join(".");return new t(r)}mask(e){return e===void 0&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,r){return this.binaryZeroPad().slice(e,r)}reverseForm(e){e||(e={});let r=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?r:`${r}.in-addr.arpa.`}isMulticast(){return this.isInSubnet(new t("224.0.0.0/4"))}binaryZeroPad(){return this.bigInt().toString(2).padStart(wn.BITS,"0")}groupForV6(){let e=this.parsedAddress;return this.address.replace(wn.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(".")}</span>`)}};ni.Address4=uC});var dC=p(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.RE_URL_WITH_PORT=Nt.RE_URL=Nt.RE_ZONE_STRING=Nt.RE_SUBNET_STRING=Nt.RE_BAD_ADDRESS=Nt.RE_BAD_CHARACTERS=Nt.TYPES=Nt.SCOPES=Nt.GROUPS=Nt.BITS=void 0;Nt.BITS=128;Nt.GROUPS=8;Nt.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};Nt.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"};Nt.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;Nt.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;Nt.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;Nt.RE_ZONE_STRING=/%.*$/;Nt.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/;Nt.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/});var fC=p(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});yl.spanAllZeroes=iW;yl.spanAll=Yye;yl.spanLeadingZeroes=Hye;yl.simpleGroup=Vye;function iW(t){return t.replace(/(0+)/g,'<span class="zero">$1</span>')}function Yye(t,e=0){return t.split("").map((n,i)=>`<span class="digit value-${n} position-${i+e}">${iW(n)}</span>`).join("")}function aW(t){return t.replace(/^(0+)/,'<span class="zero">$1</span>')}function Hye(t){return t.split(":").map(r=>aW(r)).join(":")}function Vye(t,e=0){return t.split(":").map((n,i)=>/group-v4/.test(n)?n:`<span class="hover-group group-${i+e}">${aW(n)}</span>`)}});var sW=p(Ir=>{"use strict";var Wye=Ir&&Ir.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),zye=Ir&&Ir.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),$ye=Ir&&Ir.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Wye(e,t,r);return zye(e,t),e};Object.defineProperty(Ir,"__esModule",{value:!0});Ir.ADDRESS_BOUNDARY=void 0;Ir.groupPossibilities=Yh;Ir.padGroup=Gh;Ir.simpleRegularExpression=Qye;Ir.possibleElisions=jye;var Kye=$ye(dC());function Yh(t){return`(${t.join("|")})`}function Gh(t){return t.length<4?`0{0,${4-t.length}}${t}`:t}Ir.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function Qye(t){let e=[];t.forEach((n,i)=>{parseInt(n,16)===0&&e.push(i)});let r=e.map(n=>t.map((i,a)=>{if(a===n){let s=a===0||a===Kye.GROUPS-1?":":"";return Yh([Gh(i),s])}return Gh(i)}).join(":"));return r.push(t.map(Gh).join(":")),Yh(r)}function jye(t,e,r){let n=e?"":":",i=r?"":":",a=[];!e&&!r&&a.push("::"),e&&r&&a.push(""),(r&&!e||!r&&e)&&a.push(":"),a.push(`${n}(:0{1,4}){1,${t-1}}`),a.push(`(0{1,4}:){1,${t-1}}${i}`),a.push(`(0{1,4}:){${t-1}}0{1,4}`);for(let s=1;s<t-1;s++)for(let o=1;o<t-s;o++)a.push(`(0{1,4}:){${o}}:(0{1,4}:){${t-o-s-1}}0{1,4}`);return Yh(a)}});var cW=p(ii=>{"use strict";var Xye=ii&&ii.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Zye=ii&&ii.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Wh=ii&&ii.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Xye(e,t,r);return Zye(e,t),e};Object.defineProperty(ii,"__esModule",{value:!0});ii.Address6=void 0;var oW=Wh(Fh()),_C=Wh(oC()),at=Wh(dC()),pC=Wh(fC()),qs=cC(),Gs=sW(),qi=qh(),Hh=Fh();function Vh(t){if(!t)throw new Error("Assertion failed.")}function Jye(t){let e=/(\d+)(\d{3})/;for(;e.test(t);)t=t.replace(e,"$1,$2");return t}function eTe(t){return t=t.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2'),t=t.replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2'),t}function tTe(t,e){let r=[],n=[],i;for(i=0;i<t.length;i++)i<e[0]?r.push(t[i]):i>e[1]&&n.push(t[i]);return r.concat(["compact"]).concat(n)}function lW(t){return parseInt(t,16).toString(16).padStart(4,"0")}function uW(t){return t&255}var hC=class t{constructor(e,r){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=oW.isInSubnet,this.isCorrect=oW.isCorrect(at.BITS),r===void 0?this.groups=at.GROUPS:this.groups=r,this.address=e;let n=at.RE_SUBNET_STRING.exec(e);if(n){if(this.parsedSubnet=n[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>at.BITS)throw new qi.AddressError("Invalid subnet mask.");e=e.replace(at.RE_SUBNET_STRING,"")}else if(/\//.test(e))throw new qi.AddressError("Invalid subnet mask.");let i=at.RE_ZONE_STRING.exec(e);i&&(this.zone=i[0],e=e.replace(at.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new t(e),!0}catch{return!1}}static fromBigInt(e){let r=e.toString(16).padStart(32,"0"),n=[],i;for(i=0;i<at.GROUPS;i++)n.push(r.slice(i*4,(i+1)*4));return new t(n.join(":"))}static fromURL(e){let r,n=null,i;if(e.indexOf("[")!==-1&&e.indexOf("]:")!==-1){if(i=at.RE_URL_WITH_PORT.exec(e),i===null)return{error:"failed to parse address with port",address:null,port:null};r=i[1],n=i[2]}else if(e.indexOf("/")!==-1){if(e=e.replace(/^[a-z0-9]+:\/\//,""),i=at.RE_URL.exec(e),i===null)return{error:"failed to parse address from URL",address:null,port:null};r=i[1]}else r=e;return n?(n=parseInt(n,10),(n<0||n>65536)&&(n=null)):n=null,{address:new t(r),port:n}}static fromAddress4(e){let r=new qs.Address4(e),n=at.BITS-(_C.BITS-r.subnetMask);return new t(`::ffff:${r.correctForm()}/${n}`)}static fromArpa(e){let r=e.replace(/(\.ip6\.arpa)?\.$/,""),n=7;if(r.length!==63)throw new qi.AddressError("Invalid 'ip6.arpa' form.");let i=r.split(".").reverse();for(let a=n;a>0;a--){let s=a*4;i.splice(s,0,":")}return r=i.join(""),new t(r)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){let r=at.BITS-this.subnetMask,n=Math.abs(e-at.BITS),i=r-n;return i<0?"0":Jye((BigInt("2")**BigInt(i)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(at.BITS-this.subnetMask)}`)}startAddress(){return t.fromBigInt(this._startAddress())}startAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(at.BITS-this.subnetMask)}`)}endAddress(){return t.fromBigInt(this._endAddress())}endAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._endAddress()-e)}getScope(){let e=at.SCOPES[parseInt(this.getBits(12,16).toString(10),10)];return this.getType()==="Global unicast"&&e!=="Link local"&&(e="Global"),e||"Unknown"}getType(){for(let e of Object.keys(at.TYPES))if(this.isInSubnet(new t(e)))return at.TYPES[e];return"Global unicast"}getBits(e,r){return BigInt(`0b${this.getBitsBase2(e,r)}`)}getBitsBase2(e,r){return this.binaryZeroPad().slice(e,r)}getBitsBase16(e,r){let n=r-e;if(n%4!==0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,r).toString(16).padStart(n/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,at.BITS)}reverseForm(e){e||(e={});let r=Math.floor(this.subnetMask/4),n=this.canonicalForm().replace(/:/g,"").split("").slice(0,r).reverse().join(".");return r>0?e.omitSuffix?n:`${n}.ip6.arpa.`:e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,r=[],n=0,i=[];for(e=0;e<this.parsedAddress.length;e++){let o=parseInt(this.parsedAddress[e],16);o===0&&n++,o!==0&&n>0&&(n>1&&i.push([e-n,e-1]),n=0)}n>1&&i.push([this.parsedAddress.length-n,this.parsedAddress.length-1]);let a=i.map(o=>o[1]-o[0]+1);if(i.length>0){let o=a.indexOf(Math.max(...a));r=tTe(this.parsedAddress,i[o])}else r=this.parsedAddress;for(e=0;e<r.length;e++)r[e]!=="compact"&&(r[e]=parseInt(r[e],16).toString(16));let s=r.join(":");return s=s.replace(/^compact$/,"::"),s=s.replace(/(^compact)|(compact$)/,":"),s=s.replace(/compact/,""),s}binaryZeroPad(){return this.bigInt().toString(2).padStart(at.BITS,"0")}parse4in6(e){let r=e.split(":"),i=r.slice(-1)[0].match(_C.RE_ADDRESS);if(i){this.parsedAddress4=i[0],this.address4=new qs.Address4(this.parsedAddress4);for(let a=0;a<this.address4.groups;a++)if(/^0[0-9]+/.test(this.address4.parsedAddress[a]))throw new qi.AddressError("IPv4 addresses can't have leading zeroes.",e.replace(_C.RE_ADDRESS,this.address4.parsedAddress.map(eTe).join(".")));this.v4=!0,r[r.length-1]=this.address4.toGroup6(),e=r.join(":")}return e}parse(e){e=this.parse4in6(e);let r=e.match(at.RE_BAD_CHARACTERS);if(r)throw new qi.AddressError(`Bad character${r.length>1?"s":""} detected in address: ${r.join("")}`,e.replace(at.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let n=e.match(at.RE_BAD_ADDRESS);if(n)throw new qi.AddressError(`Address failed regex: ${n.join("")}`,e.replace(at.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let i=[],a=e.split("::");if(a.length===2){let s=a[0].split(":"),o=a[1].split(":");s.length===1&&s[0]===""&&(s=[]),o.length===1&&o[0]===""&&(o=[]);let l=this.groups-(s.length+o.length);if(!l)throw new qi.AddressError("Error parsing groups");this.elidedGroups=l,this.elisionBegin=s.length,this.elisionEnd=s.length+this.elidedGroups,i=i.concat(s);for(let c=0;c<l;c++)i.push("0");i=i.concat(o)}else if(a.length===1)i=e.split(":"),this.elidedGroups=0;else throw new qi.AddressError("Too many :: groups found");if(i=i.map(s=>parseInt(s,16).toString(16)),i.length!==this.groups)throw new qi.AddressError("Incorrect number of groups found");return i}canonicalForm(){return this.parsedAddress.map(lW).join(":")}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(lW).join("")}`)}to4(){let e=this.binaryZeroPad().split("");return qs.Address4.fromHex(BigInt(`0b${e.slice(96,128).join("")}`).toString(16))}to4in6(){let e=this.to4(),n=new t(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),i="";return/:$/.test(n)||(i=":"),n+i+e.address}inspectTeredo(){let e=this.getBitsBase16(0,32),n=(this.getBits(80,96)^BigInt("0xffff")).toString(),i=qs.Address4.fromHex(this.getBitsBase16(32,64)),a=this.getBits(96,128),s=qs.Address4.fromHex((a^BigInt("0xffffffff")).toString(16)),o=this.getBitsBase2(64,80),l=(0,Hh.testBit)(o,15),c=(0,Hh.testBit)(o,14),_=(0,Hh.testBit)(o,8),d=(0,Hh.testBit)(o,9),m=BigInt(`0b${o.slice(2,6)+o.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:i.address,client4:s.address,flags:o,coneNat:l,microsoft:{reserved:c,universalLocal:d,groupIndividual:_,nonce:m},udpPort:n}}inspect6to4(){let e=this.getBitsBase16(0,16),r=qs.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:r.address}}to6to4(){if(!this.is4())return null;let e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new t(e)}toByteArray(){let e=this.bigInt().toString(16),n=`${"0".repeat(e.length%2)}${e}`,i=[];for(let a=0,s=n.length;a<s;a+=2)i.push(parseInt(n.substring(a,a+2),16));return i}toUnsignedByteArray(){return this.toByteArray().map(uW)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(uW))}static fromUnsignedByteArray(e){let r=BigInt("256"),n=BigInt("0"),i=BigInt("1");for(let a=e.length-1;a>=0;a--)n+=i*BigInt(e[a].toString(10)),i*=r;return t.fromBigInt(n)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){return this.getBitsBase2(0,64)==="1111111010000000000000000000000000000000000000000000000000000000"}isMulticast(){return this.getType()==="Multicast"}is4(){return this.v4}isTeredo(){return this.isInSubnet(new t("2001::/32"))}is6to4(){return this.isInSubnet(new t("2002::/16"))}isLoopback(){return this.getType()==="Loopback"}href(e){return e===void 0?e="":e=`:${e}`,`http://[${this.correctForm()}]${e}/`}link(e){e||(e={}),e.className===void 0&&(e.className=""),e.prefix===void 0&&(e.prefix="/#address="),e.v4===void 0&&(e.v4=!1);let r=this.correctForm;e.v4&&(r=this.to4in6);let n=r.call(this);return e.className?`<a href="${e.prefix}${n}" class="${e.className}">${n}</a>`:`<a href="${e.prefix}${n}">${n}</a>`}group(){if(this.elidedGroups===0)return pC.simpleGroup(this.address).join(":");Vh(typeof this.elidedGroups=="number"),Vh(typeof this.elisionBegin=="number");let e=[],[r,n]=this.address.split("::");r.length?e.push(...pC.simpleGroup(r)):e.push("");let i=["hover-group"];for(let a=this.elisionBegin;a<this.elisionBegin+this.elidedGroups;a++)i.push(`group-${a}`);return e.push(`<span class="${i.join(" ")}"></span>`),n.length?e.push(...pC.simpleGroup(n,this.elisionEnd)):e.push(""),this.is4()&&(Vh(this.address4 instanceof qs.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let r=[],n=new t(this.correctForm());if(n.elidedGroups===0)r.push((0,Gs.simpleRegularExpression)(n.parsedAddress));else if(n.elidedGroups===at.GROUPS)r.push((0,Gs.possibleElisions)(at.GROUPS));else{let i=n.address.split("::");i[0].length&&r.push((0,Gs.simpleRegularExpression)(i[0].split(":"))),Vh(typeof n.elidedGroups=="number"),r.push((0,Gs.possibleElisions)(n.elidedGroups,i[0].length!==0,i[1].length!==0)),i[1].length&&r.push((0,Gs.simpleRegularExpression)(i[1].split(":"))),r=[r.join(":")]}return e||(r=["(?=^|",Gs.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...r,")(?=[^\\w\\:]|",Gs.ADDRESS_BOUNDARY,"|$)"]),r.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}};ii.Address6=hC});var mC=p(dr=>{"use strict";var rTe=dr&&dr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),nTe=dr&&dr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),iTe=dr&&dr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rTe(e,t,r);return nTe(e,t),e};Object.defineProperty(dr,"__esModule",{value:!0});dr.v6=dr.AddressError=dr.Address6=dr.Address4=void 0;var aTe=cC();Object.defineProperty(dr,"Address4",{enumerable:!0,get:function(){return aTe.Address4}});var sTe=cW();Object.defineProperty(dr,"Address6",{enumerable:!0,get:function(){return sTe.Address6}});var oTe=qh();Object.defineProperty(dr,"AddressError",{enumerable:!0,get:function(){return oTe.AddressError}});var lTe=iTe(fC());dr.v6={helpers:lTe}});var mW=p(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.ipToBuffer=nn.int32ToIpv4=nn.ipv4ToInt32=nn.validateSocksClientChainOptions=nn.validateSocksClientOptions=void 0;var yr=sC(),Jt=iC(),uTe=require("stream"),gC=mC(),dW=require("net");function cTe(t,e=["connect","bind","associate"]){if(!Jt.SocksCommand[t.command])throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksCommand,t);if(e.indexOf(t.command)===-1)throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksCommandForOperation,t);if(!_W(t.destination))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsDestination,t);if(!pW(t.proxy))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsProxy,t);if(fW(t.proxy,t),t.timeout&&!hW(t.timeout))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsTimeout,t);if(t.existing_socket&&!(t.existing_socket instanceof uTe.Duplex))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsExistingSocket,t)}nn.validateSocksClientOptions=cTe;function dTe(t){if(t.command!=="connect")throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksCommandChain,t);if(!_W(t.destination))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsDestination,t);if(!(t.proxies&&Array.isArray(t.proxies)&&t.proxies.length>=2))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsProxiesLength,t);if(t.proxies.forEach(e=>{if(!pW(e))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsProxy,t);fW(e,t)}),t.timeout&&!hW(t.timeout))throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsTimeout,t)}nn.validateSocksClientChainOptions=dTe;function fW(t,e){if(t.custom_auth_method!==void 0){if(t.custom_auth_method<Jt.SOCKS5_CUSTOM_AUTH_START||t.custom_auth_method>Jt.SOCKS5_CUSTOM_AUTH_END)throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsCustomAuthRange,e);if(t.custom_auth_request_handler===void 0||typeof t.custom_auth_request_handler!="function")throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,e);if(t.custom_auth_response_size===void 0)throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,e);if(t.custom_auth_response_handler===void 0||typeof t.custom_auth_response_handler!="function")throw new yr.SocksClientError(Jt.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,e)}}function _W(t){return t&&typeof t.host=="string"&&Buffer.byteLength(t.host)<256&&typeof t.port=="number"&&t.port>=0&&t.port<=65535}function pW(t){return t&&(typeof t.host=="string"||typeof t.ipaddress=="string")&&typeof t.port=="number"&&t.port>=0&&t.port<=65535&&(t.type===4||t.type===5)}function hW(t){return typeof t=="number"&&t>0}function fTe(t){return new gC.Address4(t).toArray().reduce((r,n)=>(r<<8)+n,0)>>>0}nn.ipv4ToInt32=fTe;function _Te(t){let e=t>>>24&255,r=t>>>16&255,n=t>>>8&255,i=t&255;return[e,r,n,i].join(".")}nn.int32ToIpv4=_Te;function pTe(t){if(dW.isIPv4(t)){let e=new gC.Address4(t);return Buffer.from(e.toArray())}else if(dW.isIPv6(t)){let e=new gC.Address6(t);return Buffer.from(e.canonicalForm().split(":").map(r=>r.padStart(4,"0")).join(""),"hex")}else throw new Error("Invalid IP address format")}nn.ipToBuffer=pTe});var gW=p(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});zh.ReceiveBuffer=void 0;var EC=class{constructor(e=4096){this.buffer=Buffer.allocUnsafe(e),this.offset=0,this.originalSize=e}get length(){return this.offset}append(e){if(!Buffer.isBuffer(e))throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer.");if(this.offset+e.length>=this.buffer.length){let r=this.buffer;this.buffer=Buffer.allocUnsafe(Math.max(this.buffer.length+this.originalSize,this.buffer.length+e.length)),r.copy(this.buffer)}return e.copy(this.buffer,this.offset),this.offset+=e.length}peek(e){if(e>this.offset)throw new Error("Attempted to read beyond the bounds of the managed internal data.");return this.buffer.slice(0,e)}get(e){if(e>this.offset)throw new Error("Attempted to read beyond the bounds of the managed internal data.");let r=Buffer.allocUnsafe(e);return this.buffer.slice(0,e).copy(r),this.buffer.copyWithin(0,e,e+this.offset-e),this.offset-=e,r}};zh.ReceiveBuffer=EC});var EW=p(Ia=>{"use strict";var Tl=Ia&&Ia.__awaiter||function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(_){try{c(n.next(_))}catch(d){s(d)}}function l(_){try{c(n.throw(_))}catch(d){s(d)}}function c(_){_.done?a(_.value):i(_.value).then(o,l)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Ia,"__esModule",{value:!0});Ia.SocksClientError=Ia.SocksClient=void 0;var hTe=require("events"),Cl=require("net"),Dr=Q7(),U=iC(),Fr=mW(),mTe=gW(),bC=sC();Object.defineProperty(Ia,"SocksClientError",{enumerable:!0,get:function(){return bC.SocksClientError}});var SC=mC(),vC=class t extends hTe.EventEmitter{constructor(e){super(),this.options=Object.assign({},e),(0,Fr.validateSocksClientOptions)(e),this.setState(U.SocksClientState.Created)}static createConnection(e,r){return new Promise((n,i)=>{try{(0,Fr.validateSocksClientOptions)(e,["connect"])}catch(s){return typeof r=="function"?(r(s),n(s)):i(s)}let a=new t(e);a.connect(e.existing_socket),a.once("established",s=>{a.removeAllListeners(),typeof r=="function"&&r(null,s),n(s)}),a.once("error",s=>{a.removeAllListeners(),typeof r=="function"?(r(s),n(s)):i(s)})})}static createConnectionChain(e,r){return new Promise((n,i)=>Tl(this,void 0,void 0,function*(){try{(0,Fr.validateSocksClientChainOptions)(e)}catch(a){return typeof r=="function"?(r(a),n(a)):i(a)}e.randomizeChain&&(0,bC.shuffleArray)(e.proxies);try{let a;for(let s=0;s<e.proxies.length;s++){let o=e.proxies[s],l=s===e.proxies.length-1?e.destination:{host:e.proxies[s+1].host||e.proxies[s+1].ipaddress,port:e.proxies[s+1].port},c=yield t.createConnection({command:"connect",proxy:o,destination:l,existing_socket:a});a=a||c.socket}typeof r=="function"?(r(null,{socket:a}),n({socket:a})):n({socket:a})}catch(a){typeof r=="function"?(r(a),n(a)):i(a)}}))}static createUDPFrame(e){let r=new Dr.SmartBuffer;return r.writeUInt16BE(0),r.writeUInt8(e.frameNumber||0),Cl.isIPv4(e.remoteHost.host)?(r.writeUInt8(U.Socks5HostType.IPv4),r.writeUInt32BE((0,Fr.ipv4ToInt32)(e.remoteHost.host))):Cl.isIPv6(e.remoteHost.host)?(r.writeUInt8(U.Socks5HostType.IPv6),r.writeBuffer((0,Fr.ipToBuffer)(e.remoteHost.host))):(r.writeUInt8(U.Socks5HostType.Hostname),r.writeUInt8(Buffer.byteLength(e.remoteHost.host)),r.writeString(e.remoteHost.host)),r.writeUInt16BE(e.remoteHost.port),r.writeBuffer(e.data),r.toBuffer()}static parseUDPFrame(e){let r=Dr.SmartBuffer.fromBuffer(e);r.readOffset=2;let n=r.readUInt8(),i=r.readUInt8(),a;i===U.Socks5HostType.IPv4?a=(0,Fr.int32ToIpv4)(r.readUInt32BE()):i===U.Socks5HostType.IPv6?a=SC.Address6.fromByteArray(Array.from(r.readBuffer(16))).canonicalForm():a=r.readString(r.readUInt8());let s=r.readUInt16BE();return{frameNumber:n,remoteHost:{host:a,port:s},data:r.readBuffer()}}setState(e){this.state!==U.SocksClientState.Error&&(this.state=e)}connect(e){this.onDataReceived=n=>this.onDataReceivedHandler(n),this.onClose=()=>this.onCloseHandler(),this.onError=n=>this.onErrorHandler(n),this.onConnect=()=>this.onConnectHandler();let r=setTimeout(()=>this.onEstablishedTimeout(),this.options.timeout||U.DEFAULT_TIMEOUT);r.unref&&typeof r.unref=="function"&&r.unref(),e?this.socket=e:this.socket=new Cl.Socket,this.socket.once("close",this.onClose),this.socket.once("error",this.onError),this.socket.once("connect",this.onConnect),this.socket.on("data",this.onDataReceived),this.setState(U.SocksClientState.Connecting),this.receiveBuffer=new mTe.ReceiveBuffer,e?this.socket.emit("connect"):(this.socket.connect(this.getSocketOptions()),this.options.set_tcp_nodelay!==void 0&&this.options.set_tcp_nodelay!==null&&this.socket.setNoDelay(!!this.options.set_tcp_nodelay)),this.prependOnceListener("established",n=>{setImmediate(()=>{if(this.receiveBuffer.length>0){let i=this.receiveBuffer.get(this.receiveBuffer.length);n.socket.emit("data",i)}n.socket.resume()})})}getSocketOptions(){return Object.assign(Object.assign({},this.options.socket_options),{host:this.options.proxy.host||this.options.proxy.ipaddress,port:this.options.proxy.port})}onEstablishedTimeout(){this.state!==U.SocksClientState.Established&&this.state!==U.SocksClientState.BoundWaitingForConnection&&this.closeSocket(U.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){this.setState(U.SocksClientState.Connected),this.options.proxy.type===4?this.sendSocks4InitialHandshake():this.sendSocks5InitialHandshake(),this.setState(U.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(e){this.receiveBuffer.append(e),this.processData()}processData(){for(;this.state!==U.SocksClientState.Established&&this.state!==U.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize;)if(this.state===U.SocksClientState.SentInitialHandshake)this.options.proxy.type===4?this.handleSocks4FinalHandshakeResponse():this.handleInitialSocks5HandshakeResponse();else if(this.state===U.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===U.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else if(this.state===U.SocksClientState.BoundWaitingForConnection)this.options.proxy.type===4?this.handleSocks4IncomingConnectionResponse():this.handleSocks5IncomingConnectionResponse();else{this.closeSocket(U.ERRORS.InternalError);break}}onCloseHandler(){this.closeSocket(U.ERRORS.SocketClosed)}onErrorHandler(e){this.closeSocket(e.message)}removeInternalSocketHandlers(){this.socket.pause(),this.socket.removeListener("data",this.onDataReceived),this.socket.removeListener("close",this.onClose),this.socket.removeListener("error",this.onError),this.socket.removeListener("connect",this.onConnect)}closeSocket(e){this.state!==U.SocksClientState.Error&&(this.setState(U.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new bC.SocksClientError(e,this.options)))}sendSocks4InitialHandshake(){let e=this.options.proxy.userId||"",r=new Dr.SmartBuffer;r.writeUInt8(4),r.writeUInt8(U.SocksCommand[this.options.command]),r.writeUInt16BE(this.options.destination.port),Cl.isIPv4(this.options.destination.host)?(r.writeBuffer((0,Fr.ipToBuffer)(this.options.destination.host)),r.writeStringNT(e)):(r.writeUInt8(0),r.writeUInt8(0),r.writeUInt8(0),r.writeUInt8(1),r.writeStringNT(e),r.writeStringNT(this.options.destination.host)),this.nextRequiredPacketBufferSize=U.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write(r.toBuffer())}handleSocks4FinalHandshakeResponse(){let e=this.receiveBuffer.get(8);if(e[1]!==U.Socks4Response.Granted)this.closeSocket(`${U.ERRORS.Socks4ProxyRejectedConnection} - (${U.Socks4Response[e[1]]})`);else if(U.SocksCommand[this.options.command]===U.SocksCommand.bind){let r=Dr.SmartBuffer.fromBuffer(e);r.readOffset=2;let n={port:r.readUInt16BE(),host:(0,Fr.int32ToIpv4)(r.readUInt32BE())};n.host==="0.0.0.0"&&(n.host=this.options.proxy.ipaddress),this.setState(U.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost:n,socket:this.socket})}else this.setState(U.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){let e=this.receiveBuffer.get(8);if(e[1]!==U.Socks4Response.Granted)this.closeSocket(`${U.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${U.Socks4Response[e[1]]})`);else{let r=Dr.SmartBuffer.fromBuffer(e);r.readOffset=2;let n={port:r.readUInt16BE(),host:(0,Fr.int32ToIpv4)(r.readUInt32BE())};this.setState(U.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:n,socket:this.socket})}}sendSocks5InitialHandshake(){let e=new Dr.SmartBuffer,r=[U.Socks5Auth.NoAuth];(this.options.proxy.userId||this.options.proxy.password)&&r.push(U.Socks5Auth.UserPass),this.options.proxy.custom_auth_method!==void 0&&r.push(this.options.proxy.custom_auth_method),e.writeUInt8(5),e.writeUInt8(r.length);for(let n of r)e.writeUInt8(n);this.nextRequiredPacketBufferSize=U.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(e.toBuffer()),this.setState(U.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){let e=this.receiveBuffer.get(2);e[0]!==5?this.closeSocket(U.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion):e[1]===U.SOCKS5_NO_ACCEPTABLE_AUTH?this.closeSocket(U.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType):e[1]===U.Socks5Auth.NoAuth?(this.socks5ChosenAuthType=U.Socks5Auth.NoAuth,this.sendSocks5CommandRequest()):e[1]===U.Socks5Auth.UserPass?(this.socks5ChosenAuthType=U.Socks5Auth.UserPass,this.sendSocks5UserPassAuthentication()):e[1]===this.options.proxy.custom_auth_method?(this.socks5ChosenAuthType=this.options.proxy.custom_auth_method,this.sendSocks5CustomAuthentication()):this.closeSocket(U.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType)}sendSocks5UserPassAuthentication(){let e=this.options.proxy.userId||"",r=this.options.proxy.password||"",n=new Dr.SmartBuffer;n.writeUInt8(1),n.writeUInt8(Buffer.byteLength(e)),n.writeString(e),n.writeUInt8(Buffer.byteLength(r)),n.writeString(r),this.nextRequiredPacketBufferSize=U.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(n.toBuffer()),this.setState(U.SocksClientState.SentAuthentication)}sendSocks5CustomAuthentication(){return Tl(this,void 0,void 0,function*(){this.nextRequiredPacketBufferSize=this.options.proxy.custom_auth_response_size,this.socket.write(yield this.options.proxy.custom_auth_request_handler()),this.setState(U.SocksClientState.SentAuthentication)})}handleSocks5CustomAuthHandshakeResponse(e){return Tl(this,void 0,void 0,function*(){return yield this.options.proxy.custom_auth_response_handler(e)})}handleSocks5AuthenticationNoAuthHandshakeResponse(e){return Tl(this,void 0,void 0,function*(){return e[1]===0})}handleSocks5AuthenticationUserPassHandshakeResponse(e){return Tl(this,void 0,void 0,function*(){return e[1]===0})}handleInitialSocks5AuthenticationHandshakeResponse(){return Tl(this,void 0,void 0,function*(){this.setState(U.SocksClientState.ReceivedAuthenticationResponse);let e=!1;this.socks5ChosenAuthType===U.Socks5Auth.NoAuth?e=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2)):this.socks5ChosenAuthType===U.Socks5Auth.UserPass?e=yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2)):this.socks5ChosenAuthType===this.options.proxy.custom_auth_method&&(e=yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size))),e?this.sendSocks5CommandRequest():this.closeSocket(U.ERRORS.Socks5AuthenticationFailed)})}sendSocks5CommandRequest(){let e=new Dr.SmartBuffer;e.writeUInt8(5),e.writeUInt8(U.SocksCommand[this.options.command]),e.writeUInt8(0),Cl.isIPv4(this.options.destination.host)?(e.writeUInt8(U.Socks5HostType.IPv4),e.writeBuffer((0,Fr.ipToBuffer)(this.options.destination.host))):Cl.isIPv6(this.options.destination.host)?(e.writeUInt8(U.Socks5HostType.IPv6),e.writeBuffer((0,Fr.ipToBuffer)(this.options.destination.host))):(e.writeUInt8(U.Socks5HostType.Hostname),e.writeUInt8(this.options.destination.host.length),e.writeString(this.options.destination.host)),e.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(e.toBuffer()),this.setState(U.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){let e=this.receiveBuffer.peek(5);if(e[0]!==5||e[1]!==U.Socks5Response.Granted)this.closeSocket(`${U.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${U.Socks5Response[e[1]]}`);else{let r=e[3],n,i;if(r===U.Socks5HostType.IPv4){let a=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<a){this.nextRequiredPacketBufferSize=a;return}i=Dr.SmartBuffer.fromBuffer(this.receiveBuffer.get(a).slice(4)),n={host:(0,Fr.int32ToIpv4)(i.readUInt32BE()),port:i.readUInt16BE()},n.host==="0.0.0.0"&&(n.host=this.options.proxy.ipaddress)}else if(r===U.Socks5HostType.Hostname){let a=e[4],s=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(a);if(this.receiveBuffer.length<s){this.nextRequiredPacketBufferSize=s;return}i=Dr.SmartBuffer.fromBuffer(this.receiveBuffer.get(s).slice(5)),n={host:i.readString(a),port:i.readUInt16BE()}}else if(r===U.Socks5HostType.IPv6){let a=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<a){this.nextRequiredPacketBufferSize=a;return}i=Dr.SmartBuffer.fromBuffer(this.receiveBuffer.get(a).slice(4)),n={host:SC.Address6.fromByteArray(Array.from(i.readBuffer(16))).canonicalForm(),port:i.readUInt16BE()}}this.setState(U.SocksClientState.ReceivedFinalResponse),U.SocksCommand[this.options.command]===U.SocksCommand.connect?(this.setState(U.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:n,socket:this.socket})):U.SocksCommand[this.options.command]===U.SocksCommand.bind?(this.setState(U.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost:n,socket:this.socket})):U.SocksCommand[this.options.command]===U.SocksCommand.associate&&(this.setState(U.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:n,socket:this.socket}))}}handleSocks5IncomingConnectionResponse(){let e=this.receiveBuffer.peek(5);if(e[0]!==5||e[1]!==U.Socks5Response.Granted)this.closeSocket(`${U.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${U.Socks5Response[e[1]]}`);else{let r=e[3],n,i;if(r===U.Socks5HostType.IPv4){let a=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<a){this.nextRequiredPacketBufferSize=a;return}i=Dr.SmartBuffer.fromBuffer(this.receiveBuffer.get(a).slice(4)),n={host:(0,Fr.int32ToIpv4)(i.readUInt32BE()),port:i.readUInt16BE()},n.host==="0.0.0.0"&&(n.host=this.options.proxy.ipaddress)}else if(r===U.Socks5HostType.Hostname){let a=e[4],s=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(a);if(this.receiveBuffer.length<s){this.nextRequiredPacketBufferSize=s;return}i=Dr.SmartBuffer.fromBuffer(this.receiveBuffer.get(s).slice(5)),n={host:i.readString(a),port:i.readUInt16BE()}}else if(r===U.Socks5HostType.IPv6){let a=U.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<a){this.nextRequiredPacketBufferSize=a;return}i=Dr.SmartBuffer.fromBuffer(this.receiveBuffer.get(a).slice(4)),n={host:SC.Address6.fromByteArray(Array.from(i.readBuffer(16))).canonicalForm(),port:i.readUInt16BE()}}this.setState(U.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:n,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}};Ia.SocksClient=vC});var SW=p(Ys=>{"use strict";var gTe=Ys&&Ys.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),ETe=Ys&&Ys.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&gTe(e,t,r)};Object.defineProperty(Ys,"__esModule",{value:!0});ETe(EW(),Ys)});var CC=p(In=>{"use strict";var STe=In&&In.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),bTe=In&&In.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),vTe=In&&In.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&STe(r,e,n[i]);return bTe(r,e),r}})(),bW=In&&In.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(In,"__esModule",{value:!0});In.default=ITe;var yTe=bW(Tn()),TTe=require("stream"),CTe=SW(),ATe=vTe(require("dns")),RTe=require("util"),yC=bW(require("assert")),Gi=(0,yTe.default)("mqttjs:socks"),TC=class extends TTe.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1}),this.cork()}_start(e){if(Gi("proxy stream started"),(0,yC.default)(!this._socket),this.destroyed){e.destroy(this.errored);return}this._socket=e,this._flowing||e.pause(),e.on("data",this._onData),e.on("end",this._onEnd),e.on("error",this._onError),e.on("close",this._onClose),e.emit("connect"),this.uncork()}_write(e,r,n){(0,yC.default)(this._socket),this._socket.write(e,n)}_read(e){this._flowing=!0,this._socket?.resume?.()}_destroy(e,r){this._socket?.destroy?.(e),r(e)}_onData=e=>{(0,yC.default)(this._socket),this._flowing=this.push(e),this._flowing||this._socket.pause()};_onEnd=()=>{Gi("proxy stream received EOF"),this.push(null)};_onClose=()=>{Gi("proxy stream closed"),this.destroy()};_onError=e=>{Gi("proxy stream died with error %s",e),this.destroy(e)}};function $h(t){try{return t.code===void 0&&(t.code="SOCKS"),t}catch{return t}}function OTe(t){switch(t){case"socks5h:":return[5,!0];case"socks4a:":return[4,!0];case"socks5:":return[5,!1];case"socks4:":return[4,!1];default:return[void 0,!1]}}function NTe(t){let e=new URL(t);if(e.pathname||e.hash||e.search)throw $h(new Error("bad SOCKS URL"));let[r,n]=OTe(e.protocol);if(!r)throw $h(new Error("bad SOCKS URL: invalid protocol"));let i=parseInt(e.port,10);if(Number.isNaN(i))throw $h(new Error("bad SOCKS URL: invalid port"));return[{host:e.hostname,port:i,type:r},n]}async function wTe(t,e,r,n,i={}){let a=i.lookup??(0,RTe.promisify)(ATe.lookup),[s,o]=NTe(r);o||(Gi("resolving %s locally",t),t=(await a(t,{family:s.type===4?4:0})).address),Gi("establishing SOCKS%d connection to %s:%d via %s:%d",s.type,t,e,s.host,s.port);let l=new CTe.SocksClient({command:"connect",destination:{host:t,port:e},proxy:{...s},timeout:i.timeout});l.connect(),l.on("established",({socket:c})=>n._start(c)),l.on("error",c=>{Gi("SOCKS failed: %s",c),n.destroy($h(c))})}function ITe(t,e,r,n){Gi("SOCKS connection to %s:%d via %s",t,e,r);let i=new TC;return wTe(t,e,r,i,n).catch(a=>{Gi("SOCKS failed: %s",a),i.destroy(a)}),i}});var RC=p(jc=>{"use strict";var AC=jc&&jc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(jc,"__esModule",{value:!0});var DTe=AC(require("net")),xTe=AC(Tn()),MTe=AC(CC()),LTe=(0,xTe.default)("mqttjs:tcp"),PTe=(t,e)=>{if(e.port=e.port||1883,e.hostname=e.hostname||e.host||"localhost",e.socksProxy)return(0,MTe.default)(e.hostname,e.port,e.socksProxy,{timeout:e.socksTimeout});let{port:r,path:n}=e,i=e.hostname;return LTe("port %d and host %s",r,i),DTe.default.createConnection({port:r,host:i,path:n})};jc.default=PTe});var NC=p(Xc=>{"use strict";var OC=Xc&&Xc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Xc,"__esModule",{value:!0});var vW=require("tls"),kTe=OC(require("net")),BTe=OC(Tn()),FTe=OC(CC()),UTe=(0,BTe.default)("mqttjs:tls");function qTe(t){let{host:e,port:r,socksProxy:n,...i}=t;if(n!==void 0){let a=(0,FTe.default)(e,r,n,{timeout:t.socksTimeout});return(0,vW.connect)({...i,socket:a})}return(0,vW.connect)(t)}var GTe=(t,e)=>{e.port=e.port||8883,e.host=e.hostname||e.host||"localhost",kTe.default.isIP(e.host)===0&&(e.servername=e.host),e.rejectUnauthorized=e.rejectUnauthorized!==!1,delete e.path,UTe("port %d host %s rejectUnauthorized %b",e.port,e.host,e.rejectUnauthorized);let r=qTe(e);r.on("secureConnect",()=>{e.rejectUnauthorized&&!r.authorized?r.emit("error",new Error("TLS not authorized")):r.removeListener("error",n)});function n(i){e.rejectUnauthorized&&t.emit("error",i),r.end()}return r.on("error",n),r};Xc.default=GTe});var DC=p(IC=>{"use strict";Object.defineProperty(IC,"__esModule",{value:!0});var yW=require("buffer"),YTe=Sa(),HTe=kh(),ai,wC,Ur;function VTe(){let t=new YTe.Transform;return t._write=(e,r,n)=>{ai.send({data:e.buffer,success(){n()},fail(i){n(new Error(i))}})},t._flush=e=>{ai.close({success(){e()}})},t}function WTe(t){t.hostname||(t.hostname="localhost"),t.path||(t.path="/"),t.wsOptions||(t.wsOptions={})}function zTe(t,e){let r=t.protocol==="wxs"?"wss":"ws",n=`${r}://${t.hostname}${t.path}`;return t.port&&t.port!==80&&t.port!==443&&(n=`${r}://${t.hostname}:${t.port}${t.path}`),typeof t.transformWsUrl=="function"&&(n=t.transformWsUrl(n,t,e)),n}function $Te(){ai.onOpen(()=>{Ur.socketReady()}),ai.onMessage(t=>{let{data:e}=t;e instanceof ArrayBuffer?e=yW.Buffer.from(e):e=yW.Buffer.from(e,"utf8"),wC.push(e)}),ai.onClose(()=>{Ur.emit("close"),Ur.end(),Ur.destroy()}),ai.onError(t=>{let e=new Error(t.errMsg);Ur.destroy(e)})}var KTe=(t,e)=>{if(e.hostname=e.hostname||e.host,!e.hostname)throw new Error("Could not determine host. Specify host manually.");let r=e.protocolId==="MQIsdp"&&e.protocolVersion===3?"mqttv3.1":"mqtt";WTe(e);let n=zTe(e,t);ai=wx.connectSocket({url:n,protocols:[r]}),wC=VTe(),Ur=new HTe.BufferedDuplex(e,wC,ai),Ur._destroy=(a,s)=>{ai.close({success(){s&&s(a)}})};let i=Ur.destroy;return Ur.destroy=(a,s)=>(Ur.destroy=i,setTimeout(()=>{ai.close({fail(){Ur._destroy(a,s)}})},0),Ur),$Te(),Ur};IC.default=KTe});var LC=p(MC=>{"use strict";Object.defineProperty(MC,"__esModule",{value:!0});var xC=require("buffer"),QTe=Sa(),jTe=kh(),Yi,Zc,Al,TW=!1;function XTe(){let t=new QTe.Transform;return t._write=(e,r,n)=>{Yi.sendSocketMessage({data:e.buffer,success(){n()},fail(){n(new Error)}})},t._flush=e=>{Yi.closeSocket({success(){e()}})},t}function ZTe(t){t.hostname||(t.hostname="localhost"),t.path||(t.path="/"),t.wsOptions||(t.wsOptions={})}function JTe(t,e){let r=t.protocol==="alis"?"wss":"ws",n=`${r}://${t.hostname}${t.path}`;return t.port&&t.port!==80&&t.port!==443&&(n=`${r}://${t.hostname}:${t.port}${t.path}`),typeof t.transformWsUrl=="function"&&(n=t.transformWsUrl(n,t,e)),n}function eCe(){TW||(TW=!0,Yi.onSocketOpen(()=>{Al.socketReady()}),Yi.onSocketMessage(t=>{if(typeof t.data=="string"){let e=xC.Buffer.from(t.data,"base64");Zc.push(e)}else{let e=new FileReader;e.addEventListener("load",()=>{if(e.result instanceof ArrayBuffer){Zc.push(xC.Buffer.from(e.result));return}Zc.push(xC.Buffer.from(e.result,"utf-8"))}),e.readAsArrayBuffer(t.data)}}),Yi.onSocketClose(()=>{Al.end(),Al.destroy()}),Yi.onSocketError(t=>{Al.destroy(t)}))}var tCe=(t,e)=>{if(e.hostname=e.hostname||e.host,!e.hostname)throw new Error("Could not determine host. Specify host manually.");let r=e.protocolId==="MQIsdp"&&e.protocolVersion===3?"mqttv3.1":"mqtt";ZTe(e);let n=JTe(e,t);return Yi=e.my,Yi.connectSocket({url:n,protocols:r}),Zc=XTe(),Al=new jTe.BufferedDuplex(e,Zc,Yi),eCe(),Al};MC.default=tCe});var OW=p(Rl=>{"use strict";var Kh=Rl&&Rl.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Rl,"__esModule",{value:!0});Rl.connectAsync=sCe;var rCe=Kh(Tn()),nCe=Kh(require("url")),iCe=Kh(yh()),CW=Kh(kc());typeof process?.nextTick!="function"&&(process.nextTick=setImmediate);var AW=(0,rCe.default)("mqttjs"),Vt=null;function aCe(t){let e;if(t.auth)if(e=t.auth.match(/^(.+):(.+)$/),e){let[,r,n]=e;t.username=r,t.password=n}else t.username=t.auth}function RW(t,e){if(AW("connecting to an MQTT broker..."),typeof t=="object"&&!e&&(e=t,t=""),e=e||{},t&&typeof t=="string"){let i=nCe.default.parse(t,!0),a={};if(i.port!=null&&(a.port=Number(i.port)),a.host=i.hostname,a.query=i.query,a.auth=i.auth,a.protocol=i.protocol,a.path=i.path,e={...a,...e},!e.protocol)throw new Error("Missing protocol");e.protocol=e.protocol.replace(/:$/,"")}if(e.unixSocket=e.unixSocket||e.protocol?.includes("+unix"),e.unixSocket?e.protocol=e.protocol.replace("+unix",""):!e.protocol?.startsWith("ws")&&!e.protocol?.startsWith("wx")&&delete e.path,aCe(e),e.query&&typeof e.query.clientId=="string"&&(e.clientId=e.query.clientId),CW.default||e.unixSocket?e.socksProxy=void 0:e.socksProxy===void 0&&typeof process<"u"&&(e.socksProxy=process.env.MQTTJS_SOCKS_PROXY),e.cert&&e.key)if(e.protocol){if(["mqtts","wss","wxs","alis"].indexOf(e.protocol)===-1)switch(e.protocol){case"mqtt":e.protocol="mqtts";break;case"ws":e.protocol="wss";break;case"wx":e.protocol="wxs";break;case"ali":e.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${e.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(Vt||(Vt={},!CW.default&&!e.forceNativeWebSocket?(Vt.ws=Kc().streamBuilder,Vt.wss=Kc().streamBuilder,Vt.mqtt=RC().default,Vt.tcp=RC().default,Vt.ssl=NC().default,Vt.tls=Vt.ssl,Vt.mqtts=NC().default):(Vt.ws=Kc().browserStreamBuilder,Vt.wss=Kc().browserStreamBuilder,Vt.wx=DC().default,Vt.wxs=DC().default,Vt.ali=LC().default,Vt.alis=LC().default)),!Vt[e.protocol]){let i=["mqtts","wss"].indexOf(e.protocol)!==-1;e.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((a,s)=>i&&s%2===0?!1:typeof Vt[a]=="function")[0]}if(e.clean===!1&&!e.clientId)throw new Error("Missing clientId for unclean clients");e.protocol&&(e.defaultProtocol=e.protocol);function r(i){return e.servers&&((!i._reconnectCount||i._reconnectCount===e.servers.length)&&(i._reconnectCount=0),e.host=e.servers[i._reconnectCount].host,e.port=e.servers[i._reconnectCount].port,e.protocol=e.servers[i._reconnectCount].protocol?e.servers[i._reconnectCount].protocol:e.defaultProtocol,e.hostname=e.host,i._reconnectCount++),AW("calling streambuilder for",e.protocol),Vt[e.protocol](i,e)}let n=new iCe.default(r,e);return n.on("error",()=>{}),n}function sCe(t,e,r=!0){return new Promise((n,i)=>{let a=RW(t,e),s={connect:l=>{o(),n(a)},end:()=>{o(),n(a)},error:l=>{o(),a.end(),i(l)}};r===!1&&(s.close=()=>{s.error(new Error("Couldn't connect to server"))});function o(){Object.keys(s).forEach(l=>{a.off(l,s[l])})}Object.keys(s).forEach(l=>{a.on(l,s[l])})})}Rl.default=RW});var PC=p(He=>{"use strict";var NW=He&&He.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),oCe=He&&He.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),lCe=He&&He.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&NW(r,e,n[i]);return oCe(r,e),r}})(),wW=He&&He.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&NW(e,t,r)},Jc=He&&He.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(He,"__esModule",{value:!0});He.ReasonCodes=He.KeepaliveManager=He.UniqueMessageIdProvider=He.DefaultMessageIdProvider=He.Store=He.MqttClient=He.connectAsync=He.connect=He.Client=void 0;var IW=Jc(yh());He.MqttClient=IW.default;var uCe=Jc(dT());He.DefaultMessageIdProvider=uCe.default;var cCe=Jc(xV());He.UniqueMessageIdProvider=cCe.default;var dCe=Jc(Cy());He.Store=dCe.default;var DW=lCe(OW());He.connect=DW.default;Object.defineProperty(He,"connectAsync",{enumerable:!0,get:function(){return DW.connectAsync}});var fCe=Jc(RT());He.KeepaliveManager=fCe.default;He.Client=IW.default;wW(yh(),He);wW(As(),He);var _Ce=pc();Object.defineProperty(He,"ReasonCodes",{enumerable:!0,get:function(){return _Ce.ReasonCodes}})});var MW=p(an=>{"use strict";var xW=an&&an.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),pCe=an&&an.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),hCe=an&&an.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&xW(r,e,n[i]);return pCe(r,e),r}})(),mCe=an&&an.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&xW(e,t,r)};Object.defineProperty(an,"__esModule",{value:!0});var gCe=hCe(PC());an.default=gCe;mCe(PC(),an)});var SCe={};UK(SCe,{ConnectorRunnerMqtt:()=>kC});module.exports=qK(SCe);var kl=Zs(require("node:process")),Rd=class{#e="connector-runtime";#r;constructor(e,r){this.#r=r,kl.default.on?kl.default.on("message",n=>{n.cmd===this.#e&&r.logger.verbose(`${kl.default.pid} Received message from parent process:`,n)}):r.logger.warn("IPC channel is not available. process.on is undefined."),kl.default.send||r.logger.warn("IPC channel is not available. process.send is undefined."),e.actions?.forEach(n=>{if(n.config.templates===void 0)return;let i={};Object.entries(n.config.templates).forEach(([a,s])=>{try{i[a]=r.templating.compile(s)}catch(o){r.logger.error(`Error compiling template ${a} for action ${n.identifier}`,o)}}),n.config.parsedTemplates=i})}init=()=>Promise.resolve();start=()=>Promise.resolve();stop=()=>Promise.resolve();set callbackFunction(e){this.connectorSDK.receiver.registerCallback(this.#o(e))}get connectorSDK(){return this.#r}#o(e){return async r=>{let n=await this.#r.receiver.getActionConfig(r);return n?e(r,n):this.#r.receiver.responses.badRequest("Action not found")(r)}}};var Qh=Zs(cf()),kW=Zs(n3());var En=Zs(require("node:process")),Er=Zs(m4()),g4=(a=>(a.error="error",a.warn="warn",a.info="info",a.http="http",a.debug="debug",a))(g4||{}),ap=class t{static instance;logger;#e;constructor(e="default",r="info"){this.logger=Er.default.createLogger({level:r,format:Er.default.format.combine(Er.default.format.label({label:e}),Er.default.format.timestamp(),Er.default.format.json(),Er.default.format.errors({stack:!0}))});let n=!1;(En.default.env.NODE_ENV!=="production"||En.default.env.LOG_TO_CONSOLE==="true")&&(n=!0,this.logger.add(new Er.default.transports.Console({format:Er.default.format.printf(({label:i,level:a,message:s})=>{let o=new Date().toLocaleString();return`[${i}] ${En.default.pid} - ${o} ${a}: ${s}`})}))),En.default.env.LOG_TO_FILE==="true"&&(n=!0,this.logger.add(new Er.default.transports.File({filename:"error.log",level:"error"})),this.logger.add(new Er.default.transports.File({filename:"combined.log"}))),n||this.logger.add(new Er.default.transports.Console({format:Er.default.format.printf(({label:i,level:a,message:s})=>`[${i}] ${a}: ${s}`)}))}static getInstance(e,r){return t.instance||(t.instance=new t(e??"default",t.#o(r))),t.instance}setDatadogTransport(e){let r=e?.apiKey??En.default.env.DATADOG_API_KEY;if(!r)return this.debug("DATADOG_API_KEY is not set, cannot add Datadog transport"),this;let n=new URLSearchParams({"dd-api-key":r,ddsource:e?.source??En.default.env.DD_SOURCE??"nodejs",service:e?.service??En.default.env.DD_SERVICE??"unknown",env:e?.env??En.default.env.DD_ENV??"prod"});e?.tags&&n.append("ddtags",Object.entries(e.tags).map(([a,s])=>`${a}:${s}`).join(","));let i={host:`http-intake.logs.${En.default.env.DD_SITE??"datadoghq.eu"}`,path:`/api/v2/logs?${n.toString()}`,ssl:!0,batch:!0,format:Er.default.format.json(),level:"info"};return this.#e&&this.logger.remove(this.#e),this.#e=new Er.default.transports.Http(i),this.logger.add(this.#e),this}info(...e){this.#r(this.logger.info,...e)}static info(...e){this.getInstance().info(...e)}debug(...e){this.#r(this.logger.debug,...e)}static debug(...e){this.getInstance().debug(...e)}error(...e){this.#r(this.logger.error,...e)}static error(...e){this.getInstance().error(...e)}warn(...e){this.#r(this.logger.warn,...e)}static warn(...e){this.getInstance().warn(...e)}verbose(...e){this.#r(this.logger.verbose,...e)}static verbose(...e){this.getInstance().verbose(...e)}#r(e,...r){try{let n=r.map(i=>typeof i=="object"?JSON.stringify(i):String(i));e(n.join(" "),...r)}catch(n){console.error("unknown error in log, function",n)}}static#o=e=>{if(e!==void 0)return e;let r=En.default.env.LOG_LEVEL||"info",i=!Object.values(g4).includes(r);return i&&(r="info"),i&&console.error(`Invalid log level: ${r} only allow; 'error', 'warn', 'info', 'debug', 'trace'. Using info as default.`),r}};var PW=Zs(MW());function ECe(t,e){if(t===e)return!0;let r=t.split("/"),n=e.split("/"),i=n.indexOf("#");if(i!==-1){if(i!==n.length-1)return!1;for(let a=0;a<i;a+=1)if(a>=r.length||n[a]!=="+"&&n[a]!==r[a])return!1;return!0}if(r.length!==n.length)return!1;for(let a=0;a<n.length;a+=1)if(n[a]!=="+"&&n[a]!==r[a])return!1;return!0}function LW(t,e){let r=e.find(i=>i.topic===t);if(r)return r.collection;let n=e.find(i=>ECe(t,i.topic));if(n)return n.collection}var ed=class{#e;#r;#o;#l;get brokerUrl(){return this.#e.brokerUrl}constructor(e,r){this.#l=ap.getInstance(),this.#e=e,this.#o=r,this.#r=(0,PW.connect)(this.#e.brokerUrl,{clientId:this.#e.clientId,username:this.#e.username,password:this.#e.password,rejectUnauthorized:!1}),this.#r.on("connect",()=>{this.#l.info("Connected to MQTT broker"),this.#e.topic&&this.#r?.subscribe(this.#e.topic),this.#e.topics&&this.#e.topics.forEach(n=>{this.#r?.subscribe(n.topic)})}),this.#r.on("error",n=>{this.#l.error("MQTT connection error:",n)}),this.#r.on("message",async(n,i)=>{let a=i.toString().replace(/\u0000+$/,"");this.#l.debug(`Received message from MQTT broker with topic ${n}: ${a.trim().replace(/\s+/g," ").slice(0,100)}`);let s;try{s=JSON.parse(a)}catch(l){this.#l.error(`Error parsing message ${a}:`,l),s={body:a}}let o=LW(n,this.#e.topics||[]);!o&&this.#e.topics&&this.#l.warn(`No corresponding collection found for topic ${n}. Using topic as collection.`),await this.#o.sender.metricsLegacy([s],{collection:o??n},{},o)})}async stop(){this.#r?.removeAllListeners(),this.#e.topic&&await this.#r?.unsubscribeAsync(this.#e.topic),this.#e.topics&&await Promise.all(this.#e.topics.map(e=>this.#r?.unsubscribeAsync(e.topic))),await this.#r?.endAsync()}async publish(e,r){this.#r?.publish(e,r)}};var kC=class extends Rd{CONNECTOR_INSTANCE="XOD_CONNECTOR_MQTT_SOURCE_CONFIG";#e;constructor(e,r){super(e,r),(0,kW.default)()}init=async()=>{let{config:e}=this.connectorSDK;if(e.servers!==void 0){let n=e;this.#e=n.servers.map(i=>new ed(i,this.connectorSDK))}else{let n=e;this.#e=[new ed(n,this.connectorSDK)]}this.callbackFunction=this.callbackFunctionChain};#r(e){return async(r,n)=>{let i={};Object.keys(n.config).forEach(_=>{try{let d=n.config[_];i[_]=Qh.default.compile(d)}catch(d){this.connectorSDK.logger.error(`Error compiling template ${_} for action ${n.identifier}`),d instanceof Qh.Exception&&this.connectorSDK.logger.error(d.message)}});let s=i.payload({inputs:r.payload}).trim(),o=i.topic({inputs:r.payload}).trim(),l=i.servers?JSON.parse(i.servers({inputs:r.payload}).trim()):void 0,c=l?this.#e?.filter(_=>l.includes(_.brokerUrl)):this.#e;if(!c||c.length===0){let _=`[MQTT] No MQTT client available for the specified servers: ${l?.join(", ")}`;return this.connectorSDK.logger.warn(_),this.connectorSDK.receiver.responses.badRequest(_)(r)}return c.forEach(_=>{_.publish(o,s),this.connectorSDK.logger.info(`Published message to MQTT broker ${_.brokerUrl} on topic ${o}`)}),e(r)}}get callbackFunctionChain(){return this.#r(this.connectorSDK.receiver.emitEventType(this.connectorSDK.receiver.responses.ok()))}stop=async()=>{this.#e?.forEach(e=>e.stop())}};0&&(module.exports={ConnectorRunnerMqtt});
134
134
  /*! Bundled license information:
135
135
 
136
136
  for-in/index.js: