rtsp2web 3.0.0 → 3.0.1
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/README.md +13 -11
- package/dist/rtsp2web.js +2 -3
- package/dist/rtsp2web.min.js +2 -3
- package/package.json +1 -1
- package/dist/rtsp2web.js.map +0 -1
- package/dist/rtsp2web.min.js.map +0 -1
package/README.md
CHANGED
|
@@ -2,12 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
`rtsp2web` 是一个提供在 `web` 页面中可以直接播放 `rtsp` 视频流解决方案的工具。
|
|
4
4
|
|
|
5
|
-
**【前言】**
|
|
6
|
-
|
|
7
|
-
> 在项目的 Github 代码仓库中,有一个 [refer](./refer) 目录, 它是一个小的独立的 `demo` 程序,学习它对你有很大的帮助(都有注释的);
|
|
8
|
-
>
|
|
9
|
-
> 当然,如果你现在只想快速的解决 `rtsp` 视频流在 `web` 页面中的播放问题,你可以跳过本段话;继续往下阅读文档。
|
|
10
|
-
|
|
11
5
|
# How to use(如何在你的项目中使用这个工具)
|
|
12
6
|
|
|
13
7
|
## 准备工作
|
|
@@ -55,10 +49,13 @@ new RTSP2web({
|
|
|
55
49
|
|
|
56
50
|
4.1、参数说明
|
|
57
51
|
|
|
58
|
-
|
|
|
59
|
-
|
|
|
60
|
-
|
|
|
61
|
-
|
|
|
52
|
+
| 参数 | 解释说明 |
|
|
53
|
+
| :-------: | :-------------------------------------------------------------------------------------------------------------------------------------: |
|
|
54
|
+
| port | 转码服务占用的端口号;(type:Number)<br/>可以不传;默认值:9999 |
|
|
55
|
+
| path | FFmpeg 命令在你机器上的启动名称,(type: String) <br/> 一般情况下不传;默认值:'ffmpeg' |
|
|
56
|
+
| audio | audio: false - 禁止输出音频 <br/> 默认不传,即:输出音频 |
|
|
57
|
+
| freeTime | 任一视频流空闲(未被使用)时间超过这个值,就会停止该视频流的转码,释放机器资源(type: Number;单位:秒) <br/> 一般情况下不传;默认值:60 |
|
|
58
|
+
| checkTime | 检测视频空闲的时间间隔(type: Number;单位:秒) <br/> 一般情况下不传;默认值:10 |
|
|
62
59
|
|
|
63
60
|
5、 运行 `node main.js`,启动视频流转码服务
|
|
64
61
|
|
|
@@ -91,6 +88,9 @@ new RTSP2web({
|
|
|
91
88
|
<canvas id="canvas_1" style="width: 640px; height: 360px;"></canvas>
|
|
92
89
|
<!-- 只给定宽度或者高度,另外一个值将会自适应 -->
|
|
93
90
|
<canvas id="canvas_2" style="width: 600px;"></canvas>
|
|
91
|
+
<!-- 不给定宽度和高度,视频将会和视频源大小保持一致 -->
|
|
92
|
+
<canvas id="canvas_3"></canvas>
|
|
93
|
+
<div class="jsmpeg" data-url="ws://localhost:9999/rtsp?url=cnRzcDovL3dvd3phZWMyZGVtby5zdHJlYW1sb2NrLm5ldC92b2QvbXA0OkJpZ0J1Y2tCdW5ueV8xMTVrLm1wNA==">
|
|
94
94
|
</body>
|
|
95
95
|
<script>
|
|
96
96
|
var rtsp1 =
|
|
@@ -153,7 +153,7 @@ new JSMpeg.Player(
|
|
|
153
153
|
|
|
154
154
|
# 去水印
|
|
155
155
|
|
|
156
|
-
|
|
156
|
+
正确的去除水印能减小 `FFmpeg` 性能开销,有效提高 `FFMpeg` 运行效率,提升视频播放质量,可支撑更多的视频;
|
|
157
157
|
|
|
158
158
|
如何去除水印,[联系我](https://neveryu.blog.csdn.net/article/details/124124137);
|
|
159
159
|
|
|
@@ -165,6 +165,8 @@ wechat: miracle421354532
|
|
|
165
165
|
|
|
166
166
|
# change log [更新日志]
|
|
167
167
|
|
|
168
|
+
【2023-03-12】鲁棒性加强,调试播放稳定性。
|
|
169
|
+
|
|
168
170
|
【2023-02-21】断网重连??
|
|
169
171
|
|
|
170
172
|
【2023-02-20】默认支持播放声音;(禁止输出音频有利于减少带宽消耗)
|
package/dist/rtsp2web.js
CHANGED
|
@@ -5,6 +5,5 @@
|
|
|
5
5
|
* 微信(wechat):miracle421354532
|
|
6
6
|
* Released under the ISC License.
|
|
7
7
|
*/
|
|
8
|
-
"use strict";var e=require("http"),t=require("https"),r=require("fs"),n=require("net"),s=require("path"),i=require("crypto"),o=require("child_process"),a=require("events"),c=require("tls"),l=require("stream"),u=require("url"),f=require("zlib"),h=require("buffer");function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=p(e),m=p(t),y=p(r),_=p(n),v=p(s),g=p(i),b=p(o),w=p(a),E=p(c),S=p(l),x=p(u),k=p(f),T=p(h);function P(e){return P="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},P(e)}function C(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function O(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,D(n.key),n)}}function N(e,t,r){return t&&O(e.prototype,t),r&&O(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function I(e,t,r){return(t=D(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function A(e){return A=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},A(e)}function L(e,t){return L=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},L(e,t)}function R(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function F(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,n=A(e);if(t){var s=A(this).constructor;r=Reflect.construct(n,arguments,s)}else r=n.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return R(e)}(this,r)}}function M(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,s,i,o,a=[],c=!0,l=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){l=!0,s=e}finally{try{if(!c&&null!=r.return&&(o=r.return(),Object(o)!==o))return}finally{if(l)throw s}}return a}}(e,t)||B(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function U(e){return function(e){if(Array.isArray(e))return W(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||B(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function B(e,t){if(e){if("string"==typeof e)return W(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?W(e,t):void 0}}function W(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function j(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=B(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,s=function(){};return{s:s,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return o=e.done,e},e:function(e){a=!0,i=e},f:function(){try{o||null==r.return||r.return()}finally{if(a)throw i}}}}function D(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}var q="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function K(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var $={},G={};Object.defineProperty(G,"__esModule",{value:!0}),G.promisify=z;var V="__ES6-PROMISIFY--CUSTOM-ARGUMENTS__";function z(e){if("function"!=typeof e)throw new TypeError("Argument to promisify must be a function");var t=e[V],r=z.Promise||Promise;if("function"!=typeof r)throw new Error("No Promise implementation found; do you need a polyfill?");return function(){for(var n=this,s=arguments.length,i=new Array(s),o=0;o<s;o++)i[o]=arguments[o];return new r((function(r,s){i.push((function(e){if(e)return s(e);for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];if(1===i.length||!t)return r(i[0]);var a={};i.forEach((function(e,r){var n=t[r];n&&(a[n]=e)})),r(a)})),e.apply(n,i)}))}}z.argumentNames=V,z.Promise=void 0;var Y={exports:{}},H="win32"===process.platform,J=H?/[^:]\\$/:/.\/$/,X=function(){var e;return e=H?process.env.TEMP||process.env.TMP||(process.env.SystemRoot||process.env.windir)+"\\temp":process.env.TMPDIR||process.env.TMP||process.env.TEMP||"/tmp",J.test(e)&&(e=e.slice(0,-1)),e};!function(e){var t=v.default,r=y.default,n=g.default,s=X,i=process.env.PEMJS_TMPDIR||s();e.exports.isNumber=function(e){return!Array.isArray(e)&&/^\d+$/g.test(e)},e.exports.isHex=function(e){return/^(0x){0,1}([0-9A-F]{1,40}|[0-9A-F]{1,40})$/gi.test(e)},e.exports.toHex=function(e){for(var t="",r=0;r<e.length;r++)t+=""+e.charCodeAt(r).toString(16);return t},e.exports.ciphers=["aes128","aes192","aes256","camellia128","camellia192","camellia256","des","des3","idea"];var o=e.exports.ciphers;e.exports.createPasswordFile=function(e,s,a){if(!(e&&Object.prototype.hasOwnProperty.call(e,"password")&&Object.prototype.hasOwnProperty.call(e,"passType")&&/^(word|in|out)$/.test(e.passType)))return!1;var c=t.join(i,n.randomBytes(20).toString("hex"));return a.push(c),e.password=e.password.trim(),""===e.password&&(e.mustPass=!0),e.cipher&&-1!==o.indexOf(e.cipher)&&s.push("-"+e.cipher),s.push("-pass"+e.passType),e.mustPass?s.push("pass:"+e.password):(r.writeFileSync(c,e.password),s.push("file:"+c)),!0},e.exports.deleteTempFiles=function(e,t){var n=[];if("string"==typeof e)n.push(e);else{if(!Array.isArray(e))return t(new Error("Unexcepted files parameter type; only string or array supported"));n=e}var s=function(e,t){if(!e.length)return t(null);var n=e.shift();if(!n||"string"!=typeof n)return s(e,t);r.unlink(n,(function(r){return r&&"ENOENT"===r.code?s(e,t):r?t(r):s(e,t)}))};s(n,t)}}(Y);var Z=te;te.sync=function(e,t){return ee(Q.statSync(e),e,t)};var Q=y.default;function ee(e,t,r){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var r=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!r)return!0;if(-1!==(r=r.split(";")).indexOf(""))return!0;for(var n=0;n<r.length;n++){var s=r[n].toLowerCase();if(s&&e.substr(-s.length).toLowerCase()===s)return!0}return!1}(t,r)}function te(e,t,r){Q.stat(e,(function(n,s){r(n,!n&&ee(s,e,t))}))}var re=ie;ie.sync=function(e,t){return oe(se.statSync(e),t)};var ne,se=y.default;function ie(e,t,r){se.stat(e,(function(e,n){r(e,!e&&oe(n,t))}))}function oe(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,s=e.gid,i=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),o=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),l=parseInt("001",8),u=a|c;return r&l||r&c&&s===o||r&a&&n===i||r&u&&0===i}(e,t)}ne="win32"===process.platform||q.TESTING_WINDOWS?Z:re;var ae=ce;function ce(e,t,r){if("function"==typeof t&&(r=t,t={}),!r){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise((function(r,n){ce(e,t||{},(function(e,t){e?n(e):r(t)}))}))}ne(e,t||{},(function(e,n){e&&("EACCES"===e.code||t&&t.ignoreErrors)&&(e=null,n=!1),r(e,n)}))}ce.sync=function(e,t){try{return ne.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||"EACCES"===e.code)return!1;throw e}};const le="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,ue=v.default,fe=le?";":":",he=ae,pe=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),de=(e,t)=>{const r=t.colon||fe,n=e.match(/\//)||le&&e.match(/\\/)?[""]:[...le?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],s=le?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=le?s.split(r):[""];return le&&-1!==e.indexOf(".")&&""!==i[0]&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:s}},me=(e,t,r)=>{"function"==typeof t&&(r=t,t={}),t||(t={});const{pathEnv:n,pathExt:s,pathExtExe:i}=de(e,t),o=[],a=r=>new Promise(((s,i)=>{if(r===n.length)return t.all&&o.length?s(o):i(pe(e));const a=n[r],l=/^".*"$/.test(a)?a.slice(1,-1):a,u=ue.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(c(f,r,0))})),c=(e,r,n)=>new Promise(((l,u)=>{if(n===s.length)return l(a(r+1));const f=s[n];he(e+f,{pathExt:i},((s,i)=>{if(!s&&i){if(!t.all)return l(e+f);o.push(e+f)}return l(c(e,r,n+1))}))}));return r?a(0).then((e=>r(null,e)),r):a(0)};var ye=me;me.sync=(e,t)=>{t=t||{};const{pathEnv:r,pathExt:n,pathExtExe:s}=de(e,t),i=[];for(let o=0;o<r.length;o++){const a=r[o],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=ue.join(c,e),u=!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+l:l;for(let e=0;e<n.length;e++){const r=u+n[e];try{if(he.sync(r,{pathExt:s})){if(!t.all)return r;i.push(r)}}catch(e){}}}if(t.all&&i.length)return i;if(t.nothrow)return null;throw pe(e)};var _e=Y.exports,ve=b.default.spawn,ge=v.default,be=y.default,we=X,Ee=g.default,Se=ye,xe={},ke=process.env.PEMJS_TMPDIR||we();function Te(e,t){xe[e]=t}function Pe(e){return xe[e]||null}function Ce(e,t,r){var n=Pe("pathOpenSSL")||process.env.OPENSSL_BIN||"openssl";!function(e,t){Se(e,(function(r){if(r)return t(new Error("Could not find openssl on your system on this path: "+e));t()}))}(n,(function(s){if(s)return r(s);var i=ve(n,e),o="",a=t?Buffer.alloc(0):"";i.stdout.on("data",(function(e){t?a=Buffer.concat([a,e]):a+=e.toString("binary")})),i.stderr.on("data",(function(e){o+=e.toString("binary")}));var c=2,l=-1,u=!1,f=function(t){if(!u)return t?(u=!0,r(t)):--c<1?(u=!0,l&&(2!==l||""!==o&&!/depth lookup: unable to/.test(o))?r(new Error("Invalid openssl exit code: "+l+"\n% openssl "+e.join(" ")+"\n"+o),l):r(null,l,a,o)):void 0};i.on("error",f),i.on("exit",(function(e){l=e,f()})),i.on("close",(function(){a=t?a:Buffer.from(a,"binary").toString("utf-8"),o=Buffer.from(o,"binary").toString("utf-8"),f()}))}))}function Oe(e,t,r,n){n||"function"!=typeof r||(n=r,r=!1);var s,i,o,a=[],c=[];if(t)for(t=[].concat(t),i=0;i<e.length;i++)"--TMPFILE--"===e[i]&&(s=ge.join(ke,Ee.randomBytes(20).toString("hex")),a.push({path:s,contents:t.shift()}),e[i]=s,c.push(s));for(i=0;i<a.length;i++)o=a[i],be.writeFileSync(o.path,o.contents);Ce(e,r,(function(e,t,r,s){_e.deleteTempFiles(c,(function(i){n(e||i,t,r,s)}))}))}Ce(["version"],!1,(function(e,t,r,n){var s=(String(r)+"\n"+String(n)+"\n"+String(e)).match(/^LibreSSL/i);Te("openSslVersion",(s&&s[0]?"LibreSSL":"openssl").toUpperCase())}));var Ne={exec:function(e,t,r,n){n||"function"!=typeof r||(n=r,r=!1),Oe(e,r,(function(e,r,s,i){var o,a;return e?n(e):(o=(o=s.match(new RegExp("\\-+BEGIN "+t+"\\-+$","m")))?o.index:-1,"EC PARAMETERS"===t&&(t="EC PRIVATE KEY"),a=(a=s.match(new RegExp("^\\-+END "+t+"\\-+","m")))?a.index+a[0].length:-1,o>=0&&a>=0?n(null,s.substring(o,a)):n(new Error(t+" not found from openssl output:\n---stdout---\n"+s+"\n---stderr---\n"+i+"\ncode: "+r)))}))},execBinary:function(e,t,r){r||"function"!=typeof t||(r=t,t=!1),Oe(e,t,!0,(function(e,t,n,s){return e?r(e):r(null,n)}))},spawn:Ce,spawnWrapper:Oe,set:Te,get:Pe},Ie={},Ae=Ne,Le=Y.exports;Ie.PEM2DER=function(e,t,r,n){n||"function"!=typeof r||(n=r,r="x509");var s=[r,"-outform","der","-in",e,"-out",t];Ae.spawnWrapper(s,!1,(function(e,t){e?n(e):n(null,0===t)}))},Ie.DER2PEM=function(e,t,r,n){n||"function"!=typeof r||(n=r,r="x509");var s=[r,"-inform","der","-in",e,"-out",t];Ae.spawnWrapper(s,!1,(function(e,t){e?n(e):n(null,0===t)}))},Ie.PEM2P7B=function(e,t,r){var n=["crl2pkcs7","-nocrl","-certfile",e.cert,"-out",t];e.ca&&(Array.isArray(e.ca)||(e.ca=[e.ca]),e.ca.forEach((function(e){n.push("-certfile"),n.push(e)}))),Ae.spawnWrapper(n,!1,(function(e,t){e?r(e):r(null,0===t)}))},Ie.P7B2PEM=function(e,t,r){var n=["pkcs7","-print_certs","-in",e,"-out",t];Ae.spawnWrapper(n,!1,(function(e,t){e?r(e):r(null,0===t)}))},Ie.PEM2PFX=function(e,t,r,n){var s=["pkcs12","-export","-out",t,"-inkey",e.key,"-in",e.cert];e.ca&&(Array.isArray(e.ca)||(e.ca=[e.ca]),e.ca.forEach((function(e){s.push("-certfile"),s.push(e)})));var i=[];Le.createPasswordFile({cipher:"",password:r,passType:"in"},s,i),Le.createPasswordFile({cipher:"",password:r,passType:"out"},s,i),Ae.spawnWrapper(s,!1,(function(e,t){Le.deleteTempFiles(i,(function(r){!function(e){e?n(e):n(null,0===t)}(e||r)}))}))},Ie.PFX2PEM=function(e,t,r,n){var s=["pkcs12","-in",e,"-out",t,"-nodes"],i=[];Le.createPasswordFile({cipher:"",password:r,passType:"in"},s,i),Le.createPasswordFile({cipher:"",password:r,passType:"out"},s,i),Ae.spawnWrapper(s,!1,(function(e,t){Le.deleteTempFiles(i,(function(r){!function(e){e?n(e):n(null,0===t)}(e||r)}))}))},Ie.P7B2PFX=function(e,t,r,n){var s=e.cert.replace(/\.[^.]+$/,".cer"),i=["pkcs7","-print_certs","-in",e.cert,"-out",s];Ae.spawnWrapper(i,!1,(function(i,o){if(i)n(i);else{var a=["pkcs12","-export","-in",s,"-inkey",e.key,"-out",t];e.ca&&(Array.isArray(e.ca)||(e.ca=[e.ca]),e.ca.forEach((function(e){a.push("-certfile"),a.push(e)})));var c=[s];Le.createPasswordFile({cipher:"",password:r,passType:"in"},a,c),Le.createPasswordFile({cipher:"",password:r,passType:"out"},a,c),Ae.spawnWrapper(a,!1,(function(e,t){Le.deleteTempFiles(c,(function(r){!function(e){e?n(e):n(null,0===t)}(e||r)}))}))}}))};const{promisify:Re}=G;var Fe=_.default,Me=Y.exports,Ue=Ne;$.createPrivateKey=Ve,$.createDhparam=ze,$.createEcparam=Ye,$.createCSR=He,$.createCertificate=Je,$.readCertificateInfo=Ze,$.getPublicKey=Xe,$.getFingerprint=tt,$.getModulus=Qe,$.getDhparamInfo=et,$.createPkcs12=rt,$.readPkcs12=nt,$.verifySigningChain=ot,$.checkCertificate=st,$.checkPkcs12=it,$.config=function(e){Object.keys(e).forEach((function(t){Ue.set(t,e[t])}))},$.convert=Ie;var Be="-----BEGIN PRIVATE KEY-----",We="-----END PRIVATE KEY-----",je="-----BEGIN RSA PRIVATE KEY-----",De="-----END RSA PRIVATE KEY-----",qe="-----BEGIN ENCRYPTED PRIVATE KEY-----",Ke="-----END ENCRYPTED PRIVATE KEY-----",$e="-----BEGIN CERTIFICATE-----",Ge="-----END CERTIFICATE-----";function Ve(e,t,r){r||t||"function"!=typeof e?!r&&e&&"function"==typeof t&&(r=t,t={}):(r=e,e=void 0,t={}),e=Number(e)||2048;var n=["genrsa"],s=[];t&&t.cipher&&-1!==Number(Me.ciphers.indexOf(t.cipher))&&t.password&&Me.createPasswordFile({cipher:t.cipher,password:t.password,passType:"out"},n,s),n.push(e),Ue.exec(n,"RSA PRIVATE KEY",(function(e,t){Me.deleteTempFiles(s,(function(n){!function(e){if(e)return r(e);r(null,{key:t})}(e||n)}))}))}function ze(e,t){t||"function"!=typeof e||(t=e,e=void 0);var r=["dhparam","-outform","PEM",e=Number(e)||512];Ue.exec(r,"DH PARAMETERS",(function(e,r){return e?t(e):t(null,{dhparam:r})}))}function Ye(e,t,r,n){n||void 0!==r||t||"function"!=typeof e?!n&&void 0===r&&e&&"function"==typeof t?(n=t,t=void 0):!n&&"function"==typeof r&&e&&t&&(n=r,r=void 0):(n=e,e=void 0);var s=["ecparam","-name",e=e||"secp256k1","-genkey","-param_enc",t=t||"explicit"],i="EC PARAMETERS";(r=r||!1)&&(s.push("-noout"),i="EC PRIVATE KEY"),Ue.exec(s,i,(function(e,t){return e?n(e):n(null,{ecparam:t})}))}function He(e,t){if(t||"function"!=typeof e||(t=e,e=void 0),(e=e||{}).commonName&&(Fe.isIPv4(e.commonName)||Fe.isIPv6(e.commonName))&&(e.altNames?-1===e.altNames.indexOf(e.commonName)&&(e.altNames=e.altNames.concat([e.commonName])):e.altNames=[e.commonName]),e.clientKey){var r=["req","-new","-"+(e.hash||"sha256")];e.csrConfigFile?(r.push("-config"),r.push(e.csrConfigFile)):(r.push("-subj"),r.push(function(e){e=e||{};var t={C:e.country||e.C,ST:e.state||e.ST,L:e.locality||e.L,O:e.organization||e.O,OU:e.organizationUnit||e.OU,CN:e.commonName||e.CN||"localhost",DC:e.dc||e.DC||"",emailAddress:e.emailAddress};return Object.keys(t).map((function(e){if(t[e]){if("object"==typeof t[e]&&t[e].length>=1){var r="";return t[e].map((function(t){r+="/"+e+"="+t.replace(/[^\w .*\-,@']+/g," ").trim()})),r}return"/"+e+"="+t[e].replace(/[^\w .*\-,@']+/g," ").trim()}})).join("")}(e))),r.push("-key"),r.push("--TMPFILE--");var n=[e.clientKey],s=null;if(e.altNames&&Array.isArray(e.altNames)&&e.altNames.length){r.push("-extensions"),r.push("v3_req"),r.push("-config"),r.push("--TMPFILE--");for(var i=[],o=0;o<e.altNames.length;o++)i.push((Fe.isIP(e.altNames[o])?"IP":"DNS")+"."+(o+1)+" = "+e.altNames[o]);n.push(s=["[req]","req_extensions = v3_req","distinguished_name = req_distinguished_name","[v3_req]","subjectAltName = @alt_names","[alt_names]",i.join("\n"),"[req_distinguished_name]","commonName = Common Name","commonName_max = 64"].join("\n"))}else e.config&&(s=e.config);var a=[];e.clientKeyPassword&&Me.createPasswordFile({cipher:"",password:e.clientKeyPassword,passType:"in"},r,a),Ue.exec(r,"CERTIFICATE REQUEST",n,(function(r,n){Me.deleteTempFiles(a,(function(i){!function(r){if(r)return t(r);t(null,{csr:n,config:s,clientKey:e.clientKey})}(r||i)}))}))}else Ve(e.keyBitsize||2048,(function(r,n){if(r)return t(r);e.clientKey=n.key,He(e,t)}))}function Je(e,t){if(t||"function"!=typeof e||(t=e,e=void 0),(e=e||{}).csr){if(e.clientKey||(e.clientKey=""),!e.serviceKey){if(!e.selfSigned)return void Ve(e.keyBitsize||2048,(function(r,n){if(r)return t(r);e.serviceKey=n.key,Je(e,t)}));e.serviceKey=e.clientKey}Ze(e.csr,(function(r,n){if(r)return t(r);var s=["x509","-req","-"+(e.hash||"sha256"),"-days",Number(e.days)||"365","-in","--TMPFILE--"],i=[e.csr],o=[];if(e.serviceCertificate?(s.push("-CA"),s.push("--TMPFILE--"),s.push("-CAkey"),s.push("--TMPFILE--"),e.serial?(s.push("-set_serial"),Me.isNumber(e.serial)?s.push("0x"+("0000000000000000000000000000000000000000"+e.serial.toString(16)).slice(-40)):Me.isHex(e.serial)?(e.serial.startsWith("0x")&&(e.serial=e.serial.substring(2,e.serial.length)),s.push("0x"+("0000000000000000000000000000000000000000"+e.serial).slice(-40))):s.push("0x"+("0000000000000000000000000000000000000000"+Me.toHex(e.serial)).slice(-40))):(s.push("-CAcreateserial"),e.serialFile&&(s.push("-CAserial"),s.push(e.serialFile+".srl"))),e.serviceKeyPassword&&Me.createPasswordFile({cipher:"",password:e.serviceKeyPassword,passType:"in"},s,o),i.push(e.serviceCertificate),i.push(e.serviceKey)):(s.push("-signkey"),s.push("--TMPFILE--"),e.serviceKeyPassword&&Me.createPasswordFile({cipher:"",password:e.serviceKeyPassword,passType:"in"},s,o),i.push(e.serviceKey)),e.config)s.push("-extensions"),s.push("v3_req"),s.push("-extfile"),s.push("--TMPFILE--"),i.push(e.config);else if(e.extFile)s.push("-extfile"),s.push(e.extFile);else{var a=[];if(n&&n.san){for(var c=0;c<n.san.dns.length;c++)a.push("DNS."+(c+1)+" = "+n.san.dns[c]);for(var l=0;l<n.san.ip.length;l++)a.push("IP."+(l+1)+" = "+n.san.ip[l]);for(var u=0;u<n.san.email.length;u++)a.push("email."+(u+1)+" = "+n.san.email[u]);s.push("-extensions"),s.push("v3_req"),s.push("-extfile"),s.push("--TMPFILE--"),i.push(["[v3_req]","subjectAltName = @alt_names","[alt_names]",a.join("\n")].join("\n"))}}e.clientKeyPassword&&Me.createPasswordFile({cipher:"",password:e.clientKeyPassword,passType:"in"},s,o),Ue.exec(s,"CERTIFICATE",i,(function(r,n){Me.deleteTempFiles(o,(function(s){!function(r){if(r)return t(r);var s={csr:e.csr,clientKey:e.clientKey,certificate:n,serviceKey:e.serviceKey};t(null,s)}(r||s)}))}))}))}else He(e,(function(r,n){if(r)return t(r);e.csr=n.csr,e.config=n.config,e.clientKey=n.clientKey,Je(e,t)}))}function Xe(e,t){var r;t||"function"!=typeof e||(t=e,e=void 0),r=(e=(e||"").toString()).match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)?["req","-in","--TMPFILE--","-pubkey","-noout"]:e.match(/BEGIN RSA PRIVATE KEY/)||e.match(/BEGIN PRIVATE KEY/)?["rsa","-in","--TMPFILE--","-pubout"]:["x509","-in","--TMPFILE--","-pubkey","-noout"],Ue.exec(r,"PUBLIC KEY",e,(function(e,r){return e?t(e):t(null,{publicKey:r})}))}function Ze(e,t){t||"function"!=typeof e||(t=e,e=void 0);var r=[(e=(e||"").toString()).match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)?"req":"x509","-noout","-nameopt","RFC2253,sep_multiline,space_eq,-esc_msb,utf8","-text","-in","--TMPFILE--"];Ue.spawnWrapper(r,e,(function(e,r,n,s){return e?t(e):s?t(s):function(e,t){try{var r,n,s,i;e=(e||"").toString();var o,a,c,l={issuer:{}},u={};if((r=e.match(/\s*Serial Number:\r?\n?\s*([^\r\n]*)\r?\n\s*\b/))&&r.length>1&&(l.serial=r[1]),(n=e.match(/\s*Subject:\r?\n(\s*(([a-zA-Z0-9.]+)\s=\s[^\r\n]+\r?\n))*\s*\b/))&&n.length>1){if(s=at(n=n[0],/\s([a-zA-Z0-9.]+)\s=\s([^\r\n].*)/g))for(c=0;c<s.length;c++)(a=s[c][1].trim()).match("(C|ST|L|O|OU|CN|emailAddress|DC)")||""===a||(l[a]=s[c][2].trim());s=n.match(/\sC\s=\s([^\r\n].*?)[\r\n]/),l.country=s&&s[1]||"",s=n.match(/\sST\s=\s([^\r\n].*?)[\r\n]/),l.state=s&&s[1]||"",s=n.match(/\sL\s=\s([^\r\n].*?)[\r\n]/),l.locality=s&&s[1]||"",s=at(n,/\sO\s=\s([^\r\n].*)/g),l.organization=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(n,/\sOU\s=\s([^\r\n].*)/g),l.organizationUnit=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(n,/\sCN\s=\s([^\r\n].*)/g),l.commonName=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(n,/emailAddress\s=\s([^\r\n].*)/g),l.emailAddress=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(n,/\sDC\s=\s([^\r\n].*)/g),l.dc=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:""}if((i=e.match(/\s*Issuer:\r?\n(\s*([a-zA-Z0-9.]+)\s=\s[^\r\n].*\r?\n)*\s*\b/))&&i.length>1){for(s=at(i=i[0],/\s([a-zA-Z0-9.]+)\s=\s([^\r\n].*)/g),c=0;c<s.length;c++)(a=s[c][1].toString()).match("(C|ST|L|O|OU|CN|emailAddress|DC)")||(l.issuer[a]=s[c][2].toString());s=i.match(/\sC\s=\s([^\r\n].*?)[\r\n]/),l.issuer.country=s&&s[1]||"",s=i.match(/\sST\s=\s([^\r\n].*?)[\r\n]/),l.issuer.state=s&&s[1]||"",s=i.match(/\sL\s=\s([^\r\n].*?)[\r\n]/),l.issuer.locality=s&&s[1]||"",s=at(i,/\sO\s=\s([^\r\n].*)/g),l.issuer.organization=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(i,/\sOU\s=\s([^\r\n].*)/g),l.issuer.organizationUnit=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(i,/\sCN\s=\s([^\r\n].*)/g),l.issuer.commonName=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(i,/\sDC\s=\s([^\r\n].*)/g),l.issuer.dc=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:""}(o=e.match(/X509v3 Subject Alternative Name: \r?\n([^\r\n]*)\r?\n/))&&o.length>1&&(o=o[1].trim()+"\n",l.san={},s=ct("DNS:([^,\\r\\n].*?)[,\\r\\n\\s]",o),l.san.dns=s||"",s=ct("IP Address:([^,\\r\\n].*?)[,\\r\\n\\s]",o),l.san.ip=s||"",s=ct("email:([^,\\r\\n].*?)[,\\r\\n\\s]",o),l.san.email=s||""),(s=e.match(/Not Before\s?:\s?([^\r\n]*)\r?\n/))&&s.length>1&&(u.start=Date.parse(s&&s[1]||"")),(s=e.match(/Not After\s?:\s?([^\r\n]*)\r?\n/))&&s.length>1&&(u.end=Date.parse(s&&s[1]||"")),u.start&&u.end&&(l.validity=u),(s=e.match(/Signature Algorithm: ([^\r\n]*)\r?\n/))&&s.length>1&&(l.signatureAlgorithm=s&&s[1]||""),(s=e.match(/Public[ -]Key: ([^\r\n]*)\r?\n/))&&s.length>1&&(l.publicKeySize=(s&&s[1]||"").replace(/[()]/g,"")),(s=e.match(/Public Key Algorithm: ([^\r\n]*)\r?\n/))&&s.length>1&&(l.publicKeyAlgorithm=s&&s[1]||""),t(null,l)}catch(e){t(e)}}(n,t)}))}function Qe(e,t,r,n){n||r||"function"!=typeof t?!n&&r&&"function"==typeof r&&(n=r,r=!1):(n=t,t=void 0,r=!1),r&&"md5"!==r&&(r=!1);var s=[(e=Buffer.isBuffer(e)&&e.toString()||e).match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)?"req":e.match(/BEGIN RSA PRIVATE KEY/)||e.match(/BEGIN PRIVATE KEY/)?"rsa":"x509","-noout","-modulus","-in","--TMPFILE--"],i=[];t&&Me.createPasswordFile({cipher:"",password:t,passType:"in"},s,i),Ue.spawnWrapper(s,e,(function(e,t,s,o){Me.deleteTempFiles(i,(function(t){!function(e){if(e)return n(e);var t=s.match(/Modulus=([0-9a-fA-F]+)$/m);t?n(null,{modulus:r?K(r)(t[1]):t[1]}):n(new Error("No modulus"))}(e||t||o)}))}))}function et(e,t){e=Buffer.isBuffer(e)&&e.toString()||e;Ue.spawnWrapper(["dhparam","-text","-in","--TMPFILE--"],e,(function(e,r,n,s){if(e)return t(e);if(s)return t(s);var i={},o=n.match(/Parameters: \((\d+) bit\)/);o&&(i.size=Number(o[1]));var a="";return n.split("\n").forEach((function(e){/\s+([0-9a-f][0-9a-f]:)+[0-9a-f]?[0-9a-f]?/g.test(e)&&(a+=e.trim())})),a&&(i.prime=a),o||a?t(null,i):t(new Error("No DH info found"))}))}function tt(e,t,r){r||"function"!=typeof t||(r=t,t=void 0);var n=["x509","-in","--TMPFILE--","-fingerprint","-noout","-"+(t=t||"sha1")];Ue.spawnWrapper(n,e,(function(e,t,n,s){if(e)return r(e);if(s)return r(s);var i=n.match(/Fingerprint=([0-9a-fA-F:]+)$/m);return i?r(null,{fingerprint:i[1]}):r(new Error("No fingerprint"))}))}function rt(e,t,r,n,s){s||"function"!=typeof n||(s=n,n={});var i=["pkcs12","-export"],o=[];n.cipher&&n.clientKeyPassword&&Me.createPasswordFile({cipher:n.cipher,password:n.clientKeyPassword,passType:"in"},i,o),Me.createPasswordFile({cipher:"",password:r,passType:"word"},i,o),i.push("-in"),i.push("--TMPFILE--"),i.push("-inkey"),i.push("--TMPFILE--");var a=[t,e];n.certFiles&&(a.push(n.certFiles.join("")),i.push("-certfile"),i.push("--TMPFILE--")),Ue.execBinary(i,a,(function(e,t){Me.deleteTempFiles(o,(function(r){var n;(n=e||r)?s(n):s(null,{pkcs12:t})}))}))}function nt(e,t,r){r||"function"!=typeof t||(r=t,t={}),t.p12Password=t.p12Password||"";var n=[],s=[],i=["pkcs12","-in",e];Me.createPasswordFile({cipher:"",password:t.p12Password,passType:"in"},i,s),Buffer.isBuffer(e)&&(n=[e],i[2]="--TMPFILE--"),t.clientKeyPassword?Me.createPasswordFile({cipher:"",password:t.clientKeyPassword,passType:"out"},i,s):i.push("-nodes"),Ue.execBinary(i,n,(function(e,n){Me.deleteTempFiles(s,(function(s){!function(e){var s={};if(e&&-1!==e.message.indexOf("No such file or directory")&&(e.code="ENOENT"),!e){var i=lt(n,$e,Ge);if(s.cert=i.shift(),s.ca=i,s.key=lt(n,Be,We).pop(),s.key)return Ue.exec(["rsa","-in","--TMPFILE--"],"RSA PRIVATE KEY",[s.key],(function(e,t){return s.key=t,r(e,s)}));t.clientKeyPassword?s.key=lt(n,qe,Ke).pop():s.key=lt(n,je,De).pop()}r(e,s)}(e||s)}))}))}function st(e,t,r){var n,s=[];r||"function"!=typeof t||(r=t,t=void 0),e=(e||"").toString(),n=e.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)?["req","-text","-noout","-verify","-in","--TMPFILE--"]:e.match(/BEGIN RSA PRIVATE KEY/)||e.match(/BEGIN PRIVATE KEY/)?["rsa","-noout","-check","-in","--TMPFILE--"]:["x509","-text","-noout","-in","--TMPFILE--"],t&&Me.createPasswordFile({cipher:"",password:t,passType:"in"},n,s),Ue.spawnWrapper(n,e,(function(e,t,i,o){Me.deleteTempFiles(s,(function(t){!function(e){if(e&&"verify OK"!==e.toString().trim())return r(e);var t;t="rsa"===n[0]?/^Rsa key ok$/i.test(i.trim()):/Signature Algorithm/im.test(i);r(null,t)}(e||t||o)}))}))}function it(e,t,r){r||"function"!=typeof t||(r=t,t="");var n=[],s=[],i=["pkcs12","-info","-in",e,"-noout","-maciter","-nodes"];Me.createPasswordFile({cipher:"",password:t,passType:"in"},i,s),Buffer.isBuffer(e)&&(n=[e],i[3]="--TMPFILE--"),Ue.spawnWrapper(i,n,(function(e,t,n,i){Me.deleteTempFiles(s,(function(t){!function(e){if(e)return r(e);r(null,/MAC verified OK/im.test(i)||!/MAC verified OK/im.test(i)&&!/Mac verify error/im.test(i))}(e||t)}))}))}function ot(e,t,r){r||"function"!=typeof t||(r=t,t=void 0),Array.isArray(e)||(e=[e]),Array.isArray(t)||void 0===t||""!==t&&(t=[t]);var n=[];void 0!==t&&n.push(t.join("\n")),n.push(e.join("\n"));var s=["verify"];void 0!==t&&(s.push("-CAfile"),s.push("--TMPFILE--")),s.push("--TMPFILE--"),Ue.spawnWrapper(s,n,(function(e,t,n,s){if(e)return r(e);r(null,": OK"===n.trim().slice(-4))}))}function at(e,t){var r=[];return e.replace(t,(function(){var e=[].slice.call(arguments,0),t=e.splice(-2);e.index=t[0],e.input=t[1],r.push(e)})),r.length?r:null}function ct(e,t){for(var r,n,s=new RegExp(e,"g"),i=t.match(s)||[],o=[],a=0;a<i.length;a++)r=new RegExp(e),n=i[a].match(r),o.push(n[1]);return o}function lt(e,t,r){Buffer.isBuffer(e)&&(e=e.toString("utf8"));var n=[];if(!e)return n;for(var s=e.indexOf(t);-1!==s;){var i=(e=e.substring(s)).indexOf(r);if(-1===i)break;i+=r.length,n.push(e.substring(0,i)),s=e.indexOf(t,i)}return n}$.promisified={createPrivateKey:Re(Ve),createDhparam:Re(ze),createEcparam:Re(Ye),createCSR:Re(He),createCertificate:Re(Je),readCertificateInfo:Re(Ze),getPublicKey:Re(Xe),getFingerprint:Re(tt),getModulus:Re(Qe),getDhparamInfo:Re(et),createPkcs12:Re(rt),readPkcs12:Re(nt),verifySigningChain:Re(ot),checkCertificate:Re(st),checkPkcs12:Re(it)};var ut={exports:{}};
|
|
9
|
-
/*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */!function(e,t){!function(r){var n=t,s=e&&e.exports==n&&e,i="object"==typeof q&&q;i.global!==i&&i.window!==i||(r=i);var o=function(e){this.message=e};(o.prototype=new Error).name="InvalidCharacterError";var a=function(e){throw new o(e)},c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=/[\t\n\f\r ]/g,u={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&a("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,n,s,i=e.length%3,o="",l=-1,u=e.length-i;++l<u;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,n=e.charCodeAt(++l),o+=c.charAt((s=t+r+n)>>18&63)+c.charAt(s>>12&63)+c.charAt(s>>6&63)+c.charAt(63&s);return 2==i?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),o+=c.charAt((s=t+r)>>10)+c.charAt(s>>4&63)+c.charAt(s<<2&63)+"="):1==i&&(s=e.charCodeAt(l),o+=c.charAt(s>>2)+c.charAt(s<<4&63)+"=="),o},decode:function(e){var t=(e=String(e).replace(l,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&a("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,s=0,i="",o=-1;++o<t;)n=c.indexOf(e.charAt(o)),r=s%4?64*r+n:n,s++%4&&(i+=String.fromCharCode(255&r>>(-2*s&6)));return i},version:"1.0.0"};if(n&&!n.nodeType)if(s)s.exports=u;else for(var f in u)u.hasOwnProperty(f)&&(n[f]=u[f]);else r.base64=u}(q)}(ut,ut.exports);var ft={exports:{}},ht={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:pt}=ht,dt=Buffer[Symbol.species];function mt(e,t,r,n,s){for(let i=0;i<s;i++)r[n+i]=e[i]^t[3&i]}function yt(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(ft.exports={concat:function(e,t){if(0===e.length)return pt;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let n=0;for(let t=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return n<t?new dt(r.buffer,r.byteOffset,n):r},mask:mt,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let r;return t instanceof ArrayBuffer?r=new dt(t):ArrayBuffer.isView(t)?r=new dt(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:yt},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");ft.exports.mask=function(t,r,n,s,i){i<48?mt(t,r,n,s,i):e.mask(t,r,n,s,i)},ft.exports.unmask=function(t,r){t.length<32?yt(t,r):e.unmask(t,r)}}catch(e){}const _t=Symbol("kDone"),vt=Symbol("kRun");var gt=class{constructor(e){this[_t]=()=>{this.pending--,this[vt]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[vt]()}[vt](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[_t])}}};const bt=k.default,wt=ft.exports,Et=gt,{kStatusCode:St}=ht,xt=Buffer[Symbol.species],kt=Buffer.from([0,0,255,255]),Tt=Symbol("permessage-deflate"),Pt=Symbol("total-length"),Ct=Symbol("callback"),Ot=Symbol("buffers"),Nt=Symbol("error");let It;var At=class{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!It){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;It=new Et(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[Ct];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,r){It.add((n=>{this._decompress(e,t,((e,t)=>{n(),r(e,t)}))}))}compress(e,t,r){It.add((n=>{this._compress(e,t,((e,t)=>{n(),r(e,t)}))}))}_decompress(e,t,r){const n=this._isServer?"client":"server";if(!this._inflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?bt.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=bt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Tt]=this,this._inflate[Pt]=0,this._inflate[Ot]=[],this._inflate.on("error",Ft),this._inflate.on("data",Rt)}this._inflate[Ct]=r,this._inflate.write(e),t&&this._inflate.write(kt),this._inflate.flush((()=>{const e=this._inflate[Nt];if(e)return this._inflate.close(),this._inflate=null,void r(e);const s=wt.concat(this._inflate[Ot],this._inflate[Pt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Pt]=0,this._inflate[Ot]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),r(null,s)}))}_compress(e,t,r){const n=this._isServer?"server":"client";if(!this._deflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?bt.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=bt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[Pt]=0,this._deflate[Ot]=[],this._deflate.on("data",Lt)}this._deflate[Ct]=r,this._deflate.write(e),this._deflate.flush(bt.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=wt.concat(this._deflate[Ot],this._deflate[Pt]);t&&(e=new xt(e.buffer,e.byteOffset,e.length-4)),this._deflate[Ct]=null,this._deflate[Pt]=0,this._deflate[Ot]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function Lt(e){this[Ot].push(e),this[Pt]+=e.length}function Rt(e){this[Pt]+=e.length,this[Tt]._maxPayload<1||this[Pt]<=this[Tt]._maxPayload?this[Ot].push(e):(this[Nt]=new RangeError("Max payload size exceeded"),this[Nt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Nt][St]=1009,this.removeListener("data",Rt),this.reset())}function Ft(e){this[Tt]._inflate=null,e[St]=1007,this[Ct](e)}var Mt={exports:{}};const{isUtf8:Ut}=T.default;function Bt(e){const t=e.length;let r=0;for(;r<t;)if(0==(128&e[r]))r++;else if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0}if(Mt.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:Bt,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},Ut)Mt.exports.isValidUTF8=function(e){return e.length<24?Bt(e):Ut(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Mt.exports.isValidUTF8=function(t){return t.length<32?Bt(t):e(t)}}catch(e){}const{Writable:Wt}=S.default,jt=At,{BINARY_TYPES:Dt,EMPTY_BUFFER:qt,kStatusCode:Kt,kWebSocket:$t}=ht,{concat:Gt,toArrayBuffer:Vt,unmask:zt}=ft.exports,{isValidStatusCode:Yt,isValidUTF8:Ht}=Mt.exports,Jt=Buffer[Symbol.species];var Xt=class extends Wt{constructor(e={}){super(),this._binaryType=e.binaryType||Dt[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[$t]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._state=0,this._loop=!1}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new Jt(t.buffer,t.byteOffset+e,t.length-e),new Jt(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new Jt(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){let t;this._loop=!0;do{switch(this._state){case 0:t=this.getInfo();break;case 1:t=this.getPayloadLength16();break;case 2:t=this.getPayloadLength64();break;case 3:this.getMask();break;case 4:t=this.getData(e);break;default:return void(this._loop=!1)}}while(this._loop);e(t)}getInfo(){if(this._bufferedBytes<2)return void(this._loop=!1);const e=this.consume(2);if(0!=(48&e[0]))return this._loop=!1,Zt(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");const t=64==(64&e[0]);if(t&&!this._extensions[jt.extensionName])return this._loop=!1,Zt(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._fin=128==(128&e[0]),this._opcode=15&e[0],this._payloadLength=127&e[1],0===this._opcode){if(t)return this._loop=!1,Zt(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Zt(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return this._loop=!1,Zt(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");this._compressed=t}else{if(!(this._opcode>7&&this._opcode<11))return this._loop=!1,Zt(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Zt(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Zt(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return this._loop=!1,Zt(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH")}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=128==(128&e[1]),this._isServer){if(!this._masked)return this._loop=!1,Zt(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Zt(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");if(126===this._payloadLength)this._state=1;else{if(127!==this._payloadLength)return this.haveLength();this._state=2}}getPayloadLength16(){if(!(this._bufferedBytes<2))return this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength();this._loop=!1}getPayloadLength64(){if(this._bufferedBytes<8)return void(this._loop=!1);const e=this.consume(8),t=e.readUInt32BE(0);return t>Math.pow(2,21)-1?(this._loop=!1,Zt(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=t*Math.pow(2,32)+e.readUInt32BE(4),this.haveLength())}haveLength(){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0))return this._loop=!1,Zt(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=qt;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!=(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&zt(t,this._mask)}return this._opcode>7?this.controlMessage(t):this._compressed?(this._state=5,void this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage())}decompress(e,t){this._extensions[jt.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return t(Zt(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const n=this.dataMessage();if(n)return t(n);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?Gt(t,e):"arraybuffer"===this._binaryType?Vt(Gt(t,e)):t,this.emit("message",r,!0)}else{const r=Gt(t,e);if(!this._skipUTF8Validation&&!Ht(r))return this._loop=!1,Zt(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("message",r,!1)}}this._state=0}controlMessage(e){if(8===this._opcode)if(this._loop=!1,0===e.length)this.emit("conclude",1005,qt),this.end();else{const t=e.readUInt16BE(0);if(!Yt(t))return Zt(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=new Jt(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ht(r))return Zt(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("conclude",t,r),this.end()}else 9===this._opcode?this.emit("ping",e):this.emit("pong",e);this._state=0}};function Zt(e,t,r,n,s){const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,Zt),i.code=s,i[Kt]=n,i}const{randomFillSync:Qt}=g.default,er=At,{EMPTY_BUFFER:tr}=ht,{isValidStatusCode:rr}=Mt.exports,{mask:nr,toBuffer:sr}=ft.exports,ir=Symbol("kByteLength"),or=Buffer.alloc(4);class ar{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let r,n,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||or,t.generateMask?t.generateMask(r):Qt(r,0,4),o=0==(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?n=t.mask&&!o||void 0===t[ir]?(e=Buffer.from(e)).length:t[ir]:(n=e.length,s=t.mask&&t.readOnly&&!o);let a=n;n>=65536?(i+=8,a=127):n>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(s?n+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(n,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(n,4,6)),t.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(nr(e,r,c,i,n),[c]):(nr(e,r,e,0,n),[c,e])):[c,e]}close(e,t,r,n){let s;if(void 0===e)s=tr;else{if("number"!=typeof e||!rr(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+r),s.writeUInt16BE(e,0),"string"==typeof t?s.write(t,2):s.set(t,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0)}const i={[ir]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,s,!1,i,n]):this.sendFrame(ar.frame(s,i),n)}ping(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=sr(e)).length,s=sr.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[ir]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(ar.frame(e,i),r)}pong(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=sr(e)).length,s=sr.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[ir]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(ar.frame(e,i),r)}send(e,t,r){const n=this._extensions[er.extensionName];let s,i,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=sr(e)).length,i=sr.readOnly),this._firstFragment?(this._firstFragment=!1,a&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=n._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),n){const n={[ir]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:a};this._deflating?this.enqueue([this.dispatch,e,this._compress,n,r]):this.dispatch(e,this._compress,n,r)}else this.sendFrame(ar.frame(e,{[ir]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:!1}),r)}dispatch(e,t,r,n){if(!t)return void this.sendFrame(ar.frame(e,r),n);const s=this._extensions[er.extensionName];this._bufferedBytes+=r[ir],this._deflating=!0,s.compress(e,r.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof n&&n(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],n=r[r.length-1];"function"==typeof n&&n(e)}}else this._bufferedBytes-=r[ir],this._deflating=!1,r.readOnly=!1,this.sendFrame(ar.frame(t,r),n),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][ir],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ir],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}var cr=ar;const{kForOnEventAttribute:lr,kListener:ur}=ht,fr=Symbol("kCode"),hr=Symbol("kData"),pr=Symbol("kError"),dr=Symbol("kMessage"),mr=Symbol("kReason"),yr=Symbol("kTarget"),_r=Symbol("kType"),vr=Symbol("kWasClean");class gr{constructor(e){this[yr]=null,this[_r]=e}get target(){return this[yr]}get type(){return this[_r]}}Object.defineProperty(gr.prototype,"target",{enumerable:!0}),Object.defineProperty(gr.prototype,"type",{enumerable:!0});class br extends gr{constructor(e,t={}){super(e),this[fr]=void 0===t.code?0:t.code,this[mr]=void 0===t.reason?"":t.reason,this[vr]=void 0!==t.wasClean&&t.wasClean}get code(){return this[fr]}get reason(){return this[mr]}get wasClean(){return this[vr]}}Object.defineProperty(br.prototype,"code",{enumerable:!0}),Object.defineProperty(br.prototype,"reason",{enumerable:!0}),Object.defineProperty(br.prototype,"wasClean",{enumerable:!0});class wr extends gr{constructor(e,t={}){super(e),this[pr]=void 0===t.error?null:t.error,this[dr]=void 0===t.message?"":t.message}get error(){return this[pr]}get message(){return this[dr]}}Object.defineProperty(wr.prototype,"error",{enumerable:!0}),Object.defineProperty(wr.prototype,"message",{enumerable:!0});class Er extends gr{constructor(e,t={}){super(e),this[hr]=void 0===t.data?null:t.data}get data(){return this[hr]}}Object.defineProperty(Er.prototype,"data",{enumerable:!0});const Sr={addEventListener(e,t,r={}){for(const n of this.listeners(e))if(!r[lr]&&n[ur]===t&&!n[lr])return;let n;if("message"===e)n=function(e,r){const n=new Er("message",{data:r?e:e.toString()});n[yr]=this,kr(t,this,n)};else if("close"===e)n=function(e,r){const n=new br("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[yr]=this,kr(t,this,n)};else if("error"===e)n=function(e){const r=new wr("error",{error:e,message:e.message});r[yr]=this,kr(t,this,r)};else{if("open"!==e)return;n=function(){const e=new gr("open");e[yr]=this,kr(t,this,e)}}n[lr]=!!r[lr],n[ur]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[ur]===t&&!r[lr]){this.removeListener(e,r);break}}};var xr={CloseEvent:br,ErrorEvent:wr,Event:gr,EventTarget:Sr,MessageEvent:Er};function kr(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:Tr}=Mt.exports;function Pr(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var Cr={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let r,n,s=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,u=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===u&&1===Tr[l])-1===c&&(c=f);else if(0===f||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===u&&(u=f);const n=e.slice(c,u);44===l?(Pr(t,n,s),s=Object.create(null)):r=n,c=u=-1}}else-1===u&&-1!==c&&(u=f);else if(void 0===n)if(-1===u&&1===Tr[l])-1===c&&(c=f);else if(32===l||9===l)-1===u&&-1!==c&&(u=f);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===u&&(u=f),Pr(s,e.slice(c,u),!0),44===l&&(Pr(t,r,s),s=Object.create(null),r=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${f}`);n=e.slice(c,f),c=u=-1}else if(o){if(1!==Tr[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:i||(i=!0),o=!1}else if(a)if(1===Tr[l])-1===c&&(c=f);else if(34===l&&-1!==c)a=!1,u=f;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${f}`);o=!0}else if(34===l&&61===e.charCodeAt(f-1))a=!0;else if(-1===u&&1===Tr[l])-1===c&&(c=f);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===u&&(u=f);let o=e.slice(c,u);i&&(o=o.replace(/\\/g,""),i=!1),Pr(s,n,o),44===l&&(Pr(t,r,s),s=Object.create(null),r=void 0),n=void 0,c=u=-1}}else-1===u&&(u=f);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===u&&(u=f);const h=e.slice(c,u);return void 0===r?Pr(t,h,s):(void 0===n?Pr(s,h,!0):Pr(s,n,i?h.replace(/\\/g,""):h),Pr(t,r,s)),t}};const Or=w.default,Nr=m.default,Ir=d.default,Ar=_.default,Lr=E.default,{randomBytes:Rr,createHash:Fr}=g.default,{URL:Mr}=x.default,Ur=At,Br=Xt,Wr=cr,{BINARY_TYPES:jr,EMPTY_BUFFER:Dr,GUID:qr,kForOnEventAttribute:Kr,kListener:$r,kStatusCode:Gr,kWebSocket:Vr,NOOP:zr}=ht,{EventTarget:{addEventListener:Yr,removeEventListener:Hr}}=xr,{format:Jr,parse:Xr}=Cr,{toBuffer:Zr}=ft.exports,Qr=Symbol("kAborted"),en=[8,13],tn=["CONNECTING","OPEN","CLOSING","CLOSED"],rn=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class nn extends Or{constructor(e,t,r){super(),this._binaryType=jr[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Dr,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=nn.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),on(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){jr.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const n=new Br({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new Wr(e,this._extensions,r.generateMask),this._receiver=n,this._socket=e,n[Vr]=this,e[Vr]=this,n.on("conclude",hn),n.on("drain",pn),n.on("error",dn),n.on("message",yn),n.on("ping",_n),n.on("pong",vn),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",bn),e.on("data",wn),e.on("end",En),e.on("error",Sn),this._readyState=nn.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=nn.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[Ur.extensionName]&&this._extensions[Ur.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=nn.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==nn.CLOSED)if(this.readyState!==nn.CONNECTING)this.readyState!==nn.CLOSING?(this._readyState=nn.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),3e4)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";un(this,this._req,e)}}pause(){this.readyState!==nn.CONNECTING&&this.readyState!==nn.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===nn.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===nn.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||Dr,t,r)):fn(this,e,r)}pong(e,t,r){if(this.readyState===nn.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===nn.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||Dr,t,r)):fn(this,e,r)}resume(){this.readyState!==nn.CONNECTING&&this.readyState!==nn.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===nn.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==nn.OPEN)return void fn(this,e,r);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Ur.extensionName]||(n.compress=!1),this._sender.send(e||Dr,n,r)}terminate(){if(this.readyState!==nn.CLOSED)if(this.readyState!==nn.CONNECTING)this._socket&&(this._readyState=nn.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";un(this,this._req,e)}}}Object.defineProperty(nn,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")}),Object.defineProperty(nn.prototype,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")}),Object.defineProperty(nn,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")}),Object.defineProperty(nn.prototype,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")}),Object.defineProperty(nn,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")}),Object.defineProperty(nn.prototype,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")}),Object.defineProperty(nn,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")}),Object.defineProperty(nn.prototype,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(nn.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(nn.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[Kr])return t[$r];return null},set(t){for(const t of this.listeners(e))if(t[Kr]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[Kr]:!0})}})})),nn.prototype.addEventListener=Yr,nn.prototype.removeEventListener=Hr;var sn=nn;function on(e,t,r,n){const s={protocolVersion:en[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!en.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${en.join(", ")})`);let i;if(t instanceof Mr)i=t,e._url=t.href;else{try{i=new Mr(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}e._url=t}const o="wss:"===i.protocol,a="ws+unix:"===i.protocol;let c;if("ws:"===i.protocol||o||a?a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void an(e,t)}const l=o?443:80,u=Rr(16).toString("base64"),f=o?Nr.request:Ir.request,h=new Set;let p,d;if(s.createConnection=o?ln:cn,s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(p=new Ur(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Jr({[Ur.extensionName]:p.offer()})),r.length){for(const e of r){if("string"!=typeof e||!rn.test(e)||h.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(e)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?s.socketPath:i.host;const t=n&&n.headers;if(n={...n,headers:{}},t)for(const[e,r]of Object.entries(t))n.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),d=e._req=f(s),e._redirects&&e.emit("redirect",e.url,d)}else d=e._req=f(s);s.timeout&&d.on("timeout",(()=>{un(e,d,"Opening handshake has timed out")})),d.on("error",(t=>{null===d||d[Qr]||(d=e._req=null,an(e,t))})),d.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void un(e,d,"Maximum redirects exceeded");let i;d.abort();try{i=new Mr(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void an(e,r)}on(e,i,r,n)}else e.emit("unexpected-response",d,i)||un(e,d,`Unexpected server response: ${i.statusCode}`)})),d.on("upgrade",((t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==nn.CONNECTING)return;if(d=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void un(e,r,"Invalid Upgrade header");const i=Fr("sha1").update(u+qr).digest("base64");if(t.headers["sec-websocket-accept"]!==i)return void un(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?h.size?h.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":h.size&&(a="Server sent no subprotocol"),a)return void un(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!p){return void un(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Xr(c)}catch(t){return void un(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==Ur.extensionName){return void un(e,r,"Server indicated an extension that was not requested")}try{p.accept(t[Ur.extensionName])}catch(t){return void un(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Ur.extensionName]=p}e.setSocket(r,n,{generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),d.end()}function an(e,t){e._readyState=nn.CLOSING,e.emit("error",t),e.emitClose()}function cn(e){return e.path=e.socketPath,Ar.connect(e)}function ln(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Ar.isIP(e.host)?"":e.host),Lr.connect(e)}function un(e,t,r){e._readyState=nn.CLOSING;const n=new Error(r);Error.captureStackTrace(n,un),t.setHeader?(t[Qr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(an,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function fn(e,t,r){if(t){const r=Zr(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${tn[e.readyState]})`);process.nextTick(r,t)}}function hn(e,t){const r=this[Vr];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[Vr]&&(r._socket.removeListener("data",wn),process.nextTick(gn,r._socket),1005===e?r.close():r.close(e,t))}function pn(){const e=this[Vr];e.isPaused||e._socket.resume()}function dn(e){const t=this[Vr];void 0!==t._socket[Vr]&&(t._socket.removeListener("data",wn),process.nextTick(gn,t._socket),t.close(e[Gr])),t.emit("error",e)}function mn(){this[Vr].emitClose()}function yn(e,t){this[Vr].emit("message",e,t)}function _n(e){const t=this[Vr];t.pong(e,!t._isServer,zr),t.emit("ping",e)}function vn(e){this[Vr].emit("pong",e)}function gn(e){e.resume()}function bn(){const e=this[Vr];let t;this.removeListener("close",bn),this.removeListener("data",wn),this.removeListener("end",En),e._readyState=nn.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Vr]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",mn),e._receiver.on("finish",mn))}function wn(e){this[Vr]._receiver.write(e)||this.pause()}function En(){const e=this[Vr];e._readyState=nn.CLOSING,e._receiver.end(),this.end()}function Sn(){const e=this[Vr];this.removeListener("error",Sn),this.on("error",zr),e&&(e._readyState=nn.CLOSING,this.destroy())}const{Duplex:xn}=S.default;function kn(e){e.emit("close")}function Tn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Pn(e){this.removeListener("error",Pn),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var Cn=function(e,t){let r=!0;const n=new xn({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const s=!r&&n._readableState.objectMode?t.toString():t;n.push(s)||e.pause()})),e.once("error",(function(e){n.destroyed||(r=!1,n.destroy(e))})),e.once("close",(function(){n.destroyed||n.push(null)})),n._destroy=function(t,s){if(e.readyState===e.CLOSED)return s(t),void process.nextTick(kn,n);let i=!1;e.once("error",(function(e){i=!0,s(e)})),e.once("close",(function(){i||s(t),process.nextTick(kn,n)})),r&&e.terminate()},n._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){n._final(t)}))},n._read=function(){e.isPaused&&e.resume()},n._write=function(t,r,s){e.readyState!==e.CONNECTING?e.send(t,s):e.once("open",(function(){n._write(t,r,s)}))},n.on("end",Tn),n.on("error",Pn),n};const{tokenChars:On}=Mt.exports;var Nn={parse:function(e){const t=new Set;let r=-1,n=-1,s=0;for(;s<e.length;s++){const i=e.charCodeAt(s);if(-1===n&&1===On[i])-1===r&&(r=s);else if(0===s||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${s}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${s}`);-1===n&&(n=s);const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=n=-1}}else-1===n&&-1!==r&&(n=s)}if(-1===r||-1!==n)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const In=w.default,An=d.default,{createHash:Ln}=g.default,Rn=Cr,Fn=At,Mn=Nn,Un=sn,{GUID:Bn,kWebSocket:Wn}=ht,jn=/^[+/0-9A-Za-z]{22}==$/,Dn=2;var qn=class extends In{constructor(e,t){if(super(),null==(e={maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Un,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=An.createServer(((e,t)=>{const r=An.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Dn)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(Kn,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(Kn,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Kn(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",$n);const s=e.headers["sec-websocket-key"],i=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Vn(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void Vn(this,e,t,400,"Invalid Upgrade header")}if(!s||!jn.test(s)){return void Vn(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==i&&13!==i){return void Vn(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void Gn(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=Mn.parse(o)}catch(r){return void Vn(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const c=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&void 0!==c){const r=new Fn(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Rn.parse(c);e[Fn.extensionName]&&(r.accept(e[Fn.extensionName]),l[Fn.extensionName]=r)}catch(r){return void Vn(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[""+(8===i?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,((i,o,c,u)=>{if(!i)return Gn(t,o||401,c,u);this.completeUpgrade(l,s,a,e,t,r,n)}));if(!this.options.verifyClient(o))return Gn(t,401)}this.completeUpgrade(l,s,a,e,t,r,n)}completeUpgrade(e,t,r,n,s,i,o){if(!s.readable||!s.writable)return s.destroy();if(s[Wn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Gn(s,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ln("sha1").update(t+Bn).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[Fn.extensionName]){const t=e[Fn.extensionName].params,r=Rn.format({[Fn.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,n),s.write(a.concat("\r\n").join("\r\n")),s.removeListener("error",$n),c.setSocket(s,i,{maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Kn,this)}))),o(c,n)}};function Kn(e){e._state=Dn,e.emit("close")}function $n(){this.destroy()}function Gn(e,t,r,n){r=r||An.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${An.STATUS_CODES[t]}\r\n`+Object.keys(n).map((e=>`${e}: ${n[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function Vn(e,t,r,n,s){if(e.listenerCount("wsClientError")){const n=new Error(s);Error.captureStackTrace(n,Vn),e.emit("wsClientError",n,r,t)}else Gn(r,n,s)}const zn=sn;zn.createWebSocketStream=Cn,zn.Server=qn,zn.Receiver=Xt,zn.Sender=cr,zn.WebSocket=zn,zn.WebSocketServer=zn.Server;var Yn=zn,Hn=require("child_process"),Jn=require("events"),Xn=require("url"),Zn=Yn.Server,Qn="mpeg1video",es=!1,ts="drawtext=x=w-tw-100:y=100:fontcolor=white:fontsize=36:text="+decodeURIComponent(ut.exports.decode("JUU1JThFJUJCJUU5JTk5JUE0JUU2JUIwJUI0JUU1JThEJUIwUVElRUYlQkMlOUE0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",rs="scale=-1:-1,eq=",ns=["vcodec","c:v","-c:v","codec:v"],ss=["-s","-b:v","scale","contrast","brightness","saturation","gamma"].concat(ns),is=["scale","contrast","brightness","saturation","gamma"],os=function(e,t){switch(e){case"-s":if(t.includes("x")&&t.split("x")[0]&&t.split("x")[0]>0&&t.split("x")[1]&&t.split("x")[1]>0)return!0;break;case"vcodec":case"c:v":case"-c:v":case"codec:v":case"contrast":case"brightness":case"saturation":case"gamma":if(t)return!0;break;case"-b:v":if(t.endsWith("k"))return!0;break;case"scale":if(t.includes(":")&&t.split(":")[0]&&t.split(":")[1])return!0}},as=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&L(e,t)}(r,Jn.EventEmitter);var t=F(r);function r(e){var n;return C(this,r),I(R(n=t.call(this)),"exitCode",void 0),I(R(n),"additionalFlags",[]),I(R(n),"stream",null),I(R(n),"inputStreamStarted",!1),n.options=e,n.ffmpegPath=e.ffmpegPath||"ffmpeg",n.url=e.url,n.ffmpegOptions=e.ffmpegOptions,n.initMpeg2Muxer(),n}return N(r,[{key:"initMpeg2Muxer",value:function(){var e=this;if(this.ffmpegOptions)for(var t in this.ffmpegOptions)this.additionalFlags.push(t),""!==String(this.ffmpegOptions[t])&&this.additionalFlags.push(String(this.ffmpegOptions[t]));this.spawnOptions=["-rtsp_transport","tcp","-thread_queue_size","256","-i",this.url,"-f","mpegts"].concat(U(this.additionalFlags),["-codec:a","mp2",es?"-an":null,"-ar","44100","-ac","2","-nostats","-r","29.97","-"]),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=Hn.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数")})),this.stream.on("exit",(function(t,r){if(1===t)return console.error("***由于ffmpeg退出,ffmpeg启动不成功,请检查ffmpeg参数或相关情况或联系作者***"),e.exitCode=1,e.emit("exitWithError")})),this.stream.on("close",(function(t,r){return console.log("ffmpeg关闭,code:",t),e.emit("ffmpegClosed")})),this.inputStreamStarted=!0,this.stream.stdout.on("data",(function(t){return e.emit("mpeg2data",t)})),this.stream.stderr.on("data",(function(t){return e.emit("ffmpegStderr",t)}))}}]),r}(),cs=function(){function e(t){C(this,e),I(this,"freeTime",0),I(this,"isStreamWrap",!1),I(this,"clients",[]),I(this,"mpeg2Muxer",{instance:null,stream:null,data:null}),this.config=t,this.url=t.url}return N(e,[{key:"createStream",value:function(){var e=this;this.isStreamWrap||(console.log("创建一个新的ffmpeg子进程"),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new as({ffmpegOptions:this.formatParams(this.config),url:this.url,ffmpegPath:"ffmpeg"}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.mpeg2Muxer.instance.on("mpeg2data",(function(t){e.broadcast(t)})),this.mpeg2Muxer.instance.on("exitWithError",(function(){})),this.mpeg2Muxer.instance.on("ffmpegClosed",(function(){e.destroy()})))}},{key:"formatParams",value:function(e){for(var t={"-codec:v":Qn,"-vf":ts},r=0,n=Object.entries(e);r<n.length;r++){var s=M(n[r],2),i=s[0],o=s[1];"wm"===i&&"0"===o&&(t["-vf"]=rs),ss.includes(i)&&(is.includes(i)?"scale"===i?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(o)):t["-vf"]+="".concat(i,"=").concat(o,":"):ns.includes(i)?t["-codec:v"]=o:os(i,o)&&(t[i]=o))}return t}},{key:"destroy",value:function(){var e,t;null===(e=this.mpeg2Muxer.stream)||void 0===e||e.kill(),this.mpeg2Muxer.stream=null,null===(t=this.mpeg2Muxer.instance)||void 0===t||t.removeAllListeners(),this.mpeg2Muxer.instance=null,this.isStreamWrap=!1,this.dropAllClient()}},{key:"broadcast",value:function(e){var t,r=j(this.clients);try{for(r.s();!(t=r.n()).done;){var n=t.value;n.isSegment&&n.send(e)}}catch(e){r.e(e)}finally{r.f()}}},{key:"addClient",value:function(e){var t=this;e.once("close",(function(){t.dropClient(e)})),this.clients.push(e),this.isStreamWrap||this.createStream(),e.isSegment=!0}},{key:"dropClient",value:function(e){var t=this.clients.indexOf(e);e.isSegment=!1,e.terminate(),e=null,console.log("视频关闭,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=j(this.clients);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.isSegment=!1,r.terminate()}}catch(e){t.e(e)}finally{t.f()}this.clients=[]}}]),e}(),ls=function(){function e(t){var r=this;C(this,e),I(this,"channels",[]),t&&"boolean"==typeof t.wm&&!t.wm&&(ts=rs),t&&"string"==typeof t.vcodec&&t.vcodec.length>0&&(Qn=t.vcodec),t&&"boolean"==typeof t.audio&&!t.audio&&(es=!0),setInterval((function(){return r.checkFree()}),1e4);var n=d.default.createServer();if(t&&"object"===P(t.wss))if(console.log("wss启动中...."),t.wss.hasOwnProperty("pfx"))if(t.wss.hasOwnProperty("passphrase"))try{var s={pfx:y.default.readFileSync(t.wss.pfx),passphrase:y.default.readFileSync(t.wss.passphrase)};$.readPkcs12(s.pfx,{p12Password:s.passphrase},(function(e,t){n=m.default.createServer({cert:t.cert,key:t.key})}))}catch(e){console.error("--【读取pfx安全证书文件出错,wss启动失败,退回到ws;错误信息如下,有问题请联系我】--"),console.log(e)}else console.error("【wss启动失败;请传入正确的pfx文件指定密码:passphrase】");else if(t.wss.hasOwnProperty("cert"))if(t.wss.hasOwnProperty("key"))try{n=m.default.createServer({cert:y.default.readFileSync(t.wss.cert),key:y.default.readFileSync(t.wss.key)})}catch(e){console.error("--【读取cert安全证书文件出错,wss启动失败,退回到ws;错误信息如下,有问题请联系我】--"),console.log(e)}else console.error("【wss启动失败;请传入正确的安全证书私钥:key】");else console.error("【wss启动失败;请传入正确的安全证书公钥:cert】");this.wss=new Zn({server:n}),this.wss.on("connection",(function(e,t){var n=Xn.parse(t.url,!0);if(n.query.url){var s=ut.exports.decode(n.query.url.toString());n.query.url=s,r.registeClient(e,{url:s,options:n.query})}console.log("一个新的client(ws句柄)连接成功")})),n.listen(t&&t.port||9999)}return N(e,[{key:"registeClient",value:function(e,t){var r=this.getChannel(t.url);r||(r=this.createChannel(t.options,e)),r.addClient(e)}},{key:"getChannel",value:function(e){var t,r=j(this.channels);try{for(r.s();!(t=r.n()).done;){var n=t.value;if(n.url===e)return n}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new cs(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=j(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=10,r.freeTime>=60&&this.destroyedChannel(r)}}catch(e){t.e(e)}finally{t.f()}}},{key:"destroyedChannel",value:function(e){var t=this.channels.indexOf(e);t>-1&&(this.channels.splice(t,1),e.destroy())}}]),e}();I(ls,"version","3.0.0"),module.exports=ls;
|
|
10
|
-
//# sourceMappingURL=rtsp2web.js.map
|
|
8
|
+
"use strict";var e=require("http"),t=require("https"),r=require("fs"),n=require("net"),s=require("path"),i=require("crypto"),o=require("child_process"),a=require("events"),c=require("tls"),l=require("stream"),u=require("url"),f=require("zlib"),h=require("buffer");function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=p(e),m=p(t),y=p(r),_=p(n),g=p(s),v=p(i),b=p(o),w=p(a),E=p(c),S=p(l),x=p(u),k=p(f),T=p(h);function C(e){return C="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},C(e)}function P(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function N(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,j(n.key),n)}}function O(e,t,r){return t&&N(e.prototype,t),r&&N(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function I(e,t,r){return(t=j(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function A(e){return A=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},A(e)}function R(e,t){return R=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},R(e,t)}function F(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function L(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,n=A(e);if(t){var s=A(this).constructor;r=Reflect.construct(n,arguments,s)}else r=n.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return F(e)}(this,r)}}function M(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,s,i,o,a=[],c=!0,l=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){l=!0,s=e}finally{try{if(!c&&null!=r.return&&(o=r.return(),Object(o)!==o))return}finally{if(l)throw s}}return a}}(e,t)||B(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function U(e){return function(e){if(Array.isArray(e))return W(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||B(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function B(e,t){if(e){if("string"==typeof e)return W(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?W(e,t):void 0}}function W(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function D(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=B(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,s=function(){};return{s:s,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return o=e.done,e},e:function(e){a=!0,i=e},f:function(){try{o||null==r.return||r.return()}finally{if(a)throw i}}}}function j(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}var q="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function V(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var G={},K={};Object.defineProperty(K,"__esModule",{value:!0}),K.promisify=z;var $="__ES6-PROMISIFY--CUSTOM-ARGUMENTS__";function z(e){if("function"!=typeof e)throw new TypeError("Argument to promisify must be a function");var t=e[$],r=z.Promise||Promise;if("function"!=typeof r)throw new Error("No Promise implementation found; do you need a polyfill?");return function(){for(var n=this,s=arguments.length,i=new Array(s),o=0;o<s;o++)i[o]=arguments[o];return new r((function(r,s){i.push((function(e){if(e)return s(e);for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];if(1===i.length||!t)return r(i[0]);var a={};i.forEach((function(e,r){var n=t[r];n&&(a[n]=e)})),r(a)})),e.apply(n,i)}))}}z.argumentNames=$,z.Promise=void 0;var Y={exports:{}},H="win32"===process.platform,J=H?/[^:]\\$/:/.\/$/,X=function(){var e;return e=H?process.env.TEMP||process.env.TMP||(process.env.SystemRoot||process.env.windir)+"\\temp":process.env.TMPDIR||process.env.TMP||process.env.TEMP||"/tmp",J.test(e)&&(e=e.slice(0,-1)),e};!function(e){var t=g.default,r=y.default,n=v.default,s=X,i=process.env.PEMJS_TMPDIR||s();e.exports.isNumber=function(e){return!Array.isArray(e)&&/^\d+$/g.test(e)},e.exports.isHex=function(e){return/^(0x){0,1}([0-9A-F]{1,40}|[0-9A-F]{1,40})$/gi.test(e)},e.exports.toHex=function(e){for(var t="",r=0;r<e.length;r++)t+=""+e.charCodeAt(r).toString(16);return t},e.exports.ciphers=["aes128","aes192","aes256","camellia128","camellia192","camellia256","des","des3","idea"];var o=e.exports.ciphers;e.exports.createPasswordFile=function(e,s,a){if(!(e&&Object.prototype.hasOwnProperty.call(e,"password")&&Object.prototype.hasOwnProperty.call(e,"passType")&&/^(word|in|out)$/.test(e.passType)))return!1;var c=t.join(i,n.randomBytes(20).toString("hex"));return a.push(c),e.password=e.password.trim(),""===e.password&&(e.mustPass=!0),e.cipher&&-1!==o.indexOf(e.cipher)&&s.push("-"+e.cipher),s.push("-pass"+e.passType),e.mustPass?s.push("pass:"+e.password):(r.writeFileSync(c,e.password),s.push("file:"+c)),!0},e.exports.deleteTempFiles=function(e,t){var n=[];if("string"==typeof e)n.push(e);else{if(!Array.isArray(e))return t(new Error("Unexcepted files parameter type; only string or array supported"));n=e}var s=function(e,t){if(!e.length)return t(null);var n=e.shift();if(!n||"string"!=typeof n)return s(e,t);r.unlink(n,(function(r){return r&&"ENOENT"===r.code?s(e,t):r?t(r):s(e,t)}))};s(n,t)}}(Y);var Z=te;te.sync=function(e,t){return ee(Q.statSync(e),e,t)};var Q=y.default;function ee(e,t,r){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var r=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!r)return!0;if(-1!==(r=r.split(";")).indexOf(""))return!0;for(var n=0;n<r.length;n++){var s=r[n].toLowerCase();if(s&&e.substr(-s.length).toLowerCase()===s)return!0}return!1}(t,r)}function te(e,t,r){Q.stat(e,(function(n,s){r(n,!n&&ee(s,e,t))}))}var re=ie;ie.sync=function(e,t){return oe(se.statSync(e),t)};var ne,se=y.default;function ie(e,t,r){se.stat(e,(function(e,n){r(e,!e&&oe(n,t))}))}function oe(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,s=e.gid,i=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),o=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),l=parseInt("001",8),u=a|c;return r&l||r&c&&s===o||r&a&&n===i||r&u&&0===i}(e,t)}ne="win32"===process.platform||q.TESTING_WINDOWS?Z:re;var ae=ce;function ce(e,t,r){if("function"==typeof t&&(r=t,t={}),!r){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise((function(r,n){ce(e,t||{},(function(e,t){e?n(e):r(t)}))}))}ne(e,t||{},(function(e,n){e&&("EACCES"===e.code||t&&t.ignoreErrors)&&(e=null,n=!1),r(e,n)}))}ce.sync=function(e,t){try{return ne.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||"EACCES"===e.code)return!1;throw e}};const le="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,ue=g.default,fe=le?";":":",he=ae,pe=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),de=(e,t)=>{const r=t.colon||fe,n=e.match(/\//)||le&&e.match(/\\/)?[""]:[...le?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],s=le?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=le?s.split(r):[""];return le&&-1!==e.indexOf(".")&&""!==i[0]&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:s}},me=(e,t,r)=>{"function"==typeof t&&(r=t,t={}),t||(t={});const{pathEnv:n,pathExt:s,pathExtExe:i}=de(e,t),o=[],a=r=>new Promise(((s,i)=>{if(r===n.length)return t.all&&o.length?s(o):i(pe(e));const a=n[r],l=/^".*"$/.test(a)?a.slice(1,-1):a,u=ue.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(c(f,r,0))})),c=(e,r,n)=>new Promise(((l,u)=>{if(n===s.length)return l(a(r+1));const f=s[n];he(e+f,{pathExt:i},((s,i)=>{if(!s&&i){if(!t.all)return l(e+f);o.push(e+f)}return l(c(e,r,n+1))}))}));return r?a(0).then((e=>r(null,e)),r):a(0)};var ye=me;me.sync=(e,t)=>{t=t||{};const{pathEnv:r,pathExt:n,pathExtExe:s}=de(e,t),i=[];for(let o=0;o<r.length;o++){const a=r[o],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=ue.join(c,e),u=!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+l:l;for(let e=0;e<n.length;e++){const r=u+n[e];try{if(he.sync(r,{pathExt:s})){if(!t.all)return r;i.push(r)}}catch(e){}}}if(t.all&&i.length)return i;if(t.nothrow)return null;throw pe(e)};var _e=Y.exports,ge=b.default.spawn,ve=g.default,be=y.default,we=X,Ee=v.default,Se=ye,xe={},ke=process.env.PEMJS_TMPDIR||we();function Te(e,t){xe[e]=t}function Ce(e){return xe[e]||null}function Pe(e,t,r){var n=Ce("pathOpenSSL")||process.env.OPENSSL_BIN||"openssl";!function(e,t){Se(e,(function(r){if(r)return t(new Error("Could not find openssl on your system on this path: "+e));t()}))}(n,(function(s){if(s)return r(s);var i=ge(n,e),o="",a=t?Buffer.alloc(0):"";i.stdout.on("data",(function(e){t?a=Buffer.concat([a,e]):a+=e.toString("binary")})),i.stderr.on("data",(function(e){o+=e.toString("binary")}));var c=2,l=-1,u=!1,f=function(t){if(!u)return t?(u=!0,r(t)):--c<1?(u=!0,l&&(2!==l||""!==o&&!/depth lookup: unable to/.test(o))?r(new Error("Invalid openssl exit code: "+l+"\n% openssl "+e.join(" ")+"\n"+o),l):r(null,l,a,o)):void 0};i.on("error",f),i.on("exit",(function(e){l=e,f()})),i.on("close",(function(){a=t?a:Buffer.from(a,"binary").toString("utf-8"),o=Buffer.from(o,"binary").toString("utf-8"),f()}))}))}function Ne(e,t,r,n){n||"function"!=typeof r||(n=r,r=!1);var s,i,o,a=[],c=[];if(t)for(t=[].concat(t),i=0;i<e.length;i++)"--TMPFILE--"===e[i]&&(s=ve.join(ke,Ee.randomBytes(20).toString("hex")),a.push({path:s,contents:t.shift()}),e[i]=s,c.push(s));for(i=0;i<a.length;i++)o=a[i],be.writeFileSync(o.path,o.contents);Pe(e,r,(function(e,t,r,s){_e.deleteTempFiles(c,(function(i){n(e||i,t,r,s)}))}))}Pe(["version"],!1,(function(e,t,r,n){var s=(String(r)+"\n"+String(n)+"\n"+String(e)).match(/^LibreSSL/i);Te("openSslVersion",(s&&s[0]?"LibreSSL":"openssl").toUpperCase())}));var Oe={exec:function(e,t,r,n){n||"function"!=typeof r||(n=r,r=!1),Ne(e,r,(function(e,r,s,i){var o,a;return e?n(e):(o=(o=s.match(new RegExp("\\-+BEGIN "+t+"\\-+$","m")))?o.index:-1,"EC PARAMETERS"===t&&(t="EC PRIVATE KEY"),a=(a=s.match(new RegExp("^\\-+END "+t+"\\-+","m")))?a.index+a[0].length:-1,o>=0&&a>=0?n(null,s.substring(o,a)):n(new Error(t+" not found from openssl output:\n---stdout---\n"+s+"\n---stderr---\n"+i+"\ncode: "+r)))}))},execBinary:function(e,t,r){r||"function"!=typeof t||(r=t,t=!1),Ne(e,t,!0,(function(e,t,n,s){return e?r(e):r(null,n)}))},spawn:Pe,spawnWrapper:Ne,set:Te,get:Ce},Ie={},Ae=Oe,Re=Y.exports;Ie.PEM2DER=function(e,t,r,n){n||"function"!=typeof r||(n=r,r="x509");var s=[r,"-outform","der","-in",e,"-out",t];Ae.spawnWrapper(s,!1,(function(e,t){e?n(e):n(null,0===t)}))},Ie.DER2PEM=function(e,t,r,n){n||"function"!=typeof r||(n=r,r="x509");var s=[r,"-inform","der","-in",e,"-out",t];Ae.spawnWrapper(s,!1,(function(e,t){e?n(e):n(null,0===t)}))},Ie.PEM2P7B=function(e,t,r){var n=["crl2pkcs7","-nocrl","-certfile",e.cert,"-out",t];e.ca&&(Array.isArray(e.ca)||(e.ca=[e.ca]),e.ca.forEach((function(e){n.push("-certfile"),n.push(e)}))),Ae.spawnWrapper(n,!1,(function(e,t){e?r(e):r(null,0===t)}))},Ie.P7B2PEM=function(e,t,r){var n=["pkcs7","-print_certs","-in",e,"-out",t];Ae.spawnWrapper(n,!1,(function(e,t){e?r(e):r(null,0===t)}))},Ie.PEM2PFX=function(e,t,r,n){var s=["pkcs12","-export","-out",t,"-inkey",e.key,"-in",e.cert];e.ca&&(Array.isArray(e.ca)||(e.ca=[e.ca]),e.ca.forEach((function(e){s.push("-certfile"),s.push(e)})));var i=[];Re.createPasswordFile({cipher:"",password:r,passType:"in"},s,i),Re.createPasswordFile({cipher:"",password:r,passType:"out"},s,i),Ae.spawnWrapper(s,!1,(function(e,t){Re.deleteTempFiles(i,(function(r){!function(e){e?n(e):n(null,0===t)}(e||r)}))}))},Ie.PFX2PEM=function(e,t,r,n){var s=["pkcs12","-in",e,"-out",t,"-nodes"],i=[];Re.createPasswordFile({cipher:"",password:r,passType:"in"},s,i),Re.createPasswordFile({cipher:"",password:r,passType:"out"},s,i),Ae.spawnWrapper(s,!1,(function(e,t){Re.deleteTempFiles(i,(function(r){!function(e){e?n(e):n(null,0===t)}(e||r)}))}))},Ie.P7B2PFX=function(e,t,r,n){var s=e.cert.replace(/\.[^.]+$/,".cer"),i=["pkcs7","-print_certs","-in",e.cert,"-out",s];Ae.spawnWrapper(i,!1,(function(i,o){if(i)n(i);else{var a=["pkcs12","-export","-in",s,"-inkey",e.key,"-out",t];e.ca&&(Array.isArray(e.ca)||(e.ca=[e.ca]),e.ca.forEach((function(e){a.push("-certfile"),a.push(e)})));var c=[s];Re.createPasswordFile({cipher:"",password:r,passType:"in"},a,c),Re.createPasswordFile({cipher:"",password:r,passType:"out"},a,c),Ae.spawnWrapper(a,!1,(function(e,t){Re.deleteTempFiles(c,(function(r){!function(e){e?n(e):n(null,0===t)}(e||r)}))}))}}))};const{promisify:Fe}=K;var Le=_.default,Me=Y.exports,Ue=Oe;G.createPrivateKey=$e,G.createDhparam=ze,G.createEcparam=Ye,G.createCSR=He,G.createCertificate=Je,G.readCertificateInfo=Ze,G.getPublicKey=Xe,G.getFingerprint=tt,G.getModulus=Qe,G.getDhparamInfo=et,G.createPkcs12=rt,G.readPkcs12=nt,G.verifySigningChain=ot,G.checkCertificate=st,G.checkPkcs12=it,G.config=function(e){Object.keys(e).forEach((function(t){Ue.set(t,e[t])}))},G.convert=Ie;var Be="-----BEGIN PRIVATE KEY-----",We="-----END PRIVATE KEY-----",De="-----BEGIN RSA PRIVATE KEY-----",je="-----END RSA PRIVATE KEY-----",qe="-----BEGIN ENCRYPTED PRIVATE KEY-----",Ve="-----END ENCRYPTED PRIVATE KEY-----",Ge="-----BEGIN CERTIFICATE-----",Ke="-----END CERTIFICATE-----";function $e(e,t,r){r||t||"function"!=typeof e?!r&&e&&"function"==typeof t&&(r=t,t={}):(r=e,e=void 0,t={}),e=Number(e)||2048;var n=["genrsa"],s=[];t&&t.cipher&&-1!==Number(Me.ciphers.indexOf(t.cipher))&&t.password&&Me.createPasswordFile({cipher:t.cipher,password:t.password,passType:"out"},n,s),n.push(e),Ue.exec(n,"RSA PRIVATE KEY",(function(e,t){Me.deleteTempFiles(s,(function(n){!function(e){if(e)return r(e);r(null,{key:t})}(e||n)}))}))}function ze(e,t){t||"function"!=typeof e||(t=e,e=void 0);var r=["dhparam","-outform","PEM",e=Number(e)||512];Ue.exec(r,"DH PARAMETERS",(function(e,r){return e?t(e):t(null,{dhparam:r})}))}function Ye(e,t,r,n){n||void 0!==r||t||"function"!=typeof e?!n&&void 0===r&&e&&"function"==typeof t?(n=t,t=void 0):!n&&"function"==typeof r&&e&&t&&(n=r,r=void 0):(n=e,e=void 0);var s=["ecparam","-name",e=e||"secp256k1","-genkey","-param_enc",t=t||"explicit"],i="EC PARAMETERS";(r=r||!1)&&(s.push("-noout"),i="EC PRIVATE KEY"),Ue.exec(s,i,(function(e,t){return e?n(e):n(null,{ecparam:t})}))}function He(e,t){if(t||"function"!=typeof e||(t=e,e=void 0),(e=e||{}).commonName&&(Le.isIPv4(e.commonName)||Le.isIPv6(e.commonName))&&(e.altNames?-1===e.altNames.indexOf(e.commonName)&&(e.altNames=e.altNames.concat([e.commonName])):e.altNames=[e.commonName]),e.clientKey){var r=["req","-new","-"+(e.hash||"sha256")];e.csrConfigFile?(r.push("-config"),r.push(e.csrConfigFile)):(r.push("-subj"),r.push(function(e){e=e||{};var t={C:e.country||e.C,ST:e.state||e.ST,L:e.locality||e.L,O:e.organization||e.O,OU:e.organizationUnit||e.OU,CN:e.commonName||e.CN||"localhost",DC:e.dc||e.DC||"",emailAddress:e.emailAddress};return Object.keys(t).map((function(e){if(t[e]){if("object"==typeof t[e]&&t[e].length>=1){var r="";return t[e].map((function(t){r+="/"+e+"="+t.replace(/[^\w .*\-,@']+/g," ").trim()})),r}return"/"+e+"="+t[e].replace(/[^\w .*\-,@']+/g," ").trim()}})).join("")}(e))),r.push("-key"),r.push("--TMPFILE--");var n=[e.clientKey],s=null;if(e.altNames&&Array.isArray(e.altNames)&&e.altNames.length){r.push("-extensions"),r.push("v3_req"),r.push("-config"),r.push("--TMPFILE--");for(var i=[],o=0;o<e.altNames.length;o++)i.push((Le.isIP(e.altNames[o])?"IP":"DNS")+"."+(o+1)+" = "+e.altNames[o]);n.push(s=["[req]","req_extensions = v3_req","distinguished_name = req_distinguished_name","[v3_req]","subjectAltName = @alt_names","[alt_names]",i.join("\n"),"[req_distinguished_name]","commonName = Common Name","commonName_max = 64"].join("\n"))}else e.config&&(s=e.config);var a=[];e.clientKeyPassword&&Me.createPasswordFile({cipher:"",password:e.clientKeyPassword,passType:"in"},r,a),Ue.exec(r,"CERTIFICATE REQUEST",n,(function(r,n){Me.deleteTempFiles(a,(function(i){!function(r){if(r)return t(r);t(null,{csr:n,config:s,clientKey:e.clientKey})}(r||i)}))}))}else $e(e.keyBitsize||2048,(function(r,n){if(r)return t(r);e.clientKey=n.key,He(e,t)}))}function Je(e,t){if(t||"function"!=typeof e||(t=e,e=void 0),(e=e||{}).csr){if(e.clientKey||(e.clientKey=""),!e.serviceKey){if(!e.selfSigned)return void $e(e.keyBitsize||2048,(function(r,n){if(r)return t(r);e.serviceKey=n.key,Je(e,t)}));e.serviceKey=e.clientKey}Ze(e.csr,(function(r,n){if(r)return t(r);var s=["x509","-req","-"+(e.hash||"sha256"),"-days",Number(e.days)||"365","-in","--TMPFILE--"],i=[e.csr],o=[];if(e.serviceCertificate?(s.push("-CA"),s.push("--TMPFILE--"),s.push("-CAkey"),s.push("--TMPFILE--"),e.serial?(s.push("-set_serial"),Me.isNumber(e.serial)?s.push("0x"+("0000000000000000000000000000000000000000"+e.serial.toString(16)).slice(-40)):Me.isHex(e.serial)?(e.serial.startsWith("0x")&&(e.serial=e.serial.substring(2,e.serial.length)),s.push("0x"+("0000000000000000000000000000000000000000"+e.serial).slice(-40))):s.push("0x"+("0000000000000000000000000000000000000000"+Me.toHex(e.serial)).slice(-40))):(s.push("-CAcreateserial"),e.serialFile&&(s.push("-CAserial"),s.push(e.serialFile+".srl"))),e.serviceKeyPassword&&Me.createPasswordFile({cipher:"",password:e.serviceKeyPassword,passType:"in"},s,o),i.push(e.serviceCertificate),i.push(e.serviceKey)):(s.push("-signkey"),s.push("--TMPFILE--"),e.serviceKeyPassword&&Me.createPasswordFile({cipher:"",password:e.serviceKeyPassword,passType:"in"},s,o),i.push(e.serviceKey)),e.config)s.push("-extensions"),s.push("v3_req"),s.push("-extfile"),s.push("--TMPFILE--"),i.push(e.config);else if(e.extFile)s.push("-extfile"),s.push(e.extFile);else{var a=[];if(n&&n.san){for(var c=0;c<n.san.dns.length;c++)a.push("DNS."+(c+1)+" = "+n.san.dns[c]);for(var l=0;l<n.san.ip.length;l++)a.push("IP."+(l+1)+" = "+n.san.ip[l]);for(var u=0;u<n.san.email.length;u++)a.push("email."+(u+1)+" = "+n.san.email[u]);s.push("-extensions"),s.push("v3_req"),s.push("-extfile"),s.push("--TMPFILE--"),i.push(["[v3_req]","subjectAltName = @alt_names","[alt_names]",a.join("\n")].join("\n"))}}e.clientKeyPassword&&Me.createPasswordFile({cipher:"",password:e.clientKeyPassword,passType:"in"},s,o),Ue.exec(s,"CERTIFICATE",i,(function(r,n){Me.deleteTempFiles(o,(function(s){!function(r){if(r)return t(r);var s={csr:e.csr,clientKey:e.clientKey,certificate:n,serviceKey:e.serviceKey};t(null,s)}(r||s)}))}))}))}else He(e,(function(r,n){if(r)return t(r);e.csr=n.csr,e.config=n.config,e.clientKey=n.clientKey,Je(e,t)}))}function Xe(e,t){var r;t||"function"!=typeof e||(t=e,e=void 0),r=(e=(e||"").toString()).match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)?["req","-in","--TMPFILE--","-pubkey","-noout"]:e.match(/BEGIN RSA PRIVATE KEY/)||e.match(/BEGIN PRIVATE KEY/)?["rsa","-in","--TMPFILE--","-pubout"]:["x509","-in","--TMPFILE--","-pubkey","-noout"],Ue.exec(r,"PUBLIC KEY",e,(function(e,r){return e?t(e):t(null,{publicKey:r})}))}function Ze(e,t){t||"function"!=typeof e||(t=e,e=void 0);var r=[(e=(e||"").toString()).match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)?"req":"x509","-noout","-nameopt","RFC2253,sep_multiline,space_eq,-esc_msb,utf8","-text","-in","--TMPFILE--"];Ue.spawnWrapper(r,e,(function(e,r,n,s){return e?t(e):s?t(s):function(e,t){try{var r,n,s,i;e=(e||"").toString();var o,a,c,l={issuer:{}},u={};if((r=e.match(/\s*Serial Number:\r?\n?\s*([^\r\n]*)\r?\n\s*\b/))&&r.length>1&&(l.serial=r[1]),(n=e.match(/\s*Subject:\r?\n(\s*(([a-zA-Z0-9.]+)\s=\s[^\r\n]+\r?\n))*\s*\b/))&&n.length>1){if(s=at(n=n[0],/\s([a-zA-Z0-9.]+)\s=\s([^\r\n].*)/g))for(c=0;c<s.length;c++)(a=s[c][1].trim()).match("(C|ST|L|O|OU|CN|emailAddress|DC)")||""===a||(l[a]=s[c][2].trim());s=n.match(/\sC\s=\s([^\r\n].*?)[\r\n]/),l.country=s&&s[1]||"",s=n.match(/\sST\s=\s([^\r\n].*?)[\r\n]/),l.state=s&&s[1]||"",s=n.match(/\sL\s=\s([^\r\n].*?)[\r\n]/),l.locality=s&&s[1]||"",s=at(n,/\sO\s=\s([^\r\n].*)/g),l.organization=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(n,/\sOU\s=\s([^\r\n].*)/g),l.organizationUnit=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(n,/\sCN\s=\s([^\r\n].*)/g),l.commonName=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(n,/emailAddress\s=\s([^\r\n].*)/g),l.emailAddress=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(n,/\sDC\s=\s([^\r\n].*)/g),l.dc=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:""}if((i=e.match(/\s*Issuer:\r?\n(\s*([a-zA-Z0-9.]+)\s=\s[^\r\n].*\r?\n)*\s*\b/))&&i.length>1){for(s=at(i=i[0],/\s([a-zA-Z0-9.]+)\s=\s([^\r\n].*)/g),c=0;c<s.length;c++)(a=s[c][1].toString()).match("(C|ST|L|O|OU|CN|emailAddress|DC)")||(l.issuer[a]=s[c][2].toString());s=i.match(/\sC\s=\s([^\r\n].*?)[\r\n]/),l.issuer.country=s&&s[1]||"",s=i.match(/\sST\s=\s([^\r\n].*?)[\r\n]/),l.issuer.state=s&&s[1]||"",s=i.match(/\sL\s=\s([^\r\n].*?)[\r\n]/),l.issuer.locality=s&&s[1]||"",s=at(i,/\sO\s=\s([^\r\n].*)/g),l.issuer.organization=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(i,/\sOU\s=\s([^\r\n].*)/g),l.issuer.organizationUnit=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(i,/\sCN\s=\s([^\r\n].*)/g),l.issuer.commonName=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:"",s=at(i,/\sDC\s=\s([^\r\n].*)/g),l.issuer.dc=s?s.length>1?s.sort((function(e,t){var r=e[1].toUpperCase(),n=t[1].toUpperCase();return n>r?-1:r>n?1:0})).sort((function(e,t){return e[1].length-t[1].length})).map((function(e){return e[1]})):s[0][1]:""}(o=e.match(/X509v3 Subject Alternative Name: \r?\n([^\r\n]*)\r?\n/))&&o.length>1&&(o=o[1].trim()+"\n",l.san={},s=ct("DNS:([^,\\r\\n].*?)[,\\r\\n\\s]",o),l.san.dns=s||"",s=ct("IP Address:([^,\\r\\n].*?)[,\\r\\n\\s]",o),l.san.ip=s||"",s=ct("email:([^,\\r\\n].*?)[,\\r\\n\\s]",o),l.san.email=s||""),(s=e.match(/Not Before\s?:\s?([^\r\n]*)\r?\n/))&&s.length>1&&(u.start=Date.parse(s&&s[1]||"")),(s=e.match(/Not After\s?:\s?([^\r\n]*)\r?\n/))&&s.length>1&&(u.end=Date.parse(s&&s[1]||"")),u.start&&u.end&&(l.validity=u),(s=e.match(/Signature Algorithm: ([^\r\n]*)\r?\n/))&&s.length>1&&(l.signatureAlgorithm=s&&s[1]||""),(s=e.match(/Public[ -]Key: ([^\r\n]*)\r?\n/))&&s.length>1&&(l.publicKeySize=(s&&s[1]||"").replace(/[()]/g,"")),(s=e.match(/Public Key Algorithm: ([^\r\n]*)\r?\n/))&&s.length>1&&(l.publicKeyAlgorithm=s&&s[1]||""),t(null,l)}catch(e){t(e)}}(n,t)}))}function Qe(e,t,r,n){n||r||"function"!=typeof t?!n&&r&&"function"==typeof r&&(n=r,r=!1):(n=t,t=void 0,r=!1),r&&"md5"!==r&&(r=!1);var s=[(e=Buffer.isBuffer(e)&&e.toString()||e).match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)?"req":e.match(/BEGIN RSA PRIVATE KEY/)||e.match(/BEGIN PRIVATE KEY/)?"rsa":"x509","-noout","-modulus","-in","--TMPFILE--"],i=[];t&&Me.createPasswordFile({cipher:"",password:t,passType:"in"},s,i),Ue.spawnWrapper(s,e,(function(e,t,s,o){Me.deleteTempFiles(i,(function(t){!function(e){if(e)return n(e);var t=s.match(/Modulus=([0-9a-fA-F]+)$/m);t?n(null,{modulus:r?V(r)(t[1]):t[1]}):n(new Error("No modulus"))}(e||t||o)}))}))}function et(e,t){e=Buffer.isBuffer(e)&&e.toString()||e;Ue.spawnWrapper(["dhparam","-text","-in","--TMPFILE--"],e,(function(e,r,n,s){if(e)return t(e);if(s)return t(s);var i={},o=n.match(/Parameters: \((\d+) bit\)/);o&&(i.size=Number(o[1]));var a="";return n.split("\n").forEach((function(e){/\s+([0-9a-f][0-9a-f]:)+[0-9a-f]?[0-9a-f]?/g.test(e)&&(a+=e.trim())})),a&&(i.prime=a),o||a?t(null,i):t(new Error("No DH info found"))}))}function tt(e,t,r){r||"function"!=typeof t||(r=t,t=void 0);var n=["x509","-in","--TMPFILE--","-fingerprint","-noout","-"+(t=t||"sha1")];Ue.spawnWrapper(n,e,(function(e,t,n,s){if(e)return r(e);if(s)return r(s);var i=n.match(/Fingerprint=([0-9a-fA-F:]+)$/m);return i?r(null,{fingerprint:i[1]}):r(new Error("No fingerprint"))}))}function rt(e,t,r,n,s){s||"function"!=typeof n||(s=n,n={});var i=["pkcs12","-export"],o=[];n.cipher&&n.clientKeyPassword&&Me.createPasswordFile({cipher:n.cipher,password:n.clientKeyPassword,passType:"in"},i,o),Me.createPasswordFile({cipher:"",password:r,passType:"word"},i,o),i.push("-in"),i.push("--TMPFILE--"),i.push("-inkey"),i.push("--TMPFILE--");var a=[t,e];n.certFiles&&(a.push(n.certFiles.join("")),i.push("-certfile"),i.push("--TMPFILE--")),Ue.execBinary(i,a,(function(e,t){Me.deleteTempFiles(o,(function(r){var n;(n=e||r)?s(n):s(null,{pkcs12:t})}))}))}function nt(e,t,r){r||"function"!=typeof t||(r=t,t={}),t.p12Password=t.p12Password||"";var n=[],s=[],i=["pkcs12","-in",e];Me.createPasswordFile({cipher:"",password:t.p12Password,passType:"in"},i,s),Buffer.isBuffer(e)&&(n=[e],i[2]="--TMPFILE--"),t.clientKeyPassword?Me.createPasswordFile({cipher:"",password:t.clientKeyPassword,passType:"out"},i,s):i.push("-nodes"),Ue.execBinary(i,n,(function(e,n){Me.deleteTempFiles(s,(function(s){!function(e){var s={};if(e&&-1!==e.message.indexOf("No such file or directory")&&(e.code="ENOENT"),!e){var i=lt(n,Ge,Ke);if(s.cert=i.shift(),s.ca=i,s.key=lt(n,Be,We).pop(),s.key)return Ue.exec(["rsa","-in","--TMPFILE--"],"RSA PRIVATE KEY",[s.key],(function(e,t){return s.key=t,r(e,s)}));t.clientKeyPassword?s.key=lt(n,qe,Ve).pop():s.key=lt(n,De,je).pop()}r(e,s)}(e||s)}))}))}function st(e,t,r){var n,s=[];r||"function"!=typeof t||(r=t,t=void 0),e=(e||"").toString(),n=e.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)?["req","-text","-noout","-verify","-in","--TMPFILE--"]:e.match(/BEGIN RSA PRIVATE KEY/)||e.match(/BEGIN PRIVATE KEY/)?["rsa","-noout","-check","-in","--TMPFILE--"]:["x509","-text","-noout","-in","--TMPFILE--"],t&&Me.createPasswordFile({cipher:"",password:t,passType:"in"},n,s),Ue.spawnWrapper(n,e,(function(e,t,i,o){Me.deleteTempFiles(s,(function(t){!function(e){if(e&&"verify OK"!==e.toString().trim())return r(e);var t;t="rsa"===n[0]?/^Rsa key ok$/i.test(i.trim()):/Signature Algorithm/im.test(i);r(null,t)}(e||t||o)}))}))}function it(e,t,r){r||"function"!=typeof t||(r=t,t="");var n=[],s=[],i=["pkcs12","-info","-in",e,"-noout","-maciter","-nodes"];Me.createPasswordFile({cipher:"",password:t,passType:"in"},i,s),Buffer.isBuffer(e)&&(n=[e],i[3]="--TMPFILE--"),Ue.spawnWrapper(i,n,(function(e,t,n,i){Me.deleteTempFiles(s,(function(t){!function(e){if(e)return r(e);r(null,/MAC verified OK/im.test(i)||!/MAC verified OK/im.test(i)&&!/Mac verify error/im.test(i))}(e||t)}))}))}function ot(e,t,r){r||"function"!=typeof t||(r=t,t=void 0),Array.isArray(e)||(e=[e]),Array.isArray(t)||void 0===t||""!==t&&(t=[t]);var n=[];void 0!==t&&n.push(t.join("\n")),n.push(e.join("\n"));var s=["verify"];void 0!==t&&(s.push("-CAfile"),s.push("--TMPFILE--")),s.push("--TMPFILE--"),Ue.spawnWrapper(s,n,(function(e,t,n,s){if(e)return r(e);r(null,": OK"===n.trim().slice(-4))}))}function at(e,t){var r=[];return e.replace(t,(function(){var e=[].slice.call(arguments,0),t=e.splice(-2);e.index=t[0],e.input=t[1],r.push(e)})),r.length?r:null}function ct(e,t){for(var r,n,s=new RegExp(e,"g"),i=t.match(s)||[],o=[],a=0;a<i.length;a++)r=new RegExp(e),n=i[a].match(r),o.push(n[1]);return o}function lt(e,t,r){Buffer.isBuffer(e)&&(e=e.toString("utf8"));var n=[];if(!e)return n;for(var s=e.indexOf(t);-1!==s;){var i=(e=e.substring(s)).indexOf(r);if(-1===i)break;i+=r.length,n.push(e.substring(0,i)),s=e.indexOf(t,i)}return n}G.promisified={createPrivateKey:Fe($e),createDhparam:Fe(ze),createEcparam:Fe(Ye),createCSR:Fe(He),createCertificate:Fe(Je),readCertificateInfo:Fe(Ze),getPublicKey:Fe(Xe),getFingerprint:Fe(tt),getModulus:Fe(Qe),getDhparamInfo:Fe(et),createPkcs12:Fe(rt),readPkcs12:Fe(nt),verifySigningChain:Fe(ot),checkCertificate:Fe(st),checkPkcs12:Fe(it)};var ut={exports:{}};
|
|
9
|
+
/*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */!function(e,t){!function(r){var n=t,s=e&&e.exports==n&&e,i="object"==typeof q&&q;i.global!==i&&i.window!==i||(r=i);var o=function(e){this.message=e};(o.prototype=new Error).name="InvalidCharacterError";var a=function(e){throw new o(e)},c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=/[\t\n\f\r ]/g,u={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&a("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,n,s,i=e.length%3,o="",l=-1,u=e.length-i;++l<u;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,n=e.charCodeAt(++l),o+=c.charAt((s=t+r+n)>>18&63)+c.charAt(s>>12&63)+c.charAt(s>>6&63)+c.charAt(63&s);return 2==i?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),o+=c.charAt((s=t+r)>>10)+c.charAt(s>>4&63)+c.charAt(s<<2&63)+"="):1==i&&(s=e.charCodeAt(l),o+=c.charAt(s>>2)+c.charAt(s<<4&63)+"=="),o},decode:function(e){var t=(e=String(e).replace(l,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&a("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,s=0,i="",o=-1;++o<t;)n=c.indexOf(e.charAt(o)),r=s%4?64*r+n:n,s++%4&&(i+=String.fromCharCode(255&r>>(-2*s&6)));return i},version:"1.0.0"};if(n&&!n.nodeType)if(s)s.exports=u;else for(var f in u)u.hasOwnProperty(f)&&(n[f]=u[f]);else r.base64=u}(q)}(ut,ut.exports);var ft={exports:{}},ht={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:pt}=ht,dt=Buffer[Symbol.species];function mt(e,t,r,n,s){for(let i=0;i<s;i++)r[n+i]=e[i]^t[3&i]}function yt(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(ft.exports={concat:function(e,t){if(0===e.length)return pt;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let n=0;for(let t=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return n<t?new dt(r.buffer,r.byteOffset,n):r},mask:mt,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let r;return t instanceof ArrayBuffer?r=new dt(t):ArrayBuffer.isView(t)?r=new dt(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:yt},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");ft.exports.mask=function(t,r,n,s,i){i<48?mt(t,r,n,s,i):e.mask(t,r,n,s,i)},ft.exports.unmask=function(t,r){t.length<32?yt(t,r):e.unmask(t,r)}}catch(e){}const _t=Symbol("kDone"),gt=Symbol("kRun");var vt=class{constructor(e){this[_t]=()=>{this.pending--,this[gt]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[gt]()}[gt](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[_t])}}};const bt=k.default,wt=ft.exports,Et=vt,{kStatusCode:St}=ht,xt=Buffer[Symbol.species],kt=Buffer.from([0,0,255,255]),Tt=Symbol("permessage-deflate"),Ct=Symbol("total-length"),Pt=Symbol("callback"),Nt=Symbol("buffers"),Ot=Symbol("error");let It;var At=class{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!It){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;It=new Et(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[Pt];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,r){It.add((n=>{this._decompress(e,t,((e,t)=>{n(),r(e,t)}))}))}compress(e,t,r){It.add((n=>{this._compress(e,t,((e,t)=>{n(),r(e,t)}))}))}_decompress(e,t,r){const n=this._isServer?"client":"server";if(!this._inflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?bt.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=bt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Tt]=this,this._inflate[Ct]=0,this._inflate[Nt]=[],this._inflate.on("error",Lt),this._inflate.on("data",Ft)}this._inflate[Pt]=r,this._inflate.write(e),t&&this._inflate.write(kt),this._inflate.flush((()=>{const e=this._inflate[Ot];if(e)return this._inflate.close(),this._inflate=null,void r(e);const s=wt.concat(this._inflate[Nt],this._inflate[Ct]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ct]=0,this._inflate[Nt]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),r(null,s)}))}_compress(e,t,r){const n=this._isServer?"server":"client";if(!this._deflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?bt.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=bt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[Ct]=0,this._deflate[Nt]=[],this._deflate.on("data",Rt)}this._deflate[Pt]=r,this._deflate.write(e),this._deflate.flush(bt.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=wt.concat(this._deflate[Nt],this._deflate[Ct]);t&&(e=new xt(e.buffer,e.byteOffset,e.length-4)),this._deflate[Pt]=null,this._deflate[Ct]=0,this._deflate[Nt]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function Rt(e){this[Nt].push(e),this[Ct]+=e.length}function Ft(e){this[Ct]+=e.length,this[Tt]._maxPayload<1||this[Ct]<=this[Tt]._maxPayload?this[Nt].push(e):(this[Ot]=new RangeError("Max payload size exceeded"),this[Ot].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ot][St]=1009,this.removeListener("data",Ft),this.reset())}function Lt(e){this[Tt]._inflate=null,e[St]=1007,this[Pt](e)}var Mt={exports:{}};const{isUtf8:Ut}=T.default;function Bt(e){const t=e.length;let r=0;for(;r<t;)if(0==(128&e[r]))r++;else if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0}if(Mt.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:Bt,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},Ut)Mt.exports.isValidUTF8=function(e){return e.length<24?Bt(e):Ut(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Mt.exports.isValidUTF8=function(t){return t.length<32?Bt(t):e(t)}}catch(e){}const{Writable:Wt}=S.default,Dt=At,{BINARY_TYPES:jt,EMPTY_BUFFER:qt,kStatusCode:Vt,kWebSocket:Gt}=ht,{concat:Kt,toArrayBuffer:$t,unmask:zt}=ft.exports,{isValidStatusCode:Yt,isValidUTF8:Ht}=Mt.exports,Jt=Buffer[Symbol.species];var Xt=class extends Wt{constructor(e={}){super(),this._binaryType=e.binaryType||jt[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Gt]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._state=0,this._loop=!1}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new Jt(t.buffer,t.byteOffset+e,t.length-e),new Jt(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new Jt(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){let t;this._loop=!0;do{switch(this._state){case 0:t=this.getInfo();break;case 1:t=this.getPayloadLength16();break;case 2:t=this.getPayloadLength64();break;case 3:this.getMask();break;case 4:t=this.getData(e);break;default:return void(this._loop=!1)}}while(this._loop);e(t)}getInfo(){if(this._bufferedBytes<2)return void(this._loop=!1);const e=this.consume(2);if(0!=(48&e[0]))return this._loop=!1,Zt(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");const t=64==(64&e[0]);if(t&&!this._extensions[Dt.extensionName])return this._loop=!1,Zt(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._fin=128==(128&e[0]),this._opcode=15&e[0],this._payloadLength=127&e[1],0===this._opcode){if(t)return this._loop=!1,Zt(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Zt(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return this._loop=!1,Zt(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");this._compressed=t}else{if(!(this._opcode>7&&this._opcode<11))return this._loop=!1,Zt(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Zt(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Zt(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return this._loop=!1,Zt(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH")}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=128==(128&e[1]),this._isServer){if(!this._masked)return this._loop=!1,Zt(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Zt(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");if(126===this._payloadLength)this._state=1;else{if(127!==this._payloadLength)return this.haveLength();this._state=2}}getPayloadLength16(){if(!(this._bufferedBytes<2))return this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength();this._loop=!1}getPayloadLength64(){if(this._bufferedBytes<8)return void(this._loop=!1);const e=this.consume(8),t=e.readUInt32BE(0);return t>Math.pow(2,21)-1?(this._loop=!1,Zt(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=t*Math.pow(2,32)+e.readUInt32BE(4),this.haveLength())}haveLength(){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0))return this._loop=!1,Zt(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=qt;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!=(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&zt(t,this._mask)}return this._opcode>7?this.controlMessage(t):this._compressed?(this._state=5,void this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage())}decompress(e,t){this._extensions[Dt.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return t(Zt(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const n=this.dataMessage();if(n)return t(n);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?Kt(t,e):"arraybuffer"===this._binaryType?$t(Kt(t,e)):t,this.emit("message",r,!0)}else{const r=Kt(t,e);if(!this._skipUTF8Validation&&!Ht(r))return this._loop=!1,Zt(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("message",r,!1)}}this._state=0}controlMessage(e){if(8===this._opcode)if(this._loop=!1,0===e.length)this.emit("conclude",1005,qt),this.end();else{const t=e.readUInt16BE(0);if(!Yt(t))return Zt(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=new Jt(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ht(r))return Zt(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("conclude",t,r),this.end()}else 9===this._opcode?this.emit("ping",e):this.emit("pong",e);this._state=0}};function Zt(e,t,r,n,s){const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,Zt),i.code=s,i[Vt]=n,i}const{randomFillSync:Qt}=v.default,er=At,{EMPTY_BUFFER:tr}=ht,{isValidStatusCode:rr}=Mt.exports,{mask:nr,toBuffer:sr}=ft.exports,ir=Symbol("kByteLength"),or=Buffer.alloc(4);class ar{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let r,n,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||or,t.generateMask?t.generateMask(r):Qt(r,0,4),o=0==(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?n=t.mask&&!o||void 0===t[ir]?(e=Buffer.from(e)).length:t[ir]:(n=e.length,s=t.mask&&t.readOnly&&!o);let a=n;n>=65536?(i+=8,a=127):n>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(s?n+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(n,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(n,4,6)),t.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(nr(e,r,c,i,n),[c]):(nr(e,r,e,0,n),[c,e])):[c,e]}close(e,t,r,n){let s;if(void 0===e)s=tr;else{if("number"!=typeof e||!rr(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+r),s.writeUInt16BE(e,0),"string"==typeof t?s.write(t,2):s.set(t,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0)}const i={[ir]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,s,!1,i,n]):this.sendFrame(ar.frame(s,i),n)}ping(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=sr(e)).length,s=sr.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[ir]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(ar.frame(e,i),r)}pong(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=sr(e)).length,s=sr.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[ir]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(ar.frame(e,i),r)}send(e,t,r){const n=this._extensions[er.extensionName];let s,i,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=sr(e)).length,i=sr.readOnly),this._firstFragment?(this._firstFragment=!1,a&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=n._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),n){const n={[ir]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:a};this._deflating?this.enqueue([this.dispatch,e,this._compress,n,r]):this.dispatch(e,this._compress,n,r)}else this.sendFrame(ar.frame(e,{[ir]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:!1}),r)}dispatch(e,t,r,n){if(!t)return void this.sendFrame(ar.frame(e,r),n);const s=this._extensions[er.extensionName];this._bufferedBytes+=r[ir],this._deflating=!0,s.compress(e,r.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof n&&n(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],n=r[r.length-1];"function"==typeof n&&n(e)}}else this._bufferedBytes-=r[ir],this._deflating=!1,r.readOnly=!1,this.sendFrame(ar.frame(t,r),n),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][ir],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ir],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}var cr=ar;const{kForOnEventAttribute:lr,kListener:ur}=ht,fr=Symbol("kCode"),hr=Symbol("kData"),pr=Symbol("kError"),dr=Symbol("kMessage"),mr=Symbol("kReason"),yr=Symbol("kTarget"),_r=Symbol("kType"),gr=Symbol("kWasClean");class vr{constructor(e){this[yr]=null,this[_r]=e}get target(){return this[yr]}get type(){return this[_r]}}Object.defineProperty(vr.prototype,"target",{enumerable:!0}),Object.defineProperty(vr.prototype,"type",{enumerable:!0});class br extends vr{constructor(e,t={}){super(e),this[fr]=void 0===t.code?0:t.code,this[mr]=void 0===t.reason?"":t.reason,this[gr]=void 0!==t.wasClean&&t.wasClean}get code(){return this[fr]}get reason(){return this[mr]}get wasClean(){return this[gr]}}Object.defineProperty(br.prototype,"code",{enumerable:!0}),Object.defineProperty(br.prototype,"reason",{enumerable:!0}),Object.defineProperty(br.prototype,"wasClean",{enumerable:!0});class wr extends vr{constructor(e,t={}){super(e),this[pr]=void 0===t.error?null:t.error,this[dr]=void 0===t.message?"":t.message}get error(){return this[pr]}get message(){return this[dr]}}Object.defineProperty(wr.prototype,"error",{enumerable:!0}),Object.defineProperty(wr.prototype,"message",{enumerable:!0});class Er extends vr{constructor(e,t={}){super(e),this[hr]=void 0===t.data?null:t.data}get data(){return this[hr]}}Object.defineProperty(Er.prototype,"data",{enumerable:!0});const Sr={addEventListener(e,t,r={}){for(const n of this.listeners(e))if(!r[lr]&&n[ur]===t&&!n[lr])return;let n;if("message"===e)n=function(e,r){const n=new Er("message",{data:r?e:e.toString()});n[yr]=this,kr(t,this,n)};else if("close"===e)n=function(e,r){const n=new br("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[yr]=this,kr(t,this,n)};else if("error"===e)n=function(e){const r=new wr("error",{error:e,message:e.message});r[yr]=this,kr(t,this,r)};else{if("open"!==e)return;n=function(){const e=new vr("open");e[yr]=this,kr(t,this,e)}}n[lr]=!!r[lr],n[ur]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[ur]===t&&!r[lr]){this.removeListener(e,r);break}}};var xr={CloseEvent:br,ErrorEvent:wr,Event:vr,EventTarget:Sr,MessageEvent:Er};function kr(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:Tr}=Mt.exports;function Cr(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var Pr={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let r,n,s=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,u=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===u&&1===Tr[l])-1===c&&(c=f);else if(0===f||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===u&&(u=f);const n=e.slice(c,u);44===l?(Cr(t,n,s),s=Object.create(null)):r=n,c=u=-1}}else-1===u&&-1!==c&&(u=f);else if(void 0===n)if(-1===u&&1===Tr[l])-1===c&&(c=f);else if(32===l||9===l)-1===u&&-1!==c&&(u=f);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===u&&(u=f),Cr(s,e.slice(c,u),!0),44===l&&(Cr(t,r,s),s=Object.create(null),r=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${f}`);n=e.slice(c,f),c=u=-1}else if(o){if(1!==Tr[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:i||(i=!0),o=!1}else if(a)if(1===Tr[l])-1===c&&(c=f);else if(34===l&&-1!==c)a=!1,u=f;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${f}`);o=!0}else if(34===l&&61===e.charCodeAt(f-1))a=!0;else if(-1===u&&1===Tr[l])-1===c&&(c=f);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===u&&(u=f);let o=e.slice(c,u);i&&(o=o.replace(/\\/g,""),i=!1),Cr(s,n,o),44===l&&(Cr(t,r,s),s=Object.create(null),r=void 0),n=void 0,c=u=-1}}else-1===u&&(u=f);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===u&&(u=f);const h=e.slice(c,u);return void 0===r?Cr(t,h,s):(void 0===n?Cr(s,h,!0):Cr(s,n,i?h.replace(/\\/g,""):h),Cr(t,r,s)),t}};const Nr=w.default,Or=m.default,Ir=d.default,Ar=_.default,Rr=E.default,{randomBytes:Fr,createHash:Lr}=v.default,{URL:Mr}=x.default,Ur=At,Br=Xt,Wr=cr,{BINARY_TYPES:Dr,EMPTY_BUFFER:jr,GUID:qr,kForOnEventAttribute:Vr,kListener:Gr,kStatusCode:Kr,kWebSocket:$r,NOOP:zr}=ht,{EventTarget:{addEventListener:Yr,removeEventListener:Hr}}=xr,{format:Jr,parse:Xr}=Pr,{toBuffer:Zr}=ft.exports,Qr=Symbol("kAborted"),en=[8,13],tn=["CONNECTING","OPEN","CLOSING","CLOSED"],rn=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class nn extends Nr{constructor(e,t,r){super(),this._binaryType=Dr[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=jr,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=nn.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),on(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){Dr.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const n=new Br({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new Wr(e,this._extensions,r.generateMask),this._receiver=n,this._socket=e,n[$r]=this,e[$r]=this,n.on("conclude",hn),n.on("drain",pn),n.on("error",dn),n.on("message",yn),n.on("ping",_n),n.on("pong",gn),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",bn),e.on("data",wn),e.on("end",En),e.on("error",Sn),this._readyState=nn.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=nn.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[Ur.extensionName]&&this._extensions[Ur.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=nn.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==nn.CLOSED)if(this.readyState!==nn.CONNECTING)this.readyState!==nn.CLOSING?(this._readyState=nn.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),3e4)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";un(this,this._req,e)}}pause(){this.readyState!==nn.CONNECTING&&this.readyState!==nn.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===nn.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===nn.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||jr,t,r)):fn(this,e,r)}pong(e,t,r){if(this.readyState===nn.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===nn.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||jr,t,r)):fn(this,e,r)}resume(){this.readyState!==nn.CONNECTING&&this.readyState!==nn.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===nn.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==nn.OPEN)return void fn(this,e,r);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Ur.extensionName]||(n.compress=!1),this._sender.send(e||jr,n,r)}terminate(){if(this.readyState!==nn.CLOSED)if(this.readyState!==nn.CONNECTING)this._socket&&(this._readyState=nn.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";un(this,this._req,e)}}}Object.defineProperty(nn,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")}),Object.defineProperty(nn.prototype,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")}),Object.defineProperty(nn,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")}),Object.defineProperty(nn.prototype,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")}),Object.defineProperty(nn,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")}),Object.defineProperty(nn.prototype,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")}),Object.defineProperty(nn,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")}),Object.defineProperty(nn.prototype,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(nn.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(nn.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[Vr])return t[Gr];return null},set(t){for(const t of this.listeners(e))if(t[Vr]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[Vr]:!0})}})})),nn.prototype.addEventListener=Yr,nn.prototype.removeEventListener=Hr;var sn=nn;function on(e,t,r,n){const s={protocolVersion:en[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!en.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${en.join(", ")})`);let i;if(t instanceof Mr)i=t,e._url=t.href;else{try{i=new Mr(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}e._url=t}const o="wss:"===i.protocol,a="ws+unix:"===i.protocol;let c;if("ws:"===i.protocol||o||a?a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void an(e,t)}const l=o?443:80,u=Fr(16).toString("base64"),f=o?Or.request:Ir.request,h=new Set;let p,d;if(s.createConnection=o?ln:cn,s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(p=new Ur(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Jr({[Ur.extensionName]:p.offer()})),r.length){for(const e of r){if("string"!=typeof e||!rn.test(e)||h.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(e)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?s.socketPath:i.host;const t=n&&n.headers;if(n={...n,headers:{}},t)for(const[e,r]of Object.entries(t))n.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),d=e._req=f(s),e._redirects&&e.emit("redirect",e.url,d)}else d=e._req=f(s);s.timeout&&d.on("timeout",(()=>{un(e,d,"Opening handshake has timed out")})),d.on("error",(t=>{null===d||d[Qr]||(d=e._req=null,an(e,t))})),d.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void un(e,d,"Maximum redirects exceeded");let i;d.abort();try{i=new Mr(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void an(e,r)}on(e,i,r,n)}else e.emit("unexpected-response",d,i)||un(e,d,`Unexpected server response: ${i.statusCode}`)})),d.on("upgrade",((t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==nn.CONNECTING)return;if(d=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void un(e,r,"Invalid Upgrade header");const i=Lr("sha1").update(u+qr).digest("base64");if(t.headers["sec-websocket-accept"]!==i)return void un(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?h.size?h.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":h.size&&(a="Server sent no subprotocol"),a)return void un(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!p){return void un(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Xr(c)}catch(t){return void un(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==Ur.extensionName){return void un(e,r,"Server indicated an extension that was not requested")}try{p.accept(t[Ur.extensionName])}catch(t){return void un(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Ur.extensionName]=p}e.setSocket(r,n,{generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),d.end()}function an(e,t){e._readyState=nn.CLOSING,e.emit("error",t),e.emitClose()}function cn(e){return e.path=e.socketPath,Ar.connect(e)}function ln(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Ar.isIP(e.host)?"":e.host),Rr.connect(e)}function un(e,t,r){e._readyState=nn.CLOSING;const n=new Error(r);Error.captureStackTrace(n,un),t.setHeader?(t[Qr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(an,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function fn(e,t,r){if(t){const r=Zr(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${tn[e.readyState]})`);process.nextTick(r,t)}}function hn(e,t){const r=this[$r];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[$r]&&(r._socket.removeListener("data",wn),process.nextTick(vn,r._socket),1005===e?r.close():r.close(e,t))}function pn(){const e=this[$r];e.isPaused||e._socket.resume()}function dn(e){const t=this[$r];void 0!==t._socket[$r]&&(t._socket.removeListener("data",wn),process.nextTick(vn,t._socket),t.close(e[Kr])),t.emit("error",e)}function mn(){this[$r].emitClose()}function yn(e,t){this[$r].emit("message",e,t)}function _n(e){const t=this[$r];t.pong(e,!t._isServer,zr),t.emit("ping",e)}function gn(e){this[$r].emit("pong",e)}function vn(e){e.resume()}function bn(){const e=this[$r];let t;this.removeListener("close",bn),this.removeListener("data",wn),this.removeListener("end",En),e._readyState=nn.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[$r]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",mn),e._receiver.on("finish",mn))}function wn(e){this[$r]._receiver.write(e)||this.pause()}function En(){const e=this[$r];e._readyState=nn.CLOSING,e._receiver.end(),this.end()}function Sn(){const e=this[$r];this.removeListener("error",Sn),this.on("error",zr),e&&(e._readyState=nn.CLOSING,this.destroy())}const{Duplex:xn}=S.default;function kn(e){e.emit("close")}function Tn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Cn(e){this.removeListener("error",Cn),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var Pn=function(e,t){let r=!0;const n=new xn({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const s=!r&&n._readableState.objectMode?t.toString():t;n.push(s)||e.pause()})),e.once("error",(function(e){n.destroyed||(r=!1,n.destroy(e))})),e.once("close",(function(){n.destroyed||n.push(null)})),n._destroy=function(t,s){if(e.readyState===e.CLOSED)return s(t),void process.nextTick(kn,n);let i=!1;e.once("error",(function(e){i=!0,s(e)})),e.once("close",(function(){i||s(t),process.nextTick(kn,n)})),r&&e.terminate()},n._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){n._final(t)}))},n._read=function(){e.isPaused&&e.resume()},n._write=function(t,r,s){e.readyState!==e.CONNECTING?e.send(t,s):e.once("open",(function(){n._write(t,r,s)}))},n.on("end",Tn),n.on("error",Cn),n};const{tokenChars:Nn}=Mt.exports;var On={parse:function(e){const t=new Set;let r=-1,n=-1,s=0;for(;s<e.length;s++){const i=e.charCodeAt(s);if(-1===n&&1===Nn[i])-1===r&&(r=s);else if(0===s||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${s}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${s}`);-1===n&&(n=s);const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=n=-1}}else-1===n&&-1!==r&&(n=s)}if(-1===r||-1!==n)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const In=w.default,An=d.default,{createHash:Rn}=v.default,Fn=Pr,Ln=At,Mn=On,Un=sn,{GUID:Bn,kWebSocket:Wn}=ht,Dn=/^[+/0-9A-Za-z]{22}==$/,jn=2;var qn=class extends In{constructor(e,t){if(super(),null==(e={maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Un,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=An.createServer(((e,t)=>{const r=An.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===jn)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(Vn,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(Vn,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Vn(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",Gn);const s=e.headers["sec-websocket-key"],i=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void $n(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void $n(this,e,t,400,"Invalid Upgrade header")}if(!s||!Dn.test(s)){return void $n(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==i&&13!==i){return void $n(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void Kn(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=Mn.parse(o)}catch(r){return void $n(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const c=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&void 0!==c){const r=new Ln(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Fn.parse(c);e[Ln.extensionName]&&(r.accept(e[Ln.extensionName]),l[Ln.extensionName]=r)}catch(r){return void $n(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[""+(8===i?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,((i,o,c,u)=>{if(!i)return Kn(t,o||401,c,u);this.completeUpgrade(l,s,a,e,t,r,n)}));if(!this.options.verifyClient(o))return Kn(t,401)}this.completeUpgrade(l,s,a,e,t,r,n)}completeUpgrade(e,t,r,n,s,i,o){if(!s.readable||!s.writable)return s.destroy();if(s[Wn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Kn(s,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Rn("sha1").update(t+Bn).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[Ln.extensionName]){const t=e[Ln.extensionName].params,r=Fn.format({[Ln.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,n),s.write(a.concat("\r\n").join("\r\n")),s.removeListener("error",Gn),c.setSocket(s,i,{maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Vn,this)}))),o(c,n)}};function Vn(e){e._state=jn,e.emit("close")}function Gn(){this.destroy()}function Kn(e,t,r,n){r=r||An.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${An.STATUS_CODES[t]}\r\n`+Object.keys(n).map((e=>`${e}: ${n[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function $n(e,t,r,n,s){if(e.listenerCount("wsClientError")){const n=new Error(s);Error.captureStackTrace(n,$n),e.emit("wsClientError",n,r,t)}else Kn(r,n,s)}const zn=sn;zn.createWebSocketStream=Pn,zn.Server=qn,zn.Receiver=Xt,zn.Sender=cr,zn.WebSocket=zn,zn.WebSocketServer=zn.Server;var Yn=zn,Hn="3.0.0",Jn=require("child_process"),Xn=require("url"),Zn=require("events"),Qn=Yn.Server,es="ffmpeg",ts="mpeg1video",rs="mp2",ns=!1,ss=!0,is="drawtext=x=w-tw-100:y=100:fontcolor=white:fontsize=36:text="+decodeURIComponent(ut.exports.decode("JUU1JThFJUJCJUU5JTk5JUE0JUU2JUIwJUI0JUU1JThEJUIwUVElRUYlQkMlOUE0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",os=60,as=10,cs=["-s","-b:v","scale","contrast","brightness","saturation","gamma"].concat(["vcodec"]),ls=["scale","contrast","brightness","saturation","gamma"],us=function(e,t){switch(e){case"-s":if(t.includes("x")&&t.split("x")[0]&&t.split("x")[0]>0&&t.split("x")[1]&&t.split("x")[1]>0)return!0;break;case"vcodec":case"c:v":case"-c:v":case"codec:v":case"contrast":case"brightness":case"saturation":case"gamma":if(t)return!0;break;case"-b:v":if(t.endsWith("k"))return!0;break;case"scale":if(t.includes(":")&&t.split(":")[0]&&t.split(":")[1])return!0}},fs=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&R(e,t)}(r,Zn.EventEmitter);var t=L(r);function r(e){var n;return P(this,r),I(F(n=t.call(this)),"exitCode",void 0),I(F(n),"additionalFlags",[]),I(F(n),"stream",null),I(F(n),"inputStreamStarted",!1),n.ffmpegPath=es,n.url=e.url,n.ffmpegOptions=e.ffmpegOptions,n.options=e,n.initMpeg2Muxer(),n}return O(r,[{key:"initMpeg2Muxer",value:function(){var e=this;if(this.ffmpegOptions)for(var t in this.ffmpegOptions)this.additionalFlags.push(t),""!==String(this.ffmpegOptions[t])&&this.additionalFlags.push(String(this.ffmpegOptions[t]));this.spawnOptions=["-rtsp_transport","tcp","-i",this.url,"-f","mpegts","-codec:v",ts,"-codec:a",rs,ns?"-an":null,"-ar","48000","-ac","1","-thread_queue_size","256","-threads","8"].concat(U(this.additionalFlags),["-nostats","-r","29.97","-"]),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=Jn.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数")})),this.stream.on("exit",(function(t,r){if(1===t)return console.error("***由于ffmpeg退出,ffmpeg启动不成功,请检查ffmpeg参数或相关情况或联系作者***"),e.exitCode=1,e.emit("exitWithError")})),this.stream.on("close",(function(t,r){return console.log("ffmpeg关闭,code:",t),e.emit("ffmpegClosed")})),this.inputStreamStarted=!0,this.stream.stdout.on("data",(function(t){return e.emit("mpeg2data",t)})),this.stream.stderr.on("data",(function(t){return e.emit("ffmpegStderr",t)}))}}]),r}(),hs=function(){function e(t){P(this,e),I(this,"freeTime",0),I(this,"width",null),I(this,"height",null),I(this,"isStreamWrap",!1),I(this,"clients",[]),I(this,"mpeg2Muxer",{instance:null,stream:null,data:null}),this.config=t,this.url=t.url}return O(e,[{key:"createStream",value:function(){var e=this;this.isStreamWrap||(console.log("创建一个新的ffmpeg子进程"),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new fs({url:this.url,ffmpegOptions:this.formatParams(this.config)}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.mpeg2Muxer.instance.on("mpeg2data",(function(t){e.broadcast(t)})),this.mpeg2Muxer.instance.on("ffmpegStderr",(function(t){var r;-1!==(t=t.toString()).indexOf("Output #")&&null!=(r=t.match(/\d+x\d+/))&&(r=r[0].split("x"),null==e.width&&(e.width=parseInt(r[0],10)),null==e.height&&(e.height=parseInt(r[1],10)))})),this.mpeg2Muxer.instance.on("ffmpegStderr",(function(e){})),this.mpeg2Muxer.instance.on("exitWithError",(function(){})),this.mpeg2Muxer.instance.on("ffmpegClosed",(function(){e.destroy()})))}},{key:"formatParams",value:function(e){for(var t={"-vf":is},r=0,n=Object.entries(e);r<n.length;r++){var s=M(n[r],2),i=s[0],o=s[1];cs.includes(i)&&(ls.includes(i)?"scale"===i?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(o)):t["-vf"]+="".concat(i,"=").concat(o,":"):us(i,o)&&(t[i]=o))}return t}},{key:"destroy",value:function(){var e,t;null===(e=this.mpeg2Muxer.stream)||void 0===e||e.kill(),this.mpeg2Muxer.stream=null,null===(t=this.mpeg2Muxer.instance)||void 0===t||t.removeAllListeners(),this.mpeg2Muxer.instance=null,this.isStreamWrap=!1,this.dropAllClient()}},{key:"broadcast",value:function(e){var t,r=D(this.clients);try{for(r.s();!(t=r.n()).done;){var n=t.value;n.isSegment&&n.send(e)}}catch(e){r.e(e)}finally{r.f()}}},{key:"addClient",value:function(e){var t=this;e.once("close",(function(){t.dropClient(e)})),this.clients.push(e),this.isStreamWrap||this.createStream(),e.isSegment=!0}},{key:"dropClient",value:function(e){var t=this.clients.indexOf(e);e.isSegment=!1,e.terminate(),e=null,console.log("视频关闭,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=D(this.clients);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.isSegment=!1,r.terminate()}}catch(e){t.e(e)}finally{t.f()}this.clients=[]}}]),e}(),ps=function(){function e(t){var r=this;P(this,e),I(this,"channels",[]),console.log("current rtsp2web version: ",Hn),t&&"boolean"==typeof t.wm&&!t.wm&&(is="scale=-1:-1,eq=",ss=!1),t&&"string"==typeof t.path&&t.path.length>0&&(es=t.path),t&&"string"==typeof t.vcodec&&t.vcodec.length>0&&(ts=t.vcodec),t&&"boolean"==typeof t.audio&&!t.audio&&(ns=!0),t&&["string","number"].includes(C(t.freeTime))&&"number"==typeof parseInt(t.freeTime,10)&&(os=parseInt(t.freeTime,10)),t&&["string","number"].includes(C(t.checkTime))&&"number"==typeof parseInt(t.checkTime,10)&&(as=parseInt(t.checkTime,10)),setInterval((function(){r.checkFree(),ss&&(is.includes(decodeURIComponent(ut.exports.decode("ZHJhd3RleHQlM0R4JTNEdy10dy0xMDAlM0F5JTNEMTAwJTNBZm9udGNvbG9yJTNEd2hpdGUlM0Fmb250c2l6ZSUzRDM2JTNBdGV4dCUzRCVFNSU4RSVCQiVFOSU5OSVBNCVFNiVCMCVCNCVFNSU4RCVCMFFRJUVGJUJDJTlBNDIxMzU0NTMyJTNBYm94JTNEMSUzQWJveGNvbG9yJTNEYmxhY2s=")))||(r.destroyAllChannel(),console.log("***代码异常***,请联系作者11111"),global.process.stderr.write("***代码异常***,请联系作者22222")))}),1e3*as);var n=d.default.createServer();if(t&&"object"===C(t.wss))if(console.log("wss启动中...."),t.wss.hasOwnProperty("pfx"))if(t.wss.hasOwnProperty("passphrase"))try{var s={pfx:y.default.readFileSync(t.wss.pfx),passphrase:y.default.readFileSync(t.wss.passphrase)};G.readPkcs12(s.pfx,{p12Password:s.passphrase},(function(e,t){n=m.default.createServer({cert:t.cert,key:t.key})}))}catch(e){console.error("--【读取pfx安全证书文件出错,wss启动失败,退回到ws;错误信息如下,有问题请联系我】--"),console.log(e)}else console.error("【wss启动失败;请传入正确的pfx文件指定密码:passphrase】");else if(t.wss.hasOwnProperty("cert"))if(t.wss.hasOwnProperty("key"))try{n=m.default.createServer({cert:y.default.readFileSync(t.wss.cert),key:y.default.readFileSync(t.wss.key)})}catch(e){console.error("--【读取cert安全证书文件出错,wss启动失败,退回到ws;错误信息如下,有问题请联系我】--"),console.log(e)}else console.error("【wss启动失败;请传入正确的安全证书私钥:key】");else console.error("【wss启动失败;请传入正确的安全证书公钥:cert】");this.wss=new Qn({server:n}),this.wss.on("connection",(function(e,t){var n=Xn.parse(t.url,!0);if(n.query.url){var s=ut.exports.decode(n.query.url.toString());n.query.url=s,r.registeClient(e,{url:s,options:n.query})}console.log("一个新的client(ws句柄)连接成功")})),n.listen(t&&t.port||9999)}return O(e,[{key:"registeClient",value:function(e,t){var r=this.getChannel(t.url);r||(r=this.createChannel(t.options,e)),r.addClient(e)}},{key:"getChannel",value:function(e){var t,r=D(this.channels);try{for(r.s();!(t=r.n()).done;){var n=t.value;if(n.url===e)return n}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new hs(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=D(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=as,r.freeTime>=os&&this.destroyChannel(r)}}catch(e){t.e(e)}finally{t.f()}}},{key:"destroyChannel",value:function(e){var t=this.channels.indexOf(e);t>-1&&(this.channels.splice(t,1),e.destroy())}},{key:"destroyAllChannel",value:function(){var e,t=D(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;this.destroyChannel(r)}}catch(e){t.e(e)}finally{t.f()}}}]),e}();I(ps,"version",Hn),module.exports=ps;
|