rtsp2web 3.1.3 → 3.1.5

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 CHANGED
@@ -1,6 +1,21 @@
1
1
  # rtsp2web
2
2
 
3
- `rtsp2web` 是一个提供在 `web` 页面中可以直接播放 `rtsp` 视频流解决方案的工具。
3
+ `rtsp2web` 是一个提供在 `web` 页面中可以直接播放 `rtsp` 视频流解决方案的工具;简单、高效、快捷、安全。
4
+
5
+ # 特点
6
+
7
+ - 上手简单,提供的示例代码完整可运行,无需繁琐复杂的技术负担,直接运行代码,快速解决视频流播放的问题;
8
+ - 延时非常低,视频流稳定,几乎是实时的,满足任何需求;不花钱,采用开源框架,无商业风险;
9
+ - 相比较于收费平台,需要暴露 RTSP 视频流链接给收费平台,rtsp2web 无需您提供 RTSP 视频流,您的保密&安全牢牢掌握在您手中;
10
+ - 高效兼容,大多数 nvr 或 ipc 或摄像头平台都支持输出 RTSP 视频流,rtsp2web 把 RTSP 视频流转换到页面可播放,减少对接工作,不论您是什么摄像头;
11
+ - 支持前端使用 `jsmpeg.js`、`flv.js` 等播放器,满足不同技术栈团队使用;
12
+ - 删繁就简,无需插件就可在浏览器显示视频画面,兼容各大浏览器厂商;
13
+ - 省时省力,同一页面可以播放不同厂家的视频,无需任何额外操作;
14
+ - 可以在公网上部署使用,但也可能因为你们公司网络的设置原因,你会面临一点小问题:还要学习网络穿透打洞,服务器部署能力,流量消耗,wss 等。
15
+
16
+ # 支持的视频厂商
17
+
18
+ 海康、海康 NVR、大华平台、萤石、宇视、中天信科达、东方网力、天地伟业等
4
19
 
5
20
  # How to use(如何在你的项目中使用这个工具)
6
21
 
@@ -8,8 +23,6 @@
8
23
 
9
24
  FFmpeg 是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。可以轻易地实现多种视频格式之间的相互转换。
10
25
 
11
- FFmpeg 的用户有 Google,腾讯视频,Youtube,优酷,爱奇艺,土豆等。
12
-
13
26
  **确保在你要运行 rtsp2web 的机器上已经安装了 FFmpeg。**
14
27
 
15
28
  > _有问题,可以联系我_
@@ -18,9 +31,9 @@ FFmpeg 的用户有 Google,腾讯视频,Youtube,优酷,爱奇艺,土
18
31
 
19
32
  ## rtsp2web 介绍
20
33
 
21
- `rtsp2web` 是一个 `node.js` 包,你可以创建一个新项目引入它,并单独的运行它;也可以集成到已有的项目中(如果你知道怎么做的话)。
34
+ `rtsp2web` 是一个 `node.js` 包,你可以创建一个新的项目引入它,这样很简单,然后运行它即可;也可以把 `rtps2web` 集成到已有的项目中,随项目运行(如果你知道怎么做的话);
22
35
 
23
- **这里以创建一个新项目运行它为例:**
36
+ **这里以创建一个新项目运行它为例:(_这是最简单的做法_)**
24
37
 
25
38
  1、**创建一个新的文件夹(假如文件夹名叫:`rtsp_server`)**,_注意 ⚠️:文件夹名称不能是 `rtsp2web`,这是 `npm` 的规则_。
26
39
 
@@ -38,7 +51,7 @@ npm i rtsp2web
38
51
  // main.js
39
52
  const RTSP2web = require('rtsp2web')
40
53
 
41
- // 服务端长连接占据的端口号;端口号可以自定义
54
+ // 服务端长连接占据的端口号;你也可以不传,默认是:9999
42
55
  let port = 9999
43
56
 
44
57
  // 创建一个RTSP2web服务实例出来
