mpaas-jsapi-proxy 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,19 +1,31 @@
1
- # mPaaS JSAPI Proxy Server
1
+ # mPaaS JSAPI Proxy
2
2
 
3
- mPaaS 小程序 JSAPI 代理服务器,提供 WebSocket 连接和设备管理功能。
3
+ mPaaS 小程序 JSAPI 代理:将模拟器中的 `my.call` 调用通过 WebSocket 转发到真机执行。
4
4
 
5
+ 本仓库包含两部分:
6
+
7
+ | 目录 | 说明 |
8
+ |------|------|
9
+ | 根目录 | npm 主项目 `mpaas-jsapi-proxy`:代理服务器(`mpaas-jsapi-proxy` 命令)+ 模拟器客户端代理 |
10
+ | `miniapp/` | 真机代理小程序(mPaaS 小程序工程),运行在真机上接收并执行 API 调用 |
11
+
12
+ ## 系统架构
13
+
14
+ ```
15
+ 模拟器 (开发者工具) ←→ 代理服务器 (本项目) ←→ 真机小程序 (miniapp/)
16
+ ```
5
17
 
6
18
  ## 功能特性
7
19
 
8
- - WebSocket 服务器,支持 JSAPI 消息代理
9
- - 设备连接管理
10
- - 消息路由和分发
11
- - 心跳检测机制
12
- - 二维码终端显示
20
+ - WebSocket 代理服务器,支持 JSAPI 消息转发
21
+ - 设备连接管理、消息路由和分发、心跳检测
22
+ - 终端二维码显示服务器地址
23
+ - 模拟器客户端 `MyCallProxy`:透明劫持 `my.call`,npm 包直接引用,无需复制代码
24
+ - 蓝牙代理开关:`{ bluetooth: true }` 仅代理蓝牙 API(含事件多播)到真机,其余保持模拟器本地执行
13
25
 
14
26
  ## 快速开始
15
27
 
16
- ### 直接运行
28
+ ### 1. 启动代理服务器
17
29
 
18
30
  ```bash
19
31
  # 全局安装
@@ -22,19 +34,74 @@ npm install -g mpaas-jsapi-proxy
22
34
  # 启动服务器
23
35
  mpaas-jsapi-proxy
24
36
  ```
25
- ## 开发
37
+
38
+ ### 2. 真机小程序连接
39
+
40
+ 在真机上运行 `miniapp/` 小程序,输入服务器地址并连接,复制连接参数(含设备ID)。
41
+
42
+ ### 3. 模拟器客户端接入
43
+
44
+ 在模拟器所在的小程序项目中安装本包:
26
45
 
27
46
  ```bash
28
- # 克隆项目
29
- git clone <repository-url>
47
+ npm install mpaas-jsapi-proxy --save
48
+ ```
49
+
50
+ 在 `app.js` 中初始化(连接参数从真机小程序复制)。**包的默认导出即客户端代理**,自带 TypeScript 类型声明(d.ts):
51
+
52
+ ```javascript
53
+ import MyCallProxy from 'mpaas-jsapi-proxy';
54
+
55
+ const proxy = new MyCallProxy('ws://192.168.0.12:3000?deviceId=device_xxx');
56
+ proxy.init();
57
+
58
+ // 之后所有 my.call 自动通过代理转发到真机
59
+ my.call('scan', { type: 'qr' }, (result) => {
60
+ console.log(result);
61
+ });
62
+ ```
63
+
64
+ ### 蓝牙代理模式(可选)
65
+
66
+ 模拟器不支持蓝牙调试时,可开启蓝牙开关:只把蓝牙相关 API 转发到真机执行,其余 `my.*` 调用(含业务自定义 JSAPI)保持模拟器本地执行:
30
67
 
68
+ ```javascript
69
+ import MyCallProxy from 'mpaas-jsapi-proxy';
70
+
71
+ const proxy = new MyCallProxy('ws://192.168.0.12:3000?deviceId=device_xxx', { bluetooth: true });
72
+ proxy.init();
73
+
74
+ // 一次性 API 走真机,success/fail 按真机结果自动路由
75
+ my.openBluetoothAdapter({
76
+ success: (res) => console.log('适配器已打开', res),
77
+ fail: (err) => console.error('打开失败', err),
78
+ });
79
+
80
+ // 监听类 API:真机触发,经服务器多播回模拟器
81
+ my.onBluetoothDeviceFound((res) => {
82
+ console.log('发现设备', res.devices);
83
+ });
84
+ ```
85
+
86
+ 开启后:
87
+
88
+ - 一次性 API(`openBluetoothAdapter`、`writeBLECharacteristicValue`、`getBluetoothDevices` 等)原路返回
89
+ - 监听类 API(`onBluetoothDeviceFound`、`onBLECharacteristicValueChange` 等)由真机触发多播,`offXxx` 全量解绑并同步真机
90
+ - `my.call` 与其他 `my.*` API 完全不受影响;不传 `bluetooth` 时保持原有全量代理行为
91
+ - 注意:蓝牙模式下若通过 `my.call('openBluetoothAdapter', ...)` 泛化方式调用蓝牙 API,**不会**被代理(该模式不劫持 `my.call`),请使用具名 API 写法
92
+
93
+ ## 开发
94
+
95
+ ```bash
31
96
  # 安装依赖
32
97
  pnpm install
33
98
 
34
99
  # 开发模式(热重载)
35
100
  pnpm run dev
36
101
 
37
- # 构建
102
+ # 构建(产物:dist/ 下 js + d.ts)
103
+ # dist/index.js 客户端代理(默认导出,d.ts 随包发布)
104
+ # dist/server.js 服务器 CLI 入口(仅通过 mpaas-jsapi-proxy 命令使用)
38
105
  pnpm run build
39
106
 
40
107
  # 类型检查
@@ -54,10 +121,36 @@ npm pack --dry-run
54
121
  npm publish
55
122
  ```
56
123
 
124
+ ## 目录结构
125
+
126
+ ```
127
+ ├── src/ # TypeScript 源码
128
+ │ ├── index.ts # 模拟器客户端代理(默认导出,打包为 dist/index.js)
129
+ │ └── server/ # 代理服务器(打包为 dist/server.js)
130
+ │ ├── index.ts # 服务器 CLI 入口
131
+ │ ├── server.ts # WebSocket 服务器
132
+ │ ├── config.ts # 配置
133
+ │ ├── device-manager.ts
134
+ │ ├── message-router.ts
135
+ │ └── utils.ts
136
+ ├── bin/ # CLI 入口(指向 dist/server.js)
137
+ ├── dist/ # 构建产物(js + d.ts,随 npm 发布)
138
+ ├── tsconfig.build.json # d.ts 声明文件生成配置
139
+ └── miniapp/ # 真机代理小程序子项目
140
+ ```
141
+
142
+ ## 导出入口
143
+
144
+ | 导入路径 | 内容 |
145
+ |---------|------|
146
+ | `mpaas-jsapi-proxy` | 客户端代理 `MyCallProxy`(默认导出) |
147
+
148
+ 服务器不作为包导出,仅通过 CLI 使用:`mpaas-jsapi-proxy`。
149
+
57
150
  ## 技术栈
58
151
 
59
152
  - **TypeScript** - 类型安全的开发体验
60
- - **Vite** - 快速的构建工具
153
+ - **esbuild** - 客户端与服务端产物打包
61
154
  - **WebSocket** - 实时双向通信
62
155
  - **qrcode-terminal** - 终端二维码显示
63
156
 
