rtsp2web 3.1.5 → 3.1.6
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 +89 -70
- package/dist/rtsp2web.js +3 -3
- package/dist/rtsp2web.min.js +3 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,20 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
`rtsp2web` 是一个提供在 `web` 页面中可以直接播放 `rtsp` 视频流解决方案的工具;简单、高效、快捷、安全。
|
|
4
4
|
|
|
5
|
+
> _PS: rtmp 格式的视频流也可以使用_
|
|
6
|
+
|
|
7
|
+
使用 `rtsp2web` 后,前端代码中可以使用 `jsmpeg.js` 或者 `flv.js` 来进行视频流的直接播放。
|
|
8
|
+
|
|
5
9
|
# 特点
|
|
6
10
|
|
|
7
11
|
- 上手简单,提供的示例代码完整可运行,无需繁琐复杂的技术负担,直接运行代码,快速解决视频流播放的问题;
|
|
8
12
|
- 延时非常低,视频流稳定,几乎是实时的,满足任何需求;不花钱,采用开源框架,无商业风险;
|
|
9
|
-
-
|
|
13
|
+
- 别的收费平台,需要暴露 RTSP 视频流链接给收费平台,rtsp2web 无需您提供 RTSP 视频流,您的保密&安全牢牢掌握在您手中;
|
|
10
14
|
- 高效兼容,大多数 nvr 或 ipc 或摄像头平台都支持输出 RTSP 视频流,rtsp2web 把 RTSP 视频流转换到页面可播放,减少对接工作,不论您是什么摄像头;
|
|
11
15
|
- 支持前端使用 `jsmpeg.js`、`flv.js` 等播放器,满足不同技术栈团队使用;
|
|
12
16
|
- 删繁就简,无需插件就可在浏览器显示视频画面,兼容各大浏览器厂商;
|
|
13
|
-
-
|
|
17
|
+
- 省时省力,同一页面可以播放不同厂家的视频,无需任何额外操作,轻松支持多路视频同时播放;
|
|
14
18
|
- 可以在公网上部署使用,但也可能因为你们公司网络的设置原因,你会面临一点小问题:还要学习网络穿透打洞,服务器部署能力,流量消耗,wss 等。
|
|
15
19
|
|
|
16
20
|
# 支持的视频厂商
|
|
17
21
|
|
|
18
|
-
海康、海康 NVR
|
|
22
|
+
海康、海康 NVR、大华平台、萤石、宇视、中天信科达、东方网力、天地伟业等。
|
|
19
23
|
|
|
20
24
|
# How to use(如何在你的项目中使用这个工具)
|
|
21
25
|
|
|
@@ -25,7 +29,7 @@ FFmpeg 是一套可以用来记录、转换数字音频、视频,并能将其
|
|
|
25
29
|
|
|
26
30
|
**确保在你要运行 rtsp2web 的机器上已经安装了 FFmpeg。**
|
|
27
31
|
|
|
28
|
-
> _有问题,可以联系我_
|
|
32
|
+
> _新打开一个命令行窗口,输入:ffmpeg -version ,如果有相关信息输出,则证明 FFmpeg 的安装是 OK 的。 <br/> 有问题,可以联系我_
|
|
29
33
|
|
|
30
34
|
<br>
|
|
31
35
|
|
|
@@ -62,17 +66,17 @@ new RTSP2web({
|
|
|
62
66
|
|
|
63
67
|
4.1、参数说明(在 `new RTSP2web` 时,可配置的参数如下:)
|
|
64
68
|
|
|
65
|
-
| 参数 |
|
|
66
|
-
| :-----------: |
|
|
67
|
-
| port |
|
|
68
|
-
| path |
|
|
69
|
-
| audio |
|
|
70
|
-
| freeTime |
|
|
71
|
-
| checkTime |
|
|
72
|
-
| q |
|
|
73
|
-
| transportType |
|
|
74
|
-
| webplayer |
|
|
75
|
-
| wss |
|
|
69
|
+
| 参数 | 解释说明 |
|
|
70
|
+
| :-----------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
|
|
71
|
+
| port | 转码推流服务占用的端口号;(type:Number)<br/>可以不传;默认值:9999 |
|
|
72
|
+
| path | FFmpeg 命令在你机器上的启动名称,(type: String) <br/> 一般情况下不传;默认值:'ffmpeg' |
|
|
73
|
+
| audio | 默认不传,有声音;默认值:true;即:输出音频。<br/>如果想禁止输出音频,可以配置 audio: false |
|
|
74
|
+
| freeTime | 任一视频流空闲(未被使用)时间超过这个值,就会停止该视频流的转码,释放机器资源(type: Number;单位:秒) <br/> 一般情况下可不传;默认值:20 |
|
|
75
|
+
| checkTime | 检测视频空闲的时间间隔(type: Number;单位:秒) <br/> 一般情况下可不传;默认值:10 |
|
|
76
|
+
| q | 视频质量;取值范围:0-1000;数字越小,视频越清晰,带宽消耗越大<br/> 默认值:8; |
|
|
77
|
+
| transportType | 设置 RTSP 传输协议,默认值:无<br/>可选值:['tcp', 'udp', 'udp_multicast', 'http', 'https']<br/>ps: 这里默认值是无,也就是 rtsp2web 会自动选择一种传输协议;但事呢,并不能保证一定成功,这个时候,rtsp2web 日志会打印出错误信息,这个时候就需要你手动来配置这个参数了。详情可以参阅文档最后的【常见问题解决办法】 |
|
|
78
|
+
| webplayer | 设置前端播放器(视频流转码器),默认不传,默认值:'jsmpeg'<br/>可选值:['jsmpeg', 'flv'];如果设置为 `flv`,请参考下面 `flv.js` 小节了解详细的使用方法 |
|
|
79
|
+
| wss | 配置 wss;配置格式如下:<br/> `wss: {key: 'keyPath', cert: 'certPath'}` <br/>如果你是 pfx 的证书,那么配置格式如下:<br/>`wss: {pfx: 'pfxPath', passphrase: 'passphrasePath'}`<br/>如果你想使用`wss`的话请配置这个选项,否则不要使用这个配置。 |
|
|
76
80
|
|
|
77
81
|
---
|
|
78
82
|
|
|
@@ -179,13 +183,15 @@ new JSMpeg.Player(
|
|
|
179
183
|
|
|
180
184
|
<br>
|
|
181
185
|
|
|
186
|
+
> _ps: 目前使用 rtsp2web 的用户中,大多数情况下都正常使用;极少数用户会遇到一点问题,所以文档最后面有【常见问题解决办法】,必要时可以看看_
|
|
187
|
+
|
|
188
|
+
<br>
|
|
189
|
+
|
|
182
190
|
# 去水印
|
|
183
191
|
|
|
184
192
|
正确的去除水印能减小 `FFmpeg` 性能开销,有效提高 `FFMpeg` 运行效率,提升视频播放质量,可支撑更多的视频;
|
|
185
193
|
|
|
186
|
-
如何去除水印,[联系我](https://neveryu.blog.csdn.net/article/details/124124137);
|
|
187
|
-
|
|
188
|
-
wechat: miracle421354532
|
|
194
|
+
如何去除水印,[联系我](https://neveryu.blog.csdn.net/article/details/124124137);wechat: miracle421354532
|
|
189
195
|
|
|
190
196
|
# 声音
|
|
191
197
|
|
|
@@ -199,73 +205,81 @@ wechat: miracle421354532
|
|
|
199
205
|
|
|
200
206
|
# 支持 flv.js
|
|
201
207
|
|
|
202
|
-
|
|
208
|
+
~~`flv.js` 比 `jsmpeg.js` 的播放性能和效果更好。(这个也不好说,根据个人喜好来,治愈性能方面谁更优,待验证)~~
|
|
209
|
+
|
|
210
|
+
`flv.js` 也是现在主流的播放器之一,而且 `flv.js` 播放器,默认就有进度条、在线回放、全屏、画中画、倍速播放等功能,有需要的可以选择 `flv.js`。
|
|
203
211
|
|
|
204
212
|
如果你的前端代码中使用的是 `flv.js` 或者你想在前端代码中使用 `flv.js` 来播放视频的话,你可以按如下操作:
|
|
205
213
|
|
|
214
|
+
1、在创建 `rtsp2web` 时,增加配置项 `webplayer: 'flv'`
|
|
215
|
+
|
|
206
216
|
```js
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
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
|
-
}
|
|
217
|
+
// index.js
|
|
218
|
+
const RTSP2web = require('rtsp2web')
|
|
219
|
+
// 服务端长连接占据的端口号
|
|
220
|
+
let port = 9999
|
|
221
|
+
new RTSP2web({
|
|
222
|
+
port,
|
|
223
|
+
q: 20,
|
|
224
|
+
webplayer: 'flv'
|
|
225
|
+
})
|
|
227
226
|
```
|
|
228
227
|
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
有任何不明白的,及时与我联系:[联系我](https://neveryu.blog.csdn.net/article/details/124124137);
|
|
232
|
-
|
|
233
|
-
wechat: miracle421354532
|
|
228
|
+
2、在前端代码中引入 `flv.js`,并创建一个 `video` 标签节点,然后在 `js` 中初始化 `flv` 并播放。
|
|
234
229
|
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
230
|
+
```html
|
|
231
|
+
...
|
|
232
|
+
<script src="./flv.min.js" charset="utf-8"></script>
|
|
233
|
+
...
|
|
234
|
+
<video
|
|
235
|
+
id="flv-1"
|
|
236
|
+
height="500"
|
|
237
|
+
muted
|
|
238
|
+
style="border: thin solid green"
|
|
239
|
+
controls
|
|
240
|
+
loop
|
|
241
|
+
></video>
|
|
242
|
+
...
|
|
243
|
+
<script>
|
|
244
|
+
console.log('flvjs 是否支持:', flvjs.isSupported())
|
|
245
|
+
if (flvjs.isSupported()) {
|
|
246
|
+
var videoElement = document.getElementById('flv-1')
|
|
247
|
+
var flvPlayer = flvjs.createPlayer({
|
|
248
|
+
isLive: true,
|
|
249
|
+
type: 'flv',
|
|
250
|
+
url: 'ws://localhost:8098/rtsp?url=' + btoa(rtsp1),
|
|
251
|
+
enableWorker: true,
|
|
252
|
+
enableStashBuffer: false,
|
|
253
|
+
stashInitialSize: 128 // 减少首桢显示等待时长
|
|
254
|
+
})
|
|
255
|
+
flvPlayer.attachMediaElement(videoElement)
|
|
256
|
+
try {
|
|
257
|
+
flvPlayer.load()
|
|
258
|
+
flvPlayer.play()
|
|
259
|
+
// flvPlayer.pause()
|
|
260
|
+
} catch (err) {
|
|
261
|
+
// not do something
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
</script>
|
|
265
|
+
```
|
|
254
266
|
|
|
255
|
-
|
|
267
|
+
详细参考例子:[https://github.com/Neveryu/rtsp2web/tree/master/example/index-flv.html](https://github.com/Neveryu/rtsp2web/tree/master/example/index-flv.html)
|
|
256
268
|
|
|
257
|
-
|
|
269
|
+
有任何不明白的,及时与我联系:[联系我](https://neveryu.blog.csdn.net/article/details/124124137);wechat: miracle421354532
|
|
258
270
|
|
|
259
|
-
|
|
271
|
+
## 👉 [Change Log [更新日志]](https://github.com/Neveryu/rtsp2web/blob/master/CHANGELOG.md)
|
|
260
272
|
|
|
261
|
-
|
|
273
|
+
<br/>
|
|
262
274
|
|
|
263
275
|
# 常见问题解决办法
|
|
264
276
|
|
|
265
|
-
### 一、模式转换失败
|
|
277
|
+
### 一、模式转换失败 [或者] 进程退出,请检查 ffmpeg 参数... [或者] 其他等等问题
|
|
266
278
|
|
|
267
279
|
如果出现了这之类的提示,大多数情况下,你可能需要尝试配置 `transportType` 为其他值试试,`'tcp'`, `'udp'`是最常见的选择。
|
|
268
280
|
|
|
281
|
+
> PS: 在正常的操作下遇到视频流无法播放,或者 `rtsp2web` 提示错误信息的情况下,优先选择使用这条解决办法来尝试解决问题。
|
|
282
|
+
|
|
269
283
|
### 二、ffmpeg 进程关闭了,code:3221225477
|
|
270
284
|
|
|
271
285
|
> 如果出现了 `3221225477`;这是 NodeJS 内核反馈的[违反了访问规定]的问题,一般这个问题只发生在 `windows` 平台上,可以尝试的操作有:
|
|
@@ -275,16 +289,21 @@ wechat: miracle421354532
|
|
|
275
289
|
- 3、升级更新 `nodejs`,安装稳定版,再试试;
|
|
276
290
|
- 4、`rm -rf node_modules`,`delete package-lock.json`,重新安装,再试试;
|
|
277
291
|
- 5、[待验证]切换合适的 `node` 版本可解决;
|
|
292
|
+
- 6、也可以参考【办法一】来尝试解决这类问题;
|
|
278
293
|
|
|
279
294
|
### 三、转换失败,请尝试改变 transportType 的值,然后重试。
|
|
280
295
|
|
|
281
296
|
> 你可以尝试配置 `transportType` 为其他值试试,`'tcp'`, `'udp'`是最常见的选择。
|
|
282
297
|
|
|
298
|
+
### 四、有问题随时沟通,wechat: miracle421354532
|
|
299
|
+
|
|
300
|
+
<br/>
|
|
301
|
+
|
|
283
302
|
# 以下客户使用了 rtsp2web
|
|
284
303
|
|
|
285
|
-
|
|
304
|
+
广州天河区智慧交通、江苏石油化工油罐工厂、江苏镇江石化、武汉丽岛物业、武汉恒阳化工厂、苏州工业园区等
|
|
286
305
|
|
|
287
|
-
|
|
306
|
+
还有一些个人、企业用户等。
|
|
288
307
|
|
|
289
308
|
# donate
|
|
290
309
|
|
package/dist/rtsp2web.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* rtsp2web v3.1.
|
|
2
|
+
* rtsp2web v3.1.6
|
|
3
3
|
* (c) 2020-2023 NeverYu
|
|
4
4
|
* My home page:https://neveryu.github.io/neveryu/
|
|
5
5
|
* 微信(wechat):miracle421354532
|
|
6
6
|
* Released under the ISC License.
|
|
7
7
|
*/
|
|
8
|
-
"use strict";var e=require("http"),t=require("https"),r=require("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:{}};
|
|
8
|
+
"use strict";var e=require("http"),t=require("https"),r=require("tls"),n=require("fs"),s=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 u=f(e),d=f(t),p=f(r),_=f(n),m=f(s),y=f(i),v=f(o),g=f(a),b=f(c),w=f(l),S=f(h);function x(){x=function(){return e};var e={},t=Object.prototype,r=t.hasOwnProperty,n=Object.defineProperty||function(e,t,r){e[t]=r.value},s="function"==typeof Symbol?Symbol:{},i=s.iterator||"@@iterator",o=s.asyncIterator||"@@asyncIterator",a=s.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,s){var i=t&&t.prototype instanceof u?t:u,o=Object.create(i.prototype),a=new O(s||[]);return n(o,"_invoke",{value:w(e,r,a)}),o}function h(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var f={};function u(){}function d(){}function p(){}var _={};c(_,i,(function(){return this}));var m=Object.getPrototypeOf,y=m&&m(m(C([])));y&&y!==t&&r.call(y,i)&&(_=y);var v=p.prototype=u.prototype=Object.create(_);function g(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function b(e,t){function s(n,i,o,a){var c=h(e[n],e,i);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==typeof f&&r.call(f,"__await")?t.resolve(f.__await).then((function(e){s("next",e,o,a)}),(function(e){s("throw",e,o,a)})):t.resolve(f).then((function(e){l.value=e,o(l)}),(function(e){return s("throw",e,o,a)}))}a(c.arg)}var i;n(this,"_invoke",{value:function(e,r){function n(){return new t((function(t,n){s(e,r,t,n)}))}return i=i?i.then(n,n):n()}})}function w(e,t,r){var n="suspendedStart";return function(s,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===s)throw i;return T()}for(r.method=s,r.arg=i;;){var o=r.delegate;if(o){var a=S(o,r);if(a){if(a===f)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=h(e,t,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===f)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}function S(e,t){var r=t.method,n=e.iterator[r];if(void 0===n)return t.delegate=null,"throw"===r&&e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),f;var s=h(n,e.iterator,t.arg);if("throw"===s.type)return t.method="throw",t.arg=s.arg,t.delegate=null,f;var i=s.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,f):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,f)}function k(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function E(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(k,this),this.reset(!0)}function C(e){if(e){var t=e[i];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,s=function t(){for(;++n<e.length;)if(r.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=void 0,t.done=!0,t};return s.next=s}}return{next:T}}function T(){return{value:void 0,done:!0}}return d.prototype=p,n(v,"constructor",{value:p,configurable:!0}),n(p,"constructor",{value:d,configurable:!0}),d.displayName=c(p,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,c(e,a,"GeneratorFunction")),e.prototype=Object.create(v),e},e.awrap=function(e){return{__await:e}},g(b.prototype),c(b.prototype,o,(function(){return this})),e.AsyncIterator=b,e.async=function(t,r,n,s,i){void 0===i&&(i=Promise);var o=new b(l(t,r,n,s),i);return e.isGeneratorFunction(r)?o:o.next().then((function(e){return e.done?e.value:o.next()}))},g(v),c(v,a,"Generator"),c(v,i,(function(){return this})),c(v,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=Object(e),r=[];for(var n in t)r.push(n);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},e.values=C,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!e)for(var t in this)"t"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(r,n){return o.type="throw",o.arg=e,t.next=r,n&&(t.method="next",t.arg=void 0),!!n}for(var s=this.tryEntries.length-1;s>=0;--s){var i=this.tryEntries[s],o=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var a=r.call(i,"catchLoc"),c=r.call(i,"finallyLoc");if(a&&c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(a){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var s=this.tryEntries[n];if(s.tryLoc<=this.prev&&r.call(s,"finallyLoc")&&this.prev<s.finallyLoc){var i=s;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=e,o.arg=t,i?(this.method="next",this.next=i.finallyLoc,f):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),f},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),E(r),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var s=n.arg;E(r)}return s}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:C(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},e}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 E(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function O(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function C(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,W(n.key),n)}}function T(e,t,r){return t&&C(e.prototype,t),r&&C(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function L(e,t,r){return(t=W(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function N(e){return N=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},N(e)}function P(e,t){return P=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},P(e,t)}function M(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function R(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,n=N(e);if(t){var s=N(this).constructor;r=Reflect.construct(n,arguments,s)}else r=n.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return M(e)}(this,r)}}function I(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,s,i,o,a=[],c=!0,l=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){l=!0,s=e}finally{try{if(!c&&null!=r.return&&(o=r.return(),Object(o)!==o))return}finally{if(l)throw s}}return a}}(e,t)||A(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 B(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||A(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 A(e,t){if(e){if("string"==typeof e)return B(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)?B(e,t):void 0}}function B(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function j(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=A(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,s=function(){};return{s:s,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return o=e.done,e},e:function(e){a=!0,i=e},f:function(){try{o||null==r.return||r.return()}finally{if(a)throw i}}}}function W(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}var F="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},D={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.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;
|
|
10
|
+
!function(e,t){!function(r){var n=t,s=e&&e.exports==n&&e,i="object"==typeof F&&F;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,n,s,i=e.length%3,o="",l=-1,h=e.length-i;++l<h;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,n=e.charCodeAt(++l),o+=c.charAt((s=t+r+n)>>18&63)+c.charAt(s>>12&63)+c.charAt(s>>6&63)+c.charAt(63&s);return 2==i?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),o+=c.charAt((s=t+r)>>10)+c.charAt(s>>4&63)+c.charAt(s<<2&63)+"="):1==i&&(s=e.charCodeAt(l),o+=c.charAt(s>>2)+c.charAt(s<<4&63)+"=="),o},decode:function(e){var t=(e=String(e).replace(l,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&a("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,s=0,i="",o=-1;++o<t;)n=c.indexOf(e.charAt(o)),r=s%4?64*r+n:n,s++%4&&(i+=String.fromCharCode(255&r>>(-2*s&6)));return i},version:"1.0.0"};if(n&&!n.nodeType)if(s)s.exports=h;else for(var f in h)h.hasOwnProperty(f)&&(n[f]=h[f]);else r.base64=h}(F)}(D,D.exports);var G={exports:{}},q={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,V=Buffer[Symbol.species];function z(e,t,r,n,s){for(let i=0;i<s;i++)r[n+i]=e[i]^t[3&i]}function H(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(G.exports={concat:function(e,t){if(0===e.length)return $;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let n=0;for(let t=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return n<t?new V(r.buffer,r.byteOffset,n):r},mask:z,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 V(t):ArrayBuffer.isView(t)?r=new V(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:H},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");G.exports.mask=function(t,r,n,s,i){i<48?z(t,r,n,s,i):e.mask(t,r,n,s,i)},G.exports.unmask=function(t,r){t.length<32?H(t,r):e.unmask(t,r)}}catch(e){}const Y=Symbol("kDone"),X=Symbol("kRun");var Q=class{constructor(e){this[Y]=()=>{this.pending--,this[X]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[X]()}[X](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Y])}}};const Z=w.default,K=G.exports,J=Q,{kStatusCode:ee}=q,te=Buffer[Symbol.species],re=Buffer.from([0,0,255,255]),ne=Symbol("permessage-deflate"),se=Symbol("total-length"),ie=Symbol("callback"),oe=Symbol("buffers"),ae=Symbol("error");let ce;var le=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,!ce){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;ce=new J(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[ie];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){ce.add((n=>{this._decompress(e,t,((e,t)=>{n(),r(e,t)}))}))}compress(e,t,r){ce.add((n=>{this._compress(e,t,((e,t)=>{n(),r(e,t)}))}))}_decompress(e,t,r){const n=this._isServer?"client":"server";if(!this._inflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Z.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Z.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[ne]=this,this._inflate[se]=0,this._inflate[oe]=[],this._inflate.on("error",ue),this._inflate.on("data",fe)}this._inflate[ie]=r,this._inflate.write(e),t&&this._inflate.write(re),this._inflate.flush((()=>{const e=this._inflate[ae];if(e)return this._inflate.close(),this._inflate=null,void r(e);const s=K.concat(this._inflate[oe],this._inflate[se]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[se]=0,this._inflate[oe]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),r(null,s)}))}_compress(e,t,r){const n=this._isServer?"server":"client";if(!this._deflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Z.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Z.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[se]=0,this._deflate[oe]=[],this._deflate.on("data",he)}this._deflate[ie]=r,this._deflate.write(e),this._deflate.flush(Z.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=K.concat(this._deflate[oe],this._deflate[se]);t&&(e=new te(e.buffer,e.byteOffset,e.length-4)),this._deflate[ie]=null,this._deflate[se]=0,this._deflate[oe]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function he(e){this[oe].push(e),this[se]+=e.length}function fe(e){this[se]+=e.length,this[ne]._maxPayload<1||this[se]<=this[ne]._maxPayload?this[oe].push(e):(this[ae]=new RangeError("Max payload size exceeded"),this[ae].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ae][ee]=1009,this.removeListener("data",fe),this.reset())}function ue(e){this[ne]._inflate=null,e[ee]=1007,this[ie](e)}var de={exports:{}};const{isUtf8:pe}=S.default;function _e(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(de.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:_e,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]},pe)de.exports.isValidUTF8=function(e){return e.length<24?_e(e):pe(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");de.exports.isValidUTF8=function(t){return t.length<32?_e(t):e(t)}}catch(e){}const{Writable:me}=g.default,ye=le,{BINARY_TYPES:ve,EMPTY_BUFFER:ge,kStatusCode:be,kWebSocket:we}=q,{concat:Se,toArrayBuffer:xe,unmask:ke}=G.exports,{isValidStatusCode:Ee,isValidUTF8:Oe}=de.exports,Ce=Buffer[Symbol.species];var Te=class extends me{constructor(e={}){super(),this._binaryType=e.binaryType||ve[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[we]=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 Ce(t.buffer,t.byteOffset+e,t.length-e),new Ce(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new Ce(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,Le(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[ye.extensionName])return this._loop=!1,Le(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,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Le(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,Le(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,Le(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Le(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Le(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,Le(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,Le(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Le(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,Le(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,Le(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=ge;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])&&ke(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[ye.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(Le(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const n=this.dataMessage();if(n)return t(n);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?Se(t,e):"arraybuffer"===this._binaryType?xe(Se(t,e)):t,this.emit("message",r,!0)}else{const r=Se(t,e);if(!this._skipUTF8Validation&&!Oe(r))return this._loop=!1,Le(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,ge),this.end();else{const t=e.readUInt16BE(0);if(!Ee(t))return Le(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=new Ce(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Oe(r))return Le(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 Le(e,t,r,n,s){const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,Le),i.code=s,i[be]=n,i}const{randomFillSync:Ne}=v.default,Pe=le,{EMPTY_BUFFER:Me}=q,{isValidStatusCode:Re}=de.exports,{mask:Ie,toBuffer:Ue}=G.exports,Ae=Symbol("kByteLength"),Be=Buffer.alloc(4);class je{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let r,n,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Be,t.generateMask?t.generateMask(r):Ne(r,0,4),o=0==(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?n=t.mask&&!o||void 0===t[Ae]?(e=Buffer.from(e)).length:t[Ae]:(n=e.length,s=t.mask&&t.readOnly&&!o);let a=n;n>=65536?(i+=8,a=127):n>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(s?n+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(n,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(n,4,6)),t.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(Ie(e,r,c,i,n),[c]):(Ie(e,r,e,0,n),[c,e])):[c,e]}close(e,t,r,n){let s;if(void 0===e)s=Me;else{if("number"!=typeof e||!Re(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+r),s.writeUInt16BE(e,0),"string"==typeof t?s.write(t,2):s.set(t,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0)}const i={[Ae]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,s,!1,i,n]):this.sendFrame(je.frame(s,i),n)}ping(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Ue(e)).length,s=Ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ae]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(je.frame(e,i),r)}pong(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Ue(e)).length,s=Ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ae]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(je.frame(e,i),r)}send(e,t,r){const n=this._extensions[Pe.extensionName];let s,i,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=Ue(e)).length,i=Ue.readOnly),this._firstFragment?(this._firstFragment=!1,a&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=n._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),n){const n={[Ae]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:a};this._deflating?this.enqueue([this.dispatch,e,this._compress,n,r]):this.dispatch(e,this._compress,n,r)}else this.sendFrame(je.frame(e,{[Ae]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:!1}),r)}dispatch(e,t,r,n){if(!t)return void this.sendFrame(je.frame(e,r),n);const s=this._extensions[Pe.extensionName];this._bufferedBytes+=r[Ae],this._deflating=!0,s.compress(e,r.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof n&&n(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],n=r[r.length-1];"function"==typeof n&&n(e)}}else this._bufferedBytes-=r[Ae],this._deflating=!1,r.readOnly=!1,this.sendFrame(je.frame(t,r),n),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ae],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ae],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 We=je;const{kForOnEventAttribute:Fe,kListener:De}=q,Ge=Symbol("kCode"),qe=Symbol("kData"),$e=Symbol("kError"),Ve=Symbol("kMessage"),ze=Symbol("kReason"),He=Symbol("kTarget"),Ye=Symbol("kType"),Xe=Symbol("kWasClean");class Qe{constructor(e){this[He]=null,this[Ye]=e}get target(){return this[He]}get type(){return this[Ye]}}Object.defineProperty(Qe.prototype,"target",{enumerable:!0}),Object.defineProperty(Qe.prototype,"type",{enumerable:!0});class Ze extends Qe{constructor(e,t={}){super(e),this[Ge]=void 0===t.code?0:t.code,this[ze]=void 0===t.reason?"":t.reason,this[Xe]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Ge]}get reason(){return this[ze]}get wasClean(){return this[Xe]}}Object.defineProperty(Ze.prototype,"code",{enumerable:!0}),Object.defineProperty(Ze.prototype,"reason",{enumerable:!0}),Object.defineProperty(Ze.prototype,"wasClean",{enumerable:!0});class Ke extends Qe{constructor(e,t={}){super(e),this[$e]=void 0===t.error?null:t.error,this[Ve]=void 0===t.message?"":t.message}get error(){return this[$e]}get message(){return this[Ve]}}Object.defineProperty(Ke.prototype,"error",{enumerable:!0}),Object.defineProperty(Ke.prototype,"message",{enumerable:!0});class Je extends Qe{constructor(e,t={}){super(e),this[qe]=void 0===t.data?null:t.data}get data(){return this[qe]}}Object.defineProperty(Je.prototype,"data",{enumerable:!0});const et={addEventListener(e,t,r={}){for(const n of this.listeners(e))if(!r[Fe]&&n[De]===t&&!n[Fe])return;let n;if("message"===e)n=function(e,r){const n=new Je("message",{data:r?e:e.toString()});n[He]=this,rt(t,this,n)};else if("close"===e)n=function(e,r){const n=new Ze("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[He]=this,rt(t,this,n)};else if("error"===e)n=function(e){const r=new Ke("error",{error:e,message:e.message});r[He]=this,rt(t,this,r)};else{if("open"!==e)return;n=function(){const e=new Qe("open");e[He]=this,rt(t,this,e)}}n[Fe]=!!r[Fe],n[De]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[De]===t&&!r[Fe]){this.removeListener(e,r);break}}};var tt={CloseEvent:Ze,ErrorEvent:Ke,Event:Qe,EventTarget:et,MessageEvent:Je};function rt(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:nt}=de.exports;function st(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var it={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let r,n,s=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,h=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===h&&1===nt[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 n=e.slice(c,h);44===l?(st(t,n,s),s=Object.create(null)):r=n,c=h=-1}}else-1===h&&-1!==c&&(h=f);else if(void 0===n)if(-1===h&&1===nt[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),st(s,e.slice(c,h),!0),44===l&&(st(t,r,s),s=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}`);n=e.slice(c,f),c=h=-1}else if(o){if(1!==nt[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:i||(i=!0),o=!1}else if(a)if(1===nt[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===nt[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),st(s,n,o),44===l&&(st(t,r,s),s=Object.create(null),r=void 0),n=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 u=e.slice(c,h);return void 0===r?st(t,u,s):(void 0===n?st(s,u,!0):st(s,n,i?u.replace(/\\/g,""):u),st(t,r,s)),t}};const ot=m.default,at=d.default,ct=u.default,lt=y.default,ht=p.default,{randomBytes:ft,createHash:ut}=v.default,{URL:dt}=b.default,pt=le,_t=Te,mt=We,{BINARY_TYPES:yt,EMPTY_BUFFER:vt,GUID:gt,kForOnEventAttribute:bt,kListener:wt,kStatusCode:St,kWebSocket:xt,NOOP:kt}=q,{EventTarget:{addEventListener:Et,removeEventListener:Ot}}=tt,{format:Ct,parse:Tt}=it,{toBuffer:Lt}=G.exports,Nt=Symbol("kAborted"),Pt=[8,13],Mt=["CONNECTING","OPEN","CLOSING","CLOSED"],Rt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class It extends ot{constructor(e,t,r){super(),this._binaryType=yt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=vt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=It.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]),At(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){yt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const n=new _t({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new mt(e,this._extensions,r.generateMask),this._receiver=n,this._socket=e,n[xt]=this,e[xt]=this,n.on("conclude",Gt),n.on("drain",qt),n.on("error",$t),n.on("message",zt),n.on("ping",Ht),n.on("pong",Yt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Qt),e.on("data",Zt),e.on("end",Kt),e.on("error",Jt),this._readyState=It.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=It.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[pt.extensionName]&&this._extensions[pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=It.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==It.CLOSED)if(this.readyState!==It.CONNECTING)this.readyState!==It.CLOSING?(this._readyState=It.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";Ft(this,this._req,e)}}pause(){this.readyState!==It.CONNECTING&&this.readyState!==It.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===It.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===It.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||vt,t,r)):Dt(this,e,r)}pong(e,t,r){if(this.readyState===It.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===It.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||vt,t,r)):Dt(this,e,r)}resume(){this.readyState!==It.CONNECTING&&this.readyState!==It.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===It.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!==It.OPEN)return void Dt(this,e,r);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[pt.extensionName]||(n.compress=!1),this._sender.send(e||vt,n,r)}terminate(){if(this.readyState!==It.CLOSED)if(this.readyState!==It.CONNECTING)this._socket&&(this._readyState=It.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";Ft(this,this._req,e)}}}Object.defineProperty(It,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")}),Object.defineProperty(It.prototype,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")}),Object.defineProperty(It,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")}),Object.defineProperty(It.prototype,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")}),Object.defineProperty(It,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")}),Object.defineProperty(It.prototype,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")}),Object.defineProperty(It,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")}),Object.defineProperty(It.prototype,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(It.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(It.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[bt])return t[wt];return null},set(t){for(const t of this.listeners(e))if(t[bt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[bt]:!0})}})})),It.prototype.addEventListener=Et,It.prototype.removeEventListener=Ot;var Ut=It;function At(e,t,r,n){const s={protocolVersion:Pt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!Pt.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Pt.join(", ")})`);let i;if(t instanceof dt)i=t,e._url=t.href;else{try{i=new dt(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 Bt(e,t)}const l=o?443:80,h=ft(16).toString("base64"),f=o?at.request:ct.request,u=new Set;let d,p;if(s.createConnection=o?Wt:jt,s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(d=new pt(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Ct({[pt.extensionName]:d.offer()})),r.length){for(const e of r){if("string"!=typeof e||!Rt.test(e)||u.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(e)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?s.socketPath:i.host;const t=n&&n.headers;if(n={...n,headers:{}},t)for(const[e,r]of Object.entries(t))n.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=e._req=f(s),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(s);s.timeout&&p.on("timeout",(()=>{Ft(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Nt]||(p=e._req=null,Bt(e,t))})),p.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void Ft(e,p,"Maximum redirects exceeded");let i;p.abort();try{i=new dt(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void Bt(e,r)}At(e,i,r,n)}else e.emit("unexpected-response",p,i)||Ft(e,p,`Unexpected server response: ${i.statusCode}`)})),p.on("upgrade",((t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==It.CONNECTING)return;if(p=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void Ft(e,r,"Invalid Upgrade header");const i=ut("sha1").update(h+gt).digest("base64");if(t.headers["sec-websocket-accept"]!==i)return void Ft(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?u.size?u.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":u.size&&(a="Server sent no subprotocol"),a)return void Ft(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!d){return void Ft(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Tt(c)}catch(t){return void Ft(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==pt.extensionName){return void Ft(e,r,"Server indicated an extension that was not requested")}try{d.accept(t[pt.extensionName])}catch(t){return void Ft(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[pt.extensionName]=d}e.setSocket(r,n,{generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),p.end()}function Bt(e,t){e._readyState=It.CLOSING,e.emit("error",t),e.emitClose()}function jt(e){return e.path=e.socketPath,lt.connect(e)}function Wt(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=lt.isIP(e.host)?"":e.host),ht.connect(e)}function Ft(e,t,r){e._readyState=It.CLOSING;const n=new Error(r);Error.captureStackTrace(n,Ft),t.setHeader?(t[Nt]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Bt,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Dt(e,t,r){if(t){const r=Lt(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Mt[e.readyState]})`);process.nextTick(r,t)}}function Gt(e,t){const r=this[xt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[xt]&&(r._socket.removeListener("data",Zt),process.nextTick(Xt,r._socket),1005===e?r.close():r.close(e,t))}function qt(){const e=this[xt];e.isPaused||e._socket.resume()}function $t(e){const t=this[xt];void 0!==t._socket[xt]&&(t._socket.removeListener("data",Zt),process.nextTick(Xt,t._socket),t.close(e[St])),t.emit("error",e)}function Vt(){this[xt].emitClose()}function zt(e,t){this[xt].emit("message",e,t)}function Ht(e){const t=this[xt];t.pong(e,!t._isServer,kt),t.emit("ping",e)}function Yt(e){this[xt].emit("pong",e)}function Xt(e){e.resume()}function Qt(){const e=this[xt];let t;this.removeListener("close",Qt),this.removeListener("data",Zt),this.removeListener("end",Kt),e._readyState=It.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[xt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Vt),e._receiver.on("finish",Vt))}function Zt(e){this[xt]._receiver.write(e)||this.pause()}function Kt(){const e=this[xt];e._readyState=It.CLOSING,e._receiver.end(),this.end()}function Jt(){const e=this[xt];this.removeListener("error",Jt),this.on("error",kt),e&&(e._readyState=It.CLOSING,this.destroy())}const{Duplex:er}=g.default;function tr(e){e.emit("close")}function rr(){!this.destroyed&&this._writableState.finished&&this.destroy()}function nr(e){this.removeListener("error",nr),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var sr=function(e,t){let r=!0;const n=new er({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const s=!r&&n._readableState.objectMode?t.toString():t;n.push(s)||e.pause()})),e.once("error",(function(e){n.destroyed||(r=!1,n.destroy(e))})),e.once("close",(function(){n.destroyed||n.push(null)})),n._destroy=function(t,s){if(e.readyState===e.CLOSED)return s(t),void process.nextTick(tr,n);let i=!1;e.once("error",(function(e){i=!0,s(e)})),e.once("close",(function(){i||s(t),process.nextTick(tr,n)})),r&&e.terminate()},n._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){n._final(t)}))},n._read=function(){e.isPaused&&e.resume()},n._write=function(t,r,s){e.readyState!==e.CONNECTING?e.send(t,s):e.once("open",(function(){n._write(t,r,s)}))},n.on("end",rr),n.on("error",nr),n};const{tokenChars:ir}=de.exports;var or={parse:function(e){const t=new Set;let r=-1,n=-1,s=0;for(;s<e.length;s++){const i=e.charCodeAt(s);if(-1===n&&1===ir[i])-1===r&&(r=s);else if(0===s||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${s}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${s}`);-1===n&&(n=s);const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=n=-1}}else-1===n&&-1!==r&&(n=s)}if(-1===r||-1!==n)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const ar=m.default,cr=u.default,{createHash:lr}=v.default,hr=it,fr=le,ur=or,dr=Ut,{GUID:pr,kWebSocket:_r}=q,mr=/^[+/0-9A-Za-z]{22}==$/,yr=2;var vr=class extends ar{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:dr,...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=cr.createServer(((e,t)=>{const r=cr.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===yr)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(gr,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(gr,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{gr(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",br);const s=e.headers["sec-websocket-key"],i=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Sr(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void Sr(this,e,t,400,"Invalid Upgrade header")}if(!s||!mr.test(s)){return void Sr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==i&&13!==i){return void Sr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void wr(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=ur.parse(o)}catch(r){return void Sr(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 fr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=hr.parse(c);e[fr.extensionName]&&(r.accept(e[fr.extensionName]),l[fr.extensionName]=r)}catch(r){return void Sr(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 wr(t,o||401,c,h);this.completeUpgrade(l,s,a,e,t,r,n)}));if(!this.options.verifyClient(o))return wr(t,401)}this.completeUpgrade(l,s,a,e,t,r,n)}completeUpgrade(e,t,r,n,s,i,o){if(!s.readable||!s.writable)return s.destroy();if(s[_r])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return wr(s,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${lr("sha1").update(t+pr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[fr.extensionName]){const t=e[fr.extensionName].params,r=hr.format({[fr.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,n),s.write(a.concat("\r\n").join("\r\n")),s.removeListener("error",br),c.setSocket(s,i,{maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(gr,this)}))),o(c,n)}};function gr(e){e._state=yr,e.emit("close")}function br(){this.destroy()}function wr(e,t,r,n){r=r||cr.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${cr.STATUS_CODES[t]}\r\n`+Object.keys(n).map((e=>`${e}: ${n[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function Sr(e,t,r,n,s){if(e.listenerCount("wsClientError")){const n=new Error(s);Error.captureStackTrace(n,Sr),e.emit("wsClientError",n,r,t)}else wr(r,n,s)}const xr=Ut;xr.createWebSocketStream=sr,xr.Server=vr,xr.Receiver=Te,xr.Sender=We,xr.WebSocket=xr,xr.WebSocketServer=xr.Server;var kr=xr,Er="3.1.6",Or=require("child_process"),Cr=require("events"),Tr=require("url"),Lr=kr.Server,Nr="ffmpeg",Pr=["jsmpeg","flv"],Mr="jsmpeg",Rr={jsmpeg:"mpegts",flv:"flv"},Ir={jsmpeg:"mpeg1video",flv:"libx264"},Ur={jsmpeg:"mp2",flv:"aac"},Ar=!1,Br=8,jr=["tcp","udp","udp_multicast","http","https"],Wr="",Fr=!0,Dr=!0,Gr="drawtext=x=w-tw-5:y=80:fontcolor=white:fontsize=32:text="+decodeURIComponent(D.exports.decode("Y2xlYXIlMjB3aXRoJTIwcXElMjA0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",qr=20,$r=10,Vr=["-s","-b:v","webplayer","scale","contrast","brightness","saturation","gamma"].concat(["vcodec"]),zr=["scale","contrast","brightness","saturation","gamma"],Hr=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}},Yr=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&&P(e,t)}(r,Cr.EventEmitter);var t=R(r);function r(e){var n;return O(this,r),L(M(n=t.call(this)),"exitCode",void 0),L(M(n),"additionalFlags",[]),L(M(n),"stream",null),L(M(n),"inputStreamStarted",!1),n.ffmpegPath=Nr,n.url=e.url,n.ffmpegOptions=e.ffmpegOptions,n.modifyOptions=e.modifyOptions||{},n.options=e,n.initMpeg2Muxer(),n}return T(r,[{key:"initMpeg2Muxer",value:function(){var e,t=this;if(Fr||delete this.ffmpegOptions["-vf"],this.ffmpegOptions.webplayer&&(Mr=this.ffmpegOptions.webplayer,delete this.ffmpegOptions.webplayer),this.ffmpegOptions)for(var r in this.ffmpegOptions)this.additionalFlags.push(r),""!==String(this.ffmpegOptions[r])&&this.additionalFlags.push(String(this.ffmpegOptions[r]));(this.spawnOptions=["-re","-thread_queue_size","1024","-threads","8","-max_interleave_delta","0","-i",this.url,"-q",Br,"-f",Rr[Mr],"-c:v",Ir[Mr],"-r","30","-c:a",Ur[Mr],Ar?"-an":null,"-ar","48000","-ac","1"].concat(U(this.additionalFlags),["-nostats","-"]),this.modifyOptions)&&(this.modifyOptions.del&&(null===(e=this.modifyOptions.del)||void 0===e||e.forEach((function(e){"buffer_size"==e&&(t.spawnOptions[1]=null,t.spawnOptions[2]=null)}))));String(Wr).length>0&&this.spawnOptions.splice(1,0,"-rtsp_transport",String(Wr)),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=Or.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(e,r){return console.error("[ffmpeg]某个视频流转码进程退出了: **如果非正常关闭视频导致的退出,请检查ffmpeg参数或检查代码或联系作者解决**,code:",e,"signal:",r),t.emit("exitWithError")})),this.stream.on("close",(function(e,r){return console.log("[ffmpeg]某个视频流转码进程关闭了: code: ",e),t.emit("ffmpegClosed")})),this.inputStreamStarted=!0,this.stream.stdout.on("data",(function(e){return t.emit("mpeg2data",e)})),this.stream.stderr.on("data",(function(e){return t.emit("ffmpegStderr",e)}))}}]),r}(),Xr=function(){function e(t){O(this,e),L(this,"freeTime",0),L(this,"width",null),L(this,"height",null),L(this,"isStreamWrap",!1),L(this,"clients",[]),L(this,"mpeg2Muxer",{instance:null,stream:null,data:null}),L(this,"modifyOptions",{}),this.config=t,this.url=t.url}var t,r;return T(e,[{key:"createStream",value:function(){this.isStreamWrap||(console.log("[ffmpeg]创建一个新的视频流转码进程~"),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Yr({url:this.url,ffmpegOptions:this.formatParams(this.config)}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.eventHandler())}},{key:"eventHandler",value:function(){var e=this;this.mpeg2Muxer.instance.on("mpeg2data",(function(t){e.broadcast(t)})),this.mpeg2Muxer.instance.on("ffmpegStderr",(function(t){if(-1!==(t=t.toString()).indexOf("failed")&&(global.process.stdout.write(t+"=== L518 \n"),-1!==t.indexOf("Operation timed out")&&global.process.stdout.write(t+"哎呀~你的链接有问题,超时了!=== L519 \n"),-1!==t.indexOf("Conversion")&&console.log("*".concat(Wr,"*模式转换失败,请尝试改变transportType的值,然后重试。***")),-1!==t.indexOf("transport")&&global.process.stdout.write(t+"=== L520 \n")),-1!==t.indexOf("404 Not Found")&&global.process.stdout.write(t+"=== L521 \n"),-1!==t.indexOf("Invalid data found")&&global.process.stdout.write(t+"=== L522 \n"),-1!==t.indexOf("Unrecognized option")&&global.process.stdout.write(t+"=== L523 \n"),-1!==t.indexOf("pipe")&&global.process.stdout.write(t+"=== L524 \n"),-1!==t.indexOf("not found")){global.process.stdout.write(t+"=== L525 \n");var r=t.match(/Option (\w+) not found/)[1];if("rtsp_transport"==r)return void console.log("--[rtsp2web]请尝试修改 transportType 的值再重试,或者尝试去掉 transportType 再重试--");e.modifyOptions.del?e.modifyOptions.del.push(r):e.modifyOptions.del=[r],e.resetStream()}})),this.mpeg2Muxer.instance.on("ffmpegClosed",(function(){e.destroy()}))}},{key:"resetStream",value:(t=x().mark((function e(){var t,r;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,null===(t=this.mpeg2Muxer.stream)||void 0===t?void 0:t.kill();case 2:this.mpeg2Muxer.stream=null,null===(r=this.mpeg2Muxer.instance)||void 0===r||r.removeAllListeners(),this.mpeg2Muxer.instance=null,console.log("[rtsp2web][自动修复]一个视频流转码被自动修复并重启中..."),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Yr({url:this.url,ffmpegOptions:this.formatParams(this.config),modifyOptions:this.modifyOptions}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.eventHandler();case 10:case"end":return e.stop()}}),e,this)})),r=function(){var e=this,r=arguments;return new Promise((function(n,s){var i=t.apply(e,r);function o(e){E(i,n,s,o,a,"next",e)}function a(e){E(i,n,s,o,a,"throw",e)}o(void 0)}))},function(){return r.apply(this,arguments)})},{key:"formatParams",value:function(e){for(var t={"-vf":Gr},r=0,n=Object.entries(e);r<n.length;r++){var s=I(n[r],2),i=s[0],o=s[1];Vr.includes(i)&&(zr.includes(i)?"scale"===i?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(o)):t["-vf"]+="".concat(i,"=").concat(o,":"):Hr(i,o)&&(t[i]=o))}return t}},{key:"destroy",value:function(){var e,t;null===(e=this.mpeg2Muxer.stream)||void 0===e||e.kill(),this.mpeg2Muxer.stream=null,null===(t=this.mpeg2Muxer.instance)||void 0===t||t.removeAllListeners(),this.mpeg2Muxer.instance=null,this.isStreamWrap=!1,this.dropAllClient()}},{key:"broadcast",value:function(e){var t,r=j(this.clients);try{for(r.s();!(t=r.n()).done;){var n=t.value;n.isSegment&&n.send(e)}}catch(e){r.e(e)}finally{r.f()}}},{key:"addClient",value:function(e){var t=this;e.once("close",(function(){t.dropClient(e)})),this.clients.push(e),this.isStreamWrap||this.createStream(),e.isSegment=!0}},{key:"dropClient",value:function(e){var t=this.clients.indexOf(e);e.isSegment=!1,e.terminate(),e=null,console.log("视频播放窗口关闭1个,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=j(this.clients);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.isSegment=!1,r.terminate()}}catch(e){t.e(e)}finally{t.f()}this.clients=[]}}]),e}(),Qr=function(){function e(t){var r=this;O(this,e),L(this,"channels",[]),console.log("--[info]: current rtsp2web version: ".concat(Er,"; current platform is ").concat(global.process.platform,"--")),Or.exec("ffmpeg -version",(function(e,t,r){e&&console.log("请检查你的ffmpeg是否正确存在,错误信息:",e.stack)})),t&&"boolean"==typeof t.wm&&!t.wm&&(Gr="scale=-1:-1,eq=",Dr=!1),t&&"boolean"==typeof t.vf&&!t.vf&&(Fr=!1),t&&"string"==typeof t.path&&t.path.length>0&&(Nr=t.path),t&&"string"==typeof t.webplayer&&Pr.includes(t.webplayer)&&(Mr=t.webplayer),t&&"number"==typeof t.q&&t.q>=0&&(Br=t.q),t&&"string"==typeof t.transportType&&jr.includes(t.transportType)&&(Wr=t.transportType),t&&"boolean"==typeof t.audio&&!t.audio&&(Ar=!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(),Dr&&(Gr.includes(decodeURIComponent(D.exports.decode("eCUzRHctdHctNSUzQXklM0Q4MCUzQWZvbnRjb2xvciUzRHdoaXRlJTNBZm9udHNpemUlM0QzMiUzQXRleHQlM0RjbGVhciUyMHdpdGglMjBxcSUyMDQyMTM1NDUzMiUzQWJveCUzRDElM0Fib3hjb2xvciUzRGJsYWNr")))||(r.destroyAllChannel(),global.process.stderr.write("----wm代码异常、视频闪屏的问题----,请联系作者帮你解决!!")))}),1e3*$r);var n=u.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{n=d.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{n=d.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");n.listen(t&&t.port||9999),Object.getPrototypeOf(n)instanceof p.default.Server&&console.log("wss model success!!!"),this.wss=new Lr({server:n}),this.wss.on("connection",(function(e,t){var n=Tr.parse(t.url,!0);if(n.query.url){var s=D.exports.decode(n.query.url.toString());n.query.url=s,r.registeClient(e,{url:s,options:n.query})}console.log("一个新的视频播放窗口(client,ws句柄)连接成功,请等待画面...")}))}return T(e,[{key:"registeClient",value:function(e,t){var r=this.getChannel(t.url);r||(r=this.createChannel(t.options,e)),r.addClient(e)}},{key:"getChannel",value:function(e){var t,r=j(this.channels);try{for(r.s();!(t=r.n()).done;){var n=t.value;if(n.url===e)return n}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new Xr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=j(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=$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=j(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}();L(Qr,"version",Er),module.exports=Qr;
|
package/dist/rtsp2web.min.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* rtsp2web v3.1.
|
|
2
|
+
* rtsp2web v3.1.6
|
|
3
3
|
* (c) 2020-2023 NeverYu
|
|
4
4
|
* My home page:https://neveryu.github.io/neveryu/
|
|
5
5
|
* 微信(wechat):miracle421354532
|
|
6
6
|
* Released under the ISC License.
|
|
7
7
|
*/
|
|
8
|
-
"use strict";var e=require("http"),t=require("https"),r=require("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:{}};
|
|
8
|
+
"use strict";var e=require("http"),t=require("https"),r=require("tls"),n=require("fs"),s=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 u=f(e),d=f(t),p=f(r),_=f(n),m=f(s),y=f(i),v=f(o),g=f(a),b=f(c),w=f(l),S=f(h);function x(){x=function(){return e};var e={},t=Object.prototype,r=t.hasOwnProperty,n=Object.defineProperty||function(e,t,r){e[t]=r.value},s="function"==typeof Symbol?Symbol:{},i=s.iterator||"@@iterator",o=s.asyncIterator||"@@asyncIterator",a=s.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,s){var i=t&&t.prototype instanceof u?t:u,o=Object.create(i.prototype),a=new O(s||[]);return n(o,"_invoke",{value:w(e,r,a)}),o}function h(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var f={};function u(){}function d(){}function p(){}var _={};c(_,i,(function(){return this}));var m=Object.getPrototypeOf,y=m&&m(m(C([])));y&&y!==t&&r.call(y,i)&&(_=y);var v=p.prototype=u.prototype=Object.create(_);function g(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function b(e,t){function s(n,i,o,a){var c=h(e[n],e,i);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==typeof f&&r.call(f,"__await")?t.resolve(f.__await).then((function(e){s("next",e,o,a)}),(function(e){s("throw",e,o,a)})):t.resolve(f).then((function(e){l.value=e,o(l)}),(function(e){return s("throw",e,o,a)}))}a(c.arg)}var i;n(this,"_invoke",{value:function(e,r){function n(){return new t((function(t,n){s(e,r,t,n)}))}return i=i?i.then(n,n):n()}})}function w(e,t,r){var n="suspendedStart";return function(s,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===s)throw i;return T()}for(r.method=s,r.arg=i;;){var o=r.delegate;if(o){var a=S(o,r);if(a){if(a===f)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=h(e,t,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===f)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}function S(e,t){var r=t.method,n=e.iterator[r];if(void 0===n)return t.delegate=null,"throw"===r&&e.iterator.return&&(t.method="return",t.arg=void 0,S(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),f;var s=h(n,e.iterator,t.arg);if("throw"===s.type)return t.method="throw",t.arg=s.arg,t.delegate=null,f;var i=s.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,f):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,f)}function k(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function E(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(k,this),this.reset(!0)}function C(e){if(e){var t=e[i];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,s=function t(){for(;++n<e.length;)if(r.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=void 0,t.done=!0,t};return s.next=s}}return{next:T}}function T(){return{value:void 0,done:!0}}return d.prototype=p,n(v,"constructor",{value:p,configurable:!0}),n(p,"constructor",{value:d,configurable:!0}),d.displayName=c(p,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,c(e,a,"GeneratorFunction")),e.prototype=Object.create(v),e},e.awrap=function(e){return{__await:e}},g(b.prototype),c(b.prototype,o,(function(){return this})),e.AsyncIterator=b,e.async=function(t,r,n,s,i){void 0===i&&(i=Promise);var o=new b(l(t,r,n,s),i);return e.isGeneratorFunction(r)?o:o.next().then((function(e){return e.done?e.value:o.next()}))},g(v),c(v,a,"Generator"),c(v,i,(function(){return this})),c(v,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=Object(e),r=[];for(var n in t)r.push(n);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},e.values=C,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!e)for(var t in this)"t"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(r,n){return o.type="throw",o.arg=e,t.next=r,n&&(t.method="next",t.arg=void 0),!!n}for(var s=this.tryEntries.length-1;s>=0;--s){var i=this.tryEntries[s],o=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var a=r.call(i,"catchLoc"),c=r.call(i,"finallyLoc");if(a&&c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(a){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var s=this.tryEntries[n];if(s.tryLoc<=this.prev&&r.call(s,"finallyLoc")&&this.prev<s.finallyLoc){var i=s;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=e,o.arg=t,i?(this.method="next",this.next=i.finallyLoc,f):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),f},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),E(r),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var s=n.arg;E(r)}return s}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:C(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},e}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 E(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function O(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function C(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,W(n.key),n)}}function T(e,t,r){return t&&C(e.prototype,t),r&&C(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function L(e,t,r){return(t=W(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function N(e){return N=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},N(e)}function P(e,t){return P=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},P(e,t)}function M(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function R(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,n=N(e);if(t){var s=N(this).constructor;r=Reflect.construct(n,arguments,s)}else r=n.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return M(e)}(this,r)}}function I(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,s,i,o,a=[],c=!0,l=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(e){l=!0,s=e}finally{try{if(!c&&null!=r.return&&(o=r.return(),Object(o)!==o))return}finally{if(l)throw s}}return a}}(e,t)||A(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 B(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||A(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 A(e,t){if(e){if("string"==typeof e)return B(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)?B(e,t):void 0}}function B(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function j(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=A(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,s=function(){};return{s:s,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return o=e.done,e},e:function(e){a=!0,i=e},f:function(){try{o||null==r.return||r.return()}finally{if(a)throw i}}}}function W(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}var F="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},D={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.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;
|
|
10
|
+
!function(e,t){!function(r){var n=t,s=e&&e.exports==n&&e,i="object"==typeof F&&F;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,n,s,i=e.length%3,o="",l=-1,h=e.length-i;++l<h;)t=e.charCodeAt(l)<<16,r=e.charCodeAt(++l)<<8,n=e.charCodeAt(++l),o+=c.charAt((s=t+r+n)>>18&63)+c.charAt(s>>12&63)+c.charAt(s>>6&63)+c.charAt(63&s);return 2==i?(t=e.charCodeAt(l)<<8,r=e.charCodeAt(++l),o+=c.charAt((s=t+r)>>10)+c.charAt(s>>4&63)+c.charAt(s<<2&63)+"="):1==i&&(s=e.charCodeAt(l),o+=c.charAt(s>>2)+c.charAt(s<<4&63)+"=="),o},decode:function(e){var t=(e=String(e).replace(l,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&a("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,s=0,i="",o=-1;++o<t;)n=c.indexOf(e.charAt(o)),r=s%4?64*r+n:n,s++%4&&(i+=String.fromCharCode(255&r>>(-2*s&6)));return i},version:"1.0.0"};if(n&&!n.nodeType)if(s)s.exports=h;else for(var f in h)h.hasOwnProperty(f)&&(n[f]=h[f]);else r.base64=h}(F)}(D,D.exports);var G={exports:{}},q={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,V=Buffer[Symbol.species];function z(e,t,r,n,s){for(let i=0;i<s;i++)r[n+i]=e[i]^t[3&i]}function H(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(G.exports={concat:function(e,t){if(0===e.length)return $;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let n=0;for(let t=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return n<t?new V(r.buffer,r.byteOffset,n):r},mask:z,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 V(t):ArrayBuffer.isView(t)?r=new V(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:H},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");G.exports.mask=function(t,r,n,s,i){i<48?z(t,r,n,s,i):e.mask(t,r,n,s,i)},G.exports.unmask=function(t,r){t.length<32?H(t,r):e.unmask(t,r)}}catch(e){}const Y=Symbol("kDone"),X=Symbol("kRun");var Q=class{constructor(e){this[Y]=()=>{this.pending--,this[X]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[X]()}[X](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Y])}}};const Z=w.default,K=G.exports,J=Q,{kStatusCode:ee}=q,te=Buffer[Symbol.species],re=Buffer.from([0,0,255,255]),ne=Symbol("permessage-deflate"),se=Symbol("total-length"),ie=Symbol("callback"),oe=Symbol("buffers"),ae=Symbol("error");let ce;var le=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,!ce){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;ce=new J(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[ie];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){ce.add((n=>{this._decompress(e,t,((e,t)=>{n(),r(e,t)}))}))}compress(e,t,r){ce.add((n=>{this._compress(e,t,((e,t)=>{n(),r(e,t)}))}))}_decompress(e,t,r){const n=this._isServer?"client":"server";if(!this._inflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Z.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Z.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[ne]=this,this._inflate[se]=0,this._inflate[oe]=[],this._inflate.on("error",ue),this._inflate.on("data",fe)}this._inflate[ie]=r,this._inflate.write(e),t&&this._inflate.write(re),this._inflate.flush((()=>{const e=this._inflate[ae];if(e)return this._inflate.close(),this._inflate=null,void r(e);const s=K.concat(this._inflate[oe],this._inflate[se]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[se]=0,this._inflate[oe]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),r(null,s)}))}_compress(e,t,r){const n=this._isServer?"server":"client";if(!this._deflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Z.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Z.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[se]=0,this._deflate[oe]=[],this._deflate.on("data",he)}this._deflate[ie]=r,this._deflate.write(e),this._deflate.flush(Z.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=K.concat(this._deflate[oe],this._deflate[se]);t&&(e=new te(e.buffer,e.byteOffset,e.length-4)),this._deflate[ie]=null,this._deflate[se]=0,this._deflate[oe]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}};function he(e){this[oe].push(e),this[se]+=e.length}function fe(e){this[se]+=e.length,this[ne]._maxPayload<1||this[se]<=this[ne]._maxPayload?this[oe].push(e):(this[ae]=new RangeError("Max payload size exceeded"),this[ae].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ae][ee]=1009,this.removeListener("data",fe),this.reset())}function ue(e){this[ne]._inflate=null,e[ee]=1007,this[ie](e)}var de={exports:{}};const{isUtf8:pe}=S.default;function _e(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(de.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:_e,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]},pe)de.exports.isValidUTF8=function(e){return e.length<24?_e(e):pe(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");de.exports.isValidUTF8=function(t){return t.length<32?_e(t):e(t)}}catch(e){}const{Writable:me}=g.default,ye=le,{BINARY_TYPES:ve,EMPTY_BUFFER:ge,kStatusCode:be,kWebSocket:we}=q,{concat:Se,toArrayBuffer:xe,unmask:ke}=G.exports,{isValidStatusCode:Ee,isValidUTF8:Oe}=de.exports,Ce=Buffer[Symbol.species];var Te=class extends me{constructor(e={}){super(),this._binaryType=e.binaryType||ve[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[we]=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 Ce(t.buffer,t.byteOffset+e,t.length-e),new Ce(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new Ce(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,Le(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[ye.extensionName])return this._loop=!1,Le(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,Le(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,Le(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,Le(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,Le(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,Le(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,Le(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,Le(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,Le(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,Le(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,Le(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,Le(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=ge;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])&&ke(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[ye.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(Le(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(r)}const n=this.dataMessage();if(n)return t(n);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?Se(t,e):"arraybuffer"===this._binaryType?xe(Se(t,e)):t,this.emit("message",r,!0)}else{const r=Se(t,e);if(!this._skipUTF8Validation&&!Oe(r))return this._loop=!1,Le(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,ge),this.end();else{const t=e.readUInt16BE(0);if(!Ee(t))return Le(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const r=new Ce(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Oe(r))return Le(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 Le(e,t,r,n,s){const i=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,Le),i.code=s,i[be]=n,i}const{randomFillSync:Ne}=v.default,Pe=le,{EMPTY_BUFFER:Me}=q,{isValidStatusCode:Re}=de.exports,{mask:Ie,toBuffer:Ue}=G.exports,Ae=Symbol("kByteLength"),Be=Buffer.alloc(4);class je{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let r,n,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Be,t.generateMask?t.generateMask(r):Ne(r,0,4),o=0==(r[0]|r[1]|r[2]|r[3]),i=6),"string"==typeof e?n=t.mask&&!o||void 0===t[Ae]?(e=Buffer.from(e)).length:t[Ae]:(n=e.length,s=t.mask&&t.readOnly&&!o);let a=n;n>=65536?(i+=8,a=127):n>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(s?n+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(n,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(n,4,6)),t.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(Ie(e,r,c,i,n),[c]):(Ie(e,r,e,0,n),[c,e])):[c,e]}close(e,t,r,n){let s;if(void 0===e)s=Me;else{if("number"!=typeof e||!Re(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+r),s.writeUInt16BE(e,0),"string"==typeof t?s.write(t,2):s.set(t,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0)}const i={[Ae]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,s,!1,i,n]):this.sendFrame(je.frame(s,i),n)}ping(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Ue(e)).length,s=Ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ae]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(je.frame(e,i),r)}pong(e,t,r){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=Ue(e)).length,s=Ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const i={[Ae]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,i,r]):this.sendFrame(je.frame(e,i),r)}send(e,t,r){const n=this._extensions[Pe.extensionName];let s,i,o=t.binary?2:1,a=t.compress;if("string"==typeof e?(s=Buffer.byteLength(e),i=!1):(s=(e=Ue(e)).length,i=Ue.readOnly),this._firstFragment?(this._firstFragment=!1,a&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=n._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0),n){const n={[Ae]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:a};this._deflating?this.enqueue([this.dispatch,e,this._compress,n,r]):this.dispatch(e,this._compress,n,r)}else this.sendFrame(je.frame(e,{[Ae]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:!1}),r)}dispatch(e,t,r,n){if(!t)return void this.sendFrame(je.frame(e,r),n);const s=this._extensions[Pe.extensionName];this._bufferedBytes+=r[Ae],this._deflating=!0,s.compress(e,r.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof n&&n(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t],n=r[r.length-1];"function"==typeof n&&n(e)}}else this._bufferedBytes-=r[Ae],this._deflating=!1,r.readOnly=!1,this.sendFrame(je.frame(t,r),n),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ae],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ae],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 We=je;const{kForOnEventAttribute:Fe,kListener:De}=q,Ge=Symbol("kCode"),qe=Symbol("kData"),$e=Symbol("kError"),Ve=Symbol("kMessage"),ze=Symbol("kReason"),He=Symbol("kTarget"),Ye=Symbol("kType"),Xe=Symbol("kWasClean");class Qe{constructor(e){this[He]=null,this[Ye]=e}get target(){return this[He]}get type(){return this[Ye]}}Object.defineProperty(Qe.prototype,"target",{enumerable:!0}),Object.defineProperty(Qe.prototype,"type",{enumerable:!0});class Ze extends Qe{constructor(e,t={}){super(e),this[Ge]=void 0===t.code?0:t.code,this[ze]=void 0===t.reason?"":t.reason,this[Xe]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Ge]}get reason(){return this[ze]}get wasClean(){return this[Xe]}}Object.defineProperty(Ze.prototype,"code",{enumerable:!0}),Object.defineProperty(Ze.prototype,"reason",{enumerable:!0}),Object.defineProperty(Ze.prototype,"wasClean",{enumerable:!0});class Ke extends Qe{constructor(e,t={}){super(e),this[$e]=void 0===t.error?null:t.error,this[Ve]=void 0===t.message?"":t.message}get error(){return this[$e]}get message(){return this[Ve]}}Object.defineProperty(Ke.prototype,"error",{enumerable:!0}),Object.defineProperty(Ke.prototype,"message",{enumerable:!0});class Je extends Qe{constructor(e,t={}){super(e),this[qe]=void 0===t.data?null:t.data}get data(){return this[qe]}}Object.defineProperty(Je.prototype,"data",{enumerable:!0});const et={addEventListener(e,t,r={}){for(const n of this.listeners(e))if(!r[Fe]&&n[De]===t&&!n[Fe])return;let n;if("message"===e)n=function(e,r){const n=new Je("message",{data:r?e:e.toString()});n[He]=this,rt(t,this,n)};else if("close"===e)n=function(e,r){const n=new Ze("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[He]=this,rt(t,this,n)};else if("error"===e)n=function(e){const r=new Ke("error",{error:e,message:e.message});r[He]=this,rt(t,this,r)};else{if("open"!==e)return;n=function(){const e=new Qe("open");e[He]=this,rt(t,this,e)}}n[Fe]=!!r[Fe],n[De]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[De]===t&&!r[Fe]){this.removeListener(e,r);break}}};var tt={CloseEvent:Ze,ErrorEvent:Ke,Event:Qe,EventTarget:et,MessageEvent:Je};function rt(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}const{tokenChars:nt}=de.exports;function st(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}var it={format:function(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let r,n,s=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,h=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===r)if(-1===h&&1===nt[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 n=e.slice(c,h);44===l?(st(t,n,s),s=Object.create(null)):r=n,c=h=-1}}else-1===h&&-1!==c&&(h=f);else if(void 0===n)if(-1===h&&1===nt[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),st(s,e.slice(c,h),!0),44===l&&(st(t,r,s),s=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}`);n=e.slice(c,f),c=h=-1}else if(o){if(1!==nt[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===c?c=f:i||(i=!0),o=!1}else if(a)if(1===nt[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===nt[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),st(s,n,o),44===l&&(st(t,r,s),s=Object.create(null),r=void 0),n=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 u=e.slice(c,h);return void 0===r?st(t,u,s):(void 0===n?st(s,u,!0):st(s,n,i?u.replace(/\\/g,""):u),st(t,r,s)),t}};const ot=m.default,at=d.default,ct=u.default,lt=y.default,ht=p.default,{randomBytes:ft,createHash:ut}=v.default,{URL:dt}=b.default,pt=le,_t=Te,mt=We,{BINARY_TYPES:yt,EMPTY_BUFFER:vt,GUID:gt,kForOnEventAttribute:bt,kListener:wt,kStatusCode:St,kWebSocket:xt,NOOP:kt}=q,{EventTarget:{addEventListener:Et,removeEventListener:Ot}}=tt,{format:Ct,parse:Tt}=it,{toBuffer:Lt}=G.exports,Nt=Symbol("kAborted"),Pt=[8,13],Mt=["CONNECTING","OPEN","CLOSING","CLOSED"],Rt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class It extends ot{constructor(e,t,r){super(),this._binaryType=yt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=vt,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=It.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]),At(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){yt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const n=new _t({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation});this._sender=new mt(e,this._extensions,r.generateMask),this._receiver=n,this._socket=e,n[xt]=this,e[xt]=this,n.on("conclude",Gt),n.on("drain",qt),n.on("error",$t),n.on("message",zt),n.on("ping",Ht),n.on("pong",Yt),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Qt),e.on("data",Zt),e.on("end",Kt),e.on("error",Jt),this._readyState=It.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=It.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[pt.extensionName]&&this._extensions[pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=It.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==It.CLOSED)if(this.readyState!==It.CONNECTING)this.readyState!==It.CLOSING?(this._readyState=It.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";Ft(this,this._req,e)}}pause(){this.readyState!==It.CONNECTING&&this.readyState!==It.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===It.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===It.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||vt,t,r)):Dt(this,e,r)}pong(e,t,r){if(this.readyState===It.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===It.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||vt,t,r)):Dt(this,e,r)}resume(){this.readyState!==It.CONNECTING&&this.readyState!==It.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===It.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!==It.OPEN)return void Dt(this,e,r);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[pt.extensionName]||(n.compress=!1),this._sender.send(e||vt,n,r)}terminate(){if(this.readyState!==It.CLOSED)if(this.readyState!==It.CONNECTING)this._socket&&(this._readyState=It.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";Ft(this,this._req,e)}}}Object.defineProperty(It,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")}),Object.defineProperty(It.prototype,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")}),Object.defineProperty(It,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")}),Object.defineProperty(It.prototype,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")}),Object.defineProperty(It,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")}),Object.defineProperty(It.prototype,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")}),Object.defineProperty(It,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")}),Object.defineProperty(It.prototype,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(It.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(It.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[bt])return t[wt];return null},set(t){for(const t of this.listeners(e))if(t[bt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[bt]:!0})}})})),It.prototype.addEventListener=Et,It.prototype.removeEventListener=Ot;var Ut=It;function At(e,t,r,n){const s={protocolVersion:Pt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!Pt.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Pt.join(", ")})`);let i;if(t instanceof dt)i=t,e._url=t.href;else{try{i=new dt(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 Bt(e,t)}const l=o?443:80,h=ft(16).toString("base64"),f=o?at.request:ct.request,u=new Set;let d,p;if(s.createConnection=o?Wt:jt,s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(d=new pt(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Ct({[pt.extensionName]:d.offer()})),r.length){for(const e of r){if("string"!=typeof e||!Rt.test(e)||u.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(e)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?s.socketPath:i.host;const t=n&&n.headers;if(n={...n,headers:{}},t)for(const[e,r]of Object.entries(t))n.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=e._req=f(s),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(s);s.timeout&&p.on("timeout",(()=>{Ft(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Nt]||(p=e._req=null,Bt(e,t))})),p.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void Ft(e,p,"Maximum redirects exceeded");let i;p.abort();try{i=new dt(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void Bt(e,r)}At(e,i,r,n)}else e.emit("unexpected-response",p,i)||Ft(e,p,`Unexpected server response: ${i.statusCode}`)})),p.on("upgrade",((t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==It.CONNECTING)return;if(p=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void Ft(e,r,"Invalid Upgrade header");const i=ut("sha1").update(h+gt).digest("base64");if(t.headers["sec-websocket-accept"]!==i)return void Ft(e,r,"Invalid Sec-WebSocket-Accept header");const o=t.headers["sec-websocket-protocol"];let a;if(void 0!==o?u.size?u.has(o)||(a="Server sent an invalid subprotocol"):a="Server sent a subprotocol but none was requested":u.size&&(a="Server sent no subprotocol"),a)return void Ft(e,r,a);o&&(e._protocol=o);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!d){return void Ft(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Tt(c)}catch(t){return void Ft(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==pt.extensionName){return void Ft(e,r,"Server indicated an extension that was not requested")}try{d.accept(t[pt.extensionName])}catch(t){return void Ft(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[pt.extensionName]=d}e.setSocket(r,n,{generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),p.end()}function Bt(e,t){e._readyState=It.CLOSING,e.emit("error",t),e.emitClose()}function jt(e){return e.path=e.socketPath,lt.connect(e)}function Wt(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=lt.isIP(e.host)?"":e.host),ht.connect(e)}function Ft(e,t,r){e._readyState=It.CLOSING;const n=new Error(r);Error.captureStackTrace(n,Ft),t.setHeader?(t[Nt]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Bt,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Dt(e,t,r){if(t){const r=Lt(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Mt[e.readyState]})`);process.nextTick(r,t)}}function Gt(e,t){const r=this[xt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[xt]&&(r._socket.removeListener("data",Zt),process.nextTick(Xt,r._socket),1005===e?r.close():r.close(e,t))}function qt(){const e=this[xt];e.isPaused||e._socket.resume()}function $t(e){const t=this[xt];void 0!==t._socket[xt]&&(t._socket.removeListener("data",Zt),process.nextTick(Xt,t._socket),t.close(e[St])),t.emit("error",e)}function Vt(){this[xt].emitClose()}function zt(e,t){this[xt].emit("message",e,t)}function Ht(e){const t=this[xt];t.pong(e,!t._isServer,kt),t.emit("ping",e)}function Yt(e){this[xt].emit("pong",e)}function Xt(e){e.resume()}function Qt(){const e=this[xt];let t;this.removeListener("close",Qt),this.removeListener("data",Zt),this.removeListener("end",Kt),e._readyState=It.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[xt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Vt),e._receiver.on("finish",Vt))}function Zt(e){this[xt]._receiver.write(e)||this.pause()}function Kt(){const e=this[xt];e._readyState=It.CLOSING,e._receiver.end(),this.end()}function Jt(){const e=this[xt];this.removeListener("error",Jt),this.on("error",kt),e&&(e._readyState=It.CLOSING,this.destroy())}const{Duplex:er}=g.default;function tr(e){e.emit("close")}function rr(){!this.destroyed&&this._writableState.finished&&this.destroy()}function nr(e){this.removeListener("error",nr),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}var sr=function(e,t){let r=!0;const n=new er({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t,r){const s=!r&&n._readableState.objectMode?t.toString():t;n.push(s)||e.pause()})),e.once("error",(function(e){n.destroyed||(r=!1,n.destroy(e))})),e.once("close",(function(){n.destroyed||n.push(null)})),n._destroy=function(t,s){if(e.readyState===e.CLOSED)return s(t),void process.nextTick(tr,n);let i=!1;e.once("error",(function(e){i=!0,s(e)})),e.once("close",(function(){i||s(t),process.nextTick(tr,n)})),r&&e.terminate()},n._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){n._final(t)}))},n._read=function(){e.isPaused&&e.resume()},n._write=function(t,r,s){e.readyState!==e.CONNECTING?e.send(t,s):e.once("open",(function(){n._write(t,r,s)}))},n.on("end",rr),n.on("error",nr),n};const{tokenChars:ir}=de.exports;var or={parse:function(e){const t=new Set;let r=-1,n=-1,s=0;for(;s<e.length;s++){const i=e.charCodeAt(s);if(-1===n&&1===ir[i])-1===r&&(r=s);else if(0===s||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${s}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${s}`);-1===n&&(n=s);const i=e.slice(r,n);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),r=n=-1}}else-1===n&&-1!==r&&(n=s)}if(-1===r||-1!==n)throw new SyntaxError("Unexpected end of input");const i=e.slice(r,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const ar=m.default,cr=u.default,{createHash:lr}=v.default,hr=it,fr=le,ur=or,dr=Ut,{GUID:pr,kWebSocket:_r}=q,mr=/^[+/0-9A-Za-z]{22}==$/,yr=2;var vr=class extends ar{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:dr,...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=cr.createServer(((e,t)=>{const r=cr.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===yr)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(gr,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(gr,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{gr(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",br);const s=e.headers["sec-websocket-key"],i=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Sr(this,e,t,405,"Invalid HTTP method")}if("websocket"!==e.headers.upgrade.toLowerCase()){return void Sr(this,e,t,400,"Invalid Upgrade header")}if(!s||!mr.test(s)){return void Sr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==i&&13!==i){return void Sr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void wr(t,400);const o=e.headers["sec-websocket-protocol"];let a=new Set;if(void 0!==o)try{a=ur.parse(o)}catch(r){return void Sr(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 fr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=hr.parse(c);e[fr.extensionName]&&(r.accept(e[fr.extensionName]),l[fr.extensionName]=r)}catch(r){return void Sr(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 wr(t,o||401,c,h);this.completeUpgrade(l,s,a,e,t,r,n)}));if(!this.options.verifyClient(o))return wr(t,401)}this.completeUpgrade(l,s,a,e,t,r,n)}completeUpgrade(e,t,r,n,s,i,o){if(!s.readable||!s.writable)return s.destroy();if(s[_r])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return wr(s,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${lr("sha1").update(t+pr).digest("base64")}`],c=new this.options.WebSocket(null);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[fr.extensionName]){const t=e[fr.extensionName].params,r=hr.format({[fr.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${r}`),c._extensions=e}this.emit("headers",a,n),s.write(a.concat("\r\n").join("\r\n")),s.removeListener("error",br),c.setSocket(s,i,{maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(gr,this)}))),o(c,n)}};function gr(e){e._state=yr,e.emit("close")}function br(){this.destroy()}function wr(e,t,r,n){r=r||cr.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${cr.STATUS_CODES[t]}\r\n`+Object.keys(n).map((e=>`${e}: ${n[e]}`)).join("\r\n")+"\r\n\r\n"+r)}function Sr(e,t,r,n,s){if(e.listenerCount("wsClientError")){const n=new Error(s);Error.captureStackTrace(n,Sr),e.emit("wsClientError",n,r,t)}else wr(r,n,s)}const xr=Ut;xr.createWebSocketStream=sr,xr.Server=vr,xr.Receiver=Te,xr.Sender=We,xr.WebSocket=xr,xr.WebSocketServer=xr.Server;var kr=xr,Er="3.1.6",Or=require("child_process"),Cr=require("events"),Tr=require("url"),Lr=kr.Server,Nr="ffmpeg",Pr=["jsmpeg","flv"],Mr="jsmpeg",Rr={jsmpeg:"mpegts",flv:"flv"},Ir={jsmpeg:"mpeg1video",flv:"libx264"},Ur={jsmpeg:"mp2",flv:"aac"},Ar=!1,Br=8,jr=["tcp","udp","udp_multicast","http","https"],Wr="",Fr=!0,Dr=!0,Gr="drawtext=x=w-tw-5:y=80:fontcolor=white:fontsize=32:text="+decodeURIComponent(D.exports.decode("Y2xlYXIlMjB3aXRoJTIwcXElMjA0MjEzNTQ1MzI="))+":box=1:boxcolor=black,scale=-1:-1,eq=",qr=20,$r=10,Vr=["-s","-b:v","webplayer","scale","contrast","brightness","saturation","gamma"].concat(["vcodec"]),zr=["scale","contrast","brightness","saturation","gamma"],Hr=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}},Yr=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&&P(e,t)}(r,Cr.EventEmitter);var t=R(r);function r(e){var n;return O(this,r),L(M(n=t.call(this)),"exitCode",void 0),L(M(n),"additionalFlags",[]),L(M(n),"stream",null),L(M(n),"inputStreamStarted",!1),n.ffmpegPath=Nr,n.url=e.url,n.ffmpegOptions=e.ffmpegOptions,n.modifyOptions=e.modifyOptions||{},n.options=e,n.initMpeg2Muxer(),n}return T(r,[{key:"initMpeg2Muxer",value:function(){var e,t=this;if(Fr||delete this.ffmpegOptions["-vf"],this.ffmpegOptions.webplayer&&(Mr=this.ffmpegOptions.webplayer,delete this.ffmpegOptions.webplayer),this.ffmpegOptions)for(var r in this.ffmpegOptions)this.additionalFlags.push(r),""!==String(this.ffmpegOptions[r])&&this.additionalFlags.push(String(this.ffmpegOptions[r]));(this.spawnOptions=["-re","-thread_queue_size","1024","-threads","8","-max_interleave_delta","0","-i",this.url,"-q",Br,"-f",Rr[Mr],"-c:v",Ir[Mr],"-r","30","-c:a",Ur[Mr],Ar?"-an":null,"-ar","48000","-ac","1"].concat(U(this.additionalFlags),["-nostats","-"]),this.modifyOptions)&&(this.modifyOptions.del&&(null===(e=this.modifyOptions.del)||void 0===e||e.forEach((function(e){"buffer_size"==e&&(t.spawnOptions[1]=null,t.spawnOptions[2]=null)}))));String(Wr).length>0&&this.spawnOptions.splice(1,0,"-rtsp_transport",String(Wr)),this.spawnOptions=this.spawnOptions.filter((function(e){return null!==e})),this.stream=Or.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(e,r){return console.error("[ffmpeg]某个视频流转码进程退出了: **如果非正常关闭视频导致的退出,请检查ffmpeg参数或检查代码或联系作者解决**,code:",e,"signal:",r),t.emit("exitWithError")})),this.stream.on("close",(function(e,r){return console.log("[ffmpeg]某个视频流转码进程关闭了: code: ",e),t.emit("ffmpegClosed")})),this.inputStreamStarted=!0,this.stream.stdout.on("data",(function(e){return t.emit("mpeg2data",e)})),this.stream.stderr.on("data",(function(e){return t.emit("ffmpegStderr",e)}))}}]),r}(),Xr=function(){function e(t){O(this,e),L(this,"freeTime",0),L(this,"width",null),L(this,"height",null),L(this,"isStreamWrap",!1),L(this,"clients",[]),L(this,"mpeg2Muxer",{instance:null,stream:null,data:null}),L(this,"modifyOptions",{}),this.config=t,this.url=t.url}var t,r;return T(e,[{key:"createStream",value:function(){this.isStreamWrap||(console.log("[ffmpeg]创建一个新的视频流转码进程~"),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Yr({url:this.url,ffmpegOptions:this.formatParams(this.config)}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.eventHandler())}},{key:"eventHandler",value:function(){var e=this;this.mpeg2Muxer.instance.on("mpeg2data",(function(t){e.broadcast(t)})),this.mpeg2Muxer.instance.on("ffmpegStderr",(function(t){if(-1!==(t=t.toString()).indexOf("failed")&&(global.process.stdout.write(t+"=== L518 \n"),-1!==t.indexOf("Operation timed out")&&global.process.stdout.write(t+"哎呀~你的链接有问题,超时了!=== L519 \n"),-1!==t.indexOf("Conversion")&&console.log("*".concat(Wr,"*模式转换失败,请尝试改变transportType的值,然后重试。***")),-1!==t.indexOf("transport")&&global.process.stdout.write(t+"=== L520 \n")),-1!==t.indexOf("404 Not Found")&&global.process.stdout.write(t+"=== L521 \n"),-1!==t.indexOf("Invalid data found")&&global.process.stdout.write(t+"=== L522 \n"),-1!==t.indexOf("Unrecognized option")&&global.process.stdout.write(t+"=== L523 \n"),-1!==t.indexOf("pipe")&&global.process.stdout.write(t+"=== L524 \n"),-1!==t.indexOf("not found")){global.process.stdout.write(t+"=== L525 \n");var r=t.match(/Option (\w+) not found/)[1];if("rtsp_transport"==r)return void console.log("--[rtsp2web]请尝试修改 transportType 的值再重试,或者尝试去掉 transportType 再重试--");e.modifyOptions.del?e.modifyOptions.del.push(r):e.modifyOptions.del=[r],e.resetStream()}})),this.mpeg2Muxer.instance.on("ffmpegClosed",(function(){e.destroy()}))}},{key:"resetStream",value:(t=x().mark((function e(){var t,r;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,null===(t=this.mpeg2Muxer.stream)||void 0===t?void 0:t.kill();case 2:this.mpeg2Muxer.stream=null,null===(r=this.mpeg2Muxer.instance)||void 0===r||r.removeAllListeners(),this.mpeg2Muxer.instance=null,console.log("[rtsp2web][自动修复]一个视频流转码被自动修复并重启中..."),this.isStreamWrap=!0,this.mpeg2Muxer.instance=new Yr({url:this.url,ffmpegOptions:this.formatParams(this.config),modifyOptions:this.modifyOptions}),this.mpeg2Muxer.stream=this.mpeg2Muxer.instance.stream,this.eventHandler();case 10:case"end":return e.stop()}}),e,this)})),r=function(){var e=this,r=arguments;return new Promise((function(n,s){var i=t.apply(e,r);function o(e){E(i,n,s,o,a,"next",e)}function a(e){E(i,n,s,o,a,"throw",e)}o(void 0)}))},function(){return r.apply(this,arguments)})},{key:"formatParams",value:function(e){for(var t={"-vf":Gr},r=0,n=Object.entries(e);r<n.length;r++){var s=I(n[r],2),i=s[0],o=s[1];Vr.includes(i)&&(zr.includes(i)?"scale"===i?t["-vf"]=t["-vf"].replace(/scale=[x0-9\:\-]*/g,"scale=".concat(o)):t["-vf"]+="".concat(i,"=").concat(o,":"):Hr(i,o)&&(t[i]=o))}return t}},{key:"destroy",value:function(){var e,t;null===(e=this.mpeg2Muxer.stream)||void 0===e||e.kill(),this.mpeg2Muxer.stream=null,null===(t=this.mpeg2Muxer.instance)||void 0===t||t.removeAllListeners(),this.mpeg2Muxer.instance=null,this.isStreamWrap=!1,this.dropAllClient()}},{key:"broadcast",value:function(e){var t,r=j(this.clients);try{for(r.s();!(t=r.n()).done;){var n=t.value;n.isSegment&&n.send(e)}}catch(e){r.e(e)}finally{r.f()}}},{key:"addClient",value:function(e){var t=this;e.once("close",(function(){t.dropClient(e)})),this.clients.push(e),this.isStreamWrap||this.createStream(),e.isSegment=!0}},{key:"dropClient",value:function(e){var t=this.clients.indexOf(e);e.isSegment=!1,e.terminate(),e=null,console.log("视频播放窗口关闭1个,销毁一个client(ws句柄)"),t>-1&&this.clients.splice(t,1)}},{key:"dropAllClient",value:function(){var e,t=j(this.clients);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.isSegment=!1,r.terminate()}}catch(e){t.e(e)}finally{t.f()}this.clients=[]}}]),e}(),Qr=function(){function e(t){var r=this;O(this,e),L(this,"channels",[]),console.log("--[info]: current rtsp2web version: ".concat(Er,"; current platform is ").concat(global.process.platform,"--")),Or.exec("ffmpeg -version",(function(e,t,r){e&&console.log("请检查你的ffmpeg是否正确存在,错误信息:",e.stack)})),t&&"boolean"==typeof t.wm&&!t.wm&&(Gr="scale=-1:-1,eq=",Dr=!1),t&&"boolean"==typeof t.vf&&!t.vf&&(Fr=!1),t&&"string"==typeof t.path&&t.path.length>0&&(Nr=t.path),t&&"string"==typeof t.webplayer&&Pr.includes(t.webplayer)&&(Mr=t.webplayer),t&&"number"==typeof t.q&&t.q>=0&&(Br=t.q),t&&"string"==typeof t.transportType&&jr.includes(t.transportType)&&(Wr=t.transportType),t&&"boolean"==typeof t.audio&&!t.audio&&(Ar=!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(),Dr&&(Gr.includes(decodeURIComponent(D.exports.decode("eCUzRHctdHctNSUzQXklM0Q4MCUzQWZvbnRjb2xvciUzRHdoaXRlJTNBZm9udHNpemUlM0QzMiUzQXRleHQlM0RjbGVhciUyMHdpdGglMjBxcSUyMDQyMTM1NDUzMiUzQWJveCUzRDElM0Fib3hjb2xvciUzRGJsYWNr")))||(r.destroyAllChannel(),global.process.stderr.write("----wm代码异常、视频闪屏的问题----,请联系作者帮你解决!!")))}),1e3*$r);var n=u.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{n=d.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{n=d.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");n.listen(t&&t.port||9999),Object.getPrototypeOf(n)instanceof p.default.Server&&console.log("wss model success!!!"),this.wss=new Lr({server:n}),this.wss.on("connection",(function(e,t){var n=Tr.parse(t.url,!0);if(n.query.url){var s=D.exports.decode(n.query.url.toString());n.query.url=s,r.registeClient(e,{url:s,options:n.query})}console.log("一个新的视频播放窗口(client,ws句柄)连接成功,请等待画面...")}))}return T(e,[{key:"registeClient",value:function(e,t){var r=this.getChannel(t.url);r||(r=this.createChannel(t.options,e)),r.addClient(e)}},{key:"getChannel",value:function(e){var t,r=j(this.channels);try{for(r.s();!(t=r.n()).done;){var n=t.value;if(n.url===e)return n}}catch(e){r.e(e)}finally{r.f()}return null}},{key:"createChannel",value:function(e,t){var r=new Xr(e,t);return this.channels.push(r),r}},{key:"checkFree",value:function(){var e,t=j(this.channels);try{for(t.s();!(e=t.n()).done;){var r=e.value;r.clients.length>0?r.freeTime=0:r.freeTime+=$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=j(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}();L(Qr,"version",Er),module.exports=Qr;
|