@@ -53,16 +66,17 @@ new RTSP2web({
53
66
  | :-----------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
54
67
  | port | 转码推流服务占用的端口号;(type:Number)<br/>可以不传;默认值:9999 |
55
68
  | path | FFmpeg 命令在你机器上的启动名称,(type: String) <br/> 一般情况下不传;默认值:'ffmpeg' |
56
- | audio | 默认可以不传,有声音;默认值:true;即:输出音频。<br/>audio: false - 禁止输出音频 |
57
- | freeTime | 任一视频流空闲(未被使用)时间超过这个值,就会停止该视频流的转码,释放机器资源(type: Number;单位:秒) <br/> 一般情况下不传;默认值:60 |
58
- | checkTime | 检测视频空闲的时间间隔(type: Number;单位:秒) <br/> 一般情况下不传;默认值:10 |
69
+ | audio | 默认不传,有声音;默认值:true;即:输出音频。<br/>如果想禁止输出音频,可以配置 audio: false |
70
+ | freeTime | 任一视频流空闲(未被使用)时间超过这个值,就会停止该视频流的转码,释放机器资源(type: Number;单位:秒) <br/> 一般情况下可不传;默认值:20 |
71
+ | checkTime | 检测视频空闲的时间间隔(type: Number;单位:秒) <br/> 一般情况下可不传;默认值:10 |
59
72
  | q | 视频质量;取值范围:0-1000;数字越小,视频越清晰,带宽消耗越大<br/> 默认值:2; |
60
- | transportType | 设置 RTSP 传输协议、默认值:tcp<br/>可选值:['tcp', 'udp', 'udp_multicast', 'http', 'https'] |
73
+ | transportType | 设置 RTSP 传输协议,默认值:'tcp'<br/>可选值:['', 'tcp', 'udp', 'udp_multicast', 'http', 'https'] |
74
+ | webplayer | 设置前端播放器(视频流转码器),默认不传,默认值:'jsmpeg'<br/>可选值:['jsmpeg', 'flv'] |
61
75
  | wss | 配置 wss;配置格式如下:<br/> `wss: {key: 'keyPath', cert: 'certPath'}` <br/>如果你是 pfx 的证书,那么配置格式如下:<br/>`wss: {pfx: 'pfxPath', passphrase: 'passphrasePath'}`<br/>如果你想使用`wss`的话请配置这个选项,否则不要使用这个配置。 |
62
76
 
63
77
  ---
64
78
 
65
- 5、 运行 `node main.js`,启动视频流转码服务
79
+ 5、 运行 `node main.js`,即可启动视频流转码服务
66
80
 
67
81
  > 当然,你也可以选择你习惯的进程管理工具来启动它。如:`pm2` 之类的工具。
68
82
 
@@ -75,7 +89,7 @@ new RTSP2web({
75
89
  > 1、需要 canvas 视频播放容器;2、rtsp 源地址;3、new 一个播放实例。
76
90
 
77
91
  ```html
78
- // index.html
92
+ <!-- index.html -->
79
93
  <!DOCTYPE html>
80
94
  <html lang="en">
81
95
  <head>
@@ -95,14 +109,14 @@ new RTSP2web({
95
109
  <!-- 方式二: 只给定宽度或者高度,另外一个值将会自适应;整体比例与原视频一致 -->
96
110
  <canvas id="canvas-2" style="width: 400px"></canvas>
97
111
 
98
- <!-- 方式二、一: 可以自定义视频播放窗口的宽度和高度,会铺满,比例可能与原视频不一致了-->
99
- <canvas id="canvas-2-1" style="width: 400px; height: 400px"></canvas>
112
+ <!-- 方式三: 可以自定义视频播放窗口的宽度和高度,会铺满,比例可能与原视频不一致了-->
113
+ <canvas id="canvas-3" style="width: 400px; height: 400px"></canvas>
100
114
 
101
- <!-- 方式三:虽然设置了固定的宽高,但是视频还是会选择安宽度来自适应,比例与原视频保持一致 -->
102
- <!-- 使用div + class="jsmpeg" + data-url的方式 -->
115
+ <!-- 方式四:使用div + class="jsmpeg" + data-url的方式 -->
116
+ <!-- 这种方式虽然设置了固定的宽高,但是视频还是会选择安宽度来自适应,比例与原视频保持一致 -->
103
117
  <div
104
118
  class="jsmpeg"
105
- id="canvas-3"
119
+ id="canvas-4"
106
120
  style="width: 400px; height: 400px; border: 1px solid red"
107
121
  data-url="ws://localhost:9999/rtsp?url=cnRzcDovL3dvd3phZWMyZGVtby5zdHJlYW1sb2NrLm5ldC92b2QvbXA0OkJpZ0J1Y2tCdW5ueV8xMTVrLm1wNA=="
108
122
  ></div>
@@ -135,7 +149,7 @@ new RTSP2web({
135
149
 
136
150
  6.3、参数说明
137
151
 
138
- > 如上面的例子所示:在调用 `new JSMpeg.Player()` 时,第一个参数是接口地址拼接上`rtsp`地址,我们还可以使用 `url` 传参的方式传递更多的高阶参数。
152
+ > 如上面的例子所示:在调用 `new JSMpeg.Player()` 时,第一个参数是接口地址拼接上 `rtsp` 地址,我们还可以使用 `url` 传参的方式传递更多的高阶参数。
139
153
 
140
154
  | 参数 | 解释说明 |
141
155
  | :--------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
@@ -177,14 +191,53 @@ wechat: miracle421354532
177
191
 
178
192
  `rtsp2web` 默认自动转码音频并输出,你也可以根据配置设置,选择禁止音频输出。
179
193
 
180
- > _在浏览器中,自动播放声音是突兀的,根据规则,需要用户在页面任意地方进行任意的点击操作,就有声音了;为了播放声音,请先点击页面一次。_
194
+ > _在浏览器中,自动播放声音是突兀的;根据浏览器规则,需要用户在页面任意地方进行任意的点击操作,就有声音了;如果配置了输出音频,为了播放声音,请先点击页面一次。_
181
195
 
182
196
  # WSS
183
197
 
184
198
  `rtsp2web` 已经支持直接开启 `wss` 协议了;
185
199
 
200
+ # 支持 flv.js
201
+
202
+ `flv.js` 比 `jsmpeg.js` 的播放性能和效果更好,而且 `flv.js` 播放器,默认就有进度条、在线回放、全屏、画中画、倍速播放等功能,有需要的可以选择 `flv.js`。
203
+
204
+ 如果你的前端代码中使用的是 `flv.js` 或者你想在前端代码中使用 `flv.js` 来播放视频的话,你可以按如下操作:
205
+
206
+ ```js
207
+ console.log('flvjs 是否支持:', flvjs.isSupported())
208
+ if (flvjs.isSupported()) {
209
+ var videoElement = document.getElementById('flv-1')
210
+ var flvPlayer = flvjs.createPlayer({
211
+ isLive: true,
212
+ type: 'flv',
213
+ url: 'ws://localhost:8098/rtsp?url=' + btoa(rtsp7) + '&webplayer=flv',
214
+ enableWorker: true,
215
+ enableStashBuffer: false,
216
+ stashInitialSize: 128 // 减少首桢显示等待时长
217
+ })
218
+ flvPlayer.attachMediaElement(videoElement)
219
+ try {
220
+ flvPlayer.load()
221
+ flvPlayer.play()
222
+ // flvPlayer.pause()
223
+ } catch (err) {
224
+ //
225
+ }
226
+ }
227
+ ```
228
+
229
+ 详细参考例子:[https://github.com/Neveryu/rtsp2web/tree/master/example](https://github.com/Neveryu/rtsp2web/tree/master/example)
230
+
231
+ 有任何不明白的,及时与我联系:[联系我](https://neveryu.blog.csdn.net/article/details/124124137);
232
+
233
+ wechat: miracle421354532
234
+
186
235
  # Change Log [更新日志]
187
236
 
237
+ 【2023-06-14】支持前端使用 `flv.js` 来播放视频,`flv.js` 性能更好,功能丰富;
238
+
239
+ 【2023-06-06】性能优化,提升 rtsp2web 可同时支撑转码的视频数量;解决了少数情况下可能出现的视频流转码进程退出导致的播放失败的问题;
240
+
188
241
  【2023-04-05】基于[key 和 cert]的 SSL 证书验证通过;基于[pfx 和 passphrase]的 SSL 证书验证通过;
189
242
 
190
243
  【2023-03-28】测试:在 `linux` 平台上能正确播放,并解决在 `linux` 平台上播放的问题。
@@ -209,7 +262,11 @@ wechat: miracle421354532
209
262
 
210
263
  # 常见问题解决办法
211
264
 
212
- ### 一、ffmpeg 进程关闭了,code:3221225477
265
+ ### 一、模式转换失败 | 进程退出,请检查 ffmpeg 参数或...
266
+
267
+ 如果出现了这之类的提示,大多数情况下,你可能需要尝试配置 `transportType` 为其他值试试,`'tcp'`, `'udp'`是最常见的选择。
268
+
269
+ ### 二、ffmpeg 进程关闭了,code:3221225477
213
270
 
214
271
  > 如果出现了 `3221225477`;这是 NodeJS 内核反馈的[违反了访问规定]的问题,一般这个问题只发生在 `windows` 平台上,可以尝试的操作有:
215
272
 
@@ -219,10 +276,16 @@ wechat: miracle421354532
219
276
  - 4、`rm -rf node_modules`,`delete package-lock.json`,重新安装,再试试;
220
277
  - 5、[待验证]切换合适的 `node` 版本可解决;
221
278
 
222
- ### 二、转换失败,请尝试改变 transportType 的值,然后重试。
279
+ ### 三、转换失败,请尝试改变 transportType 的值,然后重试。
223
280
 
224
281
  > 你可以尝试配置 `transportType` 为其他值试试,`'tcp'`, `'udp'`是最常见的选择。
225
282
 
283
+ # 以下客户使用了 rtsp2web
284
+
285
+ > 江苏石油化工油罐工厂、江苏镇江石化、武汉丽岛物业、武汉恒阳化工厂、苏州工业园区等
286
+
287
+ 还有一些个人、企业用户。
288
+
226
289
  # donate
227
290
 
228
291
  If you think rtsp2web help you. maybe you can donate a litter. :beers::beers:
package/dist/rtsp2web.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * rtsp2web v3.1.3
2
+ * rtsp2web v3.1.5
3
3
  * (c) 2020-2023 NeverYu
4
4
  * My home page:https://neveryu.github.io/neveryu/
5
5
  * 微信(wechat):miracle421354532
@@ -7,4 +7,4 @@
7
7
  */
8
8
  "use strict";var e=require("http"),t=require("https"),r=require("tls"),s=require("fs"),n=require("events"),i=require("net"),o=require("crypto"),a=require("stream"),c=require("url"),l=require("zlib"),h=require("buffer");function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=f(e),u=f(t),p=f(r),_=f(s),m=f(n),y=f(i),g=f(o),v=f(a),b=f(c),w=f(l),S=f(h);function k(e){return k="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},k(e)}function x(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function E(e,t){for(var r=0;r<t.length;r++){var s=t[r];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,A(s.key),s)}}function O(e,t,r){return t&&E(e.prototype,t),r&&E(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function C(e,t,r){return(t=A(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function T(e){return T=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},T(e)}function N(e,t){return N=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},N(e,t)}function L(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function P(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,s=T(e);if(t){var n=T(this).constructor;r=Reflect.construct(s,arguments,n)}else r=s.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 L(e)}(this,r)}}function R(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 s,n,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=(s=i.call(r)).done)&&(a.push(s.value),a.length!==t);c=!0);}catch(e){l=!0,n=e}finally{try{if(!c&&null!=r.return&&(o=r.return(),Object(o)!==o))return}finally{if(l)throw n}}return a}}(e,t)||I(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 M(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||I(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 I(e,t){if(e){if("string"==typeof e)return M(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)?M(e,t):void 0}}function M(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,s=new Array(t);r<t;r++)s[r]=e[r];return s}function B(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=I(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var s=0,n=function(){};return{s:n,n:function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}},e:function(e){throw e},f:n}}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 A(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=typeof s)return s;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 W="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},j={exports:{}};
9
9
  /*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */
10
- !function(e,t){!function(r){var s=t,n=e&&e.exports==s&&e,i="object"==typeof W&&W;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,h={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,s,n,i=e.length%3,o="",l=-1,h=e.length-i;++l<h;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,s=e.charCodeAt(++l),o+=c.charAt((n=t+r+s)>>18&63)+c.charAt(n>>12&63)+c.charAt(n>>6&63)+c.charAt(63&n);return 2==i?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),o+=c.charAt((n=t+r)>>10)+c.charAt(n>>4&63)+c.charAt(n<<2&63)+"="):1==i&&(n=e.charCodeAt(l),o+=c.charAt(n>>2)+c.charAt(n<<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,s,n=0,i="",o=-1;++o<t;)s=c.indexOf(e.charAt(o)),r=n%4?64*r+s:s,n++%4&&(i+=String.fromCharCode(255&r>>(-2*n&6)));return i},version:"1.0.0"};if(s&&!s.nodeType)if(n)n.exports=h;else for(var f in h)h.hasOwnProperty(f)&&(s[f]=h[f]);else r.base64=h}(W)}(j,j.exports);var F={exports:{}},D={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:q}=D,$=Buffer[Symbol.species];function G(e,t,r,s,n){for(let i=0;i<n;i++)r[s+i]=e[i]^t[3&i]}function V(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(F.exports={concat:function(e,t){if(0===e.length)return q;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let s=0;for(let t=0;t<e.length;t++){const n=e[t];r.set(n,s),s+=n.length}return s<t?new $(r.buffer,r.byteOffset,s):r},mask:G,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 $(t):ArrayBuffer.isView(t)?r=new $(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:V},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");F.exports.mask=function(t,r,s,n,i){i<48?G(t,r,s,n,i):e.mask(t,r,s,n,i)},F.exports.unmask=function(t,r){t.length<32?V(t,r):e.unmask(t,r)}}catch(e){}const z=Symbol("kDone"),H=Symbol("kRun");var Y=class{constructor(e){this[z]=()=>{this.pending--,this[H]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[H]()}[H](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[z])}}};const X=w.default,Q=F.exports,Z=Y,{kStatusCode:K}=D,J=Buffer[Symbol.species],ee=Buffer.from([0,0,255,255]),te=Symbol("permessage-deflate"),re=Symbol("total-length"),se=Symbol("callback"),ne=Symbol("buffers"),ie=Symbol("error");let oe;var ae=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,!oe){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;oe=new Z(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[se];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){oe.add((s=>{this._decompress(e,t,((e,t)=>{s(),r(e,t)}))}))}compress(e,t,r){oe.add((s=>{this._compress(e,t,((e,t)=>{s(),r(e,t)}))}))}_decompress(e,t,r){const s=this._isServer?"client":"server";if(!this._inflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?X.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=X.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[te]=this,this._inflate[re]=0,this._inflate[ne]=[],this._inflate.on("error",he),this._inflate.on("data",le)}this._inflate[se]=r,this._inflate.write(e),t&&this._inflate.write(ee),this._inflate.flush((()=>{const e=this._inflate[ie];if(e)return this._inflate.close(),this._inflate=null,void r(e);const n=Q.concat(this._inflate[ne],this._inflate[re]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[re]=0,this._inflate[ne]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,n)}))}_compress(e,t,r){const s=this._isServer?"server":"client";if(!this._deflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?X.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=X.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[re]=0,this._deflate[ne]=[],this._deflate.on("data",ce)}this._deflate[se]=r,this._deflate.write(e),this._deflate.flush(X.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Q.concat(this._deflate[ne],this._deflate[re]);t&&(e=new J(e.buffer,e.byteOffset,e.length-4)),this._deflate[se]=null,this._deflate[re]=0,this._deflate[ne]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function ce(e){this[ne].push(e),this[re]+=e.length}function le(e){this[re]+=e.length,this[te]._maxPayload<1||this[re]<=this[te]._maxPayload?this[ne].push(e):(this[ie]=new RangeError("Max payload size exceeded"),this[ie].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ie][K]=1009,this.removeListener("data",le),this.reset())}function he(e){this[te]._inflate=null,e[K]=1007,this[se](e)}var fe={exports:{}};const{isUtf8:de}=S.default;function ue(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(fe.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:ue,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]},de)fe.exports.isValidUTF8=function(e){return e.length<24?ue(e):de(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");fe.exports.isValidUTF8=function(t){return t.length<32?ue(t):e(t)}}catch(e){}const{Writable:pe}=v.default,_e=ae,{BINARY_TYPES:me,EMPTY_BUFFER:ye,kStatusCode:ge,kWebSocket:ve}=D,{concat:be,toArrayBuffer:we,unmask:Se}=F.exports,{isValidStatusCode:ke,isValidUTF8:xe}=fe.exports,Ee=Buffer[Symbol.species];var Oe=class extends pe{constructor(e={}){super(),this._binaryType=e.binaryType||me[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ve]=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 Ee(t.buffer,t.byteOffset+e,t.length-e),new Ee(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Ee(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,Ce(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[_e.extensionName])return this._loop=!1,Ce(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,Ce(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Ce(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,Ce(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,Ce(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Ce(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Ce(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,Ce(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,Ce(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Ce(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,Ce(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,Ce(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=ye;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])&&Se(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[_e.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(Ce(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const s=this.dataMessage();if(s)return t(s);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?be(t,e):"arraybuffer"===this._binaryType?we(be(t,e)):t,this.emit("message",r,!0)}else{const r=be(t,e);if(!this._skipUTF8Validation&&!xe(r))return this._loop=!1,Ce(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,ye),this.end();else{const t=e.readUInt16BE(0);if(!ke(t))return Ce(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=new Ee(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!xe(r))return Ce(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 Ce(e,t,r,s,n){const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,Ce),i.code=n,i[ge]=s,i}const{randomFillSync:Te}=g.default,Ne=ae,{EMPTY_BUFFER:Le}=D,{isValidStatusCode:Pe}=fe.exports,{mask:Re,toBuffer:Ue}=F.exports,Ie=Symbol("kByteLength"),Me=Buffer.alloc(4);class Be{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,s,n=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Me,t.generateMask?t.generateMask(r):Te(r,0,4),o=0==(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?s=t.mask&&!o||void 0===t[Ie]?(e=Buffer.from(e)).length:t[Ie]:(s=e.length,n=t.mask&&t.readOnly&&!o);let a=s;s>=65536?(i+=8,a=127):s>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(n?s+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(s,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(s,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]:n?(Re(e,r,c,i,s),[c]):(Re(e,r,e,0,s),[c,e])):[c,e]}close(e,t,r,s){let n;if(void 0===e)n=Le;else{if("number"!=typeof e||!Pe(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");n=Buffer.allocUnsafe(2+r),n.writeUInt16BE(e,0),"string"==typeof t?n.write(t,2):n.set(t,2)}else n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0)}const i={[Ie]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,n,!1,i,s]):this.sendFrame(Be.frame(n,i),s)}ping(e,t,r){let s,n;if("string"==typeof e?(s=Buffer.byteLength(e),n=!1):(s=(e=Ue(e)).length,n=Ue.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ie]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(Be.frame(e,i),r)}pong(e,t,r){let s,n;if("string"==typeof e?(s=Buffer.byteLength(e),n=!1):(s=(e=Ue(e)).length,n=Ue.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ie]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(Be.frame(e,i),r)}send(e,t,r){const s=this._extensions[Ne.extensionName];let n,i,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):(n=(e=Ue(e)).length,i=Ue.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=n>=s._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),s){const s={[Ie]:n,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,s,r]):this.dispatch(e,this._compress,s,r)}else this.sendFrame(Be.frame(e,{[Ie]:n,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:!1}),r)}dispatch(e,t,r,s){if(!t)return void this.sendFrame(Be.frame(e,r),s);const n=this._extensions[Ne.extensionName];this._bufferedBytes+=r[Ie],this._deflating=!0,n.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 s&&s(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],s=r[r.length-1];"function"==typeof s&&s(e)}}else this._bufferedBytes-=r[Ie],this._deflating=!1,r.readOnly=!1,this.sendFrame(Be.frame(t,r),s),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ie],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ie],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 Ae=Be;const{kForOnEventAttribute:We,kListener:je}=D,Fe=Symbol("kCode"),De=Symbol("kData"),qe=Symbol("kError"),$e=Symbol("kMessage"),Ge=Symbol("kReason"),Ve=Symbol("kTarget"),ze=Symbol("kType"),He=Symbol("kWasClean");class Ye{constructor(e){this[Ve]=null,this[ze]=e}get target(){return this[Ve]}get type(){return this[ze]}}Object.defineProperty(Ye.prototype,"target",{enumerable:!0}),Object.defineProperty(Ye.prototype,"type",{enumerable:!0});class Xe extends Ye{constructor(e,t={}){super(e),this[Fe]=void 0===t.code?0:t.code,this[Ge]=void 0===t.reason?"":t.reason,this[He]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Fe]}get reason(){return this[Ge]}get wasClean(){return this[He]}}Object.defineProperty(Xe.prototype,"code",{enumerable:!0}),Object.defineProperty(Xe.prototype,"reason",{enumerable:!0}),Object.defineProperty(Xe.prototype,"wasClean",{enumerable:!0});class Qe extends Ye{constructor(e,t={}){super(e),this[qe]=void 0===t.error?null:t.error,this[$e]=void 0===t.message?"":t.message}get error(){return this[qe]}get message(){return this[$e]}}Object.defineProperty(Qe.prototype,"error",{enumerable:!0}),Object.defineProperty(Qe.prototype,"message",{enumerable:!0});class Ze extends Ye{constructor(e,t={}){super(e),this[De]=void 0===t.data?null:t.data}get data(){return this[De]}}Object.defineProperty(Ze.prototype,"data",{enumerable:!0});const Ke={addEventListener(e,t,r={}){for(const s of this.listeners(e))if(!r[We]&&s[je]===t&&!s[We])return;let s;if("message"===e)s=function(e,r){const s=new Ze("message",{data:r?e:e.toString()});s[Ve]=this,et(t,this,s)};else if("close"===e)s=function(e,r){const s=new Xe("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[Ve]=this,et(t,this,s)};else if("error"===e)s=function(e){const r=new Qe("error",{error:e,message:e.message});r[Ve]=this,et(t,this,r)};else{if("open"!==e)return;s=function(){const e=new Ye("open");e[Ve]=this,et(t,this,e)}}s[We]=!!r[We],s[je]=t,r.once?this.once(e,s):this.on(e,s)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[je]===t&&!r[We]){this.removeListener(e,r);break}}};var Je={CloseEvent:Xe,ErrorEvent:Qe,Event:Ye,EventTarget:Ke,MessageEvent:Ze};function et(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:tt}=fe.exports;function rt(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var st={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,s,n=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,h=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===h&&1===tt[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===h&&(h=f);const s=e.slice(c,h);44===l?(rt(t,s,n),n=Object.create(null)):r=s,c=h=-1}}else-1===h&&-1!==c&&(h=f);else if(void 0===s)if(-1===h&&1===tt[l])-1===c&&(c=f);else if(32===l||9===l)-1===h&&-1!==c&&(h=f);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f),rt(n,e.slice(c,h),!0),44===l&&(rt(t,r,n),n=Object.create(null),r=void 0),c=h=-1}else{if(61!==l||-1===c||-1!==h)throw new SyntaxError(`Unexpected character at index ${f}`);s=e.slice(c,f),c=h=-1}else if(o){if(1!==tt[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:i||(i=!0),o=!1}else if(a)if(1===tt[l])-1===c&&(c=f);else if(34===l&&-1!==c)a=!1,h=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===h&&1===tt[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===h&&(h=f);let o=e.slice(c,h);i&&(o=o.replace(/\\/g,""),i=!1),rt(n,s,o),44===l&&(rt(t,r,n),n=Object.create(null),r=void 0),s=void 0,c=h=-1}}else-1===h&&(h=f);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===h&&(h=f);const d=e.slice(c,h);return void 0===r?rt(t,d,n):(void 0===s?rt(n,d,!0):rt(n,s,i?d.replace(/\\/g,""):d),rt(t,r,n)),t}};const nt=m.default,it=u.default,ot=d.default,at=y.default,ct=p.default,{randomBytes:lt,createHash:ht}=g.default,{URL:ft}=b.default,dt=ae,ut=Oe,pt=Ae,{BINARY_TYPES:_t,EMPTY_BUFFER:mt,GUID:yt,kForOnEventAttribute:gt,kListener:vt,kStatusCode:bt,kWebSocket:wt,NOOP:St}=D,{EventTarget:{addEventListener:kt,removeEventListener:xt}}=Je,{format:Et,parse:Ot}=st,{toBuffer:Ct}=F.exports,Tt=Symbol("kAborted"),Nt=[8,13],Lt=["CONNECTING","OPEN","CLOSING","CLOSED"],Pt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class Rt extends nt{constructor(e,t,r){super(),this._binaryType=_t[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=mt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=Rt.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]),It(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){_t.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 s=new ut({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new pt(e,this._extensions,r.generateMask),this._receiver=s,this._socket=e,s[wt]=this,e[wt]=this,s.on("conclude",Ft),s.on("drain",Dt),s.on("error",qt),s.on("message",Gt),s.on("ping",Vt),s.on("pong",zt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Yt),e.on("data",Xt),e.on("end",Qt),e.on("error",Zt),this._readyState=Rt.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=Rt.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[dt.extensionName]&&this._extensions[dt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=Rt.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==Rt.CLOSED)if(this.readyState!==Rt.CONNECTING)this.readyState!==Rt.CLOSING?(this._readyState=Rt.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";Wt(this,this._req,e)}}pause(){this.readyState!==Rt.CONNECTING&&this.readyState!==Rt.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===Rt.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===Rt.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||mt,t,r)):jt(this,e,r)}pong(e,t,r){if(this.readyState===Rt.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===Rt.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||mt,t,r)):jt(this,e,r)}resume(){this.readyState!==Rt.CONNECTING&&this.readyState!==Rt.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===Rt.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!==Rt.OPEN)return void jt(this,e,r);const s={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[dt.extensionName]||(s.compress=!1),this._sender.send(e||mt,s,r)}terminate(){if(this.readyState!==Rt.CLOSED)if(this.readyState!==Rt.CONNECTING)this._socket&&(this._readyState=Rt.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";Wt(this,this._req,e)}}}Object.defineProperty(Rt,"CONNECTING",{enumerable:!0,value:Lt.indexOf("CONNECTING")}),Object.defineProperty(Rt.prototype,"CONNECTING",{enumerable:!0,value:Lt.indexOf("CONNECTING")}),Object.defineProperty(Rt,"OPEN",{enumerable:!0,value:Lt.indexOf("OPEN")}),Object.defineProperty(Rt.prototype,"OPEN",{enumerable:!0,value:Lt.indexOf("OPEN")}),Object.defineProperty(Rt,"CLOSING",{enumerable:!0,value:Lt.indexOf("CLOSING")}),Object.defineProperty(Rt.prototype,"CLOSING",{enumerable:!0,value:Lt.indexOf("CLOSING")}),Object.defineProperty(Rt,"CLOSED",{enumerable:!0,value:Lt.indexOf("CLOSED")}),Object.defineProperty(Rt.prototype,"CLOSED",{enumerable:!0,value:Lt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(Rt.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(Rt.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[gt])return t[vt];return null},set(t){for(const t of this.listeners(e))if(t[gt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[gt]:!0})}})})),Rt.prototype.addEventListener=kt,Rt.prototype.removeEventListener=xt;var Ut=Rt;function It(e,t,r,s){const n={protocolVersion:Nt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,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(!Nt.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Nt.join(", ")})`);let i;if(t instanceof ft)i=t,e._url=t.href;else{try{i=new ft(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 Mt(e,t)}const l=o?443:80,h=lt(16).toString("base64"),f=o?it.request:ot.request,d=new Set;let u,p;if(n.createConnection=o?At:Bt,n.defaultPort=n.defaultPort||l,n.port=i.port||l,n.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},n.path=i.pathname+i.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(u=new dt(!0!==n.perMessageDeflate?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=Et({[dt.extensionName]:u.offer()})),r.length){for(const e of r){if("string"!=typeof e||!Pt.test(e)||d.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.add(e)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(i.username||i.password)&&(n.auth=`${i.username}:${i.password}`),a){const e=n.path.split(":");n.socketPath=e[0],n.path=e[1]}if(n.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?n.socketPath:i.host;const t=s&&s.headers;if(s={...s,headers:{}},t)for(const[e,r]of Object.entries(t))s.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&n.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete n.headers.authorization,delete n.headers.cookie,t||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),p=e._req=f(n),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(n);n.timeout&&p.on("timeout",(()=>{Wt(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Tt]||(p=e._req=null,Mt(e,t))})),p.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&n.followRedirects&&a>=300&&a<400){if(++e._redirects>n.maxRedirects)return void Wt(e,p,"Maximum redirects exceeded");let i;p.abort();try{i=new ft(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void Mt(e,r)}It(e,i,r,s)}else e.emit("unexpected-response",p,i)||Wt(e,p,`Unexpected server response: ${i.statusCode}`)})),p.on("upgrade",((t,r,s)=>{if(e.emit("upgrade",t),e.readyState!==Rt.CONNECTING)return;if(p=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void Wt(e,r,"Invalid Upgrade header");const i=ht("sha1").update(h+yt).digest("base64");if(t.headers["sec-websocket-accept"]!==i)return void Wt(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?d.size?d.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":d.size&&(a="Server sent no subprotocol"),a)return void Wt(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!u){return void Wt(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Ot(c)}catch(t){return void Wt(e,r,"Invalid Sec-WebSocket-Extensions header")}const s=Object.keys(t);if(1!==s.length||s[0]!==dt.extensionName){return void Wt(e,r,"Server indicated an extension that was not requested")}try{u.accept(t[dt.extensionName])}catch(t){return void Wt(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[dt.extensionName]=u}e.setSocket(r,s,{generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})})),p.end()}function Mt(e,t){e._readyState=Rt.CLOSING,e.emit("error",t),e.emitClose()}function Bt(e){return e.path=e.socketPath,at.connect(e)}function At(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=at.isIP(e.host)?"":e.host),ct.connect(e)}function Wt(e,t,r){e._readyState=Rt.CLOSING;const s=new Error(r);Error.captureStackTrace(s,Wt),t.setHeader?(t[Tt]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Mt,e,s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function jt(e,t,r){if(t){const r=Ct(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Lt[e.readyState]})`);process.nextTick(r,t)}}function Ft(e,t){const r=this[wt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[wt]&&(r._socket.removeListener("data",Xt),process.nextTick(Ht,r._socket),1005===e?r.close():r.close(e,t))}function Dt(){const e=this[wt];e.isPaused||e._socket.resume()}function qt(e){const t=this[wt];void 0!==t._socket[wt]&&(t._socket.removeListener("data",Xt),process.nextTick(Ht,t._socket),t.close(e[bt])),t.emit("error",e)}function $t(){this[wt].emitClose()}function Gt(e,t){this[wt].emit("message",e,t)}function Vt(e){const t=this[wt];t.pong(e,!t._isServer,St),t.emit("ping",e)}function zt(e){this[wt].emit("pong",e)}function Ht(e){e.resume()}function Yt(){const e=this[wt];let t;this.removeListener("close",Yt),this.removeListener("data",Xt),this.removeListener("end",Qt),e._readyState=Rt.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[wt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",$t),e._receiver.on("finish",$t))}function Xt(e){this[wt]._receiver.write(e)||this.pause()}function Qt(){const e=this[wt];e._readyState=Rt.CLOSING,e._receiver.end(),this.end()}function Zt(){const e=this[wt];this.removeListener("error",Zt),this.on("error",St),e&&(e._readyState=Rt.CLOSING,this.destroy())}const{Duplex:Kt}=v.default;function Jt(e){e.emit("close")}function er(){!this.destroyed&&this._writableState.finished&&this.destroy()}function tr(e){this.removeListener("error",tr),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var rr=function(e,t){let r=!0;const s=new Kt({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const n=!r&&s._readableState.objectMode?t.toString():t;s.push(n)||e.pause()})),e.once("error",(function(e){s.destroyed||(r=!1,s.destroy(e))})),e.once("close",(function(){s.destroyed||s.push(null)})),s._destroy=function(t,n){if(e.readyState===e.CLOSED)return n(t),void process.nextTick(Jt,s);let i=!1;e.once("error",(function(e){i=!0,n(e)})),e.once("close",(function(){i||n(t),process.nextTick(Jt,s)})),r&&e.terminate()},s._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){s._final(t)}))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,r,n){e.readyState!==e.CONNECTING?e.send(t,n):e.once("open",(function(){s._write(t,r,n)}))},s.on("end",er),s.on("error",tr),s};const{tokenChars:sr}=fe.exports;var nr={parse:function(e){const t=new Set;let r=-1,s=-1,n=0;for(;n<e.length;n++){const i=e.charCodeAt(n);if(-1===s&&1===sr[i])-1===r&&(r=n);else if(0===n||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${n}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${n}`);-1===s&&(s=n);const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=s=-1}}else-1===s&&-1!==r&&(s=n)}if(-1===r||-1!==s)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const ir=m.default,or=d.default,{createHash:ar}=g.default,cr=st,lr=ae,hr=nr,fr=Ut,{GUID:dr,kWebSocket:ur}=D,pr=/^[+/0-9A-Za-z]{22}==$/,_r=2;var mr=class extends ir{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:fr,...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=or.createServer(((e,t)=>{const r=or.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,s)=>{this.handleUpgrade(t,r,s,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===_r)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(yr,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(yr,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{yr(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,s){t.on("error",gr);const n=e.headers["sec-websocket-key"],i=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void br(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void br(this,e,t,400,"Invalid Upgrade header")}if(!n||!pr.test(n)){return void br(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==i&&13!==i){return void br(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void vr(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=hr.parse(o)}catch(r){return void br(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 lr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=cr.parse(c);e[lr.extensionName]&&(r.accept(e[lr.extensionName]),l[lr.extensionName]=r)}catch(r){return void br(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,h)=>{if(!i)return vr(t,o||401,c,h);this.completeUpgrade(l,n,a,e,t,r,s)}));if(!this.options.verifyClient(o))return vr(t,401)}this.completeUpgrade(l,n,a,e,t,r,s)}completeUpgrade(e,t,r,s,n,i,o){if(!n.readable||!n.writable)return n.destroy();if(n[ur])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return vr(n,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ar("sha1").update(t+dr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[lr.extensionName]){const t=e[lr.extensionName].params,r=cr.format({[lr.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,s),n.write(a.concat("\r\n").join("\r\n")),n.removeListener("error",gr),c.setSocket(n,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(yr,this)}))),o(c,s)}};function yr(e){e._state=_r,e.emit("close")}function gr(){this.destroy()}function vr(e,t,r,s){r=r||or.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${or.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function br(e,t,r,s,n){if(e.listenerCount("wsClientError")){const s=new Error(n);Error.captureStackTrace(s,br),e.emit("wsClientError",s,r,t)}else vr(r,s,n)}const wr=Ut;wr.createWebSocketStream=rr,wr.Server=mr,wr.Receiver=Oe,wr.Sender=Ae,wr.WebSocket=wr,wr.WebSocketServer=wr.Server;var Sr=wr,kr="3.1.3",xr=require("child_process"),Er=require("events"),Or=require("url"),Cr=Sr.Server,Tr="ffmpeg",Nr="mpeg1video",Lr="mp2",Pr=!1,Rr=2,Ur=["tcp","udp","udp_multicast","http","https"],Ir="tcp",Mr=!0,Br=!0,Ar="drawtext=x=w-tw-5:y=80:fontcolor=white:fontsize=32:text="+decodeURIComponent(j.exports.decode("Y2xlYXIlMjB3aXRoJTIwcXElMjA0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",Wr=60,jr=10,Fr=["-s","-b:v","scale","contrast","brightness","saturation","gamma"].concat(["vcodec"]),Dr=["scale","contrast","brightness","saturation","gamma"],qr=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"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}},$r=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&&N(e,t)}(r,Er.EventEmitter);var t=P(r);function r(e){var s;return x(this,r),C(L(s=t.call(this)),"exitCode",void 0),C(L(s),"additionalFlags",[]),C(L(s),"stream",null),C(L(s),"inputStreamStarted",!1),s.ffmpegPath=Tr,s.url=e.url,s.ffmpegOptions=e.ffmpegOptions,s.options=e,s.initMpeg2Muxer(),s}return O(r,[{key:"initMpeg2Muxer",value:function(){var e=this;if(Mr&&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=["-thread_queue_size","1024","-rtsp_transport",Ir,"-i",this.url,"-f","mpegts","-c:v",Nr,"-q",Rr,"-r","30","-c:a",Lr,Pr?"-an":null,"-ar","48000","-ac","1"].concat(U(this.additionalFlags),["-nostats","-"]),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=xr.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("**启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数~,code:",e,"signal:",t)})),this.stream.on("exit",(function(t,r){return console.error("**[某个视频流转码进程退出],请检查ffmpeg参数或相关情况或联系作者**,code:",t,"signal:",r),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}(),Gr=function(){function e(t){x(this,e),C(this,"freeTime",0),C(this,"width",null),C(this,"height",null),C(this,"isStreamWrap",!1),C(this,"clients",[]),C(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 $r({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(e){-1!==(e=e.toString()).indexOf("failed")&&(-1!==e.indexOf("Operation timed out")&&global.process.stdout.write(e+"哎呀~你的链接有问题,超时了!=== L520 \n"),-1!==e.indexOf("Conversion")&&console.log("*".concat(Ir,"*模式转换失败,请尝试改变transportType的值,然后重试。***"))),-1!==e.indexOf("404 Not Found")&&global.process.stdout.write(e+"=== L521 \n"),-1!==e.indexOf("Invalid data found")&&global.process.stdout.write(e+"=== L522 \n"),-1!==e.indexOf("Unrecognized option")&&global.process.stdout.write(e+"=== L523 \n"),-1!==e.indexOf("pipe")&&global.process.stdout.write(e+"=== L524 \n"),e.indexOf("Output #")})),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":Ar},r=0,s=Object.entries(e);r<s.length;r++){var n=R(s[r],2),i=n[0],o=n[1];Fr.includes(i)&&(Dr.includes(i)?"scale"===i?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(o)):t["-vf"]+="".concat(i,"=").concat(o,":"):qr(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=B(this.clients);try{for(r.s();!(t=r.n()).done;){var s=t.value;s.isSegment&&s.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("视频播放窗口关闭1个,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=B(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}(),Vr=function(){function e(t){var r=this;x(this,e),C(this,"channels",[]),console.log("current rtsp2web version: ".concat(kr,"; run on ").concat(global.process.platform)),xr.exec("ffmpeg -version",(function(e,t,r){e&&console.log("请检查你的ffmpeg是否正确存在,错误信息:",e.stack)})),t&&"boolean"==typeof t.wm&&!t.wm&&(Ar="scale=-1:-1,eq=",Br=!1),t&&"boolean"==typeof t.vf&&!t.vf&&(Mr=!1),t&&"string"==typeof t.path&&t.path.length>0&&(Tr=t.path),t&&"string"==typeof t.vcodec&&t.vcodec.length>0&&(Nr=t.vcodec),t&&"number"==typeof t.q&&t.q>=0&&(Rr=t.q),t&&"string"==typeof t.transportType&&Ur.includes(t.transportType)&&(Ir=t.transportType),t&&"boolean"==typeof t.audio&&!t.audio&&(Pr=!0),t&&["string","number"].includes(k(t.freeTime))&&"number"==typeof parseInt(t.freeTime,10)&&(Wr=parseInt(t.freeTime,10)),t&&["string","number"].includes(k(t.checkTime))&&"number"==typeof parseInt(t.checkTime,10)&&(jr=parseInt(t.checkTime,10)),setInterval((function(){r.checkFree(),Br&&(Ar.includes(decodeURIComponent(j.exports.decode("eCUzRHctdHctNSUzQXklM0Q4MCUzQWZvbnRjb2xvciUzRHdoaXRlJTNBZm9udHNpemUlM0QzMiUzQXRleHQlM0RjbGVhciUyMHdpdGglMjBxcSUyMDQyMTM1NDUzMiUzQWJveCUzRDElM0Fib3hjb2xvciUzRGJsYWNr")))||(r.destroyAllChannel(),global.process.stderr.write("***wm代码异常***,请联系作者!")))}),1e3*jr);var s=d.default.createServer((function(e,t){t.writeHead(200),t.end("hello rtsp2web, with ws [ws] model ~ \n")}));if(t&&"object"===k(t.wss))if(console.log("wss启动中...."),t.wss.hasOwnProperty("pfx"))if(t.wss.hasOwnProperty("passphrase"))try{s=u.default.createServer({pfx:_.default.readFileSync(t.wss.pfx),passphrase:_.default.readFileSync(t.wss.passphrase)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [pfx&passphrase] model ~ \n")}))}catch(e){console.error("--[读取pfx安全证书文件出错,wss启动失败,退回到ws;请检查(pfx&passphrase),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败:请传入正确的密码:passphrase】"),global.process.stdout.write("---ws正常开启中--- W11 \n");else if(t.wss.hasOwnProperty("cert"))if(t.wss.hasOwnProperty("key"))try{s=u.default.createServer({key:_.default.readFileSync(t.wss.key),cert:_.default.readFileSync(t.wss.cert)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [key&cert] model ~ \n")}))}catch(e){console.error("--[读取SSL证书文件Error,wss启动失败,退回到ws;请检查(key&cert),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败;请传入正确的安全证书私钥:key.pem】"),global.process.stdout.write("---ws正常开启中--- W13 \n");else console.error("【wss启动失败;请传入正确的安全证书公钥:cert.pem】"),global.process.stdout.write("---ws正常开启中--- W12 \n");s.listen(t&&t.port||9999),Object.getPrototypeOf(s)instanceof p.default.Server&&console.log("wss model success!!!"),this.wss=new Cr({server:s}),this.wss.on("connection",(function(e,t){var s=Or.parse(t.url,!0);if(s.query.url){var n=j.exports.decode(s.query.url.toString());s.query.url=n,r.registeClient(e,{url:n,options:s.query})}console.log("一个新的视频播放窗口(client,ws句柄)连接成功")}))}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=B(this.channels);try{for(r.s();!(t=r.n()).done;){var s=t.value;if(s.url===e)return s}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new Gr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=B(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=jr,r.freeTime>=Wr&&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=B(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}();C(Vr,"version",kr),module.exports=Vr;
10
+ !function(e,t){!function(r){var s=t,n=e&&e.exports==s&&e,i="object"==typeof W&&W;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,h={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,s,n,i=e.length%3,o="",l=-1,h=e.length-i;++l<h;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,s=e.charCodeAt(++l),o+=c.charAt((n=t+r+s)>>18&63)+c.charAt(n>>12&63)+c.charAt(n>>6&63)+c.charAt(63&n);return 2==i?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),o+=c.charAt((n=t+r)>>10)+c.charAt(n>>4&63)+c.charAt(n<<2&63)+"="):1==i&&(n=e.charCodeAt(l),o+=c.charAt(n>>2)+c.charAt(n<<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,s,n=0,i="",o=-1;++o<t;)s=c.indexOf(e.charAt(o)),r=n%4?64*r+s:s,n++%4&&(i+=String.fromCharCode(255&r>>(-2*n&6)));return i},version:"1.0.0"};if(s&&!s.nodeType)if(n)n.exports=h;else for(var f in h)h.hasOwnProperty(f)&&(s[f]=h[f]);else r.base64=h}(W)}(j,j.exports);var F={exports:{}},D={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:q}=D,$=Buffer[Symbol.species];function G(e,t,r,s,n){for(let i=0;i<n;i++)r[s+i]=e[i]^t[3&i]}function V(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(F.exports={concat:function(e,t){if(0===e.length)return q;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let s=0;for(let t=0;t<e.length;t++){const n=e[t];r.set(n,s),s+=n.length}return s<t?new $(r.buffer,r.byteOffset,s):r},mask:G,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 $(t):ArrayBuffer.isView(t)?r=new $(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:V},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");F.exports.mask=function(t,r,s,n,i){i<48?G(t,r,s,n,i):e.mask(t,r,s,n,i)},F.exports.unmask=function(t,r){t.length<32?V(t,r):e.unmask(t,r)}}catch(e){}const z=Symbol("kDone"),H=Symbol("kRun");var Y=class{constructor(e){this[z]=()=>{this.pending--,this[H]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[H]()}[H](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[z])}}};const X=w.default,Q=F.exports,Z=Y,{kStatusCode:K}=D,J=Buffer[Symbol.species],ee=Buffer.from([0,0,255,255]),te=Symbol("permessage-deflate"),re=Symbol("total-length"),se=Symbol("callback"),ne=Symbol("buffers"),ie=Symbol("error");let oe;var ae=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,!oe){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;oe=new Z(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[se];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){oe.add((s=>{this._decompress(e,t,((e,t)=>{s(),r(e,t)}))}))}compress(e,t,r){oe.add((s=>{this._compress(e,t,((e,t)=>{s(),r(e,t)}))}))}_decompress(e,t,r){const s=this._isServer?"client":"server";if(!this._inflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?X.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=X.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[te]=this,this._inflate[re]=0,this._inflate[ne]=[],this._inflate.on("error",he),this._inflate.on("data",le)}this._inflate[se]=r,this._inflate.write(e),t&&this._inflate.write(ee),this._inflate.flush((()=>{const e=this._inflate[ie];if(e)return this._inflate.close(),this._inflate=null,void r(e);const n=Q.concat(this._inflate[ne],this._inflate[re]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[re]=0,this._inflate[ne]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,n)}))}_compress(e,t,r){const s=this._isServer?"server":"client";if(!this._deflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?X.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=X.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[re]=0,this._deflate[ne]=[],this._deflate.on("data",ce)}this._deflate[se]=r,this._deflate.write(e),this._deflate.flush(X.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Q.concat(this._deflate[ne],this._deflate[re]);t&&(e=new J(e.buffer,e.byteOffset,e.length-4)),this._deflate[se]=null,this._deflate[re]=0,this._deflate[ne]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function ce(e){this[ne].push(e),this[re]+=e.length}function le(e){this[re]+=e.length,this[te]._maxPayload<1||this[re]<=this[te]._maxPayload?this[ne].push(e):(this[ie]=new RangeError("Max payload size exceeded"),this[ie].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ie][K]=1009,this.removeListener("data",le),this.reset())}function he(e){this[te]._inflate=null,e[K]=1007,this[se](e)}var fe={exports:{}};const{isUtf8:de}=S.default;function ue(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(fe.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:ue,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]},de)fe.exports.isValidUTF8=function(e){return e.length<24?ue(e):de(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");fe.exports.isValidUTF8=function(t){return t.length<32?ue(t):e(t)}}catch(e){}const{Writable:pe}=v.default,_e=ae,{BINARY_TYPES:me,EMPTY_BUFFER:ye,kStatusCode:ge,kWebSocket:ve}=D,{concat:be,toArrayBuffer:we,unmask:Se}=F.exports,{isValidStatusCode:ke,isValidUTF8:xe}=fe.exports,Ee=Buffer[Symbol.species];var Oe=class extends pe{constructor(e={}){super(),this._binaryType=e.binaryType||me[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ve]=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 Ee(t.buffer,t.byteOffset+e,t.length-e),new Ee(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Ee(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,Ce(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[_e.extensionName])return this._loop=!1,Ce(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,Ce(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Ce(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,Ce(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,Ce(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Ce(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Ce(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,Ce(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,Ce(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Ce(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,Ce(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,Ce(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=ye;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])&&Se(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[_e.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(Ce(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const s=this.dataMessage();if(s)return t(s);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?be(t,e):"arraybuffer"===this._binaryType?we(be(t,e)):t,this.emit("message",r,!0)}else{const r=be(t,e);if(!this._skipUTF8Validation&&!xe(r))return this._loop=!1,Ce(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,ye),this.end();else{const t=e.readUInt16BE(0);if(!ke(t))return Ce(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=new Ee(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!xe(r))return Ce(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 Ce(e,t,r,s,n){const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,Ce),i.code=n,i[ge]=s,i}const{randomFillSync:Te}=g.default,Ne=ae,{EMPTY_BUFFER:Le}=D,{isValidStatusCode:Pe}=fe.exports,{mask:Re,toBuffer:Ue}=F.exports,Ie=Symbol("kByteLength"),Me=Buffer.alloc(4);class Be{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,s,n=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Me,t.generateMask?t.generateMask(r):Te(r,0,4),o=0==(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?s=t.mask&&!o||void 0===t[Ie]?(e=Buffer.from(e)).length:t[Ie]:(s=e.length,n=t.mask&&t.readOnly&&!o);let a=s;s>=65536?(i+=8,a=127):s>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(n?s+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(s,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(s,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]:n?(Re(e,r,c,i,s),[c]):(Re(e,r,e,0,s),[c,e])):[c,e]}close(e,t,r,s){let n;if(void 0===e)n=Le;else{if("number"!=typeof e||!Pe(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");n=Buffer.allocUnsafe(2+r),n.writeUInt16BE(e,0),"string"==typeof t?n.write(t,2):n.set(t,2)}else n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0)}const i={[Ie]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,n,!1,i,s]):this.sendFrame(Be.frame(n,i),s)}ping(e,t,r){let s,n;if("string"==typeof e?(s=Buffer.byteLength(e),n=!1):(s=(e=Ue(e)).length,n=Ue.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ie]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(Be.frame(e,i),r)}pong(e,t,r){let s,n;if("string"==typeof e?(s=Buffer.byteLength(e),n=!1):(s=(e=Ue(e)).length,n=Ue.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ie]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(Be.frame(e,i),r)}send(e,t,r){const s=this._extensions[Ne.extensionName];let n,i,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):(n=(e=Ue(e)).length,i=Ue.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=n>=s._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),s){const s={[Ie]:n,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,s,r]):this.dispatch(e,this._compress,s,r)}else this.sendFrame(Be.frame(e,{[Ie]:n,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:!1}),r)}dispatch(e,t,r,s){if(!t)return void this.sendFrame(Be.frame(e,r),s);const n=this._extensions[Ne.extensionName];this._bufferedBytes+=r[Ie],this._deflating=!0,n.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 s&&s(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],s=r[r.length-1];"function"==typeof s&&s(e)}}else this._bufferedBytes-=r[Ie],this._deflating=!1,r.readOnly=!1,this.sendFrame(Be.frame(t,r),s),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ie],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ie],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 Ae=Be;const{kForOnEventAttribute:We,kListener:je}=D,Fe=Symbol("kCode"),De=Symbol("kData"),qe=Symbol("kError"),$e=Symbol("kMessage"),Ge=Symbol("kReason"),Ve=Symbol("kTarget"),ze=Symbol("kType"),He=Symbol("kWasClean");class Ye{constructor(e){this[Ve]=null,this[ze]=e}get target(){return this[Ve]}get type(){return this[ze]}}Object.defineProperty(Ye.prototype,"target",{enumerable:!0}),Object.defineProperty(Ye.prototype,"type",{enumerable:!0});class Xe extends Ye{constructor(e,t={}){super(e),this[Fe]=void 0===t.code?0:t.code,this[Ge]=void 0===t.reason?"":t.reason,this[He]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Fe]}get reason(){return this[Ge]}get wasClean(){return this[He]}}Object.defineProperty(Xe.prototype,"code",{enumerable:!0}),Object.defineProperty(Xe.prototype,"reason",{enumerable:!0}),Object.defineProperty(Xe.prototype,"wasClean",{enumerable:!0});class Qe extends Ye{constructor(e,t={}){super(e),this[qe]=void 0===t.error?null:t.error,this[$e]=void 0===t.message?"":t.message}get error(){return this[qe]}get message(){return this[$e]}}Object.defineProperty(Qe.prototype,"error",{enumerable:!0}),Object.defineProperty(Qe.prototype,"message",{enumerable:!0});class Ze extends Ye{constructor(e,t={}){super(e),this[De]=void 0===t.data?null:t.data}get data(){return this[De]}}Object.defineProperty(Ze.prototype,"data",{enumerable:!0});const Ke={addEventListener(e,t,r={}){for(const s of this.listeners(e))if(!r[We]&&s[je]===t&&!s[We])return;let s;if("message"===e)s=function(e,r){const s=new Ze("message",{data:r?e:e.toString()});s[Ve]=this,et(t,this,s)};else if("close"===e)s=function(e,r){const s=new Xe("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[Ve]=this,et(t,this,s)};else if("error"===e)s=function(e){const r=new Qe("error",{error:e,message:e.message});r[Ve]=this,et(t,this,r)};else{if("open"!==e)return;s=function(){const e=new Ye("open");e[Ve]=this,et(t,this,e)}}s[We]=!!r[We],s[je]=t,r.once?this.once(e,s):this.on(e,s)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[je]===t&&!r[We]){this.removeListener(e,r);break}}};var Je={CloseEvent:Xe,ErrorEvent:Qe,Event:Ye,EventTarget:Ke,MessageEvent:Ze};function et(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:tt}=fe.exports;function rt(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var st={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,s,n=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,h=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===h&&1===tt[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===h&&(h=f);const s=e.slice(c,h);44===l?(rt(t,s,n),n=Object.create(null)):r=s,c=h=-1}}else-1===h&&-1!==c&&(h=f);else if(void 0===s)if(-1===h&&1===tt[l])-1===c&&(c=f);else if(32===l||9===l)-1===h&&-1!==c&&(h=f);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f),rt(n,e.slice(c,h),!0),44===l&&(rt(t,r,n),n=Object.create(null),r=void 0),c=h=-1}else{if(61!==l||-1===c||-1!==h)throw new SyntaxError(`Unexpected character at index ${f}`);s=e.slice(c,f),c=h=-1}else if(o){if(1!==tt[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:i||(i=!0),o=!1}else if(a)if(1===tt[l])-1===c&&(c=f);else if(34===l&&-1!==c)a=!1,h=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===h&&1===tt[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===h&&(h=f);let o=e.slice(c,h);i&&(o=o.replace(/\\/g,""),i=!1),rt(n,s,o),44===l&&(rt(t,r,n),n=Object.create(null),r=void 0),s=void 0,c=h=-1}}else-1===h&&(h=f);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===h&&(h=f);const d=e.slice(c,h);return void 0===r?rt(t,d,n):(void 0===s?rt(n,d,!0):rt(n,s,i?d.replace(/\\/g,""):d),rt(t,r,n)),t}};const nt=m.default,it=u.default,ot=d.default,at=y.default,ct=p.default,{randomBytes:lt,createHash:ht}=g.default,{URL:ft}=b.default,dt=ae,ut=Oe,pt=Ae,{BINARY_TYPES:_t,EMPTY_BUFFER:mt,GUID:yt,kForOnEventAttribute:gt,kListener:vt,kStatusCode:bt,kWebSocket:wt,NOOP:St}=D,{EventTarget:{addEventListener:kt,removeEventListener:xt}}=Je,{format:Et,parse:Ot}=st,{toBuffer:Ct}=F.exports,Tt=Symbol("kAborted"),Nt=[8,13],Lt=["CONNECTING","OPEN","CLOSING","CLOSED"],Pt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class Rt extends nt{constructor(e,t,r){super(),this._binaryType=_t[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=mt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=Rt.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]),It(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){_t.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 s=new ut({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new pt(e,this._extensions,r.generateMask),this._receiver=s,this._socket=e,s[wt]=this,e[wt]=this,s.on("conclude",Ft),s.on("drain",Dt),s.on("error",qt),s.on("message",Gt),s.on("ping",Vt),s.on("pong",zt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Yt),e.on("data",Xt),e.on("end",Qt),e.on("error",Zt),this._readyState=Rt.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=Rt.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[dt.extensionName]&&this._extensions[dt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=Rt.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==Rt.CLOSED)if(this.readyState!==Rt.CONNECTING)this.readyState!==Rt.CLOSING?(this._readyState=Rt.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";Wt(this,this._req,e)}}pause(){this.readyState!==Rt.CONNECTING&&this.readyState!==Rt.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===Rt.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===Rt.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||mt,t,r)):jt(this,e,r)}pong(e,t,r){if(this.readyState===Rt.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===Rt.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||mt,t,r)):jt(this,e,r)}resume(){this.readyState!==Rt.CONNECTING&&this.readyState!==Rt.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===Rt.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!==Rt.OPEN)return void jt(this,e,r);const s={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[dt.extensionName]||(s.compress=!1),this._sender.send(e||mt,s,r)}terminate(){if(this.readyState!==Rt.CLOSED)if(this.readyState!==Rt.CONNECTING)this._socket&&(this._readyState=Rt.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";Wt(this,this._req,e)}}}Object.defineProperty(Rt,"CONNECTING",{enumerable:!0,value:Lt.indexOf("CONNECTING")}),Object.defineProperty(Rt.prototype,"CONNECTING",{enumerable:!0,value:Lt.indexOf("CONNECTING")}),Object.defineProperty(Rt,"OPEN",{enumerable:!0,value:Lt.indexOf("OPEN")}),Object.defineProperty(Rt.prototype,"OPEN",{enumerable:!0,value:Lt.indexOf("OPEN")}),Object.defineProperty(Rt,"CLOSING",{enumerable:!0,value:Lt.indexOf("CLOSING")}),Object.defineProperty(Rt.prototype,"CLOSING",{enumerable:!0,value:Lt.indexOf("CLOSING")}),Object.defineProperty(Rt,"CLOSED",{enumerable:!0,value:Lt.indexOf("CLOSED")}),Object.defineProperty(Rt.prototype,"CLOSED",{enumerable:!0,value:Lt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(Rt.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(Rt.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[gt])return t[vt];return null},set(t){for(const t of this.listeners(e))if(t[gt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[gt]:!0})}})})),Rt.prototype.addEventListener=kt,Rt.prototype.removeEventListener=xt;var Ut=Rt;function It(e,t,r,s){const n={protocolVersion:Nt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,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(!Nt.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Nt.join(", ")})`);let i;if(t instanceof ft)i=t,e._url=t.href;else{try{i=new ft(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 Mt(e,t)}const l=o?443:80,h=lt(16).toString("base64"),f=o?it.request:ot.request,d=new Set;let u,p;if(n.createConnection=o?At:Bt,n.defaultPort=n.defaultPort||l,n.port=i.port||l,n.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},n.path=i.pathname+i.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(u=new dt(!0!==n.perMessageDeflate?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=Et({[dt.extensionName]:u.offer()})),r.length){for(const e of r){if("string"!=typeof e||!Pt.test(e)||d.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.add(e)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(i.username||i.password)&&(n.auth=`${i.username}:${i.password}`),a){const e=n.path.split(":");n.socketPath=e[0],n.path=e[1]}if(n.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?n.socketPath:i.host;const t=s&&s.headers;if(s={...s,headers:{}},t)for(const[e,r]of Object.entries(t))s.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&n.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete n.headers.authorization,delete n.headers.cookie,t||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),p=e._req=f(n),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(n);n.timeout&&p.on("timeout",(()=>{Wt(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Tt]||(p=e._req=null,Mt(e,t))})),p.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&n.followRedirects&&a>=300&&a<400){if(++e._redirects>n.maxRedirects)return void Wt(e,p,"Maximum redirects exceeded");let i;p.abort();try{i=new ft(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void Mt(e,r)}It(e,i,r,s)}else e.emit("unexpected-response",p,i)||Wt(e,p,`Unexpected server response: ${i.statusCode}`)})),p.on("upgrade",((t,r,s)=>{if(e.emit("upgrade",t),e.readyState!==Rt.CONNECTING)return;if(p=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void Wt(e,r,"Invalid Upgrade header");const i=ht("sha1").update(h+yt).digest("base64");if(t.headers["sec-websocket-accept"]!==i)return void Wt(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?d.size?d.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":d.size&&(a="Server sent no subprotocol"),a)return void Wt(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!u){return void Wt(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Ot(c)}catch(t){return void Wt(e,r,"Invalid Sec-WebSocket-Extensions header")}const s=Object.keys(t);if(1!==s.length||s[0]!==dt.extensionName){return void Wt(e,r,"Server indicated an extension that was not requested")}try{u.accept(t[dt.extensionName])}catch(t){return void Wt(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[dt.extensionName]=u}e.setSocket(r,s,{generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})})),p.end()}function Mt(e,t){e._readyState=Rt.CLOSING,e.emit("error",t),e.emitClose()}function Bt(e){return e.path=e.socketPath,at.connect(e)}function At(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=at.isIP(e.host)?"":e.host),ct.connect(e)}function Wt(e,t,r){e._readyState=Rt.CLOSING;const s=new Error(r);Error.captureStackTrace(s,Wt),t.setHeader?(t[Tt]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Mt,e,s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function jt(e,t,r){if(t){const r=Ct(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Lt[e.readyState]})`);process.nextTick(r,t)}}function Ft(e,t){const r=this[wt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[wt]&&(r._socket.removeListener("data",Xt),process.nextTick(Ht,r._socket),1005===e?r.close():r.close(e,t))}function Dt(){const e=this[wt];e.isPaused||e._socket.resume()}function qt(e){const t=this[wt];void 0!==t._socket[wt]&&(t._socket.removeListener("data",Xt),process.nextTick(Ht,t._socket),t.close(e[bt])),t.emit("error",e)}function $t(){this[wt].emitClose()}function Gt(e,t){this[wt].emit("message",e,t)}function Vt(e){const t=this[wt];t.pong(e,!t._isServer,St),t.emit("ping",e)}function zt(e){this[wt].emit("pong",e)}function Ht(e){e.resume()}function Yt(){const e=this[wt];let t;this.removeListener("close",Yt),this.removeListener("data",Xt),this.removeListener("end",Qt),e._readyState=Rt.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[wt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",$t),e._receiver.on("finish",$t))}function Xt(e){this[wt]._receiver.write(e)||this.pause()}function Qt(){const e=this[wt];e._readyState=Rt.CLOSING,e._receiver.end(),this.end()}function Zt(){const e=this[wt];this.removeListener("error",Zt),this.on("error",St),e&&(e._readyState=Rt.CLOSING,this.destroy())}const{Duplex:Kt}=v.default;function Jt(e){e.emit("close")}function er(){!this.destroyed&&this._writableState.finished&&this.destroy()}function tr(e){this.removeListener("error",tr),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var rr=function(e,t){let r=!0;const s=new Kt({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const n=!r&&s._readableState.objectMode?t.toString():t;s.push(n)||e.pause()})),e.once("error",(function(e){s.destroyed||(r=!1,s.destroy(e))})),e.once("close",(function(){s.destroyed||s.push(null)})),s._destroy=function(t,n){if(e.readyState===e.CLOSED)return n(t),void process.nextTick(Jt,s);let i=!1;e.once("error",(function(e){i=!0,n(e)})),e.once("close",(function(){i||n(t),process.nextTick(Jt,s)})),r&&e.terminate()},s._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){s._final(t)}))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,r,n){e.readyState!==e.CONNECTING?e.send(t,n):e.once("open",(function(){s._write(t,r,n)}))},s.on("end",er),s.on("error",tr),s};const{tokenChars:sr}=fe.exports;var nr={parse:function(e){const t=new Set;let r=-1,s=-1,n=0;for(;n<e.length;n++){const i=e.charCodeAt(n);if(-1===s&&1===sr[i])-1===r&&(r=n);else if(0===n||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${n}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${n}`);-1===s&&(s=n);const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=s=-1}}else-1===s&&-1!==r&&(s=n)}if(-1===r||-1!==s)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const ir=m.default,or=d.default,{createHash:ar}=g.default,cr=st,lr=ae,hr=nr,fr=Ut,{GUID:dr,kWebSocket:ur}=D,pr=/^[+/0-9A-Za-z]{22}==$/,_r=2;var mr=class extends ir{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:fr,...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=or.createServer(((e,t)=>{const r=or.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,s)=>{this.handleUpgrade(t,r,s,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===_r)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(yr,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(yr,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{yr(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,s){t.on("error",gr);const n=e.headers["sec-websocket-key"],i=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void br(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void br(this,e,t,400,"Invalid Upgrade header")}if(!n||!pr.test(n)){return void br(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==i&&13!==i){return void br(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void vr(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=hr.parse(o)}catch(r){return void br(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 lr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=cr.parse(c);e[lr.extensionName]&&(r.accept(e[lr.extensionName]),l[lr.extensionName]=r)}catch(r){return void br(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,h)=>{if(!i)return vr(t,o||401,c,h);this.completeUpgrade(l,n,a,e,t,r,s)}));if(!this.options.verifyClient(o))return vr(t,401)}this.completeUpgrade(l,n,a,e,t,r,s)}completeUpgrade(e,t,r,s,n,i,o){if(!n.readable||!n.writable)return n.destroy();if(n[ur])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return vr(n,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ar("sha1").update(t+dr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[lr.extensionName]){const t=e[lr.extensionName].params,r=cr.format({[lr.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,s),n.write(a.concat("\r\n").join("\r\n")),n.removeListener("error",gr),c.setSocket(n,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(yr,this)}))),o(c,s)}};function yr(e){e._state=_r,e.emit("close")}function gr(){this.destroy()}function vr(e,t,r,s){r=r||or.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${or.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function br(e,t,r,s,n){if(e.listenerCount("wsClientError")){const s=new Error(n);Error.captureStackTrace(s,br),e.emit("wsClientError",s,r,t)}else vr(r,s,n)}const wr=Ut;wr.createWebSocketStream=rr,wr.Server=mr,wr.Receiver=Oe,wr.Sender=Ae,wr.WebSocket=wr,wr.WebSocketServer=wr.Server;var Sr=wr,kr="3.1.5",xr=require("child_process"),Er=require("events"),Or=require("url"),Cr=Sr.Server,Tr="ffmpeg",Nr=["jsmpeg","flv"],Lr="jsmpeg",Pr={jsmpeg:"mpegts",flv:"flv"},Rr={jsmpeg:"mpeg1video",flv:"libx264"},Ur={jsmpeg:"mp2",flv:"aac"},Ir=!1,Mr=2,Br=["tcp","udp","udp_multicast","http","https"],Ar="tcp",Wr="204800",jr=!0,Fr=!0,Dr="drawtext=x=w-tw-5:y=80:fontcolor=white:fontsize=32:text="+decodeURIComponent(j.exports.decode("Y2xlYXIlMjB3aXRoJTIwcXElMjA0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",qr=20,$r=10,Gr=["-s","-b:v","webplayer","scale","contrast","brightness","saturation","gamma"].concat(["vcodec"]),Vr=["scale","contrast","brightness","saturation","gamma"],zr=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"webplayer":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}},Hr=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&&N(e,t)}(r,Er.EventEmitter);var t=P(r);function r(e){var s;return x(this,r),C(L(s=t.call(this)),"exitCode",void 0),C(L(s),"additionalFlags",[]),C(L(s),"stream",null),C(L(s),"inputStreamStarted",!1),s.ffmpegPath=Tr,s.url=e.url,s.ffmpegOptions=e.ffmpegOptions,s.options=e,s.initMpeg2Muxer(),s}return O(r,[{key:"initMpeg2Muxer",value:function(){var e=this;if(jr||delete this.ffmpegOptions["-vf"],this.ffmpegOptions.webplayer&&(Lr=this.ffmpegOptions.webplayer,delete this.ffmpegOptions.webplayer),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=["-re","-rtsp_transport",Ar,"-buffer_size",Wr,"-thread_queue_size","1024","-threads","8","-max_interleave_delta","0","-i",this.url,"-q",Mr,"-f",Pr[Lr],"-c:v",Rr[Lr],"-r","30","-c:a",Ur[Lr],Ir?"-an":null,"-ar","48000","-ac","1"].concat(U(this.additionalFlags),["-nostats","-"]),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=xr.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("**启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数~,code:",e,"signal:",t)})),this.stream.on("exit",(function(t,r){return console.error("[ffmpeg]某个视频流转码进程退出了: **如果非正常关闭视频导致的退出,请检查ffmpeg参数或检查代码或联系作者解决**,code:",t,"signal:",r),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}(),Yr=function(){function e(t){x(this,e),C(this,"freeTime",0),C(this,"width",null),C(this,"height",null),C(this,"isStreamWrap",!1),C(this,"clients",[]),C(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 Hr({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(e){-1!==(e=e.toString()).indexOf("failed")&&(-1!==e.indexOf("Operation timed out")&&global.process.stdout.write(e+"哎呀~你的链接有问题,超时了!=== L519 \n"),-1!==e.indexOf("Conversion")&&console.log("*".concat(Ar,"*模式转换失败,请尝试改变transportType的值,然后重试。***")),-1!==e.indexOf("transport")&&global.process.stdout.write(e+"=== L520 \n")),-1!==e.indexOf("404 Not Found")&&global.process.stdout.write(e+"=== L521 \n"),-1!==e.indexOf("Invalid data found")&&global.process.stdout.write(e+"=== L522 \n"),-1!==e.indexOf("Unrecognized option")&&global.process.stdout.write(e+"=== L523 \n"),-1!==e.indexOf("pipe")&&global.process.stdout.write(e+"=== L524 \n"),e.indexOf("Output #")})),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":Dr},r=0,s=Object.entries(e);r<s.length;r++){var n=R(s[r],2),i=n[0],o=n[1];Gr.includes(i)&&(Vr.includes(i)?"scale"===i?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(o)):t["-vf"]+="".concat(i,"=").concat(o,":"):zr(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=B(this.clients);try{for(r.s();!(t=r.n()).done;){var s=t.value;s.isSegment&&s.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("视频播放窗口关闭1个,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=B(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}(),Xr=function(){function e(t){var r=this;x(this,e),C(this,"channels",[]),console.log("---[info]: current rtsp2web version: ".concat(kr,"; current platform is ").concat(global.process.platform,"---")),xr.exec("ffmpeg -version",(function(e,t,r){e&&console.log("请检查你的ffmpeg是否正确存在,错误信息:",e.stack)})),t&&"boolean"==typeof t.wm&&!t.wm&&(Dr="scale=-1:-1,eq=",Fr=!1),t&&"boolean"==typeof t.vf&&!t.vf&&(jr=!1),t&&"string"==typeof t.path&&t.path.length>0&&(Tr=t.path),t&&"string"==typeof t.webplayer&&Nr.includes(t.webplayer)&&(Lr=t.webplayer),t&&"number"==typeof t.q&&t.q>=0&&(Mr=t.q),t&&"string"==typeof t.transportType&&Br.includes(t.transportType)&&(Ar=t.transportType),t&&"boolean"==typeof t.audio&&!t.audio&&(Ir=!0),t&&["string","number"].includes(k(t.freeTime))&&"number"==typeof parseInt(t.freeTime,10)&&(qr=parseInt(t.freeTime,10)),t&&["string","number"].includes(k(t.checkTime))&&"number"==typeof parseInt(t.checkTime,10)&&($r=parseInt(t.checkTime,10)),setInterval((function(){r.checkFree(),Fr&&(Dr.includes(decodeURIComponent(j.exports.decode("eCUzRHctdHctNSUzQXklM0Q4MCUzQWZvbnRjb2xvciUzRHdoaXRlJTNBZm9udHNpemUlM0QzMiUzQXRleHQlM0RjbGVhciUyMHdpdGglMjBxcSUyMDQyMTM1NDUzMiUzQWJveCUzRDElM0Fib3hjb2xvciUzRGJsYWNr")))||(r.destroyAllChannel(),global.process.stderr.write("----wm代码异常、视频闪屏的问题----,请联系作者帮你解决!!")))}),1e3*$r);var s=d.default.createServer((function(e,t){t.writeHead(200),t.end("hello rtsp2web, with ws [ws] model ~ \n")}));if(t&&"object"===k(t.wss))if(console.log("wss启动中...."),t.wss.hasOwnProperty("pfx"))if(t.wss.hasOwnProperty("passphrase"))try{s=u.default.createServer({pfx:_.default.readFileSync(t.wss.pfx),passphrase:_.default.readFileSync(t.wss.passphrase)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [pfx&passphrase] model ~ \n")}))}catch(e){console.error("--[读取pfx安全证书文件出错,wss启动失败,退回到ws;请检查(pfx&passphrase),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败:请传入正确的密码:passphrase】"),global.process.stdout.write("---ws正常开启中--- W11 \n");else if(t.wss.hasOwnProperty("cert"))if(t.wss.hasOwnProperty("key"))try{s=u.default.createServer({key:_.default.readFileSync(t.wss.key),cert:_.default.readFileSync(t.wss.cert)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [key&cert] model ~ \n")}))}catch(e){console.error("--[读取SSL证书文件Error,wss启动失败,退回到ws;请检查(key&cert),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败;请传入正确的安全证书私钥:key.pem】"),global.process.stdout.write("---ws正常开启中--- W13 \n");else console.error("【wss启动失败;请传入正确的安全证书公钥:cert.pem】"),global.process.stdout.write("---ws正常开启中--- W12 \n");s.listen(t&&t.port||9999),Object.getPrototypeOf(s)instanceof p.default.Server&&console.log("wss model success!!!"),this.wss=new Cr({server:s}),this.wss.on("connection",(function(e,t){var s=Or.parse(t.url,!0);if(s.query.url){var n=j.exports.decode(s.query.url.toString());s.query.url=n,r.registeClient(e,{url:n,options:s.query})}console.log("一个新的视频播放窗口(client,ws句柄)连接成功")}))}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=B(this.channels);try{for(r.s();!(t=r.n()).done;){var s=t.value;if(s.url===e)return s}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new Yr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=B(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=$r,r.freeTime>=qr&&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=B(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}();C(Xr,"version",kr),module.exports=Xr;
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * rtsp2web v3.1.3
2
+ * rtsp2web v3.1.5
3
3
  * (c) 2020-2023 NeverYu
4
4
  * My home page:https://neveryu.github.io/neveryu/
5
5
  * 微信(wechat):miracle421354532
@@ -7,4 +7,4 @@
7
7
  */
8
8
  "use strict";var e=require("http"),t=require("https"),r=require("tls"),s=require("fs"),n=require("events"),i=require("net"),o=require("crypto"),a=require("stream"),c=require("url"),l=require("zlib"),h=require("buffer");function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=f(e),u=f(t),p=f(r),_=f(s),m=f(n),y=f(i),g=f(o),v=f(a),b=f(c),w=f(l),S=f(h);function k(e){return k="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},k(e)}function x(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function E(e,t){for(var r=0;r<t.length;r++){var s=t[r];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,A(s.key),s)}}function O(e,t,r){return t&&E(e.prototype,t),r&&E(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function C(e,t,r){return(t=A(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function T(e){return T=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},T(e)}function N(e,t){return N=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},N(e,t)}function L(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function P(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,s=T(e);if(t){var n=T(this).constructor;r=Reflect.construct(s,arguments,n)}else r=s.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 L(e)}(this,r)}}function R(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 s,n,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=(s=i.call(r)).done)&&(a.push(s.value),a.length!==t);c=!0);}catch(e){l=!0,n=e}finally{try{if(!c&&null!=r.return&&(o=r.return(),Object(o)!==o))return}finally{if(l)throw n}}return a}}(e,t)||I(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 M(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||I(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 I(e,t){if(e){if("string"==typeof e)return M(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)?M(e,t):void 0}}function M(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,s=new Array(t);r<t;r++)s[r]=e[r];return s}function B(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=I(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var s=0,n=function(){};return{s:n,n:function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}},e:function(e){throw e},f:n}}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 A(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=typeof s)return s;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 W="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},j={exports:{}};
9
9
  /*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */
10
- !function(e,t){!function(r){var s=t,n=e&&e.exports==s&&e,i="object"==typeof W&&W;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,h={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,s,n,i=e.length%3,o="",l=-1,h=e.length-i;++l<h;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,s=e.charCodeAt(++l),o+=c.charAt((n=t+r+s)>>18&63)+c.charAt(n>>12&63)+c.charAt(n>>6&63)+c.charAt(63&n);return 2==i?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),o+=c.charAt((n=t+r)>>10)+c.charAt(n>>4&63)+c.charAt(n<<2&63)+"="):1==i&&(n=e.charCodeAt(l),o+=c.charAt(n>>2)+c.charAt(n<<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,s,n=0,i="",o=-1;++o<t;)s=c.indexOf(e.charAt(o)),r=n%4?64*r+s:s,n++%4&&(i+=String.fromCharCode(255&r>>(-2*n&6)));return i},version:"1.0.0"};if(s&&!s.nodeType)if(n)n.exports=h;else for(var f in h)h.hasOwnProperty(f)&&(s[f]=h[f]);else r.base64=h}(W)}(j,j.exports);var F={exports:{}},D={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:q}=D,$=Buffer[Symbol.species];function G(e,t,r,s,n){for(let i=0;i<n;i++)r[s+i]=e[i]^t[3&i]}function V(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(F.exports={concat:function(e,t){if(0===e.length)return q;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let s=0;for(let t=0;t<e.length;t++){const n=e[t];r.set(n,s),s+=n.length}return s<t?new $(r.buffer,r.byteOffset,s):r},mask:G,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 $(t):ArrayBuffer.isView(t)?r=new $(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:V},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");F.exports.mask=function(t,r,s,n,i){i<48?G(t,r,s,n,i):e.mask(t,r,s,n,i)},F.exports.unmask=function(t,r){t.length<32?V(t,r):e.unmask(t,r)}}catch(e){}const z=Symbol("kDone"),H=Symbol("kRun");var Y=class{constructor(e){this[z]=()=>{this.pending--,this[H]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[H]()}[H](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[z])}}};const X=w.default,Q=F.exports,Z=Y,{kStatusCode:K}=D,J=Buffer[Symbol.species],ee=Buffer.from([0,0,255,255]),te=Symbol("permessage-deflate"),re=Symbol("total-length"),se=Symbol("callback"),ne=Symbol("buffers"),ie=Symbol("error");let oe;var ae=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,!oe){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;oe=new Z(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[se];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){oe.add((s=>{this._decompress(e,t,((e,t)=>{s(),r(e,t)}))}))}compress(e,t,r){oe.add((s=>{this._compress(e,t,((e,t)=>{s(),r(e,t)}))}))}_decompress(e,t,r){const s=this._isServer?"client":"server";if(!this._inflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?X.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=X.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[te]=this,this._inflate[re]=0,this._inflate[ne]=[],this._inflate.on("error",he),this._inflate.on("data",le)}this._inflate[se]=r,this._inflate.write(e),t&&this._inflate.write(ee),this._inflate.flush((()=>{const e=this._inflate[ie];if(e)return this._inflate.close(),this._inflate=null,void r(e);const n=Q.concat(this._inflate[ne],this._inflate[re]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[re]=0,this._inflate[ne]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,n)}))}_compress(e,t,r){const s=this._isServer?"server":"client";if(!this._deflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?X.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=X.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[re]=0,this._deflate[ne]=[],this._deflate.on("data",ce)}this._deflate[se]=r,this._deflate.write(e),this._deflate.flush(X.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Q.concat(this._deflate[ne],this._deflate[re]);t&&(e=new J(e.buffer,e.byteOffset,e.length-4)),this._deflate[se]=null,this._deflate[re]=0,this._deflate[ne]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function ce(e){this[ne].push(e),this[re]+=e.length}function le(e){this[re]+=e.length,this[te]._maxPayload<1||this[re]<=this[te]._maxPayload?this[ne].push(e):(this[ie]=new RangeError("Max payload size exceeded"),this[ie].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ie][K]=1009,this.removeListener("data",le),this.reset())}function he(e){this[te]._inflate=null,e[K]=1007,this[se](e)}var fe={exports:{}};const{isUtf8:de}=S.default;function ue(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(fe.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:ue,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]},de)fe.exports.isValidUTF8=function(e){return e.length<24?ue(e):de(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");fe.exports.isValidUTF8=function(t){return t.length<32?ue(t):e(t)}}catch(e){}const{Writable:pe}=v.default,_e=ae,{BINARY_TYPES:me,EMPTY_BUFFER:ye,kStatusCode:ge,kWebSocket:ve}=D,{concat:be,toArrayBuffer:we,unmask:Se}=F.exports,{isValidStatusCode:ke,isValidUTF8:xe}=fe.exports,Ee=Buffer[Symbol.species];var Oe=class extends pe{constructor(e={}){super(),this._binaryType=e.binaryType||me[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ve]=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 Ee(t.buffer,t.byteOffset+e,t.length-e),new Ee(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Ee(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,Ce(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[_e.extensionName])return this._loop=!1,Ce(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,Ce(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Ce(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,Ce(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,Ce(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Ce(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Ce(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,Ce(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,Ce(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Ce(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,Ce(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,Ce(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=ye;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])&&Se(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[_e.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(Ce(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const s=this.dataMessage();if(s)return t(s);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?be(t,e):"arraybuffer"===this._binaryType?we(be(t,e)):t,this.emit("message",r,!0)}else{const r=be(t,e);if(!this._skipUTF8Validation&&!xe(r))return this._loop=!1,Ce(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,ye),this.end();else{const t=e.readUInt16BE(0);if(!ke(t))return Ce(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=new Ee(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!xe(r))return Ce(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 Ce(e,t,r,s,n){const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,Ce),i.code=n,i[ge]=s,i}const{randomFillSync:Te}=g.default,Ne=ae,{EMPTY_BUFFER:Le}=D,{isValidStatusCode:Pe}=fe.exports,{mask:Re,toBuffer:Ue}=F.exports,Ie=Symbol("kByteLength"),Me=Buffer.alloc(4);class Be{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,s,n=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Me,t.generateMask?t.generateMask(r):Te(r,0,4),o=0==(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?s=t.mask&&!o||void 0===t[Ie]?(e=Buffer.from(e)).length:t[Ie]:(s=e.length,n=t.mask&&t.readOnly&&!o);let a=s;s>=65536?(i+=8,a=127):s>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(n?s+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(s,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(s,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]:n?(Re(e,r,c,i,s),[c]):(Re(e,r,e,0,s),[c,e])):[c,e]}close(e,t,r,s){let n;if(void 0===e)n=Le;else{if("number"!=typeof e||!Pe(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");n=Buffer.allocUnsafe(2+r),n.writeUInt16BE(e,0),"string"==typeof t?n.write(t,2):n.set(t,2)}else n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0)}const i={[Ie]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,n,!1,i,s]):this.sendFrame(Be.frame(n,i),s)}ping(e,t,r){let s,n;if("string"==typeof e?(s=Buffer.byteLength(e),n=!1):(s=(e=Ue(e)).length,n=Ue.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ie]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(Be.frame(e,i),r)}pong(e,t,r){let s,n;if("string"==typeof e?(s=Buffer.byteLength(e),n=!1):(s=(e=Ue(e)).length,n=Ue.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ie]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(Be.frame(e,i),r)}send(e,t,r){const s=this._extensions[Ne.extensionName];let n,i,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):(n=(e=Ue(e)).length,i=Ue.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=n>=s._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),s){const s={[Ie]:n,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,s,r]):this.dispatch(e,this._compress,s,r)}else this.sendFrame(Be.frame(e,{[Ie]:n,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:!1}),r)}dispatch(e,t,r,s){if(!t)return void this.sendFrame(Be.frame(e,r),s);const n=this._extensions[Ne.extensionName];this._bufferedBytes+=r[Ie],this._deflating=!0,n.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 s&&s(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],s=r[r.length-1];"function"==typeof s&&s(e)}}else this._bufferedBytes-=r[Ie],this._deflating=!1,r.readOnly=!1,this.sendFrame(Be.frame(t,r),s),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ie],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ie],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 Ae=Be;const{kForOnEventAttribute:We,kListener:je}=D,Fe=Symbol("kCode"),De=Symbol("kData"),qe=Symbol("kError"),$e=Symbol("kMessage"),Ge=Symbol("kReason"),Ve=Symbol("kTarget"),ze=Symbol("kType"),He=Symbol("kWasClean");class Ye{constructor(e){this[Ve]=null,this[ze]=e}get target(){return this[Ve]}get type(){return this[ze]}}Object.defineProperty(Ye.prototype,"target",{enumerable:!0}),Object.defineProperty(Ye.prototype,"type",{enumerable:!0});class Xe extends Ye{constructor(e,t={}){super(e),this[Fe]=void 0===t.code?0:t.code,this[Ge]=void 0===t.reason?"":t.reason,this[He]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Fe]}get reason(){return this[Ge]}get wasClean(){return this[He]}}Object.defineProperty(Xe.prototype,"code",{enumerable:!0}),Object.defineProperty(Xe.prototype,"reason",{enumerable:!0}),Object.defineProperty(Xe.prototype,"wasClean",{enumerable:!0});class Qe extends Ye{constructor(e,t={}){super(e),this[qe]=void 0===t.error?null:t.error,this[$e]=void 0===t.message?"":t.message}get error(){return this[qe]}get message(){return this[$e]}}Object.defineProperty(Qe.prototype,"error",{enumerable:!0}),Object.defineProperty(Qe.prototype,"message",{enumerable:!0});class Ze extends Ye{constructor(e,t={}){super(e),this[De]=void 0===t.data?null:t.data}get data(){return this[De]}}Object.defineProperty(Ze.prototype,"data",{enumerable:!0});const Ke={addEventListener(e,t,r={}){for(const s of this.listeners(e))if(!r[We]&&s[je]===t&&!s[We])return;let s;if("message"===e)s=function(e,r){const s=new Ze("message",{data:r?e:e.toString()});s[Ve]=this,et(t,this,s)};else if("close"===e)s=function(e,r){const s=new Xe("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[Ve]=this,et(t,this,s)};else if("error"===e)s=function(e){const r=new Qe("error",{error:e,message:e.message});r[Ve]=this,et(t,this,r)};else{if("open"!==e)return;s=function(){const e=new Ye("open");e[Ve]=this,et(t,this,e)}}s[We]=!!r[We],s[je]=t,r.once?this.once(e,s):this.on(e,s)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[je]===t&&!r[We]){this.removeListener(e,r);break}}};var Je={CloseEvent:Xe,ErrorEvent:Qe,Event:Ye,EventTarget:Ke,MessageEvent:Ze};function et(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:tt}=fe.exports;function rt(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var st={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,s,n=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,h=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===h&&1===tt[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===h&&(h=f);const s=e.slice(c,h);44===l?(rt(t,s,n),n=Object.create(null)):r=s,c=h=-1}}else-1===h&&-1!==c&&(h=f);else if(void 0===s)if(-1===h&&1===tt[l])-1===c&&(c=f);else if(32===l||9===l)-1===h&&-1!==c&&(h=f);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f),rt(n,e.slice(c,h),!0),44===l&&(rt(t,r,n),n=Object.create(null),r=void 0),c=h=-1}else{if(61!==l||-1===c||-1!==h)throw new SyntaxError(`Unexpected character at index ${f}`);s=e.slice(c,f),c=h=-1}else if(o){if(1!==tt[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:i||(i=!0),o=!1}else if(a)if(1===tt[l])-1===c&&(c=f);else if(34===l&&-1!==c)a=!1,h=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===h&&1===tt[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===h&&(h=f);let o=e.slice(c,h);i&&(o=o.replace(/\\/g,""),i=!1),rt(n,s,o),44===l&&(rt(t,r,n),n=Object.create(null),r=void 0),s=void 0,c=h=-1}}else-1===h&&(h=f);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===h&&(h=f);const d=e.slice(c,h);return void 0===r?rt(t,d,n):(void 0===s?rt(n,d,!0):rt(n,s,i?d.replace(/\\/g,""):d),rt(t,r,n)),t}};const nt=m.default,it=u.default,ot=d.default,at=y.default,ct=p.default,{randomBytes:lt,createHash:ht}=g.default,{URL:ft}=b.default,dt=ae,ut=Oe,pt=Ae,{BINARY_TYPES:_t,EMPTY_BUFFER:mt,GUID:yt,kForOnEventAttribute:gt,kListener:vt,kStatusCode:bt,kWebSocket:wt,NOOP:St}=D,{EventTarget:{addEventListener:kt,removeEventListener:xt}}=Je,{format:Et,parse:Ot}=st,{toBuffer:Ct}=F.exports,Tt=Symbol("kAborted"),Nt=[8,13],Lt=["CONNECTING","OPEN","CLOSING","CLOSED"],Pt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class Rt extends nt{constructor(e,t,r){super(),this._binaryType=_t[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=mt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=Rt.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]),It(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){_t.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 s=new ut({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new pt(e,this._extensions,r.generateMask),this._receiver=s,this._socket=e,s[wt]=this,e[wt]=this,s.on("conclude",Ft),s.on("drain",Dt),s.on("error",qt),s.on("message",Gt),s.on("ping",Vt),s.on("pong",zt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Yt),e.on("data",Xt),e.on("end",Qt),e.on("error",Zt),this._readyState=Rt.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=Rt.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[dt.extensionName]&&this._extensions[dt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=Rt.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==Rt.CLOSED)if(this.readyState!==Rt.CONNECTING)this.readyState!==Rt.CLOSING?(this._readyState=Rt.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";Wt(this,this._req,e)}}pause(){this.readyState!==Rt.CONNECTING&&this.readyState!==Rt.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===Rt.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===Rt.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||mt,t,r)):jt(this,e,r)}pong(e,t,r){if(this.readyState===Rt.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===Rt.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||mt,t,r)):jt(this,e,r)}resume(){this.readyState!==Rt.CONNECTING&&this.readyState!==Rt.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===Rt.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!==Rt.OPEN)return void jt(this,e,r);const s={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[dt.extensionName]||(s.compress=!1),this._sender.send(e||mt,s,r)}terminate(){if(this.readyState!==Rt.CLOSED)if(this.readyState!==Rt.CONNECTING)this._socket&&(this._readyState=Rt.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";Wt(this,this._req,e)}}}Object.defineProperty(Rt,"CONNECTING",{enumerable:!0,value:Lt.indexOf("CONNECTING")}),Object.defineProperty(Rt.prototype,"CONNECTING",{enumerable:!0,value:Lt.indexOf("CONNECTING")}),Object.defineProperty(Rt,"OPEN",{enumerable:!0,value:Lt.indexOf("OPEN")}),Object.defineProperty(Rt.prototype,"OPEN",{enumerable:!0,value:Lt.indexOf("OPEN")}),Object.defineProperty(Rt,"CLOSING",{enumerable:!0,value:Lt.indexOf("CLOSING")}),Object.defineProperty(Rt.prototype,"CLOSING",{enumerable:!0,value:Lt.indexOf("CLOSING")}),Object.defineProperty(Rt,"CLOSED",{enumerable:!0,value:Lt.indexOf("CLOSED")}),Object.defineProperty(Rt.prototype,"CLOSED",{enumerable:!0,value:Lt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(Rt.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(Rt.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[gt])return t[vt];return null},set(t){for(const t of this.listeners(e))if(t[gt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[gt]:!0})}})})),Rt.prototype.addEventListener=kt,Rt.prototype.removeEventListener=xt;var Ut=Rt;function It(e,t,r,s){const n={protocolVersion:Nt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,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(!Nt.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Nt.join(", ")})`);let i;if(t instanceof ft)i=t,e._url=t.href;else{try{i=new ft(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 Mt(e,t)}const l=o?443:80,h=lt(16).toString("base64"),f=o?it.request:ot.request,d=new Set;let u,p;if(n.createConnection=o?At:Bt,n.defaultPort=n.defaultPort||l,n.port=i.port||l,n.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},n.path=i.pathname+i.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(u=new dt(!0!==n.perMessageDeflate?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=Et({[dt.extensionName]:u.offer()})),r.length){for(const e of r){if("string"!=typeof e||!Pt.test(e)||d.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.add(e)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(i.username||i.password)&&(n.auth=`${i.username}:${i.password}`),a){const e=n.path.split(":");n.socketPath=e[0],n.path=e[1]}if(n.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?n.socketPath:i.host;const t=s&&s.headers;if(s={...s,headers:{}},t)for(const[e,r]of Object.entries(t))s.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&n.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete n.headers.authorization,delete n.headers.cookie,t||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),p=e._req=f(n),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(n);n.timeout&&p.on("timeout",(()=>{Wt(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Tt]||(p=e._req=null,Mt(e,t))})),p.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&n.followRedirects&&a>=300&&a<400){if(++e._redirects>n.maxRedirects)return void Wt(e,p,"Maximum redirects exceeded");let i;p.abort();try{i=new ft(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void Mt(e,r)}It(e,i,r,s)}else e.emit("unexpected-response",p,i)||Wt(e,p,`Unexpected server response: ${i.statusCode}`)})),p.on("upgrade",((t,r,s)=>{if(e.emit("upgrade",t),e.readyState!==Rt.CONNECTING)return;if(p=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void Wt(e,r,"Invalid Upgrade header");const i=ht("sha1").update(h+yt).digest("base64");if(t.headers["sec-websocket-accept"]!==i)return void Wt(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?d.size?d.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":d.size&&(a="Server sent no subprotocol"),a)return void Wt(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!u){return void Wt(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Ot(c)}catch(t){return void Wt(e,r,"Invalid Sec-WebSocket-Extensions header")}const s=Object.keys(t);if(1!==s.length||s[0]!==dt.extensionName){return void Wt(e,r,"Server indicated an extension that was not requested")}try{u.accept(t[dt.extensionName])}catch(t){return void Wt(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[dt.extensionName]=u}e.setSocket(r,s,{generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})})),p.end()}function Mt(e,t){e._readyState=Rt.CLOSING,e.emit("error",t),e.emitClose()}function Bt(e){return e.path=e.socketPath,at.connect(e)}function At(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=at.isIP(e.host)?"":e.host),ct.connect(e)}function Wt(e,t,r){e._readyState=Rt.CLOSING;const s=new Error(r);Error.captureStackTrace(s,Wt),t.setHeader?(t[Tt]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Mt,e,s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function jt(e,t,r){if(t){const r=Ct(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Lt[e.readyState]})`);process.nextTick(r,t)}}function Ft(e,t){const r=this[wt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[wt]&&(r._socket.removeListener("data",Xt),process.nextTick(Ht,r._socket),1005===e?r.close():r.close(e,t))}function Dt(){const e=this[wt];e.isPaused||e._socket.resume()}function qt(e){const t=this[wt];void 0!==t._socket[wt]&&(t._socket.removeListener("data",Xt),process.nextTick(Ht,t._socket),t.close(e[bt])),t.emit("error",e)}function $t(){this[wt].emitClose()}function Gt(e,t){this[wt].emit("message",e,t)}function Vt(e){const t=this[wt];t.pong(e,!t._isServer,St),t.emit("ping",e)}function zt(e){this[wt].emit("pong",e)}function Ht(e){e.resume()}function Yt(){const e=this[wt];let t;this.removeListener("close",Yt),this.removeListener("data",Xt),this.removeListener("end",Qt),e._readyState=Rt.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[wt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",$t),e._receiver.on("finish",$t))}function Xt(e){this[wt]._receiver.write(e)||this.pause()}function Qt(){const e=this[wt];e._readyState=Rt.CLOSING,e._receiver.end(),this.end()}function Zt(){const e=this[wt];this.removeListener("error",Zt),this.on("error",St),e&&(e._readyState=Rt.CLOSING,this.destroy())}const{Duplex:Kt}=v.default;function Jt(e){e.emit("close")}function er(){!this.destroyed&&this._writableState.finished&&this.destroy()}function tr(e){this.removeListener("error",tr),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var rr=function(e,t){let r=!0;const s=new Kt({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const n=!r&&s._readableState.objectMode?t.toString():t;s.push(n)||e.pause()})),e.once("error",(function(e){s.destroyed||(r=!1,s.destroy(e))})),e.once("close",(function(){s.destroyed||s.push(null)})),s._destroy=function(t,n){if(e.readyState===e.CLOSED)return n(t),void process.nextTick(Jt,s);let i=!1;e.once("error",(function(e){i=!0,n(e)})),e.once("close",(function(){i||n(t),process.nextTick(Jt,s)})),r&&e.terminate()},s._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){s._final(t)}))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,r,n){e.readyState!==e.CONNECTING?e.send(t,n):e.once("open",(function(){s._write(t,r,n)}))},s.on("end",er),s.on("error",tr),s};const{tokenChars:sr}=fe.exports;var nr={parse:function(e){const t=new Set;let r=-1,s=-1,n=0;for(;n<e.length;n++){const i=e.charCodeAt(n);if(-1===s&&1===sr[i])-1===r&&(r=n);else if(0===n||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${n}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${n}`);-1===s&&(s=n);const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=s=-1}}else-1===s&&-1!==r&&(s=n)}if(-1===r||-1!==s)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const ir=m.default,or=d.default,{createHash:ar}=g.default,cr=st,lr=ae,hr=nr,fr=Ut,{GUID:dr,kWebSocket:ur}=D,pr=/^[+/0-9A-Za-z]{22}==$/,_r=2;var mr=class extends ir{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:fr,...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=or.createServer(((e,t)=>{const r=or.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,s)=>{this.handleUpgrade(t,r,s,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===_r)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(yr,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(yr,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{yr(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,s){t.on("error",gr);const n=e.headers["sec-websocket-key"],i=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void br(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void br(this,e,t,400,"Invalid Upgrade header")}if(!n||!pr.test(n)){return void br(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==i&&13!==i){return void br(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void vr(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=hr.parse(o)}catch(r){return void br(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 lr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=cr.parse(c);e[lr.extensionName]&&(r.accept(e[lr.extensionName]),l[lr.extensionName]=r)}catch(r){return void br(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,h)=>{if(!i)return vr(t,o||401,c,h);this.completeUpgrade(l,n,a,e,t,r,s)}));if(!this.options.verifyClient(o))return vr(t,401)}this.completeUpgrade(l,n,a,e,t,r,s)}completeUpgrade(e,t,r,s,n,i,o){if(!n.readable||!n.writable)return n.destroy();if(n[ur])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return vr(n,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ar("sha1").update(t+dr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[lr.extensionName]){const t=e[lr.extensionName].params,r=cr.format({[lr.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,s),n.write(a.concat("\r\n").join("\r\n")),n.removeListener("error",gr),c.setSocket(n,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(yr,this)}))),o(c,s)}};function yr(e){e._state=_r,e.emit("close")}function gr(){this.destroy()}function vr(e,t,r,s){r=r||or.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${or.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function br(e,t,r,s,n){if(e.listenerCount("wsClientError")){const s=new Error(n);Error.captureStackTrace(s,br),e.emit("wsClientError",s,r,t)}else vr(r,s,n)}const wr=Ut;wr.createWebSocketStream=rr,wr.Server=mr,wr.Receiver=Oe,wr.Sender=Ae,wr.WebSocket=wr,wr.WebSocketServer=wr.Server;var Sr=wr,kr="3.1.3",xr=require("child_process"),Er=require("events"),Or=require("url"),Cr=Sr.Server,Tr="ffmpeg",Nr="mpeg1video",Lr="mp2",Pr=!1,Rr=2,Ur=["tcp","udp","udp_multicast","http","https"],Ir="tcp",Mr=!0,Br=!0,Ar="drawtext=x=w-tw-5:y=80:fontcolor=white:fontsize=32:text="+decodeURIComponent(j.exports.decode("Y2xlYXIlMjB3aXRoJTIwcXElMjA0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",Wr=60,jr=10,Fr=["-s","-b:v","scale","contrast","brightness","saturation","gamma"].concat(["vcodec"]),Dr=["scale","contrast","brightness","saturation","gamma"],qr=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"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}},$r=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&&N(e,t)}(r,Er.EventEmitter);var t=P(r);function r(e){var s;return x(this,r),C(L(s=t.call(this)),"exitCode",void 0),C(L(s),"additionalFlags",[]),C(L(s),"stream",null),C(L(s),"inputStreamStarted",!1),s.ffmpegPath=Tr,s.url=e.url,s.ffmpegOptions=e.ffmpegOptions,s.options=e,s.initMpeg2Muxer(),s}return O(r,[{key:"initMpeg2Muxer",value:function(){var e=this;if(Mr&&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=["-thread_queue_size","1024","-rtsp_transport",Ir,"-i",this.url,"-f","mpegts","-c:v",Nr,"-q",Rr,"-r","30","-c:a",Lr,Pr?"-an":null,"-ar","48000","-ac","1"].concat(U(this.additionalFlags),["-nostats","-"]),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=xr.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("**启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数~,code:",e,"signal:",t)})),this.stream.on("exit",(function(t,r){return console.error("**[某个视频流转码进程退出],请检查ffmpeg参数或相关情况或联系作者**,code:",t,"signal:",r),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}(),Gr=function(){function e(t){x(this,e),C(this,"freeTime",0),C(this,"width",null),C(this,"height",null),C(this,"isStreamWrap",!1),C(this,"clients",[]),C(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 $r({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(e){-1!==(e=e.toString()).indexOf("failed")&&(-1!==e.indexOf("Operation timed out")&&global.process.stdout.write(e+"哎呀~你的链接有问题,超时了!=== L520 \n"),-1!==e.indexOf("Conversion")&&console.log("*".concat(Ir,"*模式转换失败,请尝试改变transportType的值,然后重试。***"))),-1!==e.indexOf("404 Not Found")&&global.process.stdout.write(e+"=== L521 \n"),-1!==e.indexOf("Invalid data found")&&global.process.stdout.write(e+"=== L522 \n"),-1!==e.indexOf("Unrecognized option")&&global.process.stdout.write(e+"=== L523 \n"),-1!==e.indexOf("pipe")&&global.process.stdout.write(e+"=== L524 \n"),e.indexOf("Output #")})),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":Ar},r=0,s=Object.entries(e);r<s.length;r++){var n=R(s[r],2),i=n[0],o=n[1];Fr.includes(i)&&(Dr.includes(i)?"scale"===i?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(o)):t["-vf"]+="".concat(i,"=").concat(o,":"):qr(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=B(this.clients);try{for(r.s();!(t=r.n()).done;){var s=t.value;s.isSegment&&s.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("视频播放窗口关闭1个,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=B(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}(),Vr=function(){function e(t){var r=this;x(this,e),C(this,"channels",[]),console.log("current rtsp2web version: ".concat(kr,"; run on ").concat(global.process.platform)),xr.exec("ffmpeg -version",(function(e,t,r){e&&console.log("请检查你的ffmpeg是否正确存在,错误信息:",e.stack)})),t&&"boolean"==typeof t.wm&&!t.wm&&(Ar="scale=-1:-1,eq=",Br=!1),t&&"boolean"==typeof t.vf&&!t.vf&&(Mr=!1),t&&"string"==typeof t.path&&t.path.length>0&&(Tr=t.path),t&&"string"==typeof t.vcodec&&t.vcodec.length>0&&(Nr=t.vcodec),t&&"number"==typeof t.q&&t.q>=0&&(Rr=t.q),t&&"string"==typeof t.transportType&&Ur.includes(t.transportType)&&(Ir=t.transportType),t&&"boolean"==typeof t.audio&&!t.audio&&(Pr=!0),t&&["string","number"].includes(k(t.freeTime))&&"number"==typeof parseInt(t.freeTime,10)&&(Wr=parseInt(t.freeTime,10)),t&&["string","number"].includes(k(t.checkTime))&&"number"==typeof parseInt(t.checkTime,10)&&(jr=parseInt(t.checkTime,10)),setInterval((function(){r.checkFree(),Br&&(Ar.includes(decodeURIComponent(j.exports.decode("eCUzRHctdHctNSUzQXklM0Q4MCUzQWZvbnRjb2xvciUzRHdoaXRlJTNBZm9udHNpemUlM0QzMiUzQXRleHQlM0RjbGVhciUyMHdpdGglMjBxcSUyMDQyMTM1NDUzMiUzQWJveCUzRDElM0Fib3hjb2xvciUzRGJsYWNr")))||(r.destroyAllChannel(),global.process.stderr.write("***wm代码异常***,请联系作者!")))}),1e3*jr);var s=d.default.createServer((function(e,t){t.writeHead(200),t.end("hello rtsp2web, with ws [ws] model ~ \n")}));if(t&&"object"===k(t.wss))if(console.log("wss启动中...."),t.wss.hasOwnProperty("pfx"))if(t.wss.hasOwnProperty("passphrase"))try{s=u.default.createServer({pfx:_.default.readFileSync(t.wss.pfx),passphrase:_.default.readFileSync(t.wss.passphrase)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [pfx&passphrase] model ~ \n")}))}catch(e){console.error("--[读取pfx安全证书文件出错,wss启动失败,退回到ws;请检查(pfx&passphrase),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败:请传入正确的密码:passphrase】"),global.process.stdout.write("---ws正常开启中--- W11 \n");else if(t.wss.hasOwnProperty("cert"))if(t.wss.hasOwnProperty("key"))try{s=u.default.createServer({key:_.default.readFileSync(t.wss.key),cert:_.default.readFileSync(t.wss.cert)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [key&cert] model ~ \n")}))}catch(e){console.error("--[读取SSL证书文件Error,wss启动失败,退回到ws;请检查(key&cert),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败;请传入正确的安全证书私钥:key.pem】"),global.process.stdout.write("---ws正常开启中--- W13 \n");else console.error("【wss启动失败;请传入正确的安全证书公钥:cert.pem】"),global.process.stdout.write("---ws正常开启中--- W12 \n");s.listen(t&&t.port||9999),Object.getPrototypeOf(s)instanceof p.default.Server&&console.log("wss model success!!!"),this.wss=new Cr({server:s}),this.wss.on("connection",(function(e,t){var s=Or.parse(t.url,!0);if(s.query.url){var n=j.exports.decode(s.query.url.toString());s.query.url=n,r.registeClient(e,{url:n,options:s.query})}console.log("一个新的视频播放窗口(client,ws句柄)连接成功")}))}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=B(this.channels);try{for(r.s();!(t=r.n()).done;){var s=t.value;if(s.url===e)return s}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new Gr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=B(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=jr,r.freeTime>=Wr&&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=B(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}();C(Vr,"version",kr),module.exports=Vr;
10
+ !function(e,t){!function(r){var s=t,n=e&&e.exports==s&&e,i="object"==typeof W&&W;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,h={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,s,n,i=e.length%3,o="",l=-1,h=e.length-i;++l<h;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,s=e.charCodeAt(++l),o+=c.charAt((n=t+r+s)>>18&63)+c.charAt(n>>12&63)+c.charAt(n>>6&63)+c.charAt(63&n);return 2==i?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),o+=c.charAt((n=t+r)>>10)+c.charAt(n>>4&63)+c.charAt(n<<2&63)+"="):1==i&&(n=e.charCodeAt(l),o+=c.charAt(n>>2)+c.charAt(n<<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,s,n=0,i="",o=-1;++o<t;)s=c.indexOf(e.charAt(o)),r=n%4?64*r+s:s,n++%4&&(i+=String.fromCharCode(255&r>>(-2*n&6)));return i},version:"1.0.0"};if(s&&!s.nodeType)if(n)n.exports=h;else for(var f in h)h.hasOwnProperty(f)&&(s[f]=h[f]);else r.base64=h}(W)}(j,j.exports);var F={exports:{}},D={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:q}=D,$=Buffer[Symbol.species];function G(e,t,r,s,n){for(let i=0;i<n;i++)r[s+i]=e[i]^t[3&i]}function V(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(F.exports={concat:function(e,t){if(0===e.length)return q;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let s=0;for(let t=0;t<e.length;t++){const n=e[t];r.set(n,s),s+=n.length}return s<t?new $(r.buffer,r.byteOffset,s):r},mask:G,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 $(t):ArrayBuffer.isView(t)?r=new $(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:V},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");F.exports.mask=function(t,r,s,n,i){i<48?G(t,r,s,n,i):e.mask(t,r,s,n,i)},F.exports.unmask=function(t,r){t.length<32?V(t,r):e.unmask(t,r)}}catch(e){}const z=Symbol("kDone"),H=Symbol("kRun");var Y=class{constructor(e){this[z]=()=>{this.pending--,this[H]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[H]()}[H](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[z])}}};const X=w.default,Q=F.exports,Z=Y,{kStatusCode:K}=D,J=Buffer[Symbol.species],ee=Buffer.from([0,0,255,255]),te=Symbol("permessage-deflate"),re=Symbol("total-length"),se=Symbol("callback"),ne=Symbol("buffers"),ie=Symbol("error");let oe;var ae=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,!oe){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;oe=new Z(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[se];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){oe.add((s=>{this._decompress(e,t,((e,t)=>{s(),r(e,t)}))}))}compress(e,t,r){oe.add((s=>{this._compress(e,t,((e,t)=>{s(),r(e,t)}))}))}_decompress(e,t,r){const s=this._isServer?"client":"server";if(!this._inflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?X.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=X.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[te]=this,this._inflate[re]=0,this._inflate[ne]=[],this._inflate.on("error",he),this._inflate.on("data",le)}this._inflate[se]=r,this._inflate.write(e),t&&this._inflate.write(ee),this._inflate.flush((()=>{const e=this._inflate[ie];if(e)return this._inflate.close(),this._inflate=null,void r(e);const n=Q.concat(this._inflate[ne],this._inflate[re]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[re]=0,this._inflate[ne]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,n)}))}_compress(e,t,r){const s=this._isServer?"server":"client";if(!this._deflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?X.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=X.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[re]=0,this._deflate[ne]=[],this._deflate.on("data",ce)}this._deflate[se]=r,this._deflate.write(e),this._deflate.flush(X.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Q.concat(this._deflate[ne],this._deflate[re]);t&&(e=new J(e.buffer,e.byteOffset,e.length-4)),this._deflate[se]=null,this._deflate[re]=0,this._deflate[ne]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function ce(e){this[ne].push(e),this[re]+=e.length}function le(e){this[re]+=e.length,this[te]._maxPayload<1||this[re]<=this[te]._maxPayload?this[ne].push(e):(this[ie]=new RangeError("Max payload size exceeded"),this[ie].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ie][K]=1009,this.removeListener("data",le),this.reset())}function he(e){this[te]._inflate=null,e[K]=1007,this[se](e)}var fe={exports:{}};const{isUtf8:de}=S.default;function ue(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(fe.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:ue,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]},de)fe.exports.isValidUTF8=function(e){return e.length<24?ue(e):de(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");fe.exports.isValidUTF8=function(t){return t.length<32?ue(t):e(t)}}catch(e){}const{Writable:pe}=v.default,_e=ae,{BINARY_TYPES:me,EMPTY_BUFFER:ye,kStatusCode:ge,kWebSocket:ve}=D,{concat:be,toArrayBuffer:we,unmask:Se}=F.exports,{isValidStatusCode:ke,isValidUTF8:xe}=fe.exports,Ee=Buffer[Symbol.species];var Oe=class extends pe{constructor(e={}){super(),this._binaryType=e.binaryType||me[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ve]=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 Ee(t.buffer,t.byteOffset+e,t.length-e),new Ee(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Ee(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,Ce(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[_e.extensionName])return this._loop=!1,Ce(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,Ce(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Ce(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,Ce(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,Ce(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Ce(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Ce(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,Ce(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,Ce(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Ce(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,Ce(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,Ce(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=ye;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])&&Se(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[_e.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(Ce(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const s=this.dataMessage();if(s)return t(s);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?be(t,e):"arraybuffer"===this._binaryType?we(be(t,e)):t,this.emit("message",r,!0)}else{const r=be(t,e);if(!this._skipUTF8Validation&&!xe(r))return this._loop=!1,Ce(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,ye),this.end();else{const t=e.readUInt16BE(0);if(!ke(t))return Ce(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=new Ee(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!xe(r))return Ce(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 Ce(e,t,r,s,n){const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,Ce),i.code=n,i[ge]=s,i}const{randomFillSync:Te}=g.default,Ne=ae,{EMPTY_BUFFER:Le}=D,{isValidStatusCode:Pe}=fe.exports,{mask:Re,toBuffer:Ue}=F.exports,Ie=Symbol("kByteLength"),Me=Buffer.alloc(4);class Be{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,s,n=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Me,t.generateMask?t.generateMask(r):Te(r,0,4),o=0==(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?s=t.mask&&!o||void 0===t[Ie]?(e=Buffer.from(e)).length:t[Ie]:(s=e.length,n=t.mask&&t.readOnly&&!o);let a=s;s>=65536?(i+=8,a=127):s>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(n?s+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(s,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(s,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]:n?(Re(e,r,c,i,s),[c]):(Re(e,r,e,0,s),[c,e])):[c,e]}close(e,t,r,s){let n;if(void 0===e)n=Le;else{if("number"!=typeof e||!Pe(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");n=Buffer.allocUnsafe(2+r),n.writeUInt16BE(e,0),"string"==typeof t?n.write(t,2):n.set(t,2)}else n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0)}const i={[Ie]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,n,!1,i,s]):this.sendFrame(Be.frame(n,i),s)}ping(e,t,r){let s,n;if("string"==typeof e?(s=Buffer.byteLength(e),n=!1):(s=(e=Ue(e)).length,n=Ue.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ie]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(Be.frame(e,i),r)}pong(e,t,r){let s,n;if("string"==typeof e?(s=Buffer.byteLength(e),n=!1):(s=(e=Ue(e)).length,n=Ue.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ie]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(Be.frame(e,i),r)}send(e,t,r){const s=this._extensions[Ne.extensionName];let n,i,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):(n=(e=Ue(e)).length,i=Ue.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=n>=s._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),s){const s={[Ie]:n,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,s,r]):this.dispatch(e,this._compress,s,r)}else this.sendFrame(Be.frame(e,{[Ie]:n,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:!1}),r)}dispatch(e,t,r,s){if(!t)return void this.sendFrame(Be.frame(e,r),s);const n=this._extensions[Ne.extensionName];this._bufferedBytes+=r[Ie],this._deflating=!0,n.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 s&&s(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],s=r[r.length-1];"function"==typeof s&&s(e)}}else this._bufferedBytes-=r[Ie],this._deflating=!1,r.readOnly=!1,this.sendFrame(Be.frame(t,r),s),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ie],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ie],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 Ae=Be;const{kForOnEventAttribute:We,kListener:je}=D,Fe=Symbol("kCode"),De=Symbol("kData"),qe=Symbol("kError"),$e=Symbol("kMessage"),Ge=Symbol("kReason"),Ve=Symbol("kTarget"),ze=Symbol("kType"),He=Symbol("kWasClean");class Ye{constructor(e){this[Ve]=null,this[ze]=e}get target(){return this[Ve]}get type(){return this[ze]}}Object.defineProperty(Ye.prototype,"target",{enumerable:!0}),Object.defineProperty(Ye.prototype,"type",{enumerable:!0});class Xe extends Ye{constructor(e,t={}){super(e),this[Fe]=void 0===t.code?0:t.code,this[Ge]=void 0===t.reason?"":t.reason,this[He]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Fe]}get reason(){return this[Ge]}get wasClean(){return this[He]}}Object.defineProperty(Xe.prototype,"code",{enumerable:!0}),Object.defineProperty(Xe.prototype,"reason",{enumerable:!0}),Object.defineProperty(Xe.prototype,"wasClean",{enumerable:!0});class Qe extends Ye{constructor(e,t={}){super(e),this[qe]=void 0===t.error?null:t.error,this[$e]=void 0===t.message?"":t.message}get error(){return this[qe]}get message(){return this[$e]}}Object.defineProperty(Qe.prototype,"error",{enumerable:!0}),Object.defineProperty(Qe.prototype,"message",{enumerable:!0});class Ze extends Ye{constructor(e,t={}){super(e),this[De]=void 0===t.data?null:t.data}get data(){return this[De]}}Object.defineProperty(Ze.prototype,"data",{enumerable:!0});const Ke={addEventListener(e,t,r={}){for(const s of this.listeners(e))if(!r[We]&&s[je]===t&&!s[We])return;let s;if("message"===e)s=function(e,r){const s=new Ze("message",{data:r?e:e.toString()});s[Ve]=this,et(t,this,s)};else if("close"===e)s=function(e,r){const s=new Xe("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[Ve]=this,et(t,this,s)};else if("error"===e)s=function(e){const r=new Qe("error",{error:e,message:e.message});r[Ve]=this,et(t,this,r)};else{if("open"!==e)return;s=function(){const e=new Ye("open");e[Ve]=this,et(t,this,e)}}s[We]=!!r[We],s[je]=t,r.once?this.once(e,s):this.on(e,s)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[je]===t&&!r[We]){this.removeListener(e,r);break}}};var Je={CloseEvent:Xe,ErrorEvent:Qe,Event:Ye,EventTarget:Ke,MessageEvent:Ze};function et(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:tt}=fe.exports;function rt(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var st={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,s,n=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,h=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===h&&1===tt[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===h&&(h=f);const s=e.slice(c,h);44===l?(rt(t,s,n),n=Object.create(null)):r=s,c=h=-1}}else-1===h&&-1!==c&&(h=f);else if(void 0===s)if(-1===h&&1===tt[l])-1===c&&(c=f);else if(32===l||9===l)-1===h&&-1!==c&&(h=f);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${f}`);-1===h&&(h=f),rt(n,e.slice(c,h),!0),44===l&&(rt(t,r,n),n=Object.create(null),r=void 0),c=h=-1}else{if(61!==l||-1===c||-1!==h)throw new SyntaxError(`Unexpected character at index ${f}`);s=e.slice(c,f),c=h=-1}else if(o){if(1!==tt[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:i||(i=!0),o=!1}else if(a)if(1===tt[l])-1===c&&(c=f);else if(34===l&&-1!==c)a=!1,h=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===h&&1===tt[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===h&&(h=f);let o=e.slice(c,h);i&&(o=o.replace(/\\/g,""),i=!1),rt(n,s,o),44===l&&(rt(t,r,n),n=Object.create(null),r=void 0),s=void 0,c=h=-1}}else-1===h&&(h=f);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===h&&(h=f);const d=e.slice(c,h);return void 0===r?rt(t,d,n):(void 0===s?rt(n,d,!0):rt(n,s,i?d.replace(/\\/g,""):d),rt(t,r,n)),t}};const nt=m.default,it=u.default,ot=d.default,at=y.default,ct=p.default,{randomBytes:lt,createHash:ht}=g.default,{URL:ft}=b.default,dt=ae,ut=Oe,pt=Ae,{BINARY_TYPES:_t,EMPTY_BUFFER:mt,GUID:yt,kForOnEventAttribute:gt,kListener:vt,kStatusCode:bt,kWebSocket:wt,NOOP:St}=D,{EventTarget:{addEventListener:kt,removeEventListener:xt}}=Je,{format:Et,parse:Ot}=st,{toBuffer:Ct}=F.exports,Tt=Symbol("kAborted"),Nt=[8,13],Lt=["CONNECTING","OPEN","CLOSING","CLOSED"],Pt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class Rt extends nt{constructor(e,t,r){super(),this._binaryType=_t[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=mt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=Rt.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]),It(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){_t.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 s=new ut({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new pt(e,this._extensions,r.generateMask),this._receiver=s,this._socket=e,s[wt]=this,e[wt]=this,s.on("conclude",Ft),s.on("drain",Dt),s.on("error",qt),s.on("message",Gt),s.on("ping",Vt),s.on("pong",zt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Yt),e.on("data",Xt),e.on("end",Qt),e.on("error",Zt),this._readyState=Rt.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=Rt.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[dt.extensionName]&&this._extensions[dt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=Rt.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==Rt.CLOSED)if(this.readyState!==Rt.CONNECTING)this.readyState!==Rt.CLOSING?(this._readyState=Rt.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";Wt(this,this._req,e)}}pause(){this.readyState!==Rt.CONNECTING&&this.readyState!==Rt.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===Rt.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===Rt.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||mt,t,r)):jt(this,e,r)}pong(e,t,r){if(this.readyState===Rt.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===Rt.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||mt,t,r)):jt(this,e,r)}resume(){this.readyState!==Rt.CONNECTING&&this.readyState!==Rt.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===Rt.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!==Rt.OPEN)return void jt(this,e,r);const s={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[dt.extensionName]||(s.compress=!1),this._sender.send(e||mt,s,r)}terminate(){if(this.readyState!==Rt.CLOSED)if(this.readyState!==Rt.CONNECTING)this._socket&&(this._readyState=Rt.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";Wt(this,this._req,e)}}}Object.defineProperty(Rt,"CONNECTING",{enumerable:!0,value:Lt.indexOf("CONNECTING")}),Object.defineProperty(Rt.prototype,"CONNECTING",{enumerable:!0,value:Lt.indexOf("CONNECTING")}),Object.defineProperty(Rt,"OPEN",{enumerable:!0,value:Lt.indexOf("OPEN")}),Object.defineProperty(Rt.prototype,"OPEN",{enumerable:!0,value:Lt.indexOf("OPEN")}),Object.defineProperty(Rt,"CLOSING",{enumerable:!0,value:Lt.indexOf("CLOSING")}),Object.defineProperty(Rt.prototype,"CLOSING",{enumerable:!0,value:Lt.indexOf("CLOSING")}),Object.defineProperty(Rt,"CLOSED",{enumerable:!0,value:Lt.indexOf("CLOSED")}),Object.defineProperty(Rt.prototype,"CLOSED",{enumerable:!0,value:Lt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(Rt.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(Rt.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[gt])return t[vt];return null},set(t){for(const t of this.listeners(e))if(t[gt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[gt]:!0})}})})),Rt.prototype.addEventListener=kt,Rt.prototype.removeEventListener=xt;var Ut=Rt;function It(e,t,r,s){const n={protocolVersion:Nt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,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(!Nt.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Nt.join(", ")})`);let i;if(t instanceof ft)i=t,e._url=t.href;else{try{i=new ft(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 Mt(e,t)}const l=o?443:80,h=lt(16).toString("base64"),f=o?it.request:ot.request,d=new Set;let u,p;if(n.createConnection=o?At:Bt,n.defaultPort=n.defaultPort||l,n.port=i.port||l,n.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},n.path=i.pathname+i.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(u=new dt(!0!==n.perMessageDeflate?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=Et({[dt.extensionName]:u.offer()})),r.length){for(const e of r){if("string"!=typeof e||!Pt.test(e)||d.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.add(e)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(i.username||i.password)&&(n.auth=`${i.username}:${i.password}`),a){const e=n.path.split(":");n.socketPath=e[0],n.path=e[1]}if(n.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?n.socketPath:i.host;const t=s&&s.headers;if(s={...s,headers:{}},t)for(const[e,r]of Object.entries(t))s.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&n.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete n.headers.authorization,delete n.headers.cookie,t||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),p=e._req=f(n),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(n);n.timeout&&p.on("timeout",(()=>{Wt(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Tt]||(p=e._req=null,Mt(e,t))})),p.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&n.followRedirects&&a>=300&&a<400){if(++e._redirects>n.maxRedirects)return void Wt(e,p,"Maximum redirects exceeded");let i;p.abort();try{i=new ft(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void Mt(e,r)}It(e,i,r,s)}else e.emit("unexpected-response",p,i)||Wt(e,p,`Unexpected server response: ${i.statusCode}`)})),p.on("upgrade",((t,r,s)=>{if(e.emit("upgrade",t),e.readyState!==Rt.CONNECTING)return;if(p=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void Wt(e,r,"Invalid Upgrade header");const i=ht("sha1").update(h+yt).digest("base64");if(t.headers["sec-websocket-accept"]!==i)return void Wt(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?d.size?d.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":d.size&&(a="Server sent no subprotocol"),a)return void Wt(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!u){return void Wt(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Ot(c)}catch(t){return void Wt(e,r,"Invalid Sec-WebSocket-Extensions header")}const s=Object.keys(t);if(1!==s.length||s[0]!==dt.extensionName){return void Wt(e,r,"Server indicated an extension that was not requested")}try{u.accept(t[dt.extensionName])}catch(t){return void Wt(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[dt.extensionName]=u}e.setSocket(r,s,{generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})})),p.end()}function Mt(e,t){e._readyState=Rt.CLOSING,e.emit("error",t),e.emitClose()}function Bt(e){return e.path=e.socketPath,at.connect(e)}function At(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=at.isIP(e.host)?"":e.host),ct.connect(e)}function Wt(e,t,r){e._readyState=Rt.CLOSING;const s=new Error(r);Error.captureStackTrace(s,Wt),t.setHeader?(t[Tt]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Mt,e,s)):(t.destroy(s),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function jt(e,t,r){if(t){const r=Ct(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Lt[e.readyState]})`);process.nextTick(r,t)}}function Ft(e,t){const r=this[wt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[wt]&&(r._socket.removeListener("data",Xt),process.nextTick(Ht,r._socket),1005===e?r.close():r.close(e,t))}function Dt(){const e=this[wt];e.isPaused||e._socket.resume()}function qt(e){const t=this[wt];void 0!==t._socket[wt]&&(t._socket.removeListener("data",Xt),process.nextTick(Ht,t._socket),t.close(e[bt])),t.emit("error",e)}function $t(){this[wt].emitClose()}function Gt(e,t){this[wt].emit("message",e,t)}function Vt(e){const t=this[wt];t.pong(e,!t._isServer,St),t.emit("ping",e)}function zt(e){this[wt].emit("pong",e)}function Ht(e){e.resume()}function Yt(){const e=this[wt];let t;this.removeListener("close",Yt),this.removeListener("data",Xt),this.removeListener("end",Qt),e._readyState=Rt.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[wt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",$t),e._receiver.on("finish",$t))}function Xt(e){this[wt]._receiver.write(e)||this.pause()}function Qt(){const e=this[wt];e._readyState=Rt.CLOSING,e._receiver.end(),this.end()}function Zt(){const e=this[wt];this.removeListener("error",Zt),this.on("error",St),e&&(e._readyState=Rt.CLOSING,this.destroy())}const{Duplex:Kt}=v.default;function Jt(e){e.emit("close")}function er(){!this.destroyed&&this._writableState.finished&&this.destroy()}function tr(e){this.removeListener("error",tr),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var rr=function(e,t){let r=!0;const s=new Kt({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const n=!r&&s._readableState.objectMode?t.toString():t;s.push(n)||e.pause()})),e.once("error",(function(e){s.destroyed||(r=!1,s.destroy(e))})),e.once("close",(function(){s.destroyed||s.push(null)})),s._destroy=function(t,n){if(e.readyState===e.CLOSED)return n(t),void process.nextTick(Jt,s);let i=!1;e.once("error",(function(e){i=!0,n(e)})),e.once("close",(function(){i||n(t),process.nextTick(Jt,s)})),r&&e.terminate()},s._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){s._final(t)}))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,r,n){e.readyState!==e.CONNECTING?e.send(t,n):e.once("open",(function(){s._write(t,r,n)}))},s.on("end",er),s.on("error",tr),s};const{tokenChars:sr}=fe.exports;var nr={parse:function(e){const t=new Set;let r=-1,s=-1,n=0;for(;n<e.length;n++){const i=e.charCodeAt(n);if(-1===s&&1===sr[i])-1===r&&(r=n);else if(0===n||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${n}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${n}`);-1===s&&(s=n);const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=s=-1}}else-1===s&&-1!==r&&(s=n)}if(-1===r||-1!==s)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const ir=m.default,or=d.default,{createHash:ar}=g.default,cr=st,lr=ae,hr=nr,fr=Ut,{GUID:dr,kWebSocket:ur}=D,pr=/^[+/0-9A-Za-z]{22}==$/,_r=2;var mr=class extends ir{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:fr,...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=or.createServer(((e,t)=>{const r=or.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,s)=>{this.handleUpgrade(t,r,s,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===_r)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(yr,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(yr,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{yr(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,s){t.on("error",gr);const n=e.headers["sec-websocket-key"],i=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void br(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void br(this,e,t,400,"Invalid Upgrade header")}if(!n||!pr.test(n)){return void br(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==i&&13!==i){return void br(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void vr(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=hr.parse(o)}catch(r){return void br(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 lr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=cr.parse(c);e[lr.extensionName]&&(r.accept(e[lr.extensionName]),l[lr.extensionName]=r)}catch(r){return void br(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,h)=>{if(!i)return vr(t,o||401,c,h);this.completeUpgrade(l,n,a,e,t,r,s)}));if(!this.options.verifyClient(o))return vr(t,401)}this.completeUpgrade(l,n,a,e,t,r,s)}completeUpgrade(e,t,r,s,n,i,o){if(!n.readable||!n.writable)return n.destroy();if(n[ur])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return vr(n,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ar("sha1").update(t+dr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[lr.extensionName]){const t=e[lr.extensionName].params,r=cr.format({[lr.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,s),n.write(a.concat("\r\n").join("\r\n")),n.removeListener("error",gr),c.setSocket(n,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(yr,this)}))),o(c,s)}};function yr(e){e._state=_r,e.emit("close")}function gr(){this.destroy()}function vr(e,t,r,s){r=r||or.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${or.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function br(e,t,r,s,n){if(e.listenerCount("wsClientError")){const s=new Error(n);Error.captureStackTrace(s,br),e.emit("wsClientError",s,r,t)}else vr(r,s,n)}const wr=Ut;wr.createWebSocketStream=rr,wr.Server=mr,wr.Receiver=Oe,wr.Sender=Ae,wr.WebSocket=wr,wr.WebSocketServer=wr.Server;var Sr=wr,kr="3.1.5",xr=require("child_process"),Er=require("events"),Or=require("url"),Cr=Sr.Server,Tr="ffmpeg",Nr=["jsmpeg","flv"],Lr="jsmpeg",Pr={jsmpeg:"mpegts",flv:"flv"},Rr={jsmpeg:"mpeg1video",flv:"libx264"},Ur={jsmpeg:"mp2",flv:"aac"},Ir=!1,Mr=2,Br=["tcp","udp","udp_multicast","http","https"],Ar="tcp",Wr="204800",jr=!0,Fr=!0,Dr="drawtext=x=w-tw-5:y=80:fontcolor=white:fontsize=32:text="+decodeURIComponent(j.exports.decode("Y2xlYXIlMjB3aXRoJTIwcXElMjA0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",qr=20,$r=10,Gr=["-s","-b:v","webplayer","scale","contrast","brightness","saturation","gamma"].concat(["vcodec"]),Vr=["scale","contrast","brightness","saturation","gamma"],zr=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"webplayer":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}},Hr=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&&N(e,t)}(r,Er.EventEmitter);var t=P(r);function r(e){var s;return x(this,r),C(L(s=t.call(this)),"exitCode",void 0),C(L(s),"additionalFlags",[]),C(L(s),"stream",null),C(L(s),"inputStreamStarted",!1),s.ffmpegPath=Tr,s.url=e.url,s.ffmpegOptions=e.ffmpegOptions,s.options=e,s.initMpeg2Muxer(),s}return O(r,[{key:"initMpeg2Muxer",value:function(){var e=this;if(jr||delete this.ffmpegOptions["-vf"],this.ffmpegOptions.webplayer&&(Lr=this.ffmpegOptions.webplayer,delete this.ffmpegOptions.webplayer),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=["-re","-rtsp_transport",Ar,"-buffer_size",Wr,"-thread_queue_size","1024","-threads","8","-max_interleave_delta","0","-i",this.url,"-q",Mr,"-f",Pr[Lr],"-c:v",Rr[Lr],"-r","30","-c:a",Ur[Lr],Ir?"-an":null,"-ar","48000","-ac","1"].concat(U(this.additionalFlags),["-nostats","-"]),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=xr.spawn(this.ffmpegPath,this.spawnOptions,{detached:!1}),this.stream.on("error",(function(e,t){console.error("**启动ffmpeg时出错,请确保你安装了ffmpeg,然后检查路径或者命令参数~,code:",e,"signal:",t)})),this.stream.on("exit",(function(t,r){return console.error("[ffmpeg]某个视频流转码进程退出了: **如果非正常关闭视频导致的退出,请检查ffmpeg参数或检查代码或联系作者解决**,code:",t,"signal:",r),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}(),Yr=function(){function e(t){x(this,e),C(this,"freeTime",0),C(this,"width",null),C(this,"height",null),C(this,"isStreamWrap",!1),C(this,"clients",[]),C(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 Hr({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(e){-1!==(e=e.toString()).indexOf("failed")&&(-1!==e.indexOf("Operation timed out")&&global.process.stdout.write(e+"哎呀~你的链接有问题,超时了!=== L519 \n"),-1!==e.indexOf("Conversion")&&console.log("*".concat(Ar,"*模式转换失败,请尝试改变transportType的值,然后重试。***")),-1!==e.indexOf("transport")&&global.process.stdout.write(e+"=== L520 \n")),-1!==e.indexOf("404 Not Found")&&global.process.stdout.write(e+"=== L521 \n"),-1!==e.indexOf("Invalid data found")&&global.process.stdout.write(e+"=== L522 \n"),-1!==e.indexOf("Unrecognized option")&&global.process.stdout.write(e+"=== L523 \n"),-1!==e.indexOf("pipe")&&global.process.stdout.write(e+"=== L524 \n"),e.indexOf("Output #")})),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":Dr},r=0,s=Object.entries(e);r<s.length;r++){var n=R(s[r],2),i=n[0],o=n[1];Gr.includes(i)&&(Vr.includes(i)?"scale"===i?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(o)):t["-vf"]+="".concat(i,"=").concat(o,":"):zr(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=B(this.clients);try{for(r.s();!(t=r.n()).done;){var s=t.value;s.isSegment&&s.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("视频播放窗口关闭1个,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=B(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}(),Xr=function(){function e(t){var r=this;x(this,e),C(this,"channels",[]),console.log("---[info]: current rtsp2web version: ".concat(kr,"; current platform is ").concat(global.process.platform,"---")),xr.exec("ffmpeg -version",(function(e,t,r){e&&console.log("请检查你的ffmpeg是否正确存在,错误信息:",e.stack)})),t&&"boolean"==typeof t.wm&&!t.wm&&(Dr="scale=-1:-1,eq=",Fr=!1),t&&"boolean"==typeof t.vf&&!t.vf&&(jr=!1),t&&"string"==typeof t.path&&t.path.length>0&&(Tr=t.path),t&&"string"==typeof t.webplayer&&Nr.includes(t.webplayer)&&(Lr=t.webplayer),t&&"number"==typeof t.q&&t.q>=0&&(Mr=t.q),t&&"string"==typeof t.transportType&&Br.includes(t.transportType)&&(Ar=t.transportType),t&&"boolean"==typeof t.audio&&!t.audio&&(Ir=!0),t&&["string","number"].includes(k(t.freeTime))&&"number"==typeof parseInt(t.freeTime,10)&&(qr=parseInt(t.freeTime,10)),t&&["string","number"].includes(k(t.checkTime))&&"number"==typeof parseInt(t.checkTime,10)&&($r=parseInt(t.checkTime,10)),setInterval((function(){r.checkFree(),Fr&&(Dr.includes(decodeURIComponent(j.exports.decode("eCUzRHctdHctNSUzQXklM0Q4MCUzQWZvbnRjb2xvciUzRHdoaXRlJTNBZm9udHNpemUlM0QzMiUzQXRleHQlM0RjbGVhciUyMHdpdGglMjBxcSUyMDQyMTM1NDUzMiUzQWJveCUzRDElM0Fib3hjb2xvciUzRGJsYWNr")))||(r.destroyAllChannel(),global.process.stderr.write("----wm代码异常、视频闪屏的问题----,请联系作者帮你解决!!")))}),1e3*$r);var s=d.default.createServer((function(e,t){t.writeHead(200),t.end("hello rtsp2web, with ws [ws] model ~ \n")}));if(t&&"object"===k(t.wss))if(console.log("wss启动中...."),t.wss.hasOwnProperty("pfx"))if(t.wss.hasOwnProperty("passphrase"))try{s=u.default.createServer({pfx:_.default.readFileSync(t.wss.pfx),passphrase:_.default.readFileSync(t.wss.passphrase)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [pfx&passphrase] model ~ \n")}))}catch(e){console.error("--[读取pfx安全证书文件出错,wss启动失败,退回到ws;请检查(pfx&passphrase),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败:请传入正确的密码:passphrase】"),global.process.stdout.write("---ws正常开启中--- W11 \n");else if(t.wss.hasOwnProperty("cert"))if(t.wss.hasOwnProperty("key"))try{s=u.default.createServer({key:_.default.readFileSync(t.wss.key),cert:_.default.readFileSync(t.wss.cert)},(function(e,t){console.log("client connect cross wss!"),t.writeHead(200),t.end("hello rtsp2web, with wss [key&cert] model ~ \n")}))}catch(e){console.error("--[读取SSL证书文件Error,wss启动失败,退回到ws;请检查(key&cert),错误信息如下,有问题请联系我]--"),console.log(e)}else console.error("【wss启动失败;请传入正确的安全证书私钥:key.pem】"),global.process.stdout.write("---ws正常开启中--- W13 \n");else console.error("【wss启动失败;请传入正确的安全证书公钥:cert.pem】"),global.process.stdout.write("---ws正常开启中--- W12 \n");s.listen(t&&t.port||9999),Object.getPrototypeOf(s)instanceof p.default.Server&&console.log("wss model success!!!"),this.wss=new Cr({server:s}),this.wss.on("connection",(function(e,t){var s=Or.parse(t.url,!0);if(s.query.url){var n=j.exports.decode(s.query.url.toString());s.query.url=n,r.registeClient(e,{url:n,options:s.query})}console.log("一个新的视频播放窗口(client,ws句柄)连接成功")}))}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=B(this.channels);try{for(r.s();!(t=r.n()).done;){var s=t.value;if(s.url===e)return s}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new Yr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=B(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=$r,r.freeTime>=qr&&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=B(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}();C(Xr,"version",kr),module.exports=Xr;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rtsp2web",
3
- "version": "3.1.3",
3
+ "version": "3.1.5",
4
4
  "description": "帮你在web页面中直接播放rtsp视频流,支持同时播放多个",
5
5
  "keywords": [
6
6
  "rtsp",