package/bin/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- require('../dist/index.js');
2
+ require('../dist/server.js');
@@ -0,0 +1,4 @@
1
+ /** 一次性调用的蓝牙 API(options 含 success/fail/complete,请求-响应模型) */
2
+ export declare const BLUETOOTH_ONE_SHOT_APIS: readonly ["openBluetoothAdapter", "closeBluetoothAdapter", "getBluetoothAdapterState", "startBluetoothDevicesDiscovery", "stopBluetoothDevicesDiscovery", "getBluetoothDevices", "getConnectedBluetoothDevices", "getBluetoothPairs", "makeBluetoothPair", "cancelBluetoothPair", "connectBLEDevice", "disconnectBLEDevice", "getBLEDeviceServices", "getBLEDeviceCharacteristics", "getBLEDeviceRSSI", "getBLEDeviceStatus", "getBLEMTU", "setBLEMTU", "readBLECharacteristicValue", "writeBLECharacteristicValue", "notifyBLECharacteristicValueChange", "showBLEPermissionGuide", "startBeaconDiscovery", "stopBeaconDiscovery", "getBeacons"];
3
+ /** 事件订阅类蓝牙 API(回调多次触发,需多播协议) */
4
+ export declare const BLUETOOTH_EVENT_APIS: readonly ["onBluetoothAdapterStateChange", "onBluetoothDeviceFound", "onBLEConnectionStateChanged", "onBLECharacteristicValueChange", "onBeaconUpdate", "onBeaconServiceChange"];
@@ -0,0 +1,73 @@
1
+ /** my.call 回调 */
2
+ type CallCallback = (result: any) => void;
3
+ /** 代理服务器消息 */
4
+ interface ProxyMessage {
5
+ type: string;
6
+ msgId: string;
7
+ deviceId?: string;
8
+ timestamp?: number;
9
+ api?: string;
10
+ params?: Record<string, unknown>;
11
+ result?: unknown;
12
+ error?: {
13
+ message?: string;
14
+ } & Record<string, unknown>;
15
+ role?: string;
16
+ proxyMode?: string;
17
+ data?: unknown;
18
+ }
19
+ /** 代理选项 */
20
+ export interface MyCallProxyOptions {
21
+ /** 蓝牙代理开关:开启后重写 my 上的蓝牙具名 API 转发真机(不劫持 my.call);缺省时劫持 my.call 全量代理 */
22
+ bluetooth?: boolean;
23
+ }
24
+ declare class MyCallProxy {
25
+ private serverUrl;
26
+ private pendingCalls;
27
+ private isConnected;
28
+ private isConnecting;
29
+ private connectPromise;
30
+ private originalMyCall;
31
+ private msgIdCounter;
32
+ private _deviceIdCache;
33
+ private _resolveConnect;
34
+ private _rejectConnect;
35
+ private options;
36
+ private originalNamedApis;
37
+ private eventListeners;
38
+ private subscribedApis;
39
+ private heartbeatTimer;
40
+ private socketListenersBound;
41
+ private offlineRetryCounts;
42
+ constructor(serverUrl: string, options?: MyCallProxyOptions);
43
+ init(options?: MyCallProxyOptions): boolean;
44
+ connect(): void;
45
+ private bindSocketListeners;
46
+ proxyCall(api: string, params: Record<string, unknown>, callback?: CallCallback): void;
47
+ handleMessage(message: ProxyMessage): void;
48
+ fallbackToOriginal(api: string, params: Record<string, unknown>, callback?: CallCallback): void;
49
+ private setupBluetoothProxy;
50
+ private overrideNamedApi;
51
+ private proxyNamedCall;
52
+ private fallbackNamedApi;
53
+ private overrideEventApi;
54
+ private ensureSubscribed;
55
+ private resubscribeAllEvents;
56
+ private sendEventSubscribe;
57
+ private overrideOffApi;
58
+ private sendSimulatorRegister;
59
+ private startHeartbeat;
60
+ private stopHeartbeat;
61
+ rejectPendingCalls(reason: string): void;
62
+ generateMsgId(): string;
63
+ getDeviceId(): string | null;
64
+ buildWebSocketUrl(path: string, extraParams?: Record<string, string>): string;
65
+ waitForConnection(): Promise<void>;
66
+ destroy(): void;
67
+ getStatus(): {
68
+ isConnected: boolean;
69
+ pending_calls: number;
70
+ serverUrl: string;
71
+ };
72
+ }
73
+ export default MyCallProxy;
package/dist/index.js CHANGED
@@ -1,12 +1 @@
1
- var b=Object.create,v=Object.defineProperty,I=Object.getOwnPropertyDescriptor,m=Object.getOwnPropertyNames,w=Object.getPrototypeOf,S=Object.prototype.hasOwnProperty,D=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(var n=m(t),c=0,o=n.length,i;c<o;c++)i=n[c],!S.call(e,i)&&i!==r&&v(e,i,{get:(u=>t[u]).bind(null,i),enumerable:!(s=I(t,i))||s.enumerable});return e},p=(e,t,r)=>(r=e!=null?b(w(e)):{},D(t||!e||!e.__esModule?v(r,"default",{value:e,enumerable:!0}):r,e));let _=require("ws"),h=require("qrcode-terminal");h=p(h);let d=require("os");d=p(d);let g=require("minimist");g=p(g);var a=class{static getLocalIP(){const e=d.default.networkInterfaces();for(const t of Object.keys(e))for(const r of e[t])if(r.family==="IPv4"&&!r.internal)return r.address;return"localhost"}static formatServerUrl(e,t,r){return`ws://${e}:${t}${r}`}static log(e,t="info"){const r=new Date().toLocaleTimeString("zh-CN");console.log(`[${r}] ${{info:"ℹ️",success:"✅",error:"❌",warn:"⚠️"}[t]||"ℹ️"} ${e}`)}},C=class{constructor(){this.devices=new Map}registerDevice(e,t,r){if(this.devices.has(e)){const s=this.devices.get(e);s.ws=t,s.deviceInfo=r,s.lastHeartbeat=Date.now(),a.log(`设备更新连接: ${e}`,"info")}else this.devices.set(e,{ws:t,simulatorWS:null,deviceInfo:r,lastHeartbeat:Date.now()}),a.log(`设备注册成功: ${e}`,"success")}disconnect(e){for(const[t,r]of this.devices)if(r.ws===e)return this.devices.delete(t),a.log(`设备断开连接: ${t}`,"warn"),!0;return!1}getDevice(e){return this.devices.get(e)}isDeviceReady(e){const t=this.devices.get(e);return!!t&&!!t.ws}updateHeartbeat(e){const t=this.devices.get(e);t&&(t.lastHeartbeat=Date.now())}getAllDevices(){return Array.from(this.devices.entries()).map(([e,t])=>({deviceId:e,hasMiniapp:!!t.ws,lastHeartbeat:t.lastHeartbeat}))}get devicesMap(){return this.devices}},y=class{constructor(e){this.httpServer=null,this.deviceManager=e,this.pendingCalls=new Map}setHttpServer(e){this.httpServer=e}handleMessage(e,t){const{type:r,msgId:s,deviceId:n}=e;if(!r||!s){this.sendError(t,s,"INVALID_MESSAGE","消息格式错误");return}switch(r){case"client_call":this.handleClientCall(e,t);break;case"register":this.handleRegister(e,t);break;case"response":this.handleResponse(e,t);break;case"heartbeat":this.handleHeartbeat(e);break;default:this.sendError(t,s,"UNKNOWN_MESSAGE_TYPE",`未知消息类型: ${r}`)}}handleRegister(e,t){const{msgId:r,deviceId:s,deviceInfo:n}=e;if(!s){this.sendError(t,r,"INVALID_DEVICE_ID","设备ID不能为空");return}this.deviceManager.registerDevice(s,t,n||{}),t.send(JSON.stringify({type:"register",msgId:r,deviceId:s,success:!0,timestamp:Date.now()}))}handleClientCall(e,t){const{msgId:r,deviceId:s,api:n,params:c}=e;if(!s){this.sendError(t,r,"INVALID_DEVICE_ID","设备ID不能为空");return}this.pendingCalls.set(r,{ws:t,deviceId:s,timestamp:Date.now()});const o=this.deviceManager.getDevice(s);if(!o||!o.ws){this.pendingCalls.delete(r),this.sendError(t,r,"DEVICE_OFFLINE","代理小程序未连接");return}try{o.ws.send(JSON.stringify(e)),a.log(`转发调用: ${n} → ${s} -> ${r}`,"info")}catch(i){this.pendingCalls.delete(r),this.sendError(t,r,"SEND_FAILED",`发送失败: ${i.message}`)}}handleResponse(e,t){const{msgId:r}=e,s=this.pendingCalls.get(r);if(!s){a.log(`未找到对应的请求: ${r}`,"warn");return}a.log(`转发响应 → msgId: ${r}`,"info");try{s.ws.send(JSON.stringify(e))}catch(n){a.log(`转发响应失败: ${n.message}`,"error")}finally{this.pendingCalls.delete(r)}}handleHeartbeat(e){const{deviceId:t}=e;t&&this.deviceManager.updateHeartbeat(t)}sendError(e,t,r,s){e&&e.readyState===1&&e.send(JSON.stringify({type:"error",msgId:t,timestamp:Date.now(),error:{code:r,message:s}}))}clearPendingCallsForWS(e){for(const[t,r]of this.pendingCalls)r.ws===e&&this.pendingCalls.delete(t)}},P=class{constructor(e){const t={port:3e3,wsPath:"/ws",heartbeatInterval:3e4};this.config={...t,...e},this.deviceManager=new C,this.messageRouter=new y(this.deviceManager),this.wss=null,this.heartbeatTimer=null}start(){this.wss=new _.WebSocketServer({port:this.config.port,path:this.config.wsPath}),this.wss.on("connection",(e,t)=>{this.handleConnection(e,t)}),this.wss.on("error",e=>{a.log(`服务器错误: ${e.message}`,"error")}),this.startHeartbeatCheck(),a.log("代理服务器启动成功","success"),a.log(`监听端口: ${this.config.port}`,"info"),this.displayConnectionInfo()}handleConnection(e,t){const r=new URL(t.url,`http://${t.headers.host}`).searchParams.get("type");a.log(`新连接: ${r||"unknown"}`,"info"),e.on("message",s=>{try{const n=JSON.parse(s.toString());this.messageRouter.handleMessage(n,e)}catch(n){a.log(`消息解析失败: ${n.message}`,"error")}}),e.on("close",()=>{this.deviceManager.disconnect(e),this.messageRouter.clearPendingCallsForWS(e)}),e.on("error",s=>{a.log(`WebSocket错误: ${s.message}`,"error")})}displayConnectionInfo(){const e=a.getLocalIP(),t=a.formatServerUrl(e,this.config.port,"");console.log(`
2
- ╔════════════════════════════════════════════════════════════╗
3
- ║ mPaaS JSAPI 代理服务器 ║
4
- ╠════════════════════════════════════════════════════════════╣
5
- ║ 请在代理小程序中输入以下地址进行注册 ║
6
- ║ ║
7
- ║ ${t.padEnd(58)}║
8
- ║ ║
9
- ║ 或扫描下方二维码快速配置: ║
10
- ╚════════════════════════════════════════════════════════════╝
11
- `),console.log("");const r=`url=${encodeURIComponent(t)}`;h.default.generate(r,{small:!0})}startHeartbeatCheck(){this.heartbeatTimer=setInterval(()=>{const e=Date.now(),t=this.config.heartbeatInterval*2;for(const[r,s]of this.deviceManager.devicesMap)e-s.lastHeartbeat>t&&(a.log(`设备心跳超时: ${r}`,"warn"),s.ws&&s.ws.close(),s.simulatorWS&&s.simulatorWS.close(),this.deviceManager.devicesMap.delete(r))},this.config.heartbeatInterval)}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.wss&&(this.wss.close(),a.log("服务器已关闭","info"))}},E={port:7521,wsPath:"/ws",heartbeatInterval:3e4},l=(0,g.default)(process.argv.slice(2)),f=new P({...E,...l.p!==void 0&&{port:Number(l.p)},...l.port!==void 0&&{port:Number(l.port)}});f.start();process.on("SIGINT",()=>{console.log(`
12
- 正在关闭服务器...`),f.stop(),process.exit(0)});
1
+ "use strict";function _slicedToArray(r,e){return _arrayWithHoles(r)||_iterableToArrayLimit(r,e)||_unsupportedIterableToArray(r,e)||_nonIterableRest();}function _nonIterableRest(){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 _iterableToArrayLimit(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1;}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r;}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return;}finally{if(o)throw n;}}return a;}}function _arrayWithHoles(r){if(Array.isArray(r))return r;}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function");}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o);}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+"";}function _toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.");}return("string"===r?String:Number)(t);}function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o;}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o;},_typeof(o);}function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]};},e:function e(r){throw r;},f:F};}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 o,a=!0,u=!1;return{s:function s(){t=t.call(r);},n:function n(){var r=t.next();return a=r.done,r;},e:function e(r){u=!0,o=r;},f:function f(){try{a||null==t.return||t.return();}finally{if(u)throw o;}}};}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0;}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n;}var BLUETOOTH_ONE_SHOT_APIS=["openBluetoothAdapter","closeBluetoothAdapter","getBluetoothAdapterState","startBluetoothDevicesDiscovery","stopBluetoothDevicesDiscovery","getBluetoothDevices","getConnectedBluetoothDevices","getBluetoothPairs","makeBluetoothPair","cancelBluetoothPair","connectBLEDevice","disconnectBLEDevice","getBLEDeviceServices","getBLEDeviceCharacteristics","getBLEDeviceRSSI","getBLEDeviceStatus","getBLEMTU","setBLEMTU","readBLECharacteristicValue","writeBLECharacteristicValue","notifyBLECharacteristicValueChange","showBLEPermissionGuide","startBeaconDiscovery","stopBeaconDiscovery","getBeacons"],BLUETOOTH_EVENT_APIS=["onBluetoothAdapterStateChange","onBluetoothDeviceFound","onBLEConnectionStateChanged","onBLECharacteristicValueChange","onBeaconUpdate","onBeaconServiceChange"];var __defProp=Object.defineProperty,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=function __defNormalProp(i,e,t){return e in i?__defProp(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;},__spreadValues=function __spreadValues(i,e){for(var t in e||(e={}))__hasOwnProp.call(e,t)&&__defNormalProp(i,t,e[t]);if(__getOwnPropSymbols){var _iterator=_createForOfIteratorHelper(__getOwnPropSymbols(e)),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var t=_step.value;__propIsEnum.call(e,t)&&__defNormalProp(i,t,e[t]);}}catch(err){_iterator.e(err);}finally{_iterator.f();}}return i;},__objRest=function __objRest(i,e){var t={};for(var s in i)__hasOwnProp.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&__getOwnPropSymbols){var _iterator2=_createForOfIteratorHelper(__getOwnPropSymbols(i)),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var s=_step2.value;e.indexOf(s)<0&&__propIsEnum.call(i,s)&&(t[s]=i[s]);}}catch(err){_iterator2.e(err);}finally{_iterator2.f();}}return t;};function isSuccessResult(i){return!i||_typeof(i)!="object"||i.success===!0?!0:i.success===!1?!1:typeof i.error=="number"?i.error===0:typeof i.error=="string"?i.error===""||i.error==="0":typeof i.errorCode=="string"?i.errorCode===""||i.errorCode==="0":!(i.error!==void 0&&i.error!==null);}var MyCallProxy=function(){function MyCallProxy(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,MyCallProxy);this.pendingCalls=new Map(),this.isConnected=!1,this.isConnecting=!1,this.connectPromise=null,this.originalMyCall=null,this.msgIdCounter=0,this._deviceIdCache=null,this._resolveConnect=null,this._rejectConnect=null,this.originalNamedApis=new Map(),this.eventListeners=new Map(),this.subscribedApis=new Set(),this.heartbeatTimer=null,this.socketListenersBound=!1,this.offlineRetryCounts=new Map(),this.serverUrl=e,this.options=t;}return _createClass(MyCallProxy,[{key:"init",value:function init(e){if(e&&(this.options=Object.assign({},this.options,e)),typeof my=="undefined"||typeof my.call!="function")return console.error("my.call \u4E0D\u5B58\u5728\uFF0C\u65E0\u6CD5\u521D\u59CB\u5316\u4EE3\u7406"),!1;if(this.originalMyCall=my.call,this.options.bluetooth)return this.setupBluetoothProxy(),this.connect(),console.log("[MyCallProxy] \u2705 \u84DD\u7259 API \u4EE3\u7406\u5DF2\u521D\u59CB\u5316\uFF08\u4EC5\u4EE3\u7406\u84DD\u7259 API\uFF09"),!0;var t=this;return my.call=function(s,o,n){t.isConnected?t.proxyCall(s,o,n):t.isConnecting?(console.log("[\u4EE3\u7406\u8FDE\u63A5\u4E2D] \u7B49\u5F85\u8FDE\u63A5: ".concat(s)),t.waitForConnection().then(function(){console.log("[\u4EE3\u7406\u8FDE\u63A5\u4E2D] \u8FDE\u63A5\u5B8C\u6210\uFF0C\u53D1\u9001: ".concat(s)),t.proxyCall(s,o,n);})):(console.warn("[\u4EE3\u7406\u672A\u8FDE\u63A5] \u4F7F\u7528\u539F\u59CB my.call"),t.originalMyCall&&t.originalMyCall(s,o,n));},this.connect(),console.log("[MyCallProxy] \u2705 my.call \u4EE3\u7406\u5DF2\u521D\u59CB\u5316"),!0;}},{key:"connect",value:function connect(){var _this=this;var e=this.getDeviceId();if(!e){console.error("[MyCallProxy] \u670D\u52A1\u5668URL\u4E2D\u7F3A\u5C11deviceId\u53C2\u6570");return;}console.log("[MyCallProxy] \u8BBE\u5907ID:",e),console.log("[MyCallProxy] \u670D\u52A1\u5668URL:",this.serverUrl);var t=this.buildWebSocketUrl("/ws",{type:"simulator"});console.log("[MyCallProxy] WebSocket URL:",t),this.isConnecting=!0,this.connectPromise=new Promise(function(s,o){_this._resolveConnect=s,_this._rejectConnect=o;});try{my.connectSocket({url:t,success:function success(){console.log("[MyCallProxy] WebSocket \u8FDE\u63A5\u521B\u5EFA\u6210\u529F");},fail:function fail(s){console.error("[MyCallProxy] WebSocket \u8FDE\u63A5\u5931\u8D25",s),_this.isConnecting=!1,_this.isConnected=!1,_this._rejectConnect&&_this._rejectConnect(s);}}),this.bindSocketListeners();}catch(s){console.error("[MyCallProxy] \u8FDE\u63A5\u5931\u8D25:",s),this.isConnecting=!1,this._rejectConnect&&this._rejectConnect(s);}}},{key:"bindSocketListeners",value:function bindSocketListeners(){var _this2=this;this.socketListenersBound||(this.socketListenersBound=!0,my.onSocketOpen(function(){console.log("[MyCallProxy] \uD83D\uDD17 \u5DF2\u8FDE\u63A5\u5230\u4EE3\u7406\u670D\u52A1\u5668"),_this2.isConnecting=!1,_this2.isConnected=!0,_this2._resolveConnect&&_this2._resolveConnect(),_this2.offlineRetryCounts.clear(),_this2.sendSimulatorRegister(),_this2.resubscribeAllEvents(),_this2.startHeartbeat();}),my.onSocketMessage(function(e){try{var t=JSON.parse(e.data);_this2.handleMessage(t);}catch(t){console.error("[MyCallProxy] \u6D88\u606F\u89E3\u6790\u5931\u8D25:",t);}}),my.onSocketError(function(e){console.error("[MyCallProxy] WebSocket \u9519\u8BEF:",e),_this2.isConnecting=!1,_this2.isConnected=!1,_this2._rejectConnect&&_this2._rejectConnect(e);}),my.onSocketClose(function(){console.warn("[MyCallProxy] WebSocket \u8FDE\u63A5\u5DF2\u5173\u95ED"),_this2.isConnecting=!1,_this2.isConnected=!1,_this2.stopHeartbeat(),_this2._rejectConnect&&_this2._rejectConnect(new Error("\u8FDE\u63A5\u5DF2\u5173\u95ED")),_this2.subscribedApis.clear(),_this2.rejectPendingCalls("\u8FDE\u63A5\u5DF2\u65AD\u5F00");}));}},{key:"proxyCall",value:function proxyCall(e,t,s){var _this3=this;var o=this.generateMsgId(),n=this.getDeviceId();if(!n){console.error("[MyCallProxy] \u670D\u52A1\u5668URL\u4E2D\u7F3A\u5C11deviceId\u53C2\u6570"),this.fallbackToOriginal(e,t,s);return;}this.pendingCalls.set(o,{callback:s||function(){},timestamp:Date.now()});var u={type:"client_call",msgId:o,deviceId:n,timestamp:Date.now(),api:e,params:t||{}};try{my.sendSocketMessage({data:JSON.stringify(u),success:function success(){console.log("[MyCallProxy] \uD83D\uDCE4 \u53D1\u9001: ".concat(e," (msgId: ").concat(o,")"));},fail:function fail(r){console.error("[MyCallProxy] \u53D1\u9001\u5931\u8D25:",r),_this3.pendingCalls.delete(o),_this3.fallbackToOriginal(e,t,s);}});}catch(r){console.error("[MyCallProxy] \u53D1\u9001\u5931\u8D25:",r),this.pendingCalls.delete(o),this.fallbackToOriginal(e,t,s);}}},{key:"handleMessage",value:function handleMessage(e){var _this4=this;var t=e.type,s=e.msgId,o=e.result,n=e.error;if(t==="response"){var u=this.pendingCalls.get(s);u?(console.log("[MyCallProxy] \uD83D\uDCE5 \u54CD\u5E94: ".concat(s)),u.callback(o),this.pendingCalls.delete(s)):console.warn("[MyCallProxy] \u672A\u627E\u5230\u5BF9\u5E94\u7684\u8BF7\u6C42: ".concat(s));}else if(t==="event"){var _u=e.api,r=e.data,l=this.eventListeners.get(_u);if(l&&l.size>0){console.log("[MyCallProxy] \uD83D\uDCE5 \u4E8B\u4EF6: ".concat(_u));var _iterator3=_createForOfIteratorHelper(l),_step3;try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var c=_step3.value;try{c(r);}catch(a){console.error("[MyCallProxy] \u4E8B\u4EF6\u56DE\u8C03\u6267\u884C\u51FA\u9519: ".concat(_u),a);}}}catch(err){_iterator3.e(err);}finally{_iterator3.f();}}}else if(t==="error"){var _u2=this.pendingCalls.get(s);if(_u2)console.error("[MyCallProxy] \u274C \u9519\u8BEF: ".concat(s),n),_u2.callback({error:n}),this.pendingCalls.delete(s);else if(e.api){var _r=e.api;if(console.error("[MyCallProxy] \u274C \u4E8B\u4EF6\u8BA2\u9605\u88AB\u62D2\u7EDD: ".concat(_r),n),this.subscribedApis.delete(_r),(n==null?void 0:n.code)==="DEVICE_OFFLINE"&&this.eventListeners.has(_r)){var _l=(this.offlineRetryCounts.get(_r)||0)+1;if(_l>30){console.warn("[MyCallProxy] \u26A0\uFE0F \u8BA2\u9605\u91CD\u8BD5\u8FBE\u4E0A\u9650\uFF0830 \u6B21\uFF09: ".concat(_r,"\uFF0C\u8BF7\u786E\u8BA4\u771F\u673A\u5C0F\u7A0B\u5E8F\u5DF2\u8FDE\u63A5\u540E\u91CD\u65B0\u8BA2\u9605"));return;}this.offlineRetryCounts.set(_r,_l),setTimeout(function(){return _this4.ensureSubscribed(_r);},2e3);}}}}},{key:"fallbackToOriginal",value:function fallbackToOriginal(e,t,s){console.warn("[MyCallProxy] \u56DE\u9000\u5230\u539F\u59CB my.call"),this.originalMyCall&&this.originalMyCall(e,t,s);}},{key:"setupBluetoothProxy",value:function setupBluetoothProxy(){for(var _i=0,_BLUETOOTH_ONE_SHOT_A=BLUETOOTH_ONE_SHOT_APIS;_i<_BLUETOOTH_ONE_SHOT_A.length;_i++){var e=_BLUETOOTH_ONE_SHOT_A[_i];this.overrideNamedApi(e);}for(var _i2=0,_BLUETOOTH_EVENT_APIS=BLUETOOTH_EVENT_APIS;_i2<_BLUETOOTH_EVENT_APIS.length;_i2++){var _e=_BLUETOOTH_EVENT_APIS[_i2];this.overrideEventApi(_e),this.overrideOffApi(_e.replace(/^on/,"off"));}}},{key:"overrideNamedApi",value:function overrideNamedApi(e){this.originalNamedApis.set(e,my[e]);var t=this;my[e]=function(s){t.proxyNamedCall(e,s);};}},{key:"proxyNamedCall",value:function proxyNamedCall(e,t){var _this5=this;var s=t||{},o=s.success,n=s.fail,u=s.complete,r=__objRest(s,["success","fail","complete"]),l=function l(c){isSuccessResult(c)?typeof o=="function"&&o(c):typeof n=="function"&&n(c),typeof u=="function"&&u(c);};this.isConnected?this.proxyCall(e,r,l):this.isConnecting?this.waitForConnection().then(function(){return _this5.proxyCall(e,r,l);}).catch(function(){return _this5.fallbackNamedApi(e,t);}):this.fallbackNamedApi(e,t);}},{key:"fallbackNamedApi",value:function fallbackNamedApi(e,t){var s=this.originalNamedApis.get(e);typeof s=="function"?(console.warn("[MyCallProxy] \u4EE3\u7406\u672A\u8FDE\u63A5\uFF0C\u56DE\u9000\u672C\u5730\u6267\u884C: ".concat(e)),s(t)):t&&typeof t.fail=="function"&&t.fail({error:4,errorMessage:"\u4EE3\u7406\u672A\u8FDE\u63A5\u4E14\u672C\u5730\u4E0D\u652F\u6301: ".concat(e)});}},{key:"overrideEventApi",value:function overrideEventApi(e){this.originalNamedApis.set(e,my[e]);var t=this;my[e]=function(s){var o=typeof s=="function"?s:s&&typeof s.success=="function"?s.success:null;if(!o){console.warn("[MyCallProxy] ".concat(e," \u53C2\u6570\u65E2\u4E0D\u662F\u51FD\u6570\u4E5F\u4E0D\u662F\u542B success \u7684\u5BF9\u8C61\uFF0C\u8C03\u7528\u88AB\u5FFD\u7565"));return;}var n=t.eventListeners.get(e);n||(n=new Set(),t.eventListeners.set(e,n)),n.add(o),t.ensureSubscribed(e);};}},{key:"ensureSubscribed",value:function ensureSubscribed(e){var _this6=this;if(!this.subscribedApis.has(e)){if(this.isConnected){this.subscribedApis.add(e),this.sendEventSubscribe(e);return;}if(!this.isConnecting){console.warn("[MyCallProxy] \u4EE3\u7406\u672A\u8FDE\u63A5\uFF0C\u5C1D\u8BD5\u91CD\u8FDE\u4EE5\u8BA2\u9605: ".concat(e));try{this.connect();}catch(t){console.error("[MyCallProxy] \u91CD\u8FDE\u5931\u8D25: ".concat(e),t);return;}}this.waitForConnection().then(function(){_this6.subscribedApis.has(e)||(_this6.subscribedApis.add(e),_this6.sendEventSubscribe(e));}).catch(function(){return console.error("[MyCallProxy] \u4E8B\u4EF6\u8BA2\u9605\u5931\u8D25\uFF08\u8FDE\u63A5\u5931\u8D25\uFF09: ".concat(e));});}}},{key:"resubscribeAllEvents",value:function resubscribeAllEvents(){var _iterator4=_createForOfIteratorHelper(this.eventListeners.keys()),_step4;try{for(_iterator4.s();!(_step4=_iterator4.n()).done;){var e=_step4.value;this.subscribedApis.has(e)||(this.subscribedApis.add(e),this.sendEventSubscribe(e));}}catch(err){_iterator4.e(err);}finally{_iterator4.f();}}},{key:"sendEventSubscribe",value:function sendEventSubscribe(e){var _this7=this;var t=this.getDeviceId();if(!t)return;var s={type:"client_call",msgId:this.generateMsgId(),deviceId:t,timestamp:Date.now(),api:e,params:{},proxyMode:"event"};my.sendSocketMessage({data:JSON.stringify(s),success:function success(){console.log("[MyCallProxy] \uD83D\uDCE4 \u8BA2\u9605: ".concat(e," (\u4E8B\u4EF6\u6A21\u5F0F)"));},fail:function fail(o){_this7.subscribedApis.delete(e),console.error("[MyCallProxy] \u4E8B\u4EF6\u8BA2\u9605\u53D1\u9001\u5931\u8D25: ".concat(e),o);}});}},{key:"overrideOffApi",value:function overrideOffApi(e){this.originalNamedApis.set(e,my[e]);var t=this;my[e]=function(){var s=e.replace(/^off/,"on");t.eventListeners.delete(s),t.subscribedApis.delete(s),t.isConnected?t.proxyCall(e,{},function(){}):t.isConnecting?t.waitForConnection().then(function(){return t.proxyCall(e,{},function(){});}).catch(function(){}):typeof t.originalNamedApis.get(e)=="function"&&t.originalNamedApis.get(e)();};}},{key:"sendSimulatorRegister",value:function sendSimulatorRegister(){var e=this.getDeviceId();e&&my.sendSocketMessage({data:JSON.stringify({type:"register",msgId:"msg_register_"+Date.now(),deviceId:e,role:"simulator",timestamp:Date.now()}),fail:function fail(t){return console.error("[MyCallProxy] \u6A21\u62DF\u5668\u6CE8\u518C\u53D1\u9001\u5931\u8D25:",t);}});}},{key:"startHeartbeat",value:function startHeartbeat(){var _this8=this;this.stopHeartbeat(),this.heartbeatTimer=setInterval(function(){var e=_this8.getDeviceId();e&&my.sendSocketMessage({data:JSON.stringify({type:"heartbeat",msgId:"heartbeat_"+Date.now(),deviceId:e,timestamp:Date.now()})});},3e4);}},{key:"stopHeartbeat",value:function stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}},{key:"rejectPendingCalls",value:function rejectPendingCalls(e){var _iterator5=_createForOfIteratorHelper(this.pendingCalls),_step5;try{for(_iterator5.s();!(_step5=_iterator5.n()).done;){var _step5$value=_slicedToArray(_step5.value,2),t=_step5$value[0],s=_step5$value[1];s.callback({error:{message:e,msgId:t}});}}catch(err){_iterator5.e(err);}finally{_iterator5.f();}this.pendingCalls.clear();}},{key:"generateMsgId",value:function generateMsgId(){return"msg_"+Date.now()+"_"+ ++this.msgIdCounter;}},{key:"getDeviceId",value:function getDeviceId(){if(this._deviceIdCache)return this._deviceIdCache;var e=this.serverUrl.match(/[?&]deviceId=([^&]+)/);return this._deviceIdCache=e?e[1]:null,this._deviceIdCache;}},{key:"buildWebSocketUrl",value:function buildWebSocketUrl(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var s=this.serverUrl.match(/^(https?:\/\/|wss?:\/\/)([^\\/?]+)(.*)$/);if(!s)return this.serverUrl;var _s=_slicedToArray(s,4),o=_s[1],n=_s[2],u=_s[3],r={},l=u.match(/\?([^#]*)/);l&&l[1].split("&").forEach(function(h){var _h$split=h.split("="),_h$split2=_slicedToArray(_h$split,2),C=_h$split2[0],f=_h$split2[1];C&&(r[C]=f||"");});var c=__spreadValues(__spreadValues({},r),t),a=Object.entries(c).map(function(_ref){var _ref2=_slicedToArray(_ref,2),d=_ref2[0],h=_ref2[1];return"".concat(d,"=").concat(h);}).join("&");return"".concat(o).concat(n).concat(e,"?").concat(a);}},{key:"waitForConnection",value:function waitForConnection(){return this.connectPromise?this.connectPromise:Promise.reject(new Error("\u8FDE\u63A5\u672A\u521D\u59CB\u5316"));}},{key:"destroy",value:function destroy(){this.isConnected=!1,this.isConnecting=!1,this.stopHeartbeat(),my.closeSocket(),this.originalMyCall&&(my.call=this.originalMyCall);var _iterator6=_createForOfIteratorHelper(this.originalNamedApis),_step6;try{for(_iterator6.s();!(_step6=_iterator6.n()).done;){var _step6$value=_slicedToArray(_step6.value,2),e=_step6$value[0],t=_step6$value[1];typeof t=="function"?my[e]=t:delete my[e];}}catch(err){_iterator6.e(err);}finally{_iterator6.f();}this.originalNamedApis.clear(),this.eventListeners.clear(),this.subscribedApis.clear(),this.rejectPendingCalls("\u4EE3\u7406\u5DF2\u9500\u6BC1"),console.log("[MyCallProxy] \uD83D\uDD0C my.call \u4EE3\u7406\u5DF2\u9500\u6BC1");}},{key:"getStatus",value:function getStatus(){return{isConnected:this.isConnected,pending_calls:this.pendingCalls.size,serverUrl:this.serverUrl};}}]);}();module.exports=MyCallProxy;
package/dist/server.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";var require$$0$3=require("events"),require$$1$1=require("https"),require$$2$1=require("http"),require$$3=require("net"),require$$4=require("tls"),require$$1=require("crypto"),require$$0$2=require("stream"),require$$7=require("url"),require$$0=require("zlib"),require$$0$1=require("buffer"),require$$2=require("util"),os=require("os");function getDefaultExportFromCjs(E){return E&&E.__esModule&&Object.prototype.hasOwnProperty.call(E,"default")?E.default:E}var bufferUtil={exports:{}},constants,hasRequiredConstants;function requireConstants(){if(hasRequiredConstants)return constants;hasRequiredConstants=1;const E=["nodebuffer","arraybuffer","fragments"],i=typeof Blob<"u";return i&&E.push("blob"),constants={BINARY_TYPES:E,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:i,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}},constants}var hasRequiredBufferUtil;function requireBufferUtil(){if(hasRequiredBufferUtil)return bufferUtil.exports;hasRequiredBufferUtil=1;const{EMPTY_BUFFER:E}=requireConstants(),i=Buffer[Symbol.species];function l(n,t){if(n.length===0)return E;if(n.length===1)return n[0];const o=Buffer.allocUnsafe(t);let c=0;for(let g=0;g<n.length;g++){const d=n[g];o.set(d,c),c+=d.length}return c<t?new i(o.buffer,o.byteOffset,c):o}function u(n,t,o,c,g){for(let d=0;d<g;d++)o[c+d]=n[d]^t[d&3]}function f(n,t){for(let o=0;o<n.length;o++)n[o]^=t[o&3]}function s(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function e(n){if(e.readOnly=!0,Buffer.isBuffer(n))return n;let t;return n instanceof ArrayBuffer?t=new i(n):ArrayBuffer.isView(n)?t=new i(n.buffer,n.byteOffset,n.byteLength):(t=Buffer.from(n),e.readOnly=!1),t}if(bufferUtil.exports={concat:l,mask:u,toArrayBuffer:s,toBuffer:e,unmask:f},!process.env.WS_NO_BUFFER_UTIL)try{const n=require("bufferutil");bufferUtil.exports.mask=function(t,o,c,g,d){d<48?u(t,o,c,g,d):n.mask(t,o,c,g,d)},bufferUtil.exports.unmask=function(t,o){t.length<32?f(t,o):n.unmask(t,o)}}catch{}return bufferUtil.exports}var limiter,hasRequiredLimiter;function requireLimiter(){if(hasRequiredLimiter)return limiter;hasRequiredLimiter=1;const E=Symbol("kDone"),i=Symbol("kRun");class l{constructor(f){this[E]=()=>{this.pending--,this[i]()},this.concurrency=f||1/0,this.jobs=[],this.pending=0}add(f){this.jobs.push(f),this[i]()}[i](){if(this.pending!==this.concurrency&&this.jobs.length){const f=this.jobs.shift();this.pending++,f(this[E])}}}return limiter=l,limiter}var permessageDeflate,hasRequiredPermessageDeflate;function requirePermessageDeflate(){if(hasRequiredPermessageDeflate)return permessageDeflate;hasRequiredPermessageDeflate=1;const E=require$$0,i=requireBufferUtil(),l=requireLimiter(),{kStatusCode:u}=requireConstants(),f=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),e=Symbol("permessage-deflate"),n=Symbol("total-length"),t=Symbol("callback"),o=Symbol("buffers"),c=Symbol("error");let g;class d{constructor(y){if(this._options=y||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!g){const C=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;g=new l(C)}}static get extensionName(){return"permessage-deflate"}offer(){const y={};return this._options.serverNoContextTakeover&&(y.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(y.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(y.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?y.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(y.client_max_window_bits=!0),y}accept(y){return y=this.normalizeParams(y),this.params=this._isServer?this.acceptAsServer(y):this.acceptAsClient(y),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const y=this._deflate[t];this._deflate.close(),this._deflate=null,y&&y(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(y){const C=this._options,L=y.find(B=>!(C.serverNoContextTakeover===!1&&B.server_no_context_takeover||B.server_max_window_bits&&(C.serverMaxWindowBits===!1||typeof C.serverMaxWindowBits=="number"&&C.serverMaxWindowBits>B.server_max_window_bits)||typeof C.clientMaxWindowBits=="number"&&!B.client_max_window_bits));if(!L)throw new Error("None of the extension offers can be accepted");return C.serverNoContextTakeover&&(L.server_no_context_takeover=!0),C.clientNoContextTakeover&&(L.client_no_context_takeover=!0),typeof C.serverMaxWindowBits=="number"&&(L.server_max_window_bits=C.serverMaxWindowBits),typeof C.clientMaxWindowBits=="number"?L.client_max_window_bits=C.clientMaxWindowBits:(L.client_max_window_bits===!0||C.clientMaxWindowBits===!1)&&delete L.client_max_window_bits,L}acceptAsClient(y){const C=y[0];if(this._options.clientNoContextTakeover===!1&&C.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!C.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(C.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&C.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return C}normalizeParams(y){return y.forEach(C=>{Object.keys(C).forEach(L=>{let B=C[L];if(B.length>1)throw new Error(`Parameter "${L}" must have only a single value`);if(B=B[0],L==="client_max_window_bits"){if(B!==!0){const a=+B;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${L}": ${B}`);B=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${L}": ${B}`)}else if(L==="server_max_window_bits"){const a=+B;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${L}": ${B}`);B=a}else if(L==="client_no_context_takeover"||L==="server_no_context_takeover"){if(B!==!0)throw new TypeError(`Invalid value for parameter "${L}": ${B}`)}else throw new Error(`Unknown parameter "${L}"`);C[L]=B})}),y}decompress(y,C,L){g.add(B=>{this._decompress(y,C,(a,h)=>{B(),L(a,h)})})}compress(y,C,L){g.add(B=>{this._compress(y,C,(a,h)=>{B(),L(a,h)})})}_decompress(y,C,L){const B=this._isServer?"client":"server";if(!this._inflate){const a=`${B}_max_window_bits`,h=typeof this.params[a]!="number"?E.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=E.createInflateRaw({...this._options.zlibInflateOptions,windowBits:h}),this._inflate[e]=this,this._inflate[n]=0,this._inflate[o]=[],this._inflate.on("error",w),this._inflate.on("data",S)}this._inflate[t]=L,this._inflate.write(y),C&&this._inflate.write(s),this._inflate.flush(()=>{const a=this._inflate[c];if(a){this._inflate.close(),this._inflate=null,L(a);return}const h=i.concat(this._inflate[o],this._inflate[n]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[n]=0,this._inflate[o]=[],C&&this.params[`${B}_no_context_takeover`]&&this._inflate.reset()),L(null,h)})}_compress(y,C,L){const B=this._isServer?"server":"client";if(!this._deflate){const a=`${B}_max_window_bits`,h=typeof this.params[a]!="number"?E.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=E.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:h}),this._deflate[n]=0,this._deflate[o]=[],this._deflate.on("data",b)}this._deflate[t]=L,this._deflate.write(y),this._deflate.flush(E.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=i.concat(this._deflate[o],this._deflate[n]);C&&(a=new f(a.buffer,a.byteOffset,a.length-4)),this._deflate[t]=null,this._deflate[n]=0,this._deflate[o]=[],C&&this.params[`${B}_no_context_takeover`]&&this._deflate.reset(),L(null,a)})}}permessageDeflate=d;function b(T){this[o].push(T),this[n]+=T.length}function S(T){if(this[n]+=T.length,this[e]._maxPayload<1||this[n]<=this[e]._maxPayload){this[o].push(T);return}this[c]=new RangeError("Max payload size exceeded"),this[c].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[c][u]=1009,this.removeListener("data",S),this.reset()}function w(T){if(this[e]._inflate=null,this[c]){this[t](this[c]);return}T[u]=1007,this[t](T)}return permessageDeflate}var validation={exports:{}},hasRequiredValidation;function requireValidation(){if(hasRequiredValidation)return validation.exports;hasRequiredValidation=1;const{isUtf8:E}=require$$0$1,{hasBlob:i}=requireConstants(),l=[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];function u(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function f(e){const n=e.length;let t=0;for(;t<n;)if((e[t]&128)===0)t++;else if((e[t]&224)===192){if(t+1===n||(e[t+1]&192)!==128||(e[t]&254)===192)return!1;t+=2}else if((e[t]&240)===224){if(t+2>=n||(e[t+1]&192)!==128||(e[t+2]&192)!==128||e[t]===224&&(e[t+1]&224)===128||e[t]===237&&(e[t+1]&224)===160)return!1;t+=3}else if((e[t]&248)===240){if(t+3>=n||(e[t+1]&192)!==128||(e[t+2]&192)!==128||(e[t+3]&192)!==128||e[t]===240&&(e[t+1]&240)===128||e[t]===244&&e[t+1]>143||e[t]>244)return!1;t+=4}else return!1;return!0}function s(e){return i&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}if(validation.exports={isBlob:s,isValidStatusCode:u,isValidUTF8:f,tokenChars:l},E)validation.exports.isValidUTF8=function(e){return e.length<24?f(e):E(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");validation.exports.isValidUTF8=function(n){return n.length<32?f(n):e(n)}}catch{}return validation.exports}var receiver,hasRequiredReceiver;function requireReceiver(){if(hasRequiredReceiver)return receiver;hasRequiredReceiver=1;const{Writable:E}=require$$0$2,i=requirePermessageDeflate(),{BINARY_TYPES:l,EMPTY_BUFFER:u,kStatusCode:f,kWebSocket:s}=requireConstants(),{concat:e,toArrayBuffer:n,unmask:t}=requireBufferUtil(),{isValidStatusCode:o,isValidUTF8:c}=requireValidation(),g=Buffer[Symbol.species],d=0,b=1,S=2,w=3,T=4,y=5,C=6;class L extends E{constructor(a={}){super(),this._allowSynchronousEvents=a.allowSynchronousEvents!==void 0?a.allowSynchronousEvents:!0,this._binaryType=a.binaryType||l[0],this._extensions=a.extensions||{},this._isServer=!!a.isServer,this._maxBufferedChunks=a.maxBufferedChunks|0,this._maxFragments=a.maxFragments|0,this._maxPayload=a.maxPayload|0,this._skipUTF8Validation=!!a.skipUTF8Validation,this[s]=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._errored=!1,this._loop=!1,this._state=d}_write(a,h,r){if(this._opcode===8&&this._state==d)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=a.length,this._buffers.push(a),this.startLoop(r)}consume(a){if(this._bufferedBytes-=a,a===this._buffers[0].length)return this._buffers.shift();if(a<this._buffers[0].length){const r=this._buffers[0];return this._buffers[0]=new g(r.buffer,r.byteOffset+a,r.length-a),new g(r.buffer,r.byteOffset,a)}const h=Buffer.allocUnsafe(a);do{const r=this._buffers[0],_=h.length-a;a>=r.length?h.set(this._buffers.shift(),_):(h.set(new Uint8Array(r.buffer,r.byteOffset,a),_),this._buffers[0]=new g(r.buffer,r.byteOffset+a,r.length-a)),a-=r.length}while(a>0);return h}startLoop(a){this._loop=!0;do switch(this._state){case d:this.getInfo(a);break;case b:this.getPayloadLength16(a);break;case S:this.getPayloadLength64(a);break;case w:this.getMask();break;case T:this.getData(a);break;case y:case C:this._loop=!1;return}while(this._loop);this._errored||a()}getInfo(a){if(this._bufferedBytes<2){this._loop=!1;return}const h=this.consume(2);if((h[0]&48)!==0){const _=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");a(_);return}const r=(h[0]&64)===64;if(r&&!this._extensions[i.extensionName]){const _=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");a(_);return}if(this._fin=(h[0]&128)===128,this._opcode=h[0]&15,this._payloadLength=h[1]&127,this._opcode===0){if(r){const _=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");a(_);return}if(!this._fragmented){const _=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");a(_);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const _=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");a(_);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const _=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");a(_);return}if(r){const _=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");a(_);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const _=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");a(_);return}}else{const _=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");a(_);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(h[1]&128)===128,this._isServer){if(!this._masked){const _=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");a(_);return}}else if(this._masked){const _=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");a(_);return}this._payloadLength===126?this._state=b:this._payloadLength===127?this._state=S:this.haveLength(a)}getPayloadLength16(a){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(a)}getPayloadLength64(a){if(this._bufferedBytes<8){this._loop=!1;return}const h=this.consume(8),r=h.readUInt32BE(0);if(r>Math.pow(2,21)-1){const _=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");a(_);return}this._payloadLength=r*Math.pow(2,32)+h.readUInt32BE(4),this.haveLength(a)}haveLength(a){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){const h=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");a(h);return}this._masked?this._state=w:this._state=T}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=T}getData(a){let h=u;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}h=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&t(h,this._mask)}if(this._opcode>7){this.controlMessage(h,a);return}if(this._compressed){this._state=y,this.decompress(h,a);return}if(h.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){const r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");a(r);return}this._messageLength=this._totalPayloadLength,this._fragments.push(h)}this.dataMessage(a)}decompress(a,h){this._extensions[i.extensionName].decompress(a,this._fin,(_,x)=>{if(_)return h(_);if(x.length){if(this._messageLength+=x.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const v=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");h(v);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){const v=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");h(v);return}this._fragments.push(x)}this.dataMessage(h),this._state===d&&this.startLoop(h)})}dataMessage(a){if(!this._fin){this._state=d;return}const h=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let _;this._binaryType==="nodebuffer"?_=e(r,h):this._binaryType==="arraybuffer"?_=n(e(r,h)):this._binaryType==="blob"?_=new Blob(r):_=r,this._allowSynchronousEvents?(this.emit("message",_,!0),this._state=d):(this._state=C,setImmediate(()=>{this.emit("message",_,!0),this._state=d,this.startLoop(a)}))}else{const _=e(r,h);if(!this._skipUTF8Validation&&!c(_)){const x=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");a(x);return}this._state===y||this._allowSynchronousEvents?(this.emit("message",_,!1),this._state=d):(this._state=C,setImmediate(()=>{this.emit("message",_,!1),this._state=d,this.startLoop(a)}))}}controlMessage(a,h){if(this._opcode===8){if(a.length===0)this._loop=!1,this.emit("conclude",1005,u),this.end();else{const r=a.readUInt16BE(0);if(!o(r)){const x=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");h(x);return}const _=new g(a.buffer,a.byteOffset+2,a.length-2);if(!this._skipUTF8Validation&&!c(_)){const x=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");h(x);return}this._loop=!1,this.emit("conclude",r,_),this.end()}this._state=d;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",a),this._state=d):(this._state=C,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",a),this._state=d,this.startLoop(h)}))}createError(a,h,r,_,x){this._loop=!1,this._errored=!0;const v=new a(r?`Invalid WebSocket frame: ${h}`:h);return Error.captureStackTrace(v,this.createError),v.code=x,v[f]=_,v}}return receiver=L,receiver}var sender,hasRequiredSender;function requireSender(){if(hasRequiredSender)return sender;hasRequiredSender=1;const{Duplex:E}=require$$0$2,{randomFillSync:i}=require$$1,{types:{isUint8Array:l}}=require$$2,u=requirePermessageDeflate(),{EMPTY_BUFFER:f,kWebSocket:s,NOOP:e}=requireConstants(),{isBlob:n,isValidStatusCode:t}=requireValidation(),{mask:o,toBuffer:c}=requireBufferUtil(),g=Symbol("kByteLength"),d=Buffer.alloc(4),b=8*1024;let S,w=b;const T=0,y=1,C=2;class L{constructor(r,_,x){this._extensions=_||{},x&&(this._generateMask=x,this._maskBuffer=Buffer.alloc(4)),this._socket=r,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=T,this.onerror=e,this[s]=void 0}static frame(r,_){let x,v=!1,R=2,A=!1;_.mask&&(x=_.maskBuffer||d,_.generateMask?_.generateMask(x):(w===b&&(S===void 0&&(S=Buffer.alloc(b)),i(S,0,b),w=0),x[0]=S[w++],x[1]=S[w++],x[2]=S[w++],x[3]=S[w++]),A=(x[0]|x[1]|x[2]|x[3])===0,R=6);let N;typeof r=="string"?(!_.mask||A)&&_[g]!==void 0?N=_[g]:(r=Buffer.from(r),N=r.length):(N=r.length,v=_.mask&&_.readOnly&&!A);let k=N;N>=65536?(R+=8,k=127):N>125&&(R+=2,k=126);const M=Buffer.allocUnsafe(v?N+R:R);return M[0]=_.fin?_.opcode|128:_.opcode,_.rsv1&&(M[0]|=64),M[1]=k,k===126?M.writeUInt16BE(N,2):k===127&&(M[2]=M[3]=0,M.writeUIntBE(N,4,6)),_.mask?(M[1]|=128,M[R-4]=x[0],M[R-3]=x[1],M[R-2]=x[2],M[R-1]=x[3],A?[M,r]:v?(o(r,x,M,R,N),[M]):(o(r,x,r,0,N),[M,r])):[M,r]}close(r,_,x,v){let R;if(r===void 0)R=f;else{if(typeof r!="number"||!t(r))throw new TypeError("First argument must be a valid error code number");if(_===void 0||!_.length)R=Buffer.allocUnsafe(2),R.writeUInt16BE(r,0);else{const N=Buffer.byteLength(_);if(N>123)throw new RangeError("The message must not be greater than 123 bytes");if(R=Buffer.allocUnsafe(2+N),R.writeUInt16BE(r,0),typeof _=="string")R.write(_,2);else if(l(_))R.set(_,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}const A={[g]:R.length,fin:!0,generateMask:this._generateMask,mask:x,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==T?this.enqueue([this.dispatch,R,!1,A,v]):this.sendFrame(L.frame(R,A),v)}ping(r,_,x){let v,R;if(typeof r=="string"?(v=Buffer.byteLength(r),R=!1):n(r)?(v=r.size,R=!1):(r=c(r),v=r.length,R=c.readOnly),v>125)throw new RangeError("The data size must not be greater than 125 bytes");const A={[g]:v,fin:!0,generateMask:this._generateMask,mask:_,maskBuffer:this._maskBuffer,opcode:9,readOnly:R,rsv1:!1};n(r)?this._state!==T?this.enqueue([this.getBlobData,r,!1,A,x]):this.getBlobData(r,!1,A,x):this._state!==T?this.enqueue([this.dispatch,r,!1,A,x]):this.sendFrame(L.frame(r,A),x)}pong(r,_,x){let v,R;if(typeof r=="string"?(v=Buffer.byteLength(r),R=!1):n(r)?(v=r.size,R=!1):(r=c(r),v=r.length,R=c.readOnly),v>125)throw new RangeError("The data size must not be greater than 125 bytes");const A={[g]:v,fin:!0,generateMask:this._generateMask,mask:_,maskBuffer:this._maskBuffer,opcode:10,readOnly:R,rsv1:!1};n(r)?this._state!==T?this.enqueue([this.getBlobData,r,!1,A,x]):this.getBlobData(r,!1,A,x):this._state!==T?this.enqueue([this.dispatch,r,!1,A,x]):this.sendFrame(L.frame(r,A),x)}send(r,_,x){const v=this._extensions[u.extensionName];let R=_.binary?2:1,A=_.compress,N,k;typeof r=="string"?(N=Buffer.byteLength(r),k=!1):n(r)?(N=r.size,k=!1):(r=c(r),N=r.length,k=c.readOnly),this._firstFragment?(this._firstFragment=!1,A&&v&&v.params[v._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(A=N>=v._threshold),this._compress=A):(A=!1,R=0),_.fin&&(this._firstFragment=!0);const M={[g]:N,fin:_.fin,generateMask:this._generateMask,mask:_.mask,maskBuffer:this._maskBuffer,opcode:R,readOnly:k,rsv1:A};n(r)?this._state!==T?this.enqueue([this.getBlobData,r,this._compress,M,x]):this.getBlobData(r,this._compress,M,x):this._state!==T?this.enqueue([this.dispatch,r,this._compress,M,x]):this.dispatch(r,this._compress,M,x)}getBlobData(r,_,x,v){this._bufferedBytes+=x[g],this._state=C,r.arrayBuffer().then(R=>{if(this._socket.destroyed){const N=new Error("The socket was closed while the blob was being read");process.nextTick(B,this,N,v);return}this._bufferedBytes-=x[g];const A=c(R);_?this.dispatch(A,_,x,v):(this._state=T,this.sendFrame(L.frame(A,x),v),this.dequeue())}).catch(R=>{process.nextTick(a,this,R,v)})}dispatch(r,_,x,v){if(!_){this.sendFrame(L.frame(r,x),v);return}const R=this._extensions[u.extensionName];this._bufferedBytes+=x[g],this._state=y,R.compress(r,x.fin,(A,N)=>{if(this._socket.destroyed){const k=new Error("The socket was closed while data was being compressed");B(this,k,v);return}this._bufferedBytes-=x[g],this._state=T,x.readOnly=!1,this.sendFrame(L.frame(N,x),v),this.dequeue()})}dequeue(){for(;this._state===T&&this._queue.length;){const r=this._queue.shift();this._bufferedBytes-=r[3][g],Reflect.apply(r[0],this,r.slice(1))}}enqueue(r){this._bufferedBytes+=r[3][g],this._queue.push(r)}sendFrame(r,_){r.length===2?(this._socket.cork(),this._socket.write(r[0]),this._socket.write(r[1],_),this._socket.uncork()):this._socket.write(r[0],_)}}sender=L;function B(h,r,_){typeof _=="function"&&_(r);for(let x=0;x<h._queue.length;x++){const v=h._queue[x],R=v[v.length-1];typeof R=="function"&&R(r)}}function a(h,r,_){B(h,r,_),h.onerror(r)}return sender}var eventTarget,hasRequiredEventTarget;function requireEventTarget(){if(hasRequiredEventTarget)return eventTarget;hasRequiredEventTarget=1;const{kForOnEventAttribute:E,kListener:i}=requireConstants(),l=Symbol("kCode"),u=Symbol("kData"),f=Symbol("kError"),s=Symbol("kMessage"),e=Symbol("kReason"),n=Symbol("kTarget"),t=Symbol("kType"),o=Symbol("kWasClean");class c{constructor(y){this[n]=null,this[t]=y}get target(){return this[n]}get type(){return this[t]}}Object.defineProperty(c.prototype,"target",{enumerable:!0}),Object.defineProperty(c.prototype,"type",{enumerable:!0});class g extends c{constructor(y,C={}){super(y),this[l]=C.code===void 0?0:C.code,this[e]=C.reason===void 0?"":C.reason,this[o]=C.wasClean===void 0?!1:C.wasClean}get code(){return this[l]}get reason(){return this[e]}get wasClean(){return this[o]}}Object.defineProperty(g.prototype,"code",{enumerable:!0}),Object.defineProperty(g.prototype,"reason",{enumerable:!0}),Object.defineProperty(g.prototype,"wasClean",{enumerable:!0});class d extends c{constructor(y,C={}){super(y),this[f]=C.error===void 0?null:C.error,this[s]=C.message===void 0?"":C.message}get error(){return this[f]}get message(){return this[s]}}Object.defineProperty(d.prototype,"error",{enumerable:!0}),Object.defineProperty(d.prototype,"message",{enumerable:!0});class b extends c{constructor(y,C={}){super(y),this[u]=C.data===void 0?null:C.data}get data(){return this[u]}}Object.defineProperty(b.prototype,"data",{enumerable:!0}),eventTarget={CloseEvent:g,ErrorEvent:d,Event:c,EventTarget:{addEventListener(T,y,C={}){for(const B of this.listeners(T))if(!C[E]&&B[i]===y&&!B[E])return;let L;if(T==="message")L=function(a,h){const r=new b("message",{data:h?a:a.toString()});r[n]=this,w(y,this,r)};else if(T==="close")L=function(a,h){const r=new g("close",{code:a,reason:h.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[n]=this,w(y,this,r)};else if(T==="error")L=function(a){const h=new d("error",{error:a,message:a.message});h[n]=this,w(y,this,h)};else if(T==="open")L=function(){const a=new c("open");a[n]=this,w(y,this,a)};else return;L[E]=!!C[E],L[i]=y,C.once?this.once(T,L):this.on(T,L)},removeEventListener(T,y){for(const C of this.listeners(T))if(C[i]===y&&!C[E]){this.removeListener(T,C);break}}},MessageEvent:b};function w(T,y,C){typeof T=="object"&&T.handleEvent?T.handleEvent.call(T,C):T.call(y,C)}return eventTarget}var extension,hasRequiredExtension;function requireExtension(){if(hasRequiredExtension)return extension;hasRequiredExtension=1;const{tokenChars:E}=requireValidation();function i(f,s,e){f[s]===void 0?f[s]=[e]:f[s].push(e)}function l(f){const s=Object.create(null);let e=Object.create(null),n=!1,t=!1,o=!1,c,g,d=-1,b=-1,S=-1,w=0;for(;w<f.length;w++)if(b=f.charCodeAt(w),c===void 0)if(S===-1&&E[b]===1)d===-1&&(d=w);else if(w!==0&&(b===32||b===9))S===-1&&d!==-1&&(S=w);else if(b===59||b===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${w}`);S===-1&&(S=w);const y=f.slice(d,S);b===44?(i(s,y,e),e=Object.create(null)):c=y,d=S=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(g===void 0)if(S===-1&&E[b]===1)d===-1&&(d=w);else if(b===32||b===9)S===-1&&d!==-1&&(S=w);else if(b===59||b===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${w}`);S===-1&&(S=w),i(e,f.slice(d,S),!0),b===44&&(i(s,c,e),e=Object.create(null),c=void 0),d=S=-1}else if(b===61&&d!==-1&&S===-1)g=f.slice(d,w),d=S=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(t){if(E[b]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);d===-1?d=w:n||(n=!0),t=!1}else if(o)if(E[b]===1)d===-1&&(d=w);else if(b===34&&d!==-1)o=!1,S=w;else if(b===92)t=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(b===34&&f.charCodeAt(w-1)===61)o=!0;else if(S===-1&&E[b]===1)d===-1&&(d=w);else if(d!==-1&&(b===32||b===9))S===-1&&(S=w);else if(b===59||b===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${w}`);S===-1&&(S=w);let y=f.slice(d,S);n&&(y=y.replace(/\\/g,""),n=!1),i(e,g,y),b===44&&(i(s,c,e),e=Object.create(null),c=void 0),g=void 0,d=S=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(d===-1||o||b===32||b===9)throw new SyntaxError("Unexpected end of input");S===-1&&(S=w);const T=f.slice(d,S);return c===void 0?i(s,T,e):(g===void 0?i(e,T,!0):n?i(e,g,T.replace(/\\/g,"")):i(e,g,T),i(s,c,e)),s}function u(f){return Object.keys(f).map(s=>{let e=f[s];return Array.isArray(e)||(e=[e]),e.map(n=>[s].concat(Object.keys(n).map(t=>{let o=n[t];return Array.isArray(o)||(o=[o]),o.map(c=>c===!0?t:`${t}=${c}`).join("; ")})).join("; ")).join(", ")}).join(", ")}return extension={format:u,parse:l},extension}var websocket,hasRequiredWebsocket;function requireWebsocket(){if(hasRequiredWebsocket)return websocket;hasRequiredWebsocket=1;const E=require$$0$3,i=require$$1$1,l=require$$2$1,u=require$$3,f=require$$4,{randomBytes:s,createHash:e}=require$$1,{Duplex:n,Readable:t}=require$$0$2,{URL:o}=require$$7,c=requirePermessageDeflate(),g=requireReceiver(),d=requireSender(),{isBlob:b}=requireValidation(),{BINARY_TYPES:S,CLOSE_TIMEOUT:w,EMPTY_BUFFER:T,GUID:y,kForOnEventAttribute:C,kListener:L,kStatusCode:B,kWebSocket:a,NOOP:h}=requireConstants(),{EventTarget:{addEventListener:r,removeEventListener:_}}=requireEventTarget(),{format:x,parse:v}=requireExtension(),{toBuffer:R}=requireBufferUtil(),A=Symbol("kAborted"),N=[8,13],k=["CONNECTING","OPEN","CLOSING","CLOSED"],M=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class P extends E{constructor(p,D,I){super(),this._binaryType=S[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=T,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=P.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,p!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,D===void 0?D=[]:Array.isArray(D)||(typeof D=="object"&&D!==null?(I=D,D=[]):D=[D]),W(this,p,D,I)):(this._autoPong=I.autoPong,this._closeTimeout=I.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(p){S.includes(p)&&(this._binaryType=p,this._receiver&&(this._receiver._binaryType=p))}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(p,D,I){const O=new g({allowSynchronousEvents:I.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:I.maxBufferedChunks,maxFragments:I.maxFragments,maxPayload:I.maxPayload,skipUTF8Validation:I.skipUTF8Validation}),U=new d(p,this._extensions,I.generateMask);this._receiver=O,this._sender=U,this._socket=p,O[a]=this,U[a]=this,p[a]=this,O.on("conclude",ve),O.on("drain",Ee),O.on("error",ye),O.on("message",Se),O.on("ping",xe),O.on("pong",be),U.onerror=we,p.setTimeout&&p.setTimeout(0),p.setNoDelay&&p.setNoDelay(),D.length>0&&p.unshift(D),p.on("close",fe),p.on("data",te),p.on("end",le),p.on("error",he),this._readyState=P.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=P.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[c.extensionName]&&this._extensions[c.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=P.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(p,D){if(this.readyState!==P.CLOSED){if(this.readyState===P.CONNECTING){G(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===P.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=P.CLOSING,this._sender.close(p,D,!this._isServer,I=>{I||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ue(this)}}pause(){this.readyState===P.CONNECTING||this.readyState===P.CLOSED||(this._paused=!0,this._socket.pause())}ping(p,D,I){if(this.readyState===P.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof p=="function"?(I=p,p=D=void 0):typeof D=="function"&&(I=D,D=void 0),typeof p=="number"&&(p=p.toString()),this.readyState!==P.OPEN){se(this,p,I);return}D===void 0&&(D=!this._isServer),this._sender.ping(p||T,D,I)}pong(p,D,I){if(this.readyState===P.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof p=="function"?(I=p,p=D=void 0):typeof D=="function"&&(I=D,D=void 0),typeof p=="number"&&(p=p.toString()),this.readyState!==P.OPEN){se(this,p,I);return}D===void 0&&(D=!this._isServer),this._sender.pong(p||T,D,I)}resume(){this.readyState===P.CONNECTING||this.readyState===P.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(p,D,I){if(this.readyState===P.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof D=="function"&&(I=D,D={}),typeof p=="number"&&(p=p.toString()),this.readyState!==P.OPEN){se(this,p,I);return}const O={binary:typeof p!="string",mask:!this._isServer,compress:!0,fin:!0,...D};this._extensions[c.extensionName]||(O.compress=!1),this._sender.send(p||T,O,I)}terminate(){if(this.readyState!==P.CLOSED){if(this.readyState===P.CONNECTING){G(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=P.CLOSING,this._socket.destroy())}}}Object.defineProperty(P,"CONNECTING",{enumerable:!0,value:k.indexOf("CONNECTING")}),Object.defineProperty(P.prototype,"CONNECTING",{enumerable:!0,value:k.indexOf("CONNECTING")}),Object.defineProperty(P,"OPEN",{enumerable:!0,value:k.indexOf("OPEN")}),Object.defineProperty(P.prototype,"OPEN",{enumerable:!0,value:k.indexOf("OPEN")}),Object.defineProperty(P,"CLOSING",{enumerable:!0,value:k.indexOf("CLOSING")}),Object.defineProperty(P.prototype,"CLOSING",{enumerable:!0,value:k.indexOf("CLOSING")}),Object.defineProperty(P,"CLOSED",{enumerable:!0,value:k.indexOf("CLOSED")}),Object.defineProperty(P.prototype,"CLOSED",{enumerable:!0,value:k.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(m=>{Object.defineProperty(P.prototype,m,{enumerable:!0})}),["open","error","close","message"].forEach(m=>{Object.defineProperty(P.prototype,`on${m}`,{enumerable:!0,get(){for(const p of this.listeners(m))if(p[C])return p[L];return null},set(p){for(const D of this.listeners(m))if(D[C]){this.removeListener(m,D);break}typeof p=="function"&&this.addEventListener(m,p,{[C]:!0})}})}),P.prototype.addEventListener=r,P.prototype.removeEventListener=_,websocket=P;function W(m,p,D,I){const O={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:w,protocolVersion:N[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...I,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(m._autoPong=O.autoPong,m._closeTimeout=O.closeTimeout,!N.includes(O.protocolVersion))throw new RangeError(`Unsupported protocol version: ${O.protocolVersion} (supported versions: ${N.join(", ")})`);let U;if(p instanceof o)U=p;else try{U=new o(p)}catch{throw new SyntaxError(`Invalid URL: ${p}`)}U.protocol==="http:"?U.protocol="ws:":U.protocol==="https:"&&(U.protocol="wss:"),m._url=U.href;const V=U.protocol==="wss:",Q=U.protocol==="ws+unix:";let z;if(U.protocol!=="ws:"&&!V&&!Q?z=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:Q&&!U.pathname?z="The URL's pathname is empty":U.hash&&(z="The URL contains a fragment identifier"),z){const F=new SyntaxError(z);if(m._redirects===0)throw F;H(m,F);return}const ce=V?443:80,de=s(16).toString("base64"),_e=V?i.request:l.request,Y=new Set;let X;if(O.createConnection=O.createConnection||(V?re:ee),O.defaultPort=O.defaultPort||ce,O.port=U.port||ce,O.host=U.hostname.startsWith("[")?U.hostname.slice(1,-1):U.hostname,O.headers={...O.headers,"Sec-WebSocket-Version":O.protocolVersion,"Sec-WebSocket-Key":de,Connection:"Upgrade",Upgrade:"websocket"},O.path=U.pathname+U.search,O.timeout=O.handshakeTimeout,O.perMessageDeflate&&(X=new c({...O.perMessageDeflate,isServer:!1,maxPayload:O.maxPayload}),O.headers["Sec-WebSocket-Extensions"]=x({[c.extensionName]:X.offer()})),D.length){for(const F of D){if(typeof F!="string"||!M.test(F)||Y.has(F))throw new SyntaxError("An invalid or duplicated subprotocol was specified");Y.add(F)}O.headers["Sec-WebSocket-Protocol"]=D.join(",")}if(O.origin&&(O.protocolVersion<13?O.headers["Sec-WebSocket-Origin"]=O.origin:O.headers.Origin=O.origin),(U.username||U.password)&&(O.auth=`${U.username}:${U.password}`),Q){const F=O.path.split(":");O.socketPath=F[0],O.path=F[1]}let $;if(O.followRedirects){if(m._redirects===0){m._originalIpc=Q,m._originalSecure=V,m._originalHostOrSocketPath=Q?O.socketPath:U.host;const F=I&&I.headers;if(I={...I,headers:{}},F)for(const[q,j]of Object.entries(F))I.headers[q.toLowerCase()]=j}else if(m.listenerCount("redirect")===0){const F=Q?m._originalIpc?O.socketPath===m._originalHostOrSocketPath:!1:m._originalIpc?!1:U.host===m._originalHostOrSocketPath;(!F||m._originalSecure&&!V)&&(delete O.headers.authorization,delete O.headers.cookie,F||delete O.headers.host,O.auth=void 0)}O.auth&&!I.headers.authorization&&(I.headers.authorization="Basic "+Buffer.from(O.auth).toString("base64")),$=m._req=_e(O),m._redirects&&m.emit("redirect",m.url,$)}else $=m._req=_e(O);O.timeout&&$.on("timeout",()=>{G(m,$,"Opening handshake has timed out")}),$.on("error",F=>{$===null||$[A]||($=m._req=null,H(m,F))}),$.on("response",F=>{const q=F.headers.location,j=F.statusCode;if(q&&O.followRedirects&&j>=300&&j<400){if(++m._redirects>O.maxRedirects){G(m,$,"Maximum redirects exceeded");return}$.abort();let J;try{J=new o(q,p)}catch{const K=new SyntaxError(`Invalid URL: ${q}`);H(m,K);return}W(m,J,D,I)}else m.emit("unexpected-response",$,F)||G(m,$,`Unexpected server response: ${F.statusCode}`)}),$.on("upgrade",(F,q,j)=>{if(m.emit("upgrade",F),m.readyState!==P.CONNECTING)return;$=m._req=null;const J=F.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){G(m,q,"Invalid Upgrade header");return}const me=e("sha1").update(de+y).digest("base64");if(F.headers["sec-websocket-accept"]!==me){G(m,q,"Invalid Sec-WebSocket-Accept header");return}const K=F.headers["sec-websocket-protocol"];let Z;if(K!==void 0?Y.size?Y.has(K)||(Z="Server sent an invalid subprotocol"):Z="Server sent a subprotocol but none was requested":Y.size&&(Z="Server sent no subprotocol"),Z){G(m,q,Z);return}K&&(m._protocol=K);const ge=F.headers["sec-websocket-extensions"];if(ge!==void 0){if(!X){G(m,q,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ie;try{ie=v(ge)}catch{G(m,q,"Invalid Sec-WebSocket-Extensions header");return}const pe=Object.keys(ie);if(pe.length!==1||pe[0]!==c.extensionName){G(m,q,"Server indicated an extension that was not requested");return}try{X.accept(ie[c.extensionName])}catch{G(m,q,"Invalid Sec-WebSocket-Extensions header");return}m._extensions[c.extensionName]=X}m.setSocket(q,j,{allowSynchronousEvents:O.allowSynchronousEvents,generateMask:O.generateMask,maxBufferedChunks:O.maxBufferedChunks,maxFragments:O.maxFragments,maxPayload:O.maxPayload,skipUTF8Validation:O.skipUTF8Validation})}),O.finishRequest?O.finishRequest($,m):$.end()}function H(m,p){m._readyState=P.CLOSING,m._errorEmitted=!0,m.emit("error",p),m.emitClose()}function ee(m){return m.path=m.socketPath,u.connect(m)}function re(m){return m.path=void 0,!m.servername&&m.servername!==""&&(m.servername=u.isIP(m.host)?"":m.host),f.connect(m)}function G(m,p,D){m._readyState=P.CLOSING;const I=new Error(D);Error.captureStackTrace(I,G),p.setHeader?(p[A]=!0,p.abort(),p.socket&&!p.socket.destroyed&&p.socket.destroy(),process.nextTick(H,m,I)):(p.destroy(I),p.once("error",m.emit.bind(m,"error")),p.once("close",m.emitClose.bind(m)))}function se(m,p,D){if(p){const I=b(p)?p.size:R(p).length;m._socket?m._sender._bufferedBytes+=I:m._bufferedAmount+=I}if(D){const I=new Error(`WebSocket is not open: readyState ${m.readyState} (${k[m.readyState]})`);process.nextTick(D,I)}}function ve(m,p){const D=this[a];D._closeFrameReceived=!0,D._closeMessage=p,D._closeCode=m,D._socket[a]!==void 0&&(D._socket.removeListener("data",te),process.nextTick(ae,D._socket),m===1005?D.close():D.close(m,p))}function Ee(){const m=this[a];m.isPaused||m._socket.resume()}function ye(m){const p=this[a];p._socket[a]!==void 0&&(p._socket.removeListener("data",te),process.nextTick(ae,p._socket),p.close(m[B])),p._errorEmitted||(p._errorEmitted=!0,p.emit("error",m))}function oe(){this[a].emitClose()}function Se(m,p){this[a].emit("message",m,p)}function xe(m){const p=this[a];p._autoPong&&p.pong(m,!this._isServer,h),p.emit("ping",m)}function be(m){this[a].emit("pong",m)}function ae(m){m.resume()}function we(m){const p=this[a];p.readyState!==P.CLOSED&&(p.readyState===P.OPEN&&(p._readyState=P.CLOSING,ue(p)),this._socket.end(),p._errorEmitted||(p._errorEmitted=!0,p.emit("error",m)))}function ue(m){m._closeTimer=setTimeout(m._socket.destroy.bind(m._socket),m._closeTimeout)}function fe(){const m=this[a];if(this.removeListener("close",fe),this.removeListener("data",te),this.removeListener("end",le),m._readyState=P.CLOSING,!this._readableState.endEmitted&&!m._closeFrameReceived&&!m._receiver._writableState.errorEmitted&&this._readableState.length!==0){const p=this.read(this._readableState.length);m._receiver.write(p)}m._receiver.end(),this[a]=void 0,clearTimeout(m._closeTimer),m._receiver._writableState.finished||m._receiver._writableState.errorEmitted?m.emitClose():(m._receiver.on("error",oe),m._receiver.on("finish",oe))}function te(m){this[a]._receiver.write(m)||this.pause()}function le(){const m=this[a];m._readyState=P.CLOSING,m._receiver.end(),this.end()}function he(){const m=this[a];this.removeListener("error",he),this.on("error",h),m&&(m._readyState=P.CLOSING,this.destroy())}return websocket}var stream,hasRequiredStream;function requireStream(){if(hasRequiredStream)return stream;hasRequiredStream=1,requireWebsocket();const{Duplex:E}=require$$0$2;function i(s){s.emit("close")}function l(){!this.destroyed&&this._writableState.finished&&this.destroy()}function u(s){this.removeListener("error",u),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}function f(s,e){let n=!0;const t=new E({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return s.on("message",function(c,g){const d=!g&&t._readableState.objectMode?c.toString():c;t.push(d)||s.pause()}),s.once("error",function(c){t.destroyed||(n=!1,t.destroy(c))}),s.once("close",function(){t.destroyed||t.push(null)}),t._destroy=function(o,c){if(s.readyState===s.CLOSED){c(o),process.nextTick(i,t);return}let g=!1;s.once("error",function(b){g=!0,c(b)}),s.once("close",function(){g||c(o),process.nextTick(i,t)}),n&&s.terminate()},t._final=function(o){if(s.readyState===s.CONNECTING){s.once("open",function(){t._final(o)});return}s._socket!==null&&(s._socket._writableState.finished?(o(),t._readableState.endEmitted&&t.destroy()):(s._socket.once("finish",function(){o()}),s.close()))},t._read=function(){s.isPaused&&s.resume()},t._write=function(o,c,g){if(s.readyState===s.CONNECTING){s.once("open",function(){t._write(o,c,g)});return}s.send(o,g)},t.on("end",l),t.on("error",u),t}return stream=f,stream}requireStream(),requireExtension(),requirePermessageDeflate(),requireReceiver(),requireSender();var subprotocol,hasRequiredSubprotocol;function requireSubprotocol(){if(hasRequiredSubprotocol)return subprotocol;hasRequiredSubprotocol=1;const{tokenChars:E}=requireValidation();function i(l){const u=new Set;let f=-1,s=-1,e=0;for(e;e<l.length;e++){const t=l.charCodeAt(e);if(s===-1&&E[t]===1)f===-1&&(f=e);else if(e!==0&&(t===32||t===9))s===-1&&f!==-1&&(s=e);else if(t===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${e}`);s===-1&&(s=e);const o=l.slice(f,s);if(u.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);u.add(o),f=s=-1}else throw new SyntaxError(`Unexpected character at index ${e}`)}if(f===-1||s!==-1)throw new SyntaxError("Unexpected end of input");const n=l.slice(f,e);if(u.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return u.add(n),u}return subprotocol={parse:i},subprotocol}requireSubprotocol(),requireWebsocket();var websocketServer,hasRequiredWebsocketServer;function requireWebsocketServer(){if(hasRequiredWebsocketServer)return websocketServer;hasRequiredWebsocketServer=1;const E=require$$0$3,i=require$$2$1,{Duplex:l}=require$$0$2,{createHash:u}=require$$1,f=requireExtension(),s=requirePermessageDeflate(),e=requireSubprotocol(),n=requireWebsocket(),{CLOSE_TIMEOUT:t,GUID:o,kWebSocket:c}=requireConstants(),g=/^[+/0-9A-Za-z]{22}==$/,d=0,b=1,S=2;class w extends E{constructor(h,r){if(super(),h={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:t,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:n,...h},h.port==null&&!h.server&&!h.noServer||h.port!=null&&(h.server||h.noServer)||h.server&&h.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(h.port!=null?(this._server=i.createServer((_,x)=>{const v=i.STATUS_CODES[426];x.writeHead(426,{"Content-Length":v.length,"Content-Type":"text/plain"}),x.end(v)}),this._server.listen(h.port,h.host,h.backlog,r)):h.server&&(this._server=h.server),this._server){const _=this.emit.bind(this,"connection");this._removeListeners=T(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(x,v,R)=>{this.handleUpgrade(x,v,R,_)}})}h.perMessageDeflate===!0&&(h.perMessageDeflate={}),h.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=h,this._state=d}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(h){if(this._state===S){h&&this.once("close",()=>{h(new Error("The server is not running"))}),process.nextTick(y,this);return}if(h&&this.once("close",h),this._state!==b)if(this._state=b,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(y,this):process.nextTick(y,this);else{const r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{y(this)})}}shouldHandle(h){if(this.options.path){const r=h.url.indexOf("?");if((r!==-1?h.url.slice(0,r):h.url)!==this.options.path)return!1}return!0}handleUpgrade(h,r,_,x){r.on("error",C);const v=h.headers["sec-websocket-key"],R=h.headers.upgrade,A=+h.headers["sec-websocket-version"];if(h.method!=="GET"){B(this,h,r,405,"Invalid HTTP method");return}if(R===void 0||R.toLowerCase()!=="websocket"){B(this,h,r,400,"Invalid Upgrade header");return}if(v===void 0||!g.test(v)){B(this,h,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(A!==13&&A!==8){B(this,h,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(h)){L(r,400);return}const N=h.headers["sec-websocket-protocol"];let k=new Set;if(N!==void 0)try{k=e.parse(N)}catch{B(this,h,r,400,"Invalid Sec-WebSocket-Protocol header");return}const M=h.headers["sec-websocket-extensions"],P={};if(this.options.perMessageDeflate&&M!==void 0){const W=new s({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{const H=f.parse(M);H[s.extensionName]&&(W.accept(H[s.extensionName]),P[s.extensionName]=W)}catch{B(this,h,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){const W={origin:h.headers[`${A===8?"sec-websocket-origin":"origin"}`],secure:!!(h.socket.authorized||h.socket.encrypted),req:h};if(this.options.verifyClient.length===2){this.options.verifyClient(W,(H,ee,re,G)=>{if(!H)return L(r,ee||401,re,G);this.completeUpgrade(P,v,k,h,r,_,x)});return}if(!this.options.verifyClient(W))return L(r,401)}this.completeUpgrade(P,v,k,h,r,_,x)}completeUpgrade(h,r,_,x,v,R,A){if(!v.readable||!v.writable)return v.destroy();if(v[c])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>d)return L(v,503);const k=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${u("sha1").update(r+o).digest("base64")}`],M=new this.options.WebSocket(null,void 0,this.options);if(_.size){const P=this.options.handleProtocols?this.options.handleProtocols(_,x):_.values().next().value;P&&(k.push(`Sec-WebSocket-Protocol: ${P}`),M._protocol=P)}if(h[s.extensionName]){const P=h[s.extensionName].params,W=f.format({[s.extensionName]:[P]});k.push(`Sec-WebSocket-Extensions: ${W}`),M._extensions=h}this.emit("headers",k,x),v.write(k.concat(`\r
2
+ `).join(`\r
3
+ `)),v.removeListener("error",C),M.setSocket(v,R,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(M),M.on("close",()=>{this.clients.delete(M),this._shouldEmitClose&&!this.clients.size&&process.nextTick(y,this)})),A(M,x)}}websocketServer=w;function T(a,h){for(const r of Object.keys(h))a.on(r,h[r]);return function(){for(const _ of Object.keys(h))a.removeListener(_,h[_])}}function y(a){a._state=S,a.emit("close")}function C(){this.destroy()}function L(a,h,r,_){r=r||i.STATUS_CODES[h],_={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),..._},a.once("finish",a.destroy),a.end(`HTTP/1.1 ${h} ${i.STATUS_CODES[h]}\r
4
+ `+Object.keys(_).map(x=>`${x}: ${_[x]}`).join(`\r
5
+ `)+`\r
6
+ \r
7
+ `+r)}function B(a,h,r,_,x,v){if(a.listenerCount("wsClientError")){const R=new Error(x);Error.captureStackTrace(R,B),a.emit("wsClientError",R,r,h)}else L(r,_,x,v)}return websocketServer}var websocketServerExports=requireWebsocketServer(),WebSocketServer=getDefaultExportFromCjs(websocketServerExports),QRMode,hasRequiredQRMode;function requireQRMode(){return hasRequiredQRMode||(hasRequiredQRMode=1,QRMode={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}),QRMode}var QR8bitByte_1,hasRequiredQR8bitByte;function requireQR8bitByte(){if(hasRequiredQR8bitByte)return QR8bitByte_1;hasRequiredQR8bitByte=1;var E=requireQRMode();function i(l){this.mode=E.MODE_8BIT_BYTE,this.data=l}return i.prototype={getLength:function(){return this.data.length},write:function(l){for(var u=0;u<this.data.length;u++)l.put(this.data.charCodeAt(u),8)}},QR8bitByte_1=i,QR8bitByte_1}var QRMath_1,hasRequiredQRMath;function requireQRMath(){if(hasRequiredQRMath)return QRMath_1;hasRequiredQRMath=1;for(var E={glog:function(l){if(l<1)throw new Error("glog("+l+")");return E.LOG_TABLE[l]},gexp:function(l){for(;l<0;)l+=255;for(;l>=256;)l-=255;return E.EXP_TABLE[l]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)},i=0;i<8;i++)E.EXP_TABLE[i]=1<<i;for(var i=8;i<256;i++)E.EXP_TABLE[i]=E.EXP_TABLE[i-4]^E.EXP_TABLE[i-5]^E.EXP_TABLE[i-6]^E.EXP_TABLE[i-8];for(var i=0;i<255;i++)E.LOG_TABLE[E.EXP_TABLE[i]]=i;return QRMath_1=E,QRMath_1}var QRPolynomial_1,hasRequiredQRPolynomial;function requireQRPolynomial(){if(hasRequiredQRPolynomial)return QRPolynomial_1;hasRequiredQRPolynomial=1;var E=requireQRMath();function i(l,u){if(l.length===void 0)throw new Error(l.length+"/"+u);for(var f=0;f<l.length&&l[f]===0;)f++;this.num=new Array(l.length-f+u);for(var s=0;s<l.length-f;s++)this.num[s]=l[s+f]}return i.prototype={get:function(l){return this.num[l]},getLength:function(){return this.num.length},multiply:function(l){for(var u=new Array(this.getLength()+l.getLength()-1),f=0;f<this.getLength();f++)for(var s=0;s<l.getLength();s++)u[f+s]^=E.gexp(E.glog(this.get(f))+E.glog(l.get(s)));return new i(u,0)},mod:function(l){if(this.getLength()-l.getLength()<0)return this;for(var u=E.glog(this.get(0))-E.glog(l.get(0)),f=new Array(this.getLength()),s=0;s<this.getLength();s++)f[s]=this.get(s);for(var e=0;e<l.getLength();e++)f[e]^=E.gexp(E.glog(l.get(e))+u);return new i(f,0).mod(l)}},QRPolynomial_1=i,QRPolynomial_1}var QRMaskPattern,hasRequiredQRMaskPattern;function requireQRMaskPattern(){return hasRequiredQRMaskPattern||(hasRequiredQRMaskPattern=1,QRMaskPattern={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}),QRMaskPattern}var QRUtil_1,hasRequiredQRUtil;function requireQRUtil(){if(hasRequiredQRUtil)return QRUtil_1;hasRequiredQRUtil=1;var E=requireQRMode(),i=requireQRPolynomial(),l=requireQRMath(),u=requireQRMaskPattern(),f={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(s){for(var e=s<<10;f.getBCHDigit(e)-f.getBCHDigit(f.G15)>=0;)e^=f.G15<<f.getBCHDigit(e)-f.getBCHDigit(f.G15);return(s<<10|e)^f.G15_MASK},getBCHTypeNumber:function(s){for(var e=s<<12;f.getBCHDigit(e)-f.getBCHDigit(f.G18)>=0;)e^=f.G18<<f.getBCHDigit(e)-f.getBCHDigit(f.G18);return s<<12|e},getBCHDigit:function(s){for(var e=0;s!==0;)e++,s>>>=1;return e},getPatternPosition:function(s){return f.PATTERN_POSITION_TABLE[s-1]},getMask:function(s,e,n){switch(s){case u.PATTERN000:return(e+n)%2===0;case u.PATTERN001:return e%2===0;case u.PATTERN010:return n%3===0;case u.PATTERN011:return(e+n)%3===0;case u.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case u.PATTERN101:return e*n%2+e*n%3===0;case u.PATTERN110:return(e*n%2+e*n%3)%2===0;case u.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+s)}},getErrorCorrectPolynomial:function(s){for(var e=new i([1],0),n=0;n<s;n++)e=e.multiply(new i([1,l.gexp(n)],0));return e},getLengthInBits:function(s,e){if(1<=e&&e<10)switch(s){case E.MODE_NUMBER:return 10;case E.MODE_ALPHA_NUM:return 9;case E.MODE_8BIT_BYTE:return 8;case E.MODE_KANJI:return 8;default:throw new Error("mode:"+s)}else if(e<27)switch(s){case E.MODE_NUMBER:return 12;case E.MODE_ALPHA_NUM:return 11;case E.MODE_8BIT_BYTE:return 16;case E.MODE_KANJI:return 10;default:throw new Error("mode:"+s)}else if(e<41)switch(s){case E.MODE_NUMBER:return 14;case E.MODE_ALPHA_NUM:return 13;case E.MODE_8BIT_BYTE:return 16;case E.MODE_KANJI:return 12;default:throw new Error("mode:"+s)}else throw new Error("type:"+e)},getLostPoint:function(s){var e=s.getModuleCount(),n=0,t=0,o=0;for(t=0;t<e;t++)for(o=0;o<e;o++){for(var c=0,g=s.isDark(t,o),d=-1;d<=1;d++)if(!(t+d<0||e<=t+d))for(var b=-1;b<=1;b++)o+b<0||e<=o+b||d===0&&b===0||g===s.isDark(t+d,o+b)&&c++;c>5&&(n+=3+c-5)}for(t=0;t<e-1;t++)for(o=0;o<e-1;o++){var S=0;s.isDark(t,o)&&S++,s.isDark(t+1,o)&&S++,s.isDark(t,o+1)&&S++,s.isDark(t+1,o+1)&&S++,(S===0||S===4)&&(n+=3)}for(t=0;t<e;t++)for(o=0;o<e-6;o++)s.isDark(t,o)&&!s.isDark(t,o+1)&&s.isDark(t,o+2)&&s.isDark(t,o+3)&&s.isDark(t,o+4)&&!s.isDark(t,o+5)&&s.isDark(t,o+6)&&(n+=40);for(o=0;o<e;o++)for(t=0;t<e-6;t++)s.isDark(t,o)&&!s.isDark(t+1,o)&&s.isDark(t+2,o)&&s.isDark(t+3,o)&&s.isDark(t+4,o)&&!s.isDark(t+5,o)&&s.isDark(t+6,o)&&(n+=40);var w=0;for(o=0;o<e;o++)for(t=0;t<e;t++)s.isDark(t,o)&&w++;var T=Math.abs(100*w/e/e-50)/5;return n+=T*10,n}};return QRUtil_1=f,QRUtil_1}var QRErrorCorrectLevel,hasRequiredQRErrorCorrectLevel;function requireQRErrorCorrectLevel(){return hasRequiredQRErrorCorrectLevel||(hasRequiredQRErrorCorrectLevel=1,QRErrorCorrectLevel={L:1,M:0,Q:3,H:2}),QRErrorCorrectLevel}var QRRSBlock_1,hasRequiredQRRSBlock;function requireQRRSBlock(){if(hasRequiredQRRSBlock)return QRRSBlock_1;hasRequiredQRRSBlock=1;var E=requireQRErrorCorrectLevel();function i(l,u){this.totalCount=l,this.dataCount=u}return i.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],i.getRSBlocks=function(l,u){var f=i.getRsBlockTable(l,u);if(f===void 0)throw new Error("bad rs block @ typeNumber:"+l+"/errorCorrectLevel:"+u);for(var s=f.length/3,e=[],n=0;n<s;n++)for(var t=f[n*3+0],o=f[n*3+1],c=f[n*3+2],g=0;g<t;g++)e.push(new i(o,c));return e},i.getRsBlockTable=function(l,u){switch(u){case E.L:return i.RS_BLOCK_TABLE[(l-1)*4+0];case E.M:return i.RS_BLOCK_TABLE[(l-1)*4+1];case E.Q:return i.RS_BLOCK_TABLE[(l-1)*4+2];case E.H:return i.RS_BLOCK_TABLE[(l-1)*4+3];default:return}},QRRSBlock_1=i,QRRSBlock_1}var QRBitBuffer_1,hasRequiredQRBitBuffer;function requireQRBitBuffer(){if(hasRequiredQRBitBuffer)return QRBitBuffer_1;hasRequiredQRBitBuffer=1;function E(){this.buffer=[],this.length=0}return E.prototype={get:function(i){var l=Math.floor(i/8);return(this.buffer[l]>>>7-i%8&1)==1},put:function(i,l){for(var u=0;u<l;u++)this.putBit((i>>>l-u-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(i){var l=Math.floor(this.length/8);this.buffer.length<=l&&this.buffer.push(0),i&&(this.buffer[l]|=128>>>this.length%8),this.length++}},QRBitBuffer_1=E,QRBitBuffer_1}var QRCode_1,hasRequiredQRCode;function requireQRCode(){if(hasRequiredQRCode)return QRCode_1;hasRequiredQRCode=1;var E=requireQR8bitByte(),i=requireQRUtil(),l=requireQRPolynomial(),u=requireQRRSBlock(),f=requireQRBitBuffer();function s(e,n){this.typeNumber=e,this.errorCorrectLevel=n,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}return s.prototype={addData:function(e){var n=new E(e);this.dataList.push(n),this.dataCache=null},isDark:function(e,n){if(e<0||this.moduleCount<=e||n<0||this.moduleCount<=n)throw new Error(e+","+n);return this.modules[e][n]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var e=1;for(e=1;e<40;e++){for(var n=u.getRSBlocks(e,this.errorCorrectLevel),t=new f,o=0,c=0;c<n.length;c++)o+=n[c].dataCount;for(var g=0;g<this.dataList.length;g++){var d=this.dataList[g];t.put(d.mode,4),t.put(d.getLength(),i.getLengthInBits(d.mode,e)),d.write(t)}if(t.getLengthInBits()<=o*8)break}this.typeNumber=e}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(e,n){this.moduleCount=this.typeNumber*4+17,this.modules=new Array(this.moduleCount);for(var t=0;t<this.moduleCount;t++){this.modules[t]=new Array(this.moduleCount);for(var o=0;o<this.moduleCount;o++)this.modules[t][o]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(e,n),this.typeNumber>=7&&this.setupTypeNumber(e),this.dataCache===null&&(this.dataCache=s.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,n)},setupPositionProbePattern:function(e,n){for(var t=-1;t<=7;t++)if(!(e+t<=-1||this.moduleCount<=e+t))for(var o=-1;o<=7;o++)n+o<=-1||this.moduleCount<=n+o||(0<=t&&t<=6&&(o===0||o===6)||0<=o&&o<=6&&(t===0||t===6)||2<=t&&t<=4&&2<=o&&o<=4?this.modules[e+t][n+o]=!0:this.modules[e+t][n+o]=!1)},getBestMaskPattern:function(){for(var e=0,n=0,t=0;t<8;t++){this.makeImpl(!0,t);var o=i.getLostPoint(this);(t===0||e>o)&&(e=o,n=t)}return n},createMovieClip:function(e,n,t){var o=e.createEmptyMovieClip(n,t),c=1;this.make();for(var g=0;g<this.modules.length;g++)for(var d=g*c,b=0;b<this.modules[g].length;b++){var S=b*c,w=this.modules[g][b];w&&(o.beginFill(0,100),o.moveTo(S,d),o.lineTo(S+c,d),o.lineTo(S+c,d+c),o.lineTo(S,d+c),o.endFill())}return o},setupTimingPattern:function(){for(var e=8;e<this.moduleCount-8;e++)this.modules[e][6]===null&&(this.modules[e][6]=e%2===0);for(var n=8;n<this.moduleCount-8;n++)this.modules[6][n]===null&&(this.modules[6][n]=n%2===0)},setupPositionAdjustPattern:function(){for(var e=i.getPatternPosition(this.typeNumber),n=0;n<e.length;n++)for(var t=0;t<e.length;t++){var o=e[n],c=e[t];if(this.modules[o][c]===null)for(var g=-2;g<=2;g++)for(var d=-2;d<=2;d++)Math.abs(g)===2||Math.abs(d)===2||g===0&&d===0?this.modules[o+g][c+d]=!0:this.modules[o+g][c+d]=!1}},setupTypeNumber:function(e){for(var n=i.getBCHTypeNumber(this.typeNumber),t,o=0;o<18;o++)t=!e&&(n>>o&1)===1,this.modules[Math.floor(o/3)][o%3+this.moduleCount-8-3]=t;for(var c=0;c<18;c++)t=!e&&(n>>c&1)===1,this.modules[c%3+this.moduleCount-8-3][Math.floor(c/3)]=t},setupTypeInfo:function(e,n){for(var t=this.errorCorrectLevel<<3|n,o=i.getBCHTypeInfo(t),c,g=0;g<15;g++)c=!e&&(o>>g&1)===1,g<6?this.modules[g][8]=c:g<8?this.modules[g+1][8]=c:this.modules[this.moduleCount-15+g][8]=c;for(var d=0;d<15;d++)c=!e&&(o>>d&1)===1,d<8?this.modules[8][this.moduleCount-d-1]=c:d<9?this.modules[8][15-d-1+1]=c:this.modules[8][15-d-1]=c;this.modules[this.moduleCount-8][8]=!e},mapData:function(e,n){for(var t=-1,o=this.moduleCount-1,c=7,g=0,d=this.moduleCount-1;d>0;d-=2)for(d===6&&d--;;){for(var b=0;b<2;b++)if(this.modules[o][d-b]===null){var S=!1;g<e.length&&(S=(e[g]>>>c&1)===1);var w=i.getMask(n,o,d-b);w&&(S=!S),this.modules[o][d-b]=S,c--,c===-1&&(g++,c=7)}if(o+=t,o<0||this.moduleCount<=o){o-=t,t=-t;break}}}},s.PAD0=236,s.PAD1=17,s.createData=function(e,n,t){for(var o=u.getRSBlocks(e,n),c=new f,g=0;g<t.length;g++){var d=t[g];c.put(d.mode,4),c.put(d.getLength(),i.getLengthInBits(d.mode,e)),d.write(c)}for(var b=0,S=0;S<o.length;S++)b+=o[S].dataCount;if(c.getLengthInBits()>b*8)throw new Error("code length overflow. ("+c.getLengthInBits()+">"+b*8+")");for(c.getLengthInBits()+4<=b*8&&c.put(0,4);c.getLengthInBits()%8!==0;)c.putBit(!1);for(;!(c.getLengthInBits()>=b*8||(c.put(s.PAD0,8),c.getLengthInBits()>=b*8));)c.put(s.PAD1,8);return s.createBytes(c,o)},s.createBytes=function(e,n){for(var t=0,o=0,c=0,g=new Array(n.length),d=new Array(n.length),b=0;b<n.length;b++){var S=n[b].dataCount,w=n[b].totalCount-S;o=Math.max(o,S),c=Math.max(c,w),g[b]=new Array(S);for(var T=0;T<g[b].length;T++)g[b][T]=255&e.buffer[T+t];t+=S;var y=i.getErrorCorrectPolynomial(w),C=new l(g[b],y.getLength()-1),L=C.mod(y);d[b]=new Array(y.getLength()-1);for(var B=0;B<d[b].length;B++){var a=B+L.getLength()-d[b].length;d[b][B]=a>=0?L.get(a):0}}for(var h=0,r=0;r<n.length;r++)h+=n[r].totalCount;for(var _=new Array(h),x=0,v=0;v<o;v++)for(var R=0;R<n.length;R++)v<g[R].length&&(_[x++]=g[R][v]);for(var A=0;A<c;A++)for(var N=0;N<n.length;N++)A<d[N].length&&(_[x++]=d[N][A]);return _},QRCode_1=s,QRCode_1}var main,hasRequiredMain;function requireMain(){if(hasRequiredMain)return main;hasRequiredMain=1;var E=requireQRCode(),i=requireQRErrorCorrectLevel(),l="\x1B[40m \x1B[0m",u="\x1B[47m \x1B[0m",f=function(n){return n?l:u},s=function(n){return{times:function(t){return new Array(t).join(n)}}},e=function(n,t){for(var o=new Array(n),c=0;c<n;c++)o[c]=t;return o};return main={error:i.L,generate:function(n,t,o){typeof t=="function"&&(o=t,t={});var c=new E(-1,this.error);c.addData(n),c.make();var g="";if(t&&t.small){var d=!0,b=!1,S=c.getModuleCount(),w=c.modules.slice(),T=S%2===1;T&&w.push(e(S,b));var y={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},C=s(y.BLACK_WHITE).times(S+3),L=s(y.WHITE_BLACK).times(S+3);g+=C+`
8
+ `;for(var B=0;B<S;B+=2){g+=y.WHITE_ALL;for(var a=0;a<S;a++)w[B][a]===b&&w[B+1][a]===b?g+=y.WHITE_ALL:w[B][a]===b&&w[B+1][a]===d?g+=y.WHITE_BLACK:w[B][a]===d&&w[B+1][a]===b?g+=y.BLACK_WHITE:g+=y.BLACK_ALL;g+=y.WHITE_ALL+`
9
+ `}T||(g+=L)}else{var h=s(u).times(c.getModuleCount()+3);g+=h+`
10
+ `,c.modules.forEach(function(r){g+=u,g+=r.map(f).join(""),g+=u+`
11
+ `}),g+=h}o?o(g):console.log(g)},setErrorLevel:function(n){this.error=i[n]||this.error}},main}var mainExports=requireMain(),QRCode=getDefaultExportFromCjs(mainExports);class Utils{static getLocalIP(){const i=os.networkInterfaces();for(const l of Object.keys(i))for(const u of i[l])if(u.family==="IPv4"&&!u.internal)return u.address;return"localhost"}static formatServerUrl(i,l,u){return`ws://${i}:${l}${u}`}static log(i,l="info"){const u=new Date().toLocaleTimeString("zh-CN");console.log(`[${u}] ${{info:"\u2139\uFE0F",success:"\u2705",error:"\u274C",warn:"\u26A0\uFE0F"}[l]||"\u2139\uFE0F"} ${i}`)}}class DeviceManager{constructor(){this.devices=new Map}registerDevice(i,l,u){if(this.devices.has(i)){const f=this.devices.get(i);f.ws=l,f.deviceInfo=u,f.lastHeartbeat=Date.now(),Utils.log(`\u8BBE\u5907\u66F4\u65B0\u8FDE\u63A5: ${i}`,"info")}else this.devices.set(i,{ws:l,simulatorWS:null,deviceInfo:u,lastHeartbeat:Date.now()}),Utils.log(`\u8BBE\u5907\u6CE8\u518C\u6210\u529F: ${i}`,"success")}registerSimulator(i,l){let u=this.devices.get(i);u||(u={ws:null,simulatorWS:null,deviceInfo:{},lastHeartbeat:Date.now()},this.devices.set(i,u)),u.simulatorWS=l,u.lastHeartbeat=Date.now(),Utils.log(`\u6A21\u62DF\u5668\u6CE8\u518C\u6210\u529F: ${i}`,"success")}disconnect(i){for(const[l,u]of this.devices){if(u.ws===i)return u.ws=null,u.simulatorWS||this.devices.delete(l),Utils.log(`\u8BBE\u5907\u65AD\u5F00\u8FDE\u63A5: ${l}`,"warn"),!0;if(u.simulatorWS===i)return u.simulatorWS=null,u.ws||this.devices.delete(l),Utils.log(`\u6A21\u62DF\u5668\u65AD\u5F00\u8FDE\u63A5: ${l}`,"warn"),!0}return!1}getDevice(i){return this.devices.get(i)}isDeviceReady(i){const l=this.devices.get(i);return!!l&&!!l.ws}updateHeartbeat(i){const l=this.devices.get(i);l&&(l.lastHeartbeat=Date.now())}getAllDevices(){return Array.from(this.devices.entries()).map(([i,l])=>({deviceId:i,hasMiniapp:!!l.ws,lastHeartbeat:l.lastHeartbeat}))}get devicesMap(){return this.devices}}class MessageRouter{constructor(i){this.httpServer=null,this.deviceManager=i,this.pendingCalls=new Map}setHttpServer(i){this.httpServer=i}handleMessage(i,l){const{type:u,msgId:f,deviceId:s}=i;if(!u||!f){this.sendError(l,f,"INVALID_MESSAGE","\u6D88\u606F\u683C\u5F0F\u9519\u8BEF");return}switch(u){case"client_call":this.handleClientCall(i,l);break;case"register":this.handleRegister(i,l);break;case"response":this.handleResponse(i,l);break;case"event":this.handleEvent(i);break;case"error":this.handlePhoneError(i);break;case"heartbeat":this.handleHeartbeat(i);break;default:this.sendError(l,f,"UNKNOWN_MESSAGE_TYPE",`\u672A\u77E5\u6D88\u606F\u7C7B\u578B: ${u}`)}}handleRegister(i,l){const{msgId:u,deviceId:f,deviceInfo:s}=i;if(!f){this.sendError(l,u,"INVALID_DEVICE_ID","\u8BBE\u5907ID\u4E0D\u80FD\u4E3A\u7A7A");return}i.role==="simulator"?this.deviceManager.registerSimulator(f,l):this.deviceManager.registerDevice(f,l,s||{}),l.send(JSON.stringify({type:"register",msgId:u,deviceId:f,success:!0,timestamp:Date.now()}))}handleClientCall(i,l){const{msgId:u,deviceId:f,api:s,params:e}=i;if(!f){this.sendError(l,u,"INVALID_DEVICE_ID","\u8BBE\u5907ID\u4E0D\u80FD\u4E3A\u7A7A",s);return}i.proxyMode!=="event"&&this.pendingCalls.set(u,{ws:l,deviceId:f,timestamp:Date.now()});const n=this.deviceManager.getDevice(f);if(!n||!n.ws){this.pendingCalls.delete(u),this.sendError(l,u,"DEVICE_OFFLINE","\u4EE3\u7406\u5C0F\u7A0B\u5E8F\u672A\u8FDE\u63A5",s);return}try{n.ws.send(JSON.stringify(i)),Utils.log(`\u8F6C\u53D1\u8C03\u7528: ${s} \u2192 ${f} -> ${u}`,"info")}catch(t){this.pendingCalls.delete(u),this.sendError(l,u,"SEND_FAILED",`\u53D1\u9001\u5931\u8D25: ${t.message}`,s)}}handleResponse(i,l){const{msgId:u}=i,f=this.pendingCalls.get(u);if(!f){Utils.log(`\u672A\u627E\u5230\u5BF9\u5E94\u7684\u8BF7\u6C42: ${u}`,"warn");return}Utils.log(`\u8F6C\u53D1\u54CD\u5E94 \u2192 msgId: ${u}`,"info");try{f.ws.send(JSON.stringify(i))}catch(s){Utils.log(`\u8F6C\u53D1\u54CD\u5E94\u5931\u8D25: ${s.message}`,"error")}finally{this.pendingCalls.delete(u)}}handleEvent(i){const{deviceId:l,api:u}=i;if(!l)return;const f=this.deviceManager.getDevice(l);if(!f||!f.simulatorWS||f.simulatorWS.readyState!==1){Utils.log(`\u4E8B\u4EF6\u65E0\u5904\u63A8\u9001: ${u} @ ${l}`,"warn");return}try{f.simulatorWS.send(JSON.stringify(i)),Utils.log(`\u63A8\u9001\u4E8B\u4EF6: ${u} \u2192 \u6A21\u62DF\u5668 (${l})`,"info")}catch(s){Utils.log(`\u4E8B\u4EF6\u63A8\u9001\u5931\u8D25: ${s.message}`,"error")}}handlePhoneError(i){const{deviceId:l}=i;if(!l)return;const u=this.deviceManager.getDevice(l);if(!(!u||!u.simulatorWS||u.simulatorWS.readyState!==1))try{u.simulatorWS.send(JSON.stringify(i))}catch(f){Utils.log(`\u9519\u8BEF\u8F6C\u53D1\u5931\u8D25: ${f.message}`,"error")}}handleHeartbeat(i){const{deviceId:l}=i;l&&this.deviceManager.updateHeartbeat(l)}sendError(i,l,u,f,s){i&&i.readyState===1&&i.send(JSON.stringify({type:"error",msgId:l,api:s,timestamp:Date.now(),error:{code:u,message:f}}))}clearPendingCallsForWS(i){for(const[l,u]of this.pendingCalls)u.ws===i&&this.pendingCalls.delete(l)}}var config={port:7521,wsPath:"/ws",heartbeatInterval:3e4,appId:"2026052614145188"};class ProxyServer{constructor(i){const l={port:3e3,wsPath:"/ws",heartbeatInterval:3e4};this.config={...l,...i},this.deviceManager=new DeviceManager,this.messageRouter=new MessageRouter(this.deviceManager),this.wss=null,this.heartbeatTimer=null}start(){this.wss=new WebSocketServer({port:this.config.port,path:this.config.wsPath}),this.wss.on("connection",(i,l)=>{this.handleConnection(i,l)}),this.wss.on("error",i=>{Utils.log(`\u670D\u52A1\u5668\u9519\u8BEF: ${i.message}`,"error")}),this.startHeartbeatCheck(),Utils.log("\u4EE3\u7406\u670D\u52A1\u5668\u542F\u52A8\u6210\u529F","success"),Utils.log(`\u76D1\u542C\u7AEF\u53E3: ${this.config.port}`,"info"),this.displayConnectionInfo()}handleConnection(i,l){const f=new URL(l.url,`http://${l.headers.host}`).searchParams.get("type");Utils.log(`\u65B0\u8FDE\u63A5: ${f||"unknown"}`,"info"),i.on("message",s=>{try{const e=JSON.parse(s.toString());this.messageRouter.handleMessage(e,i)}catch(e){Utils.log(`\u6D88\u606F\u89E3\u6790\u5931\u8D25: ${e.message}`,"error")}}),i.on("close",()=>{this.deviceManager.disconnect(i),this.messageRouter.clearPendingCallsForWS(i)}),i.on("error",s=>{Utils.log(`WebSocket\u9519\u8BEF: ${s.message}`,"error")})}displayConnectionInfo(){const i=Utils.getLocalIP(),l=Utils.formatServerUrl(i,this.config.port,"");console.log(`
12
+ \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
13
+ \u2551 mPaaS JSAPI \u4EE3\u7406\u670D\u52A1\u5668 \u2551
14
+ \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
15
+ \u2551 \u8BF7\u5728\u4EE3\u7406\u5C0F\u7A0B\u5E8F\u4E2D\u8F93\u5165\u4EE5\u4E0B\u5730\u5740\u8FDB\u884C\u6CE8\u518C \u2551
16
+ \u2551 \u2551
17
+ \u2551 ${l.padEnd(58)}\u2551
18
+ \u2551 \u2551
19
+ \u2551 \u6216\u626B\u63CF\u4E0B\u65B9\u4E8C\u7EF4\u7801\u5FEB\u901F\u914D\u7F6E\uFF1A \u2551
20
+ \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
21
+ `),console.log("");const u=`xlmpaas://${config.appId}?url=${encodeURIComponent(l)}`;QRCode.generate(u,{small:!0})}startHeartbeatCheck(){this.heartbeatTimer=setInterval(()=>{const i=Date.now(),l=this.config.heartbeatInterval*2;for(const[u,f]of this.deviceManager.devicesMap)i-f.lastHeartbeat>l&&(Utils.log(`\u8BBE\u5907\u5FC3\u8DF3\u8D85\u65F6: ${u}`,"warn"),f.ws&&f.ws.close(),f.simulatorWS&&f.simulatorWS.close(),this.deviceManager.devicesMap.delete(u))},this.config.heartbeatInterval)}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.wss&&(this.wss.close(),Utils.log("\u670D\u52A1\u5668\u5DF2\u5173\u95ED","info"))}}var minimist$1,hasRequiredMinimist;function requireMinimist(){if(hasRequiredMinimist)return minimist$1;hasRequiredMinimist=1;function E(u,f){var s=u;f.slice(0,-1).forEach(function(n){s=s[n]||{}});var e=f[f.length-1];return e in s}function i(u){return typeof u=="number"||/^0x[0-9a-f]+$/i.test(u)?!0:/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(u)}function l(u,f){return f==="constructor"&&typeof u[f]=="function"||f==="__proto__"}return minimist$1=function(u,f){f||(f={});var s={bools:{},strings:{},unknownFn:null};typeof f.unknown=="function"&&(s.unknownFn=f.unknown),typeof f.boolean=="boolean"&&f.boolean?s.allBools=!0:[].concat(f.boolean).filter(Boolean).forEach(function(r){s.bools[r]=!0});var e={};function n(r){return e[r].some(function(_){return s.bools[_]})}Object.keys(f.alias||{}).forEach(function(r){e[r]=[].concat(f.alias[r]),e[r].forEach(function(_){e[_]=[r].concat(e[r].filter(function(x){return _!==x}))})}),[].concat(f.string).filter(Boolean).forEach(function(r){s.strings[r]=!0,e[r]&&[].concat(e[r]).forEach(function(_){s.strings[_]=!0})});var t=f.default||{},o={_:[]};function c(r,_){return s.allBools&&/^--[^=]+$/.test(_)||s.strings[r]||s.bools[r]||e[r]}function g(r,_,x){for(var v=r,R=0;R<_.length-1;R++){var A=_[R];if(l(v,A))return;v[A]===void 0&&(v[A]={}),(v[A]===Object.prototype||v[A]===Number.prototype||v[A]===String.prototype)&&(v[A]={}),v[A]===Array.prototype&&(v[A]=[]),v=v[A]}var N=_[_.length-1];l(v,N)||((v===Object.prototype||v===Number.prototype||v===String.prototype)&&(v={}),v===Array.prototype&&(v=[]),v[N]===void 0||s.bools[N]||typeof v[N]=="boolean"?v[N]=x:Array.isArray(v[N])?v[N].push(x):v[N]=[v[N],x])}function d(r,_,x){if(!(x&&s.unknownFn&&!c(r,x)&&s.unknownFn(x)===!1)){var v=!s.strings[r]&&i(_)?Number(_):_;g(o,r.split("."),v),(e[r]||[]).forEach(function(R){g(o,R.split("."),v)})}}Object.keys(s.bools).forEach(function(r){d(r,t[r]===void 0?!1:t[r])});var b=[];u.indexOf("--")!==-1&&(b=u.slice(u.indexOf("--")+1),u=u.slice(0,u.indexOf("--")));for(var S=0;S<u.length;S++){var w=u[S],T,y;if(/^--.+=/.test(w)){var C=w.match(/^--([^=]+)=([\s\S]*)$/);T=C[1];var L=C[2];s.bools[T]&&(L=L!=="false"),d(T,L,w)}else if(/^--no-.+/.test(w))T=w.match(/^--no-(.+)/)[1],d(T,!1,w);else if(/^--.+/.test(w))T=w.match(/^--(.+)/)[1],y=u[S+1],y!==void 0&&!/^(-|--)[^-]/.test(y)&&!s.bools[T]&&!s.allBools&&(!e[T]||!n(T))?(d(T,y,w),S+=1):/^(true|false)$/.test(y)?(d(T,y==="true",w),S+=1):d(T,s.strings[T]?"":!0,w);else if(/^-[^-]+/.test(w)){for(var B=w.slice(1,-1).split(""),a=!1,h=0;h<B.length;h++){if(y=w.slice(h+2),y==="-"){d(B[h],y,w);continue}if(/[A-Za-z]/.test(B[h])&&y[0]==="="){d(B[h],y.slice(1),w),a=!0;break}if(/[A-Za-z]/.test(B[h])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(y)){d(B[h],y,w),a=!0;break}if(B[h+1]&&B[h+1].match(/\W/)){d(B[h],w.slice(h+2),w),a=!0;break}else d(B[h],s.strings[B[h]]?"":!0,w)}T=w.slice(-1)[0],!a&&T!=="-"&&(u[S+1]&&!/^(-|--)[^-]/.test(u[S+1])&&!s.bools[T]&&(!e[T]||!n(T))?(d(T,u[S+1],w),S+=1):u[S+1]&&/^(true|false)$/.test(u[S+1])?(d(T,u[S+1]==="true",w),S+=1):d(T,s.strings[T]?"":!0,w))}else if((!s.unknownFn||s.unknownFn(w)!==!1)&&o._.push(s.strings._||!i(w)?w:Number(w)),f.stopEarly){o._.push.apply(o._,u.slice(S+1));break}}return Object.keys(t).forEach(function(r){E(o,r.split("."))||(g(o,r.split("."),t[r]),(e[r]||[]).forEach(function(_){g(o,_.split("."),t[r])}))}),f["--"]?o["--"]=b.slice():b.forEach(function(r){o._.push(r)}),o},minimist$1}var minimistExports=requireMinimist(),minimist=getDefaultExportFromCjs(minimistExports);const args=minimist(process.argv.slice(2)),finalConfig={...config,...args.p!==void 0&&{port:Number(args.p)},...args.port!==void 0&&{port:Number(args.port)}},proxyServer=new ProxyServer(finalConfig);proxyServer.start(),process.on("SIGINT",()=>{console.log(`
22
+ \u6B63\u5728\u5173\u95ED\u670D\u52A1\u5668...`),proxyServer.stop(),process.exit(0)});
package/package.json CHANGED
@@ -1,8 +1,16 @@
1
1
  {
2
2
  "name": "mpaas-jsapi-proxy",
3
- "version": "1.0.1",
4
- "description": "mPaaS JSAPI 代理服务器",
5
- "main": "dist/index.js",
3
+ "version": "1.1.0",
4
+ "description": "mPaaS JSAPI 代理服务器与模拟器客户端代理",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
6
14
  "bin": {
7
15
  "mpaas-jsapi-proxy": "bin/index.js"
8
16
  },
@@ -11,10 +19,9 @@
11
19
  "dist"
12
20
  ],
13
21
  "scripts": {
14
- "start": "node dist/index.js",
22
+ "start": "tsx src/server/index.ts",
15
23
  "dev": "tsx watch src/index.ts",
16
- "build": "vite build",
17
- "prepublishOnly": "npm run build",
24
+ "build": "rollup -c && tsc -p tsconfig.build.json",
18
25
  "type-check": "tsc --noEmit"
19
26
  },
20
27
  "keywords": [
@@ -27,27 +34,30 @@
27
34
  "license": "MIT",
28
35
  "repository": {
29
36
  "type": "git",
30
- "url": "https://github.com/your-username/mpaas-jsapi-proxy.git"
37
+ "url": "git+https://github.com/weiminghaoo/mpaas-jsapi-proxy.git"
31
38
  },
32
39
  "bugs": {
33
- "url": "https://github.com/your-username/mpaas-jsapi-proxy/issues"
34
- },
35
- "homepage": "https://github.com/your-username/mpaas-jsapi-proxy#readme",
36
- "dependencies": {
37
- "minimist": "^1.2.8",
38
- "qrcode-terminal": "^0.12.0",
39
- "ws": "^8.14.0"
40
+ "url": "https://github.com/weiminghaoo/mpaas-jsapi-proxy/issues"
40
41
  },
42
+ "homepage": "https://github.com/weiminghaoo/mpaas-jsapi-proxy#readme",
41
43
  "devDependencies": {
44
+ "@babel/core": "^8.0.1",
45
+ "@babel/preset-env": "^8.0.2",
46
+ "@mini-types/alipay": "^3.0.14",
47
+ "@rollup/plugin-commonjs": "^29.0.3",
48
+ "@rollup/plugin-node-resolve": "^16.0.3",
42
49
  "@types/minimist": "^1.2.5",
43
50
  "@types/node": "^25.9.1",
44
51
  "@types/qrcode-terminal": "^0.12.2",
45
52
  "@types/ws": "^8.18.1",
46
53
  "esbuild": "^0.28.0",
47
- "nodemon": "^3.0.0",
54
+ "minimist": "^1.2.8",
55
+ "qrcode-terminal": "^0.12.0",
56
+ "rollup": "^4.63.1",
57
+ "rollup-plugin-esbuild": "^6.2.1",
48
58
  "tsx": "^4.22.3",
49
59
  "typescript": "^6.0.3",
50
- "vite": "^8.0.14"
60
+ "ws": "^8.14.0"
51
61
  },
52
62
  "volta": {
53
63
  "node": "18.20.8"