silvery 0.18.2 → 0.19.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.
Files changed (156) hide show
  1. package/dist/{animation-DhINOJk8.mjs → animation-Cn64yepo.mjs} +1 -1
  2. package/dist/{animation-DhINOJk8.mjs.map → animation-Cn64yepo.mjs.map} +1 -1
  3. package/dist/{ansi-C6Qs1Wn2.mjs → ansi-CLOitHKx.mjs} +1 -1
  4. package/dist/ansi-CLOitHKx.mjs.map +1 -0
  5. package/dist/{ansi-CsjnZtAw.d.mts → ansi-Cc33mW54.d.mts} +1 -1
  6. package/dist/{ansi-CsjnZtAw.d.mts.map → ansi-Cc33mW54.d.mts.map} +1 -1
  7. package/dist/{chunk-BSw8zbkd.mjs → chunk-Vs_PY4HZ.mjs} +1 -1
  8. package/dist/cli-BKp0YtBD.mjs +4 -0
  9. package/dist/{context-BjWgrikx.mjs → context-BU5LkkIy.mjs} +8 -7
  10. package/dist/context-BU5LkkIy.mjs.map +1 -0
  11. package/dist/devtools-9QY4teqI.mjs +2 -0
  12. package/dist/{devtools-CeO9X_uv.mjs → devtools-DxkSLXDA.mjs} +4 -5
  13. package/dist/devtools-DxkSLXDA.mjs.map +1 -0
  14. package/dist/{eta-BnQSZcWf.mjs → eta-Bb3RH3wh.mjs} +1 -1
  15. package/dist/{eta-BnQSZcWf.mjs.map → eta-Bb3RH3wh.mjs.map} +1 -1
  16. package/dist/{flexily-zero-adapter-BOM0cl8R.mjs → flexily-zero-adapter-BlQa46nr.mjs} +21 -64
  17. package/dist/flexily-zero-adapter-BlQa46nr.mjs.map +1 -0
  18. package/dist/{flexily-zero-adapter-V8R3HQtK.mjs → flexily-zero-adapter-CMxXhdOL.mjs} +1 -1
  19. package/dist/{image-B0zMbVUr.mjs → image-CTII5QWI.mjs} +3 -3
  20. package/dist/image-CTII5QWI.mjs.map +1 -0
  21. package/dist/{index-Bh3U1K09.d.mts → index-BXslOebb.d.mts} +547 -137
  22. package/dist/index-BXslOebb.d.mts.map +1 -0
  23. package/dist/{index-C4vrhbud.d.mts → index-BnA7mNpo.d.mts} +1 -1
  24. package/dist/{index-C4vrhbud.d.mts.map → index-BnA7mNpo.d.mts.map} +1 -1
  25. package/dist/index-D3saHouR.d.mts +1392 -0
  26. package/dist/index-D3saHouR.d.mts.map +1 -0
  27. package/dist/index.d.mts +5 -33
  28. package/dist/index.d.mts.map +1 -1
  29. package/dist/index.mjs +13 -13
  30. package/dist/{layout-engine--drvrWjD.mjs → layout-engine-B6Cdz1yZ.mjs} +1 -1
  31. package/dist/{layout-engine-Dr3cY5U4.mjs → layout-engine-ClUgv6jB.mjs} +3 -3
  32. package/dist/{layout-engine-Dr3cY5U4.mjs.map → layout-engine-ClUgv6jB.mjs.map} +1 -1
  33. package/dist/{multi-progress-CcdqJFlf.mjs → multi-progress-Bq9Oi_WI.mjs} +3 -3
  34. package/dist/{multi-progress-CcdqJFlf.mjs.map → multi-progress-Bq9Oi_WI.mjs.map} +1 -1
  35. package/dist/{multi-progress-DQ-uUzLf.d.mts → multi-progress-DAQC7eap.d.mts} +2 -2
  36. package/dist/{multi-progress-DQ-uUzLf.d.mts.map → multi-progress-DAQC7eap.d.mts.map} +1 -1
  37. package/dist/{node-CP5WChgr.mjs → node-BeWlnCPY.mjs} +4 -4
  38. package/dist/node-BeWlnCPY.mjs.map +1 -0
  39. package/dist/{progress-bar-IrUjkLfU.mjs → progress-bar-CXE5Qfkd.mjs} +4 -4
  40. package/dist/progress-bar-CXE5Qfkd.mjs.map +1 -0
  41. package/dist/reconciler-Cwgm8hRR.mjs +8459 -0
  42. package/dist/reconciler-Cwgm8hRR.mjs.map +1 -0
  43. package/dist/{render-string-DVfgc8xr.mjs → render-string-Cbuf63Ya.mjs} +936 -136
  44. package/dist/render-string-Cbuf63Ya.mjs.map +1 -0
  45. package/dist/{render-string-BwLG7rIX.mjs → render-string-Tv-jqM16.mjs} +1 -1
  46. package/dist/runtime.d.mts +2 -2
  47. package/dist/runtime.mjs +3 -3
  48. package/dist/{spinner-BRkaJI0N.d.mts → spinner-CGo34vyR.d.mts} +2 -2
  49. package/dist/{spinner-BRkaJI0N.d.mts.map → spinner-CGo34vyR.d.mts.map} +1 -1
  50. package/dist/{spinner-BmldKx0M.mjs → spinner-CeOmcuw_.mjs} +3 -3
  51. package/dist/spinner-CeOmcuw_.mjs.map +1 -0
  52. package/dist/src-B5GjfG7g.mjs +4305 -0
  53. package/dist/src-B5GjfG7g.mjs.map +1 -0
  54. package/dist/{src-CJPXf3fC.mjs → src-C2uvC-r0.mjs} +7535 -6467
  55. package/dist/src-C2uvC-r0.mjs.map +1 -0
  56. package/dist/{src-D8kLrQBT.mjs → src-CChwjk0Z.mjs} +8 -86
  57. package/dist/src-CChwjk0Z.mjs.map +1 -0
  58. package/dist/{src-D_BS-as7.mjs → src-NCKb8kE5.mjs} +777 -776
  59. package/dist/src-NCKb8kE5.mjs.map +1 -0
  60. package/dist/theme.d.mts +2 -130
  61. package/dist/theme.mjs +3 -8
  62. package/dist/{types-B4A8Ebba.d.mts → types-BH_v3iMT.d.mts} +1 -1
  63. package/dist/{types-B4A8Ebba.d.mts.map → types-BH_v3iMT.d.mts.map} +1 -1
  64. package/dist/{types-e4dpfbSa.mjs → types-Bk2yw9Qj.mjs} +3 -3
  65. package/dist/types-Bk2yw9Qj.mjs.map +1 -0
  66. package/dist/ui/animation.d.mts +1 -1
  67. package/dist/ui/animation.mjs +1 -1
  68. package/dist/ui/ansi.d.mts +1 -1
  69. package/dist/ui/ansi.mjs +1 -1
  70. package/dist/ui/cli.d.mts +3 -3
  71. package/dist/ui/cli.mjs +5 -5
  72. package/dist/ui/display.d.mts +1 -1
  73. package/dist/ui/display.mjs.map +1 -1
  74. package/dist/ui/image.d.mts +1 -1
  75. package/dist/ui/image.mjs +1 -1
  76. package/dist/ui/input.d.mts +1 -1
  77. package/dist/ui/input.d.mts.map +1 -1
  78. package/dist/ui/input.mjs +2 -4
  79. package/dist/ui/input.mjs.map +1 -1
  80. package/dist/ui/progress.d.mts +3 -3
  81. package/dist/ui/progress.d.mts.map +1 -1
  82. package/dist/ui/progress.mjs +3 -3
  83. package/dist/ui/progress.mjs.map +1 -1
  84. package/dist/ui/react.d.mts +1 -1
  85. package/dist/ui/react.d.mts.map +1 -1
  86. package/dist/ui/react.mjs +2 -2
  87. package/dist/ui/react.mjs.map +1 -1
  88. package/dist/ui/utils.mjs +1 -1
  89. package/dist/ui/wrappers.d.mts +2 -2
  90. package/dist/ui/wrappers.mjs +1 -1
  91. package/dist/ui.d.mts +5 -5
  92. package/dist/ui.mjs +6 -6
  93. package/dist/{useLatest-6xqnGIU6.d.mts → useLatest-Bg2x4bfP.d.mts} +1 -1
  94. package/dist/{useLatest-6xqnGIU6.d.mts.map → useLatest-Bg2x4bfP.d.mts.map} +1 -1
  95. package/dist/{with-text-input-lUh9gYAG.d.mts → with-text-input-CRfoiFFG.d.mts} +3 -3
  96. package/dist/with-text-input-CRfoiFFG.d.mts.map +1 -0
  97. package/dist/{wrappers-JrEYTuKA.mjs → wrappers-UTADQkSY.mjs} +4 -4
  98. package/dist/wrappers-UTADQkSY.mjs.map +1 -0
  99. package/dist/{yoga-adapter-Bc8XT9cN.mjs → yoga-adapter-8oRGRw8V.mjs} +2 -2
  100. package/dist/{yoga-adapter-Bc8XT9cN.mjs.map → yoga-adapter-8oRGRw8V.mjs.map} +1 -1
  101. package/dist/yoga-adapter-D_CcxSt5.mjs +2 -0
  102. package/package.json +54 -45
  103. package/dist/UPNG-DvKjM6wE.mjs +0 -5076
  104. package/dist/UPNG-DvKjM6wE.mjs.map +0 -1
  105. package/dist/__vite-browser-external-2447137e-DPKHHqQK.mjs +0 -6
  106. package/dist/__vite-browser-external-2447137e-DPKHHqQK.mjs.map +0 -1
  107. package/dist/ansi-C6Qs1Wn2.mjs.map +0 -1
  108. package/dist/apng-CvSlLBtc.mjs +0 -3
  109. package/dist/apng-DFFVOItr.mjs +0 -70
  110. package/dist/apng-DFFVOItr.mjs.map +0 -1
  111. package/dist/assets/resvgjs.darwin-arm64-BtufyGW1.node +0 -0
  112. package/dist/backend-DU0Y938U.mjs +0 -13396
  113. package/dist/backend-DU0Y938U.mjs.map +0 -1
  114. package/dist/backends-BihMKFY_.mjs +0 -1181
  115. package/dist/backends-BihMKFY_.mjs.map +0 -1
  116. package/dist/backends-Dk_5G_gC.mjs +0 -3
  117. package/dist/cli-GwJ0S2In.mjs +0 -4
  118. package/dist/context-BjWgrikx.mjs.map +0 -1
  119. package/dist/derive-O_Kb1Bk_.d.mts +0 -28
  120. package/dist/derive-O_Kb1Bk_.d.mts.map +0 -1
  121. package/dist/devtools-CeO9X_uv.mjs.map +0 -1
  122. package/dist/devtools-nX4tj6OH.mjs +0 -2
  123. package/dist/flexily-zero-adapter-BOM0cl8R.mjs.map +0 -1
  124. package/dist/gif-B9Uq4qZA.mjs +0 -73
  125. package/dist/gif-B9Uq4qZA.mjs.map +0 -1
  126. package/dist/gif-BdrLRBmM.mjs +0 -3
  127. package/dist/gifenc-DfhOb4xr.mjs +0 -730
  128. package/dist/gifenc-DfhOb4xr.mjs.map +0 -1
  129. package/dist/image-B0zMbVUr.mjs.map +0 -1
  130. package/dist/index-Bh3U1K09.d.mts.map +0 -1
  131. package/dist/index-dehZ18K-.d.mts +0 -679
  132. package/dist/index-dehZ18K-.d.mts.map +0 -1
  133. package/dist/key-mapping-7k2ufK2b.mjs +0 -3
  134. package/dist/key-mapping-WLUmxjx1.mjs +0 -132
  135. package/dist/key-mapping-WLUmxjx1.mjs.map +0 -1
  136. package/dist/node-CP5WChgr.mjs.map +0 -1
  137. package/dist/progress-bar-IrUjkLfU.mjs.map +0 -1
  138. package/dist/reconciler-B8uxQxaU.mjs +0 -16482
  139. package/dist/reconciler-B8uxQxaU.mjs.map +0 -1
  140. package/dist/render-string-DVfgc8xr.mjs.map +0 -1
  141. package/dist/resvg-js-Cwipz-_J.mjs +0 -203
  142. package/dist/resvg-js-Cwipz-_J.mjs.map +0 -1
  143. package/dist/spinner-BmldKx0M.mjs.map +0 -1
  144. package/dist/src-C0sOQW-t.mjs +0 -3866
  145. package/dist/src-C0sOQW-t.mjs.map +0 -1
  146. package/dist/src-CJPXf3fC.mjs.map +0 -1
  147. package/dist/src-D8kLrQBT.mjs.map +0 -1
  148. package/dist/src-D_BS-as7.mjs.map +0 -1
  149. package/dist/theme.d.mts.map +0 -1
  150. package/dist/theme.mjs.map +0 -1
  151. package/dist/types-e4dpfbSa.mjs.map +0 -1
  152. package/dist/with-text-input-lUh9gYAG.d.mts.map +0 -1
  153. package/dist/wrapper-CE6GQ27z.mjs +0 -3527
  154. package/dist/wrapper-CE6GQ27z.mjs.map +0 -1
  155. package/dist/wrappers-JrEYTuKA.mjs.map +0 -1
  156. package/dist/yoga-adapter-B8LZpQcE.mjs +0 -2
@@ -1,3527 +0,0 @@
1
- import { i as __require, o as __toESM, t as __commonJSMin } from "./chunk-BSw8zbkd.mjs";
2
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/constants.js
3
- var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4
- const BINARY_TYPES = [
5
- "nodebuffer",
6
- "arraybuffer",
7
- "fragments"
8
- ];
9
- const hasBlob = typeof Blob !== "undefined";
10
- if (hasBlob) BINARY_TYPES.push("blob");
11
- module.exports = {
12
- BINARY_TYPES,
13
- CLOSE_TIMEOUT: 3e4,
14
- EMPTY_BUFFER: Buffer.alloc(0),
15
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
16
- hasBlob,
17
- kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
18
- kListener: Symbol("kListener"),
19
- kStatusCode: Symbol("status-code"),
20
- kWebSocket: Symbol("websocket"),
21
- NOOP: () => {}
22
- };
23
- }));
24
- //#endregion
25
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/buffer-util.js
26
- var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27
- const { EMPTY_BUFFER } = require_constants();
28
- const FastBuffer = Buffer[Symbol.species];
29
- /**
30
- * Merges an array of buffers into a new buffer.
31
- *
32
- * @param {Buffer[]} list The array of buffers to concat
33
- * @param {Number} totalLength The total length of buffers in the list
34
- * @return {Buffer} The resulting buffer
35
- * @public
36
- */
37
- function concat(list, totalLength) {
38
- if (list.length === 0) return EMPTY_BUFFER;
39
- if (list.length === 1) return list[0];
40
- const target = Buffer.allocUnsafe(totalLength);
41
- let offset = 0;
42
- for (let i = 0; i < list.length; i++) {
43
- const buf = list[i];
44
- target.set(buf, offset);
45
- offset += buf.length;
46
- }
47
- if (offset < totalLength) return new FastBuffer(target.buffer, target.byteOffset, offset);
48
- return target;
49
- }
50
- /**
51
- * Masks a buffer using the given mask.
52
- *
53
- * @param {Buffer} source The buffer to mask
54
- * @param {Buffer} mask The mask to use
55
- * @param {Buffer} output The buffer where to store the result
56
- * @param {Number} offset The offset at which to start writing
57
- * @param {Number} length The number of bytes to mask.
58
- * @public
59
- */
60
- function _mask(source, mask, output, offset, length) {
61
- for (let i = 0; i < length; i++) output[offset + i] = source[i] ^ mask[i & 3];
62
- }
63
- /**
64
- * Unmasks a buffer using the given mask.
65
- *
66
- * @param {Buffer} buffer The buffer to unmask
67
- * @param {Buffer} mask The mask to use
68
- * @public
69
- */
70
- function _unmask(buffer, mask) {
71
- for (let i = 0; i < buffer.length; i++) buffer[i] ^= mask[i & 3];
72
- }
73
- /**
74
- * Converts a buffer to an `ArrayBuffer`.
75
- *
76
- * @param {Buffer} buf The buffer to convert
77
- * @return {ArrayBuffer} Converted buffer
78
- * @public
79
- */
80
- function toArrayBuffer(buf) {
81
- if (buf.length === buf.buffer.byteLength) return buf.buffer;
82
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
83
- }
84
- /**
85
- * Converts `data` to a `Buffer`.
86
- *
87
- * @param {*} data The data to convert
88
- * @return {Buffer} The buffer
89
- * @throws {TypeError}
90
- * @public
91
- */
92
- function toBuffer(data) {
93
- toBuffer.readOnly = true;
94
- if (Buffer.isBuffer(data)) return data;
95
- let buf;
96
- if (data instanceof ArrayBuffer) buf = new FastBuffer(data);
97
- else if (ArrayBuffer.isView(data)) buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
98
- else {
99
- buf = Buffer.from(data);
100
- toBuffer.readOnly = false;
101
- }
102
- return buf;
103
- }
104
- module.exports = {
105
- concat,
106
- mask: _mask,
107
- toArrayBuffer,
108
- toBuffer,
109
- unmask: _unmask
110
- };
111
- /* istanbul ignore else */
112
- if (!process.env.WS_NO_BUFFER_UTIL) try {
113
- const bufferUtil = __require("bufferutil");
114
- module.exports.mask = function(source, mask, output, offset, length) {
115
- if (length < 48) _mask(source, mask, output, offset, length);
116
- else bufferUtil.mask(source, mask, output, offset, length);
117
- };
118
- module.exports.unmask = function(buffer, mask) {
119
- if (buffer.length < 32) _unmask(buffer, mask);
120
- else bufferUtil.unmask(buffer, mask);
121
- };
122
- } catch (e) {}
123
- }));
124
- //#endregion
125
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/limiter.js
126
- var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
127
- const kDone = Symbol("kDone");
128
- const kRun = Symbol("kRun");
129
- /**
130
- * A very simple job queue with adjustable concurrency. Adapted from
131
- * https://github.com/STRML/async-limiter
132
- */
133
- var Limiter = class {
134
- /**
135
- * Creates a new `Limiter`.
136
- *
137
- * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
138
- * to run concurrently
139
- */
140
- constructor(concurrency) {
141
- this[kDone] = () => {
142
- this.pending--;
143
- this[kRun]();
144
- };
145
- this.concurrency = concurrency || Infinity;
146
- this.jobs = [];
147
- this.pending = 0;
148
- }
149
- /**
150
- * Adds a job to the queue.
151
- *
152
- * @param {Function} job The job to run
153
- * @public
154
- */
155
- add(job) {
156
- this.jobs.push(job);
157
- this[kRun]();
158
- }
159
- /**
160
- * Removes a job from the queue and runs it if possible.
161
- *
162
- * @private
163
- */
164
- [kRun]() {
165
- if (this.pending === this.concurrency) return;
166
- if (this.jobs.length) {
167
- const job = this.jobs.shift();
168
- this.pending++;
169
- job(this[kDone]);
170
- }
171
- }
172
- };
173
- module.exports = Limiter;
174
- }));
175
- //#endregion
176
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js
177
- var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
178
- const zlib = __require("zlib");
179
- const bufferUtil = require_buffer_util();
180
- const Limiter = require_limiter();
181
- const { kStatusCode } = require_constants();
182
- const FastBuffer = Buffer[Symbol.species];
183
- const TRAILER = Buffer.from([
184
- 0,
185
- 0,
186
- 255,
187
- 255
188
- ]);
189
- const kPerMessageDeflate = Symbol("permessage-deflate");
190
- const kTotalLength = Symbol("total-length");
191
- const kCallback = Symbol("callback");
192
- const kBuffers = Symbol("buffers");
193
- const kError = Symbol("error");
194
- let zlibLimiter;
195
- /**
196
- * permessage-deflate implementation.
197
- */
198
- var PerMessageDeflate = class {
199
- /**
200
- * Creates a PerMessageDeflate instance.
201
- *
202
- * @param {Object} [options] Configuration options
203
- * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
204
- * for, or request, a custom client window size
205
- * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
206
- * acknowledge disabling of client context takeover
207
- * @param {Number} [options.concurrencyLimit=10] The number of concurrent
208
- * calls to zlib
209
- * @param {Boolean} [options.isServer=false] Create the instance in either
210
- * server or client mode
211
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
212
- * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
213
- * use of a custom server window size
214
- * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
215
- * disabling of server context takeover
216
- * @param {Number} [options.threshold=1024] Size (in bytes) below which
217
- * messages should not be compressed if context takeover is disabled
218
- * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
219
- * deflate
220
- * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
221
- * inflate
222
- */
223
- constructor(options) {
224
- this._options = options || {};
225
- this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
226
- this._maxPayload = this._options.maxPayload | 0;
227
- this._isServer = !!this._options.isServer;
228
- this._deflate = null;
229
- this._inflate = null;
230
- this.params = null;
231
- if (!zlibLimiter) zlibLimiter = new Limiter(this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10);
232
- }
233
- /**
234
- * @type {String}
235
- */
236
- static get extensionName() {
237
- return "permessage-deflate";
238
- }
239
- /**
240
- * Create an extension negotiation offer.
241
- *
242
- * @return {Object} Extension parameters
243
- * @public
244
- */
245
- offer() {
246
- const params = {};
247
- if (this._options.serverNoContextTakeover) params.server_no_context_takeover = true;
248
- if (this._options.clientNoContextTakeover) params.client_no_context_takeover = true;
249
- if (this._options.serverMaxWindowBits) params.server_max_window_bits = this._options.serverMaxWindowBits;
250
- if (this._options.clientMaxWindowBits) params.client_max_window_bits = this._options.clientMaxWindowBits;
251
- else if (this._options.clientMaxWindowBits == null) params.client_max_window_bits = true;
252
- return params;
253
- }
254
- /**
255
- * Accept an extension negotiation offer/response.
256
- *
257
- * @param {Array} configurations The extension negotiation offers/reponse
258
- * @return {Object} Accepted configuration
259
- * @public
260
- */
261
- accept(configurations) {
262
- configurations = this.normalizeParams(configurations);
263
- this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
264
- return this.params;
265
- }
266
- /**
267
- * Releases all resources used by the extension.
268
- *
269
- * @public
270
- */
271
- cleanup() {
272
- if (this._inflate) {
273
- this._inflate.close();
274
- this._inflate = null;
275
- }
276
- if (this._deflate) {
277
- const callback = this._deflate[kCallback];
278
- this._deflate.close();
279
- this._deflate = null;
280
- if (callback) callback(/* @__PURE__ */ new Error("The deflate stream was closed while data was being processed"));
281
- }
282
- }
283
- /**
284
- * Accept an extension negotiation offer.
285
- *
286
- * @param {Array} offers The extension negotiation offers
287
- * @return {Object} Accepted configuration
288
- * @private
289
- */
290
- acceptAsServer(offers) {
291
- const opts = this._options;
292
- const accepted = offers.find((params) => {
293
- if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) return false;
294
- return true;
295
- });
296
- if (!accepted) throw new Error("None of the extension offers can be accepted");
297
- if (opts.serverNoContextTakeover) accepted.server_no_context_takeover = true;
298
- if (opts.clientNoContextTakeover) accepted.client_no_context_takeover = true;
299
- if (typeof opts.serverMaxWindowBits === "number") accepted.server_max_window_bits = opts.serverMaxWindowBits;
300
- if (typeof opts.clientMaxWindowBits === "number") accepted.client_max_window_bits = opts.clientMaxWindowBits;
301
- else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) delete accepted.client_max_window_bits;
302
- return accepted;
303
- }
304
- /**
305
- * Accept the extension negotiation response.
306
- *
307
- * @param {Array} response The extension negotiation response
308
- * @return {Object} Accepted configuration
309
- * @private
310
- */
311
- acceptAsClient(response) {
312
- const params = response[0];
313
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) throw new Error("Unexpected parameter \"client_no_context_takeover\"");
314
- if (!params.client_max_window_bits) {
315
- if (typeof this._options.clientMaxWindowBits === "number") params.client_max_window_bits = this._options.clientMaxWindowBits;
316
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) throw new Error("Unexpected or invalid parameter \"client_max_window_bits\"");
317
- return params;
318
- }
319
- /**
320
- * Normalize parameters.
321
- *
322
- * @param {Array} configurations The extension negotiation offers/reponse
323
- * @return {Array} The offers/response with normalized parameters
324
- * @private
325
- */
326
- normalizeParams(configurations) {
327
- configurations.forEach((params) => {
328
- Object.keys(params).forEach((key) => {
329
- let value = params[key];
330
- if (value.length > 1) throw new Error(`Parameter "${key}" must have only a single value`);
331
- value = value[0];
332
- if (key === "client_max_window_bits") {
333
- if (value !== true) {
334
- const num = +value;
335
- if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
336
- value = num;
337
- } else if (!this._isServer) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
338
- } else if (key === "server_max_window_bits") {
339
- const num = +value;
340
- if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
341
- value = num;
342
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
343
- if (value !== true) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
344
- } else throw new Error(`Unknown parameter "${key}"`);
345
- params[key] = value;
346
- });
347
- });
348
- return configurations;
349
- }
350
- /**
351
- * Decompress data. Concurrency limited.
352
- *
353
- * @param {Buffer} data Compressed data
354
- * @param {Boolean} fin Specifies whether or not this is the last fragment
355
- * @param {Function} callback Callback
356
- * @public
357
- */
358
- decompress(data, fin, callback) {
359
- zlibLimiter.add((done) => {
360
- this._decompress(data, fin, (err, result) => {
361
- done();
362
- callback(err, result);
363
- });
364
- });
365
- }
366
- /**
367
- * Compress data. Concurrency limited.
368
- *
369
- * @param {(Buffer|String)} data Data to compress
370
- * @param {Boolean} fin Specifies whether or not this is the last fragment
371
- * @param {Function} callback Callback
372
- * @public
373
- */
374
- compress(data, fin, callback) {
375
- zlibLimiter.add((done) => {
376
- this._compress(data, fin, (err, result) => {
377
- done();
378
- callback(err, result);
379
- });
380
- });
381
- }
382
- /**
383
- * Decompress data.
384
- *
385
- * @param {Buffer} data Compressed data
386
- * @param {Boolean} fin Specifies whether or not this is the last fragment
387
- * @param {Function} callback Callback
388
- * @private
389
- */
390
- _decompress(data, fin, callback) {
391
- const endpoint = this._isServer ? "client" : "server";
392
- if (!this._inflate) {
393
- const key = `${endpoint}_max_window_bits`;
394
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
395
- this._inflate = zlib.createInflateRaw({
396
- ...this._options.zlibInflateOptions,
397
- windowBits
398
- });
399
- this._inflate[kPerMessageDeflate] = this;
400
- this._inflate[kTotalLength] = 0;
401
- this._inflate[kBuffers] = [];
402
- this._inflate.on("error", inflateOnError);
403
- this._inflate.on("data", inflateOnData);
404
- }
405
- this._inflate[kCallback] = callback;
406
- this._inflate.write(data);
407
- if (fin) this._inflate.write(TRAILER);
408
- this._inflate.flush(() => {
409
- const err = this._inflate[kError];
410
- if (err) {
411
- this._inflate.close();
412
- this._inflate = null;
413
- callback(err);
414
- return;
415
- }
416
- const data = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
417
- if (this._inflate._readableState.endEmitted) {
418
- this._inflate.close();
419
- this._inflate = null;
420
- } else {
421
- this._inflate[kTotalLength] = 0;
422
- this._inflate[kBuffers] = [];
423
- if (fin && this.params[`${endpoint}_no_context_takeover`]) this._inflate.reset();
424
- }
425
- callback(null, data);
426
- });
427
- }
428
- /**
429
- * Compress data.
430
- *
431
- * @param {(Buffer|String)} data Data to compress
432
- * @param {Boolean} fin Specifies whether or not this is the last fragment
433
- * @param {Function} callback Callback
434
- * @private
435
- */
436
- _compress(data, fin, callback) {
437
- const endpoint = this._isServer ? "server" : "client";
438
- if (!this._deflate) {
439
- const key = `${endpoint}_max_window_bits`;
440
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
441
- this._deflate = zlib.createDeflateRaw({
442
- ...this._options.zlibDeflateOptions,
443
- windowBits
444
- });
445
- this._deflate[kTotalLength] = 0;
446
- this._deflate[kBuffers] = [];
447
- this._deflate.on("data", deflateOnData);
448
- }
449
- this._deflate[kCallback] = callback;
450
- this._deflate.write(data);
451
- this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
452
- if (!this._deflate) return;
453
- let data = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
454
- if (fin) data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
455
- this._deflate[kCallback] = null;
456
- this._deflate[kTotalLength] = 0;
457
- this._deflate[kBuffers] = [];
458
- if (fin && this.params[`${endpoint}_no_context_takeover`]) this._deflate.reset();
459
- callback(null, data);
460
- });
461
- }
462
- };
463
- module.exports = PerMessageDeflate;
464
- /**
465
- * The listener of the `zlib.DeflateRaw` stream `'data'` event.
466
- *
467
- * @param {Buffer} chunk A chunk of data
468
- * @private
469
- */
470
- function deflateOnData(chunk) {
471
- this[kBuffers].push(chunk);
472
- this[kTotalLength] += chunk.length;
473
- }
474
- /**
475
- * The listener of the `zlib.InflateRaw` stream `'data'` event.
476
- *
477
- * @param {Buffer} chunk A chunk of data
478
- * @private
479
- */
480
- function inflateOnData(chunk) {
481
- this[kTotalLength] += chunk.length;
482
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
483
- this[kBuffers].push(chunk);
484
- return;
485
- }
486
- this[kError] = /* @__PURE__ */ new RangeError("Max payload size exceeded");
487
- this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
488
- this[kError][kStatusCode] = 1009;
489
- this.removeListener("data", inflateOnData);
490
- this.reset();
491
- }
492
- /**
493
- * The listener of the `zlib.InflateRaw` stream `'error'` event.
494
- *
495
- * @param {Error} err The emitted error
496
- * @private
497
- */
498
- function inflateOnError(err) {
499
- this[kPerMessageDeflate]._inflate = null;
500
- if (this[kError]) {
501
- this[kCallback](this[kError]);
502
- return;
503
- }
504
- err[kStatusCode] = 1007;
505
- this[kCallback](err);
506
- }
507
- }));
508
- //#endregion
509
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/validation.js
510
- var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
511
- const { isUtf8 } = __require("buffer");
512
- const { hasBlob } = require_constants();
513
- const tokenChars = [
514
- 0,
515
- 0,
516
- 0,
517
- 0,
518
- 0,
519
- 0,
520
- 0,
521
- 0,
522
- 0,
523
- 0,
524
- 0,
525
- 0,
526
- 0,
527
- 0,
528
- 0,
529
- 0,
530
- 0,
531
- 0,
532
- 0,
533
- 0,
534
- 0,
535
- 0,
536
- 0,
537
- 0,
538
- 0,
539
- 0,
540
- 0,
541
- 0,
542
- 0,
543
- 0,
544
- 0,
545
- 0,
546
- 0,
547
- 1,
548
- 0,
549
- 1,
550
- 1,
551
- 1,
552
- 1,
553
- 1,
554
- 0,
555
- 0,
556
- 1,
557
- 1,
558
- 0,
559
- 1,
560
- 1,
561
- 0,
562
- 1,
563
- 1,
564
- 1,
565
- 1,
566
- 1,
567
- 1,
568
- 1,
569
- 1,
570
- 1,
571
- 1,
572
- 0,
573
- 0,
574
- 0,
575
- 0,
576
- 0,
577
- 0,
578
- 0,
579
- 1,
580
- 1,
581
- 1,
582
- 1,
583
- 1,
584
- 1,
585
- 1,
586
- 1,
587
- 1,
588
- 1,
589
- 1,
590
- 1,
591
- 1,
592
- 1,
593
- 1,
594
- 1,
595
- 1,
596
- 1,
597
- 1,
598
- 1,
599
- 1,
600
- 1,
601
- 1,
602
- 1,
603
- 1,
604
- 1,
605
- 0,
606
- 0,
607
- 0,
608
- 1,
609
- 1,
610
- 1,
611
- 1,
612
- 1,
613
- 1,
614
- 1,
615
- 1,
616
- 1,
617
- 1,
618
- 1,
619
- 1,
620
- 1,
621
- 1,
622
- 1,
623
- 1,
624
- 1,
625
- 1,
626
- 1,
627
- 1,
628
- 1,
629
- 1,
630
- 1,
631
- 1,
632
- 1,
633
- 1,
634
- 1,
635
- 1,
636
- 1,
637
- 0,
638
- 1,
639
- 0,
640
- 1,
641
- 0
642
- ];
643
- /**
644
- * Checks if a status code is allowed in a close frame.
645
- *
646
- * @param {Number} code The status code
647
- * @return {Boolean} `true` if the status code is valid, else `false`
648
- * @public
649
- */
650
- function isValidStatusCode(code) {
651
- return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
652
- }
653
- /**
654
- * Checks if a given buffer contains only correct UTF-8.
655
- * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
656
- * Markus Kuhn.
657
- *
658
- * @param {Buffer} buf The buffer to check
659
- * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
660
- * @public
661
- */
662
- function _isValidUTF8(buf) {
663
- const len = buf.length;
664
- let i = 0;
665
- while (i < len) if ((buf[i] & 128) === 0) i++;
666
- else if ((buf[i] & 224) === 192) {
667
- if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) return false;
668
- i += 2;
669
- } else if ((buf[i] & 240) === 224) {
670
- if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) return false;
671
- i += 3;
672
- } else if ((buf[i] & 248) === 240) {
673
- if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) return false;
674
- i += 4;
675
- } else return false;
676
- return true;
677
- }
678
- /**
679
- * Determines whether a value is a `Blob`.
680
- *
681
- * @param {*} value The value to be tested
682
- * @return {Boolean} `true` if `value` is a `Blob`, else `false`
683
- * @private
684
- */
685
- function isBlob(value) {
686
- return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
687
- }
688
- module.exports = {
689
- isBlob,
690
- isValidStatusCode,
691
- isValidUTF8: _isValidUTF8,
692
- tokenChars
693
- };
694
- if (isUtf8) module.exports.isValidUTF8 = function(buf) {
695
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
696
- };
697
- else if (!process.env.WS_NO_UTF_8_VALIDATE) try {
698
- const isValidUTF8 = __require("utf-8-validate");
699
- module.exports.isValidUTF8 = function(buf) {
700
- return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
701
- };
702
- } catch (e) {}
703
- }));
704
- //#endregion
705
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/receiver.js
706
- var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
707
- const { Writable } = __require("stream");
708
- const PerMessageDeflate = require_permessage_deflate();
709
- const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require_constants();
710
- const { concat, toArrayBuffer, unmask } = require_buffer_util();
711
- const { isValidStatusCode, isValidUTF8 } = require_validation();
712
- const FastBuffer = Buffer[Symbol.species];
713
- const GET_INFO = 0;
714
- const GET_PAYLOAD_LENGTH_16 = 1;
715
- const GET_PAYLOAD_LENGTH_64 = 2;
716
- const GET_MASK = 3;
717
- const GET_DATA = 4;
718
- const INFLATING = 5;
719
- const DEFER_EVENT = 6;
720
- /**
721
- * HyBi Receiver implementation.
722
- *
723
- * @extends Writable
724
- */
725
- var Receiver = class extends Writable {
726
- /**
727
- * Creates a Receiver instance.
728
- *
729
- * @param {Object} [options] Options object
730
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
731
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
732
- * multiple times in the same tick
733
- * @param {String} [options.binaryType=nodebuffer] The type for binary data
734
- * @param {Object} [options.extensions] An object containing the negotiated
735
- * extensions
736
- * @param {Boolean} [options.isServer=false] Specifies whether to operate in
737
- * client or server mode
738
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
739
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
740
- * not to skip UTF-8 validation for text and close messages
741
- */
742
- constructor(options = {}) {
743
- super();
744
- this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
745
- this._binaryType = options.binaryType || BINARY_TYPES[0];
746
- this._extensions = options.extensions || {};
747
- this._isServer = !!options.isServer;
748
- this._maxPayload = options.maxPayload | 0;
749
- this._skipUTF8Validation = !!options.skipUTF8Validation;
750
- this[kWebSocket] = void 0;
751
- this._bufferedBytes = 0;
752
- this._buffers = [];
753
- this._compressed = false;
754
- this._payloadLength = 0;
755
- this._mask = void 0;
756
- this._fragmented = 0;
757
- this._masked = false;
758
- this._fin = false;
759
- this._opcode = 0;
760
- this._totalPayloadLength = 0;
761
- this._messageLength = 0;
762
- this._fragments = [];
763
- this._errored = false;
764
- this._loop = false;
765
- this._state = GET_INFO;
766
- }
767
- /**
768
- * Implements `Writable.prototype._write()`.
769
- *
770
- * @param {Buffer} chunk The chunk of data to write
771
- * @param {String} encoding The character encoding of `chunk`
772
- * @param {Function} cb Callback
773
- * @private
774
- */
775
- _write(chunk, encoding, cb) {
776
- if (this._opcode === 8 && this._state == GET_INFO) return cb();
777
- this._bufferedBytes += chunk.length;
778
- this._buffers.push(chunk);
779
- this.startLoop(cb);
780
- }
781
- /**
782
- * Consumes `n` bytes from the buffered data.
783
- *
784
- * @param {Number} n The number of bytes to consume
785
- * @return {Buffer} The consumed bytes
786
- * @private
787
- */
788
- consume(n) {
789
- this._bufferedBytes -= n;
790
- if (n === this._buffers[0].length) return this._buffers.shift();
791
- if (n < this._buffers[0].length) {
792
- const buf = this._buffers[0];
793
- this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
794
- return new FastBuffer(buf.buffer, buf.byteOffset, n);
795
- }
796
- const dst = Buffer.allocUnsafe(n);
797
- do {
798
- const buf = this._buffers[0];
799
- const offset = dst.length - n;
800
- if (n >= buf.length) dst.set(this._buffers.shift(), offset);
801
- else {
802
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
803
- this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
804
- }
805
- n -= buf.length;
806
- } while (n > 0);
807
- return dst;
808
- }
809
- /**
810
- * Starts the parsing loop.
811
- *
812
- * @param {Function} cb Callback
813
- * @private
814
- */
815
- startLoop(cb) {
816
- this._loop = true;
817
- do
818
- switch (this._state) {
819
- case GET_INFO:
820
- this.getInfo(cb);
821
- break;
822
- case GET_PAYLOAD_LENGTH_16:
823
- this.getPayloadLength16(cb);
824
- break;
825
- case GET_PAYLOAD_LENGTH_64:
826
- this.getPayloadLength64(cb);
827
- break;
828
- case GET_MASK:
829
- this.getMask();
830
- break;
831
- case GET_DATA:
832
- this.getData(cb);
833
- break;
834
- case INFLATING:
835
- case DEFER_EVENT:
836
- this._loop = false;
837
- return;
838
- }
839
- while (this._loop);
840
- if (!this._errored) cb();
841
- }
842
- /**
843
- * Reads the first two bytes of a frame.
844
- *
845
- * @param {Function} cb Callback
846
- * @private
847
- */
848
- getInfo(cb) {
849
- if (this._bufferedBytes < 2) {
850
- this._loop = false;
851
- return;
852
- }
853
- const buf = this.consume(2);
854
- if ((buf[0] & 48) !== 0) {
855
- cb(this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3"));
856
- return;
857
- }
858
- const compressed = (buf[0] & 64) === 64;
859
- if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
860
- cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
861
- return;
862
- }
863
- this._fin = (buf[0] & 128) === 128;
864
- this._opcode = buf[0] & 15;
865
- this._payloadLength = buf[1] & 127;
866
- if (this._opcode === 0) {
867
- if (compressed) {
868
- cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
869
- return;
870
- }
871
- if (!this._fragmented) {
872
- cb(this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE"));
873
- return;
874
- }
875
- this._opcode = this._fragmented;
876
- } else if (this._opcode === 1 || this._opcode === 2) {
877
- if (this._fragmented) {
878
- cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
879
- return;
880
- }
881
- this._compressed = compressed;
882
- } else if (this._opcode > 7 && this._opcode < 11) {
883
- if (!this._fin) {
884
- cb(this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN"));
885
- return;
886
- }
887
- if (compressed) {
888
- cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
889
- return;
890
- }
891
- if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
892
- cb(this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"));
893
- return;
894
- }
895
- } else {
896
- cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
897
- return;
898
- }
899
- if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
900
- this._masked = (buf[1] & 128) === 128;
901
- if (this._isServer) {
902
- if (!this._masked) {
903
- cb(this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK"));
904
- return;
905
- }
906
- } else if (this._masked) {
907
- cb(this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK"));
908
- return;
909
- }
910
- if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
911
- else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
912
- else this.haveLength(cb);
913
- }
914
- /**
915
- * Gets extended payload length (7+16).
916
- *
917
- * @param {Function} cb Callback
918
- * @private
919
- */
920
- getPayloadLength16(cb) {
921
- if (this._bufferedBytes < 2) {
922
- this._loop = false;
923
- return;
924
- }
925
- this._payloadLength = this.consume(2).readUInt16BE(0);
926
- this.haveLength(cb);
927
- }
928
- /**
929
- * Gets extended payload length (7+64).
930
- *
931
- * @param {Function} cb Callback
932
- * @private
933
- */
934
- getPayloadLength64(cb) {
935
- if (this._bufferedBytes < 8) {
936
- this._loop = false;
937
- return;
938
- }
939
- const buf = this.consume(8);
940
- const num = buf.readUInt32BE(0);
941
- if (num > Math.pow(2, 21) - 1) {
942
- cb(this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"));
943
- return;
944
- }
945
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
946
- this.haveLength(cb);
947
- }
948
- /**
949
- * Payload length has been read.
950
- *
951
- * @param {Function} cb Callback
952
- * @private
953
- */
954
- haveLength(cb) {
955
- if (this._payloadLength && this._opcode < 8) {
956
- this._totalPayloadLength += this._payloadLength;
957
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
958
- cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
959
- return;
960
- }
961
- }
962
- if (this._masked) this._state = GET_MASK;
963
- else this._state = GET_DATA;
964
- }
965
- /**
966
- * Reads mask bytes.
967
- *
968
- * @private
969
- */
970
- getMask() {
971
- if (this._bufferedBytes < 4) {
972
- this._loop = false;
973
- return;
974
- }
975
- this._mask = this.consume(4);
976
- this._state = GET_DATA;
977
- }
978
- /**
979
- * Reads data bytes.
980
- *
981
- * @param {Function} cb Callback
982
- * @private
983
- */
984
- getData(cb) {
985
- let data = EMPTY_BUFFER;
986
- if (this._payloadLength) {
987
- if (this._bufferedBytes < this._payloadLength) {
988
- this._loop = false;
989
- return;
990
- }
991
- data = this.consume(this._payloadLength);
992
- if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) unmask(data, this._mask);
993
- }
994
- if (this._opcode > 7) {
995
- this.controlMessage(data, cb);
996
- return;
997
- }
998
- if (this._compressed) {
999
- this._state = INFLATING;
1000
- this.decompress(data, cb);
1001
- return;
1002
- }
1003
- if (data.length) {
1004
- this._messageLength = this._totalPayloadLength;
1005
- this._fragments.push(data);
1006
- }
1007
- this.dataMessage(cb);
1008
- }
1009
- /**
1010
- * Decompresses data.
1011
- *
1012
- * @param {Buffer} data Compressed data
1013
- * @param {Function} cb Callback
1014
- * @private
1015
- */
1016
- decompress(data, cb) {
1017
- this._extensions[PerMessageDeflate.extensionName].decompress(data, this._fin, (err, buf) => {
1018
- if (err) return cb(err);
1019
- if (buf.length) {
1020
- this._messageLength += buf.length;
1021
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1022
- cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
1023
- return;
1024
- }
1025
- this._fragments.push(buf);
1026
- }
1027
- this.dataMessage(cb);
1028
- if (this._state === GET_INFO) this.startLoop(cb);
1029
- });
1030
- }
1031
- /**
1032
- * Handles a data message.
1033
- *
1034
- * @param {Function} cb Callback
1035
- * @private
1036
- */
1037
- dataMessage(cb) {
1038
- if (!this._fin) {
1039
- this._state = GET_INFO;
1040
- return;
1041
- }
1042
- const messageLength = this._messageLength;
1043
- const fragments = this._fragments;
1044
- this._totalPayloadLength = 0;
1045
- this._messageLength = 0;
1046
- this._fragmented = 0;
1047
- this._fragments = [];
1048
- if (this._opcode === 2) {
1049
- let data;
1050
- if (this._binaryType === "nodebuffer") data = concat(fragments, messageLength);
1051
- else if (this._binaryType === "arraybuffer") data = toArrayBuffer(concat(fragments, messageLength));
1052
- else if (this._binaryType === "blob") data = new Blob(fragments);
1053
- else data = fragments;
1054
- if (this._allowSynchronousEvents) {
1055
- this.emit("message", data, true);
1056
- this._state = GET_INFO;
1057
- } else {
1058
- this._state = DEFER_EVENT;
1059
- setImmediate(() => {
1060
- this.emit("message", data, true);
1061
- this._state = GET_INFO;
1062
- this.startLoop(cb);
1063
- });
1064
- }
1065
- } else {
1066
- const buf = concat(fragments, messageLength);
1067
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1068
- cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
1069
- return;
1070
- }
1071
- if (this._state === INFLATING || this._allowSynchronousEvents) {
1072
- this.emit("message", buf, false);
1073
- this._state = GET_INFO;
1074
- } else {
1075
- this._state = DEFER_EVENT;
1076
- setImmediate(() => {
1077
- this.emit("message", buf, false);
1078
- this._state = GET_INFO;
1079
- this.startLoop(cb);
1080
- });
1081
- }
1082
- }
1083
- }
1084
- /**
1085
- * Handles a control message.
1086
- *
1087
- * @param {Buffer} data Data to handle
1088
- * @return {(Error|RangeError|undefined)} A possible error
1089
- * @private
1090
- */
1091
- controlMessage(data, cb) {
1092
- if (this._opcode === 8) {
1093
- if (data.length === 0) {
1094
- this._loop = false;
1095
- this.emit("conclude", 1005, EMPTY_BUFFER);
1096
- this.end();
1097
- } else {
1098
- const code = data.readUInt16BE(0);
1099
- if (!isValidStatusCode(code)) {
1100
- cb(this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE"));
1101
- return;
1102
- }
1103
- const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
1104
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1105
- cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
1106
- return;
1107
- }
1108
- this._loop = false;
1109
- this.emit("conclude", code, buf);
1110
- this.end();
1111
- }
1112
- this._state = GET_INFO;
1113
- return;
1114
- }
1115
- if (this._allowSynchronousEvents) {
1116
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
1117
- this._state = GET_INFO;
1118
- } else {
1119
- this._state = DEFER_EVENT;
1120
- setImmediate(() => {
1121
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
1122
- this._state = GET_INFO;
1123
- this.startLoop(cb);
1124
- });
1125
- }
1126
- }
1127
- /**
1128
- * Builds an error object.
1129
- *
1130
- * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1131
- * @param {String} message The error message
1132
- * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1133
- * `message`
1134
- * @param {Number} statusCode The status code
1135
- * @param {String} errorCode The exposed error code
1136
- * @return {(Error|RangeError)} The error
1137
- * @private
1138
- */
1139
- createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1140
- this._loop = false;
1141
- this._errored = true;
1142
- const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
1143
- Error.captureStackTrace(err, this.createError);
1144
- err.code = errorCode;
1145
- err[kStatusCode] = statusCode;
1146
- return err;
1147
- }
1148
- };
1149
- module.exports = Receiver;
1150
- }));
1151
- //#endregion
1152
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/sender.js
1153
- var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1154
- const { Duplex: Duplex$3 } = __require("stream");
1155
- const { randomFillSync } = __require("crypto");
1156
- const PerMessageDeflate = require_permessage_deflate();
1157
- const { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1158
- const { isBlob, isValidStatusCode } = require_validation();
1159
- const { mask: applyMask, toBuffer } = require_buffer_util();
1160
- const kByteLength = Symbol("kByteLength");
1161
- const maskBuffer = Buffer.alloc(4);
1162
- const RANDOM_POOL_SIZE = 8 * 1024;
1163
- let randomPool;
1164
- let randomPoolPointer = RANDOM_POOL_SIZE;
1165
- const DEFAULT = 0;
1166
- const DEFLATING = 1;
1167
- const GET_BLOB_DATA = 2;
1168
- module.exports = class Sender {
1169
- /**
1170
- * Creates a Sender instance.
1171
- *
1172
- * @param {Duplex} socket The connection socket
1173
- * @param {Object} [extensions] An object containing the negotiated extensions
1174
- * @param {Function} [generateMask] The function used to generate the masking
1175
- * key
1176
- */
1177
- constructor(socket, extensions, generateMask) {
1178
- this._extensions = extensions || {};
1179
- if (generateMask) {
1180
- this._generateMask = generateMask;
1181
- this._maskBuffer = Buffer.alloc(4);
1182
- }
1183
- this._socket = socket;
1184
- this._firstFragment = true;
1185
- this._compress = false;
1186
- this._bufferedBytes = 0;
1187
- this._queue = [];
1188
- this._state = DEFAULT;
1189
- this.onerror = NOOP;
1190
- this[kWebSocket] = void 0;
1191
- }
1192
- /**
1193
- * Frames a piece of data according to the HyBi WebSocket protocol.
1194
- *
1195
- * @param {(Buffer|String)} data The data to frame
1196
- * @param {Object} options Options object
1197
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1198
- * FIN bit
1199
- * @param {Function} [options.generateMask] The function used to generate the
1200
- * masking key
1201
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1202
- * `data`
1203
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1204
- * key
1205
- * @param {Number} options.opcode The opcode
1206
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1207
- * modified
1208
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1209
- * RSV1 bit
1210
- * @return {(Buffer|String)[]} The framed data
1211
- * @public
1212
- */
1213
- static frame(data, options) {
1214
- let mask;
1215
- let merge = false;
1216
- let offset = 2;
1217
- let skipMasking = false;
1218
- if (options.mask) {
1219
- mask = options.maskBuffer || maskBuffer;
1220
- if (options.generateMask) options.generateMask(mask);
1221
- else {
1222
- if (randomPoolPointer === RANDOM_POOL_SIZE) {
1223
- /* istanbul ignore else */
1224
- if (randomPool === void 0) randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1225
- randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1226
- randomPoolPointer = 0;
1227
- }
1228
- mask[0] = randomPool[randomPoolPointer++];
1229
- mask[1] = randomPool[randomPoolPointer++];
1230
- mask[2] = randomPool[randomPoolPointer++];
1231
- mask[3] = randomPool[randomPoolPointer++];
1232
- }
1233
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1234
- offset = 6;
1235
- }
1236
- let dataLength;
1237
- if (typeof data === "string") if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) dataLength = options[kByteLength];
1238
- else {
1239
- data = Buffer.from(data);
1240
- dataLength = data.length;
1241
- }
1242
- else {
1243
- dataLength = data.length;
1244
- merge = options.mask && options.readOnly && !skipMasking;
1245
- }
1246
- let payloadLength = dataLength;
1247
- if (dataLength >= 65536) {
1248
- offset += 8;
1249
- payloadLength = 127;
1250
- } else if (dataLength > 125) {
1251
- offset += 2;
1252
- payloadLength = 126;
1253
- }
1254
- const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1255
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
1256
- if (options.rsv1) target[0] |= 64;
1257
- target[1] = payloadLength;
1258
- if (payloadLength === 126) target.writeUInt16BE(dataLength, 2);
1259
- else if (payloadLength === 127) {
1260
- target[2] = target[3] = 0;
1261
- target.writeUIntBE(dataLength, 4, 6);
1262
- }
1263
- if (!options.mask) return [target, data];
1264
- target[1] |= 128;
1265
- target[offset - 4] = mask[0];
1266
- target[offset - 3] = mask[1];
1267
- target[offset - 2] = mask[2];
1268
- target[offset - 1] = mask[3];
1269
- if (skipMasking) return [target, data];
1270
- if (merge) {
1271
- applyMask(data, mask, target, offset, dataLength);
1272
- return [target];
1273
- }
1274
- applyMask(data, mask, data, 0, dataLength);
1275
- return [target, data];
1276
- }
1277
- /**
1278
- * Sends a close message to the other peer.
1279
- *
1280
- * @param {Number} [code] The status code component of the body
1281
- * @param {(String|Buffer)} [data] The message component of the body
1282
- * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1283
- * @param {Function} [cb] Callback
1284
- * @public
1285
- */
1286
- close(code, data, mask, cb) {
1287
- let buf;
1288
- if (code === void 0) buf = EMPTY_BUFFER;
1289
- else if (typeof code !== "number" || !isValidStatusCode(code)) throw new TypeError("First argument must be a valid error code number");
1290
- else if (data === void 0 || !data.length) {
1291
- buf = Buffer.allocUnsafe(2);
1292
- buf.writeUInt16BE(code, 0);
1293
- } else {
1294
- const length = Buffer.byteLength(data);
1295
- if (length > 123) throw new RangeError("The message must not be greater than 123 bytes");
1296
- buf = Buffer.allocUnsafe(2 + length);
1297
- buf.writeUInt16BE(code, 0);
1298
- if (typeof data === "string") buf.write(data, 2);
1299
- else buf.set(data, 2);
1300
- }
1301
- const options = {
1302
- [kByteLength]: buf.length,
1303
- fin: true,
1304
- generateMask: this._generateMask,
1305
- mask,
1306
- maskBuffer: this._maskBuffer,
1307
- opcode: 8,
1308
- readOnly: false,
1309
- rsv1: false
1310
- };
1311
- if (this._state !== DEFAULT) this.enqueue([
1312
- this.dispatch,
1313
- buf,
1314
- false,
1315
- options,
1316
- cb
1317
- ]);
1318
- else this.sendFrame(Sender.frame(buf, options), cb);
1319
- }
1320
- /**
1321
- * Sends a ping message to the other peer.
1322
- *
1323
- * @param {*} data The message to send
1324
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1325
- * @param {Function} [cb] Callback
1326
- * @public
1327
- */
1328
- ping(data, mask, cb) {
1329
- let byteLength;
1330
- let readOnly;
1331
- if (typeof data === "string") {
1332
- byteLength = Buffer.byteLength(data);
1333
- readOnly = false;
1334
- } else if (isBlob(data)) {
1335
- byteLength = data.size;
1336
- readOnly = false;
1337
- } else {
1338
- data = toBuffer(data);
1339
- byteLength = data.length;
1340
- readOnly = toBuffer.readOnly;
1341
- }
1342
- if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
1343
- const options = {
1344
- [kByteLength]: byteLength,
1345
- fin: true,
1346
- generateMask: this._generateMask,
1347
- mask,
1348
- maskBuffer: this._maskBuffer,
1349
- opcode: 9,
1350
- readOnly,
1351
- rsv1: false
1352
- };
1353
- if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
1354
- this.getBlobData,
1355
- data,
1356
- false,
1357
- options,
1358
- cb
1359
- ]);
1360
- else this.getBlobData(data, false, options, cb);
1361
- else if (this._state !== DEFAULT) this.enqueue([
1362
- this.dispatch,
1363
- data,
1364
- false,
1365
- options,
1366
- cb
1367
- ]);
1368
- else this.sendFrame(Sender.frame(data, options), cb);
1369
- }
1370
- /**
1371
- * Sends a pong message to the other peer.
1372
- *
1373
- * @param {*} data The message to send
1374
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1375
- * @param {Function} [cb] Callback
1376
- * @public
1377
- */
1378
- pong(data, mask, cb) {
1379
- let byteLength;
1380
- let readOnly;
1381
- if (typeof data === "string") {
1382
- byteLength = Buffer.byteLength(data);
1383
- readOnly = false;
1384
- } else if (isBlob(data)) {
1385
- byteLength = data.size;
1386
- readOnly = false;
1387
- } else {
1388
- data = toBuffer(data);
1389
- byteLength = data.length;
1390
- readOnly = toBuffer.readOnly;
1391
- }
1392
- if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
1393
- const options = {
1394
- [kByteLength]: byteLength,
1395
- fin: true,
1396
- generateMask: this._generateMask,
1397
- mask,
1398
- maskBuffer: this._maskBuffer,
1399
- opcode: 10,
1400
- readOnly,
1401
- rsv1: false
1402
- };
1403
- if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
1404
- this.getBlobData,
1405
- data,
1406
- false,
1407
- options,
1408
- cb
1409
- ]);
1410
- else this.getBlobData(data, false, options, cb);
1411
- else if (this._state !== DEFAULT) this.enqueue([
1412
- this.dispatch,
1413
- data,
1414
- false,
1415
- options,
1416
- cb
1417
- ]);
1418
- else this.sendFrame(Sender.frame(data, options), cb);
1419
- }
1420
- /**
1421
- * Sends a data message to the other peer.
1422
- *
1423
- * @param {*} data The message to send
1424
- * @param {Object} options Options object
1425
- * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1426
- * or text
1427
- * @param {Boolean} [options.compress=false] Specifies whether or not to
1428
- * compress `data`
1429
- * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1430
- * last one
1431
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1432
- * `data`
1433
- * @param {Function} [cb] Callback
1434
- * @public
1435
- */
1436
- send(data, options, cb) {
1437
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1438
- let opcode = options.binary ? 2 : 1;
1439
- let rsv1 = options.compress;
1440
- let byteLength;
1441
- let readOnly;
1442
- if (typeof data === "string") {
1443
- byteLength = Buffer.byteLength(data);
1444
- readOnly = false;
1445
- } else if (isBlob(data)) {
1446
- byteLength = data.size;
1447
- readOnly = false;
1448
- } else {
1449
- data = toBuffer(data);
1450
- byteLength = data.length;
1451
- readOnly = toBuffer.readOnly;
1452
- }
1453
- if (this._firstFragment) {
1454
- this._firstFragment = false;
1455
- if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) rsv1 = byteLength >= perMessageDeflate._threshold;
1456
- this._compress = rsv1;
1457
- } else {
1458
- rsv1 = false;
1459
- opcode = 0;
1460
- }
1461
- if (options.fin) this._firstFragment = true;
1462
- const opts = {
1463
- [kByteLength]: byteLength,
1464
- fin: options.fin,
1465
- generateMask: this._generateMask,
1466
- mask: options.mask,
1467
- maskBuffer: this._maskBuffer,
1468
- opcode,
1469
- readOnly,
1470
- rsv1
1471
- };
1472
- if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
1473
- this.getBlobData,
1474
- data,
1475
- this._compress,
1476
- opts,
1477
- cb
1478
- ]);
1479
- else this.getBlobData(data, this._compress, opts, cb);
1480
- else if (this._state !== DEFAULT) this.enqueue([
1481
- this.dispatch,
1482
- data,
1483
- this._compress,
1484
- opts,
1485
- cb
1486
- ]);
1487
- else this.dispatch(data, this._compress, opts, cb);
1488
- }
1489
- /**
1490
- * Gets the contents of a blob as binary data.
1491
- *
1492
- * @param {Blob} blob The blob
1493
- * @param {Boolean} [compress=false] Specifies whether or not to compress
1494
- * the data
1495
- * @param {Object} options Options object
1496
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1497
- * FIN bit
1498
- * @param {Function} [options.generateMask] The function used to generate the
1499
- * masking key
1500
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1501
- * `data`
1502
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1503
- * key
1504
- * @param {Number} options.opcode The opcode
1505
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1506
- * modified
1507
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1508
- * RSV1 bit
1509
- * @param {Function} [cb] Callback
1510
- * @private
1511
- */
1512
- getBlobData(blob, compress, options, cb) {
1513
- this._bufferedBytes += options[kByteLength];
1514
- this._state = GET_BLOB_DATA;
1515
- blob.arrayBuffer().then((arrayBuffer) => {
1516
- if (this._socket.destroyed) {
1517
- const err = /* @__PURE__ */ new Error("The socket was closed while the blob was being read");
1518
- process.nextTick(callCallbacks, this, err, cb);
1519
- return;
1520
- }
1521
- this._bufferedBytes -= options[kByteLength];
1522
- const data = toBuffer(arrayBuffer);
1523
- if (!compress) {
1524
- this._state = DEFAULT;
1525
- this.sendFrame(Sender.frame(data, options), cb);
1526
- this.dequeue();
1527
- } else this.dispatch(data, compress, options, cb);
1528
- }).catch((err) => {
1529
- process.nextTick(onError, this, err, cb);
1530
- });
1531
- }
1532
- /**
1533
- * Dispatches a message.
1534
- *
1535
- * @param {(Buffer|String)} data The message to send
1536
- * @param {Boolean} [compress=false] Specifies whether or not to compress
1537
- * `data`
1538
- * @param {Object} options Options object
1539
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1540
- * FIN bit
1541
- * @param {Function} [options.generateMask] The function used to generate the
1542
- * masking key
1543
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1544
- * `data`
1545
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1546
- * key
1547
- * @param {Number} options.opcode The opcode
1548
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1549
- * modified
1550
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1551
- * RSV1 bit
1552
- * @param {Function} [cb] Callback
1553
- * @private
1554
- */
1555
- dispatch(data, compress, options, cb) {
1556
- if (!compress) {
1557
- this.sendFrame(Sender.frame(data, options), cb);
1558
- return;
1559
- }
1560
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1561
- this._bufferedBytes += options[kByteLength];
1562
- this._state = DEFLATING;
1563
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
1564
- if (this._socket.destroyed) {
1565
- callCallbacks(this, /* @__PURE__ */ new Error("The socket was closed while data was being compressed"), cb);
1566
- return;
1567
- }
1568
- this._bufferedBytes -= options[kByteLength];
1569
- this._state = DEFAULT;
1570
- options.readOnly = false;
1571
- this.sendFrame(Sender.frame(buf, options), cb);
1572
- this.dequeue();
1573
- });
1574
- }
1575
- /**
1576
- * Executes queued send operations.
1577
- *
1578
- * @private
1579
- */
1580
- dequeue() {
1581
- while (this._state === DEFAULT && this._queue.length) {
1582
- const params = this._queue.shift();
1583
- this._bufferedBytes -= params[3][kByteLength];
1584
- Reflect.apply(params[0], this, params.slice(1));
1585
- }
1586
- }
1587
- /**
1588
- * Enqueues a send operation.
1589
- *
1590
- * @param {Array} params Send operation parameters.
1591
- * @private
1592
- */
1593
- enqueue(params) {
1594
- this._bufferedBytes += params[3][kByteLength];
1595
- this._queue.push(params);
1596
- }
1597
- /**
1598
- * Sends a frame.
1599
- *
1600
- * @param {(Buffer | String)[]} list The frame to send
1601
- * @param {Function} [cb] Callback
1602
- * @private
1603
- */
1604
- sendFrame(list, cb) {
1605
- if (list.length === 2) {
1606
- this._socket.cork();
1607
- this._socket.write(list[0]);
1608
- this._socket.write(list[1], cb);
1609
- this._socket.uncork();
1610
- } else this._socket.write(list[0], cb);
1611
- }
1612
- };
1613
- /**
1614
- * Calls queued callbacks with an error.
1615
- *
1616
- * @param {Sender} sender The `Sender` instance
1617
- * @param {Error} err The error to call the callbacks with
1618
- * @param {Function} [cb] The first callback
1619
- * @private
1620
- */
1621
- function callCallbacks(sender, err, cb) {
1622
- if (typeof cb === "function") cb(err);
1623
- for (let i = 0; i < sender._queue.length; i++) {
1624
- const params = sender._queue[i];
1625
- const callback = params[params.length - 1];
1626
- if (typeof callback === "function") callback(err);
1627
- }
1628
- }
1629
- /**
1630
- * Handles a `Sender` error.
1631
- *
1632
- * @param {Sender} sender The `Sender` instance
1633
- * @param {Error} err The error
1634
- * @param {Function} [cb] The first pending callback
1635
- * @private
1636
- */
1637
- function onError(sender, err, cb) {
1638
- callCallbacks(sender, err, cb);
1639
- sender.onerror(err);
1640
- }
1641
- }));
1642
- //#endregion
1643
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/event-target.js
1644
- var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1645
- const { kForOnEventAttribute, kListener } = require_constants();
1646
- const kCode = Symbol("kCode");
1647
- const kData = Symbol("kData");
1648
- const kError = Symbol("kError");
1649
- const kMessage = Symbol("kMessage");
1650
- const kReason = Symbol("kReason");
1651
- const kTarget = Symbol("kTarget");
1652
- const kType = Symbol("kType");
1653
- const kWasClean = Symbol("kWasClean");
1654
- /**
1655
- * Class representing an event.
1656
- */
1657
- var Event = class {
1658
- /**
1659
- * Create a new `Event`.
1660
- *
1661
- * @param {String} type The name of the event
1662
- * @throws {TypeError} If the `type` argument is not specified
1663
- */
1664
- constructor(type) {
1665
- this[kTarget] = null;
1666
- this[kType] = type;
1667
- }
1668
- /**
1669
- * @type {*}
1670
- */
1671
- get target() {
1672
- return this[kTarget];
1673
- }
1674
- /**
1675
- * @type {String}
1676
- */
1677
- get type() {
1678
- return this[kType];
1679
- }
1680
- };
1681
- Object.defineProperty(Event.prototype, "target", { enumerable: true });
1682
- Object.defineProperty(Event.prototype, "type", { enumerable: true });
1683
- /**
1684
- * Class representing a close event.
1685
- *
1686
- * @extends Event
1687
- */
1688
- var CloseEvent = class extends Event {
1689
- /**
1690
- * Create a new `CloseEvent`.
1691
- *
1692
- * @param {String} type The name of the event
1693
- * @param {Object} [options] A dictionary object that allows for setting
1694
- * attributes via object members of the same name
1695
- * @param {Number} [options.code=0] The status code explaining why the
1696
- * connection was closed
1697
- * @param {String} [options.reason=''] A human-readable string explaining why
1698
- * the connection was closed
1699
- * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1700
- * connection was cleanly closed
1701
- */
1702
- constructor(type, options = {}) {
1703
- super(type);
1704
- this[kCode] = options.code === void 0 ? 0 : options.code;
1705
- this[kReason] = options.reason === void 0 ? "" : options.reason;
1706
- this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1707
- }
1708
- /**
1709
- * @type {Number}
1710
- */
1711
- get code() {
1712
- return this[kCode];
1713
- }
1714
- /**
1715
- * @type {String}
1716
- */
1717
- get reason() {
1718
- return this[kReason];
1719
- }
1720
- /**
1721
- * @type {Boolean}
1722
- */
1723
- get wasClean() {
1724
- return this[kWasClean];
1725
- }
1726
- };
1727
- Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1728
- Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1729
- Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1730
- /**
1731
- * Class representing an error event.
1732
- *
1733
- * @extends Event
1734
- */
1735
- var ErrorEvent = class extends Event {
1736
- /**
1737
- * Create a new `ErrorEvent`.
1738
- *
1739
- * @param {String} type The name of the event
1740
- * @param {Object} [options] A dictionary object that allows for setting
1741
- * attributes via object members of the same name
1742
- * @param {*} [options.error=null] The error that generated this event
1743
- * @param {String} [options.message=''] The error message
1744
- */
1745
- constructor(type, options = {}) {
1746
- super(type);
1747
- this[kError] = options.error === void 0 ? null : options.error;
1748
- this[kMessage] = options.message === void 0 ? "" : options.message;
1749
- }
1750
- /**
1751
- * @type {*}
1752
- */
1753
- get error() {
1754
- return this[kError];
1755
- }
1756
- /**
1757
- * @type {String}
1758
- */
1759
- get message() {
1760
- return this[kMessage];
1761
- }
1762
- };
1763
- Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1764
- Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1765
- /**
1766
- * Class representing a message event.
1767
- *
1768
- * @extends Event
1769
- */
1770
- var MessageEvent = class extends Event {
1771
- /**
1772
- * Create a new `MessageEvent`.
1773
- *
1774
- * @param {String} type The name of the event
1775
- * @param {Object} [options] A dictionary object that allows for setting
1776
- * attributes via object members of the same name
1777
- * @param {*} [options.data=null] The message content
1778
- */
1779
- constructor(type, options = {}) {
1780
- super(type);
1781
- this[kData] = options.data === void 0 ? null : options.data;
1782
- }
1783
- /**
1784
- * @type {*}
1785
- */
1786
- get data() {
1787
- return this[kData];
1788
- }
1789
- };
1790
- Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1791
- module.exports = {
1792
- CloseEvent,
1793
- ErrorEvent,
1794
- Event,
1795
- EventTarget: {
1796
- addEventListener(type, handler, options = {}) {
1797
- for (const listener of this.listeners(type)) if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) return;
1798
- let wrapper;
1799
- if (type === "message") wrapper = function onMessage(data, isBinary) {
1800
- const event = new MessageEvent("message", { data: isBinary ? data : data.toString() });
1801
- event[kTarget] = this;
1802
- callListener(handler, this, event);
1803
- };
1804
- else if (type === "close") wrapper = function onClose(code, message) {
1805
- const event = new CloseEvent("close", {
1806
- code,
1807
- reason: message.toString(),
1808
- wasClean: this._closeFrameReceived && this._closeFrameSent
1809
- });
1810
- event[kTarget] = this;
1811
- callListener(handler, this, event);
1812
- };
1813
- else if (type === "error") wrapper = function onError(error) {
1814
- const event = new ErrorEvent("error", {
1815
- error,
1816
- message: error.message
1817
- });
1818
- event[kTarget] = this;
1819
- callListener(handler, this, event);
1820
- };
1821
- else if (type === "open") wrapper = function onOpen() {
1822
- const event = new Event("open");
1823
- event[kTarget] = this;
1824
- callListener(handler, this, event);
1825
- };
1826
- else return;
1827
- wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
1828
- wrapper[kListener] = handler;
1829
- if (options.once) this.once(type, wrapper);
1830
- else this.on(type, wrapper);
1831
- },
1832
- removeEventListener(type, handler) {
1833
- for (const listener of this.listeners(type)) if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1834
- this.removeListener(type, listener);
1835
- break;
1836
- }
1837
- }
1838
- },
1839
- MessageEvent
1840
- };
1841
- /**
1842
- * Call an event listener
1843
- *
1844
- * @param {(Function|Object)} listener The listener to call
1845
- * @param {*} thisArg The value to use as `this`` when calling the listener
1846
- * @param {Event} event The event to pass to the listener
1847
- * @private
1848
- */
1849
- function callListener(listener, thisArg, event) {
1850
- if (typeof listener === "object" && listener.handleEvent) listener.handleEvent.call(listener, event);
1851
- else listener.call(thisArg, event);
1852
- }
1853
- }));
1854
- //#endregion
1855
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/extension.js
1856
- var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1857
- const { tokenChars } = require_validation();
1858
- /**
1859
- * Adds an offer to the map of extension offers or a parameter to the map of
1860
- * parameters.
1861
- *
1862
- * @param {Object} dest The map of extension offers or parameters
1863
- * @param {String} name The extension or parameter name
1864
- * @param {(Object|Boolean|String)} elem The extension parameters or the
1865
- * parameter value
1866
- * @private
1867
- */
1868
- function push(dest, name, elem) {
1869
- if (dest[name] === void 0) dest[name] = [elem];
1870
- else dest[name].push(elem);
1871
- }
1872
- /**
1873
- * Parses the `Sec-WebSocket-Extensions` header into an object.
1874
- *
1875
- * @param {String} header The field value of the header
1876
- * @return {Object} The parsed object
1877
- * @public
1878
- */
1879
- function parse(header) {
1880
- const offers = Object.create(null);
1881
- let params = Object.create(null);
1882
- let mustUnescape = false;
1883
- let isEscaping = false;
1884
- let inQuotes = false;
1885
- let extensionName;
1886
- let paramName;
1887
- let start = -1;
1888
- let code = -1;
1889
- let end = -1;
1890
- let i = 0;
1891
- for (; i < header.length; i++) {
1892
- code = header.charCodeAt(i);
1893
- if (extensionName === void 0) if (end === -1 && tokenChars[code] === 1) {
1894
- if (start === -1) start = i;
1895
- } else if (i !== 0 && (code === 32 || code === 9)) {
1896
- if (end === -1 && start !== -1) end = i;
1897
- } else if (code === 59 || code === 44) {
1898
- if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
1899
- if (end === -1) end = i;
1900
- const name = header.slice(start, end);
1901
- if (code === 44) {
1902
- push(offers, name, params);
1903
- params = Object.create(null);
1904
- } else extensionName = name;
1905
- start = end = -1;
1906
- } else throw new SyntaxError(`Unexpected character at index ${i}`);
1907
- else if (paramName === void 0) if (end === -1 && tokenChars[code] === 1) {
1908
- if (start === -1) start = i;
1909
- } else if (code === 32 || code === 9) {
1910
- if (end === -1 && start !== -1) end = i;
1911
- } else if (code === 59 || code === 44) {
1912
- if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
1913
- if (end === -1) end = i;
1914
- push(params, header.slice(start, end), true);
1915
- if (code === 44) {
1916
- push(offers, extensionName, params);
1917
- params = Object.create(null);
1918
- extensionName = void 0;
1919
- }
1920
- start = end = -1;
1921
- } else if (code === 61 && start !== -1 && end === -1) {
1922
- paramName = header.slice(start, i);
1923
- start = end = -1;
1924
- } else throw new SyntaxError(`Unexpected character at index ${i}`);
1925
- else if (isEscaping) {
1926
- if (tokenChars[code] !== 1) throw new SyntaxError(`Unexpected character at index ${i}`);
1927
- if (start === -1) start = i;
1928
- else if (!mustUnescape) mustUnescape = true;
1929
- isEscaping = false;
1930
- } else if (inQuotes) if (tokenChars[code] === 1) {
1931
- if (start === -1) start = i;
1932
- } else if (code === 34 && start !== -1) {
1933
- inQuotes = false;
1934
- end = i;
1935
- } else if (code === 92) isEscaping = true;
1936
- else throw new SyntaxError(`Unexpected character at index ${i}`);
1937
- else if (code === 34 && header.charCodeAt(i - 1) === 61) inQuotes = true;
1938
- else if (end === -1 && tokenChars[code] === 1) {
1939
- if (start === -1) start = i;
1940
- } else if (start !== -1 && (code === 32 || code === 9)) {
1941
- if (end === -1) end = i;
1942
- } else if (code === 59 || code === 44) {
1943
- if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
1944
- if (end === -1) end = i;
1945
- let value = header.slice(start, end);
1946
- if (mustUnescape) {
1947
- value = value.replace(/\\/g, "");
1948
- mustUnescape = false;
1949
- }
1950
- push(params, paramName, value);
1951
- if (code === 44) {
1952
- push(offers, extensionName, params);
1953
- params = Object.create(null);
1954
- extensionName = void 0;
1955
- }
1956
- paramName = void 0;
1957
- start = end = -1;
1958
- } else throw new SyntaxError(`Unexpected character at index ${i}`);
1959
- }
1960
- if (start === -1 || inQuotes || code === 32 || code === 9) throw new SyntaxError("Unexpected end of input");
1961
- if (end === -1) end = i;
1962
- const token = header.slice(start, end);
1963
- if (extensionName === void 0) push(offers, token, params);
1964
- else {
1965
- if (paramName === void 0) push(params, token, true);
1966
- else if (mustUnescape) push(params, paramName, token.replace(/\\/g, ""));
1967
- else push(params, paramName, token);
1968
- push(offers, extensionName, params);
1969
- }
1970
- return offers;
1971
- }
1972
- /**
1973
- * Builds the `Sec-WebSocket-Extensions` header field value.
1974
- *
1975
- * @param {Object} extensions The map of extensions and parameters to format
1976
- * @return {String} A string representing the given object
1977
- * @public
1978
- */
1979
- function format(extensions) {
1980
- return Object.keys(extensions).map((extension) => {
1981
- let configurations = extensions[extension];
1982
- if (!Array.isArray(configurations)) configurations = [configurations];
1983
- return configurations.map((params) => {
1984
- return [extension].concat(Object.keys(params).map((k) => {
1985
- let values = params[k];
1986
- if (!Array.isArray(values)) values = [values];
1987
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
1988
- })).join("; ");
1989
- }).join(", ");
1990
- }).join(", ");
1991
- }
1992
- module.exports = {
1993
- format,
1994
- parse
1995
- };
1996
- }));
1997
- //#endregion
1998
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/websocket.js
1999
- var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2000
- const EventEmitter$1 = __require("events");
2001
- const https = __require("https");
2002
- const http$1 = __require("http");
2003
- const net = __require("net");
2004
- const tls = __require("tls");
2005
- const { randomBytes, createHash: createHash$1 } = __require("crypto");
2006
- const { Duplex: Duplex$2, Readable } = __require("stream");
2007
- const { URL } = __require("url");
2008
- const PerMessageDeflate = require_permessage_deflate();
2009
- const Receiver = require_receiver();
2010
- const Sender = require_sender();
2011
- const { isBlob } = require_validation();
2012
- const { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require_constants();
2013
- const { EventTarget: { addEventListener, removeEventListener } } = require_event_target();
2014
- const { format, parse } = require_extension();
2015
- const { toBuffer } = require_buffer_util();
2016
- const kAborted = Symbol("kAborted");
2017
- const protocolVersions = [8, 13];
2018
- const readyStates = [
2019
- "CONNECTING",
2020
- "OPEN",
2021
- "CLOSING",
2022
- "CLOSED"
2023
- ];
2024
- const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2025
- /**
2026
- * Class representing a WebSocket.
2027
- *
2028
- * @extends EventEmitter
2029
- */
2030
- var WebSocket = class WebSocket extends EventEmitter$1 {
2031
- /**
2032
- * Create a new `WebSocket`.
2033
- *
2034
- * @param {(String|URL)} address The URL to which to connect
2035
- * @param {(String|String[])} [protocols] The subprotocols
2036
- * @param {Object} [options] Connection options
2037
- */
2038
- constructor(address, protocols, options) {
2039
- super();
2040
- this._binaryType = BINARY_TYPES[0];
2041
- this._closeCode = 1006;
2042
- this._closeFrameReceived = false;
2043
- this._closeFrameSent = false;
2044
- this._closeMessage = EMPTY_BUFFER;
2045
- this._closeTimer = null;
2046
- this._errorEmitted = false;
2047
- this._extensions = {};
2048
- this._paused = false;
2049
- this._protocol = "";
2050
- this._readyState = WebSocket.CONNECTING;
2051
- this._receiver = null;
2052
- this._sender = null;
2053
- this._socket = null;
2054
- if (address !== null) {
2055
- this._bufferedAmount = 0;
2056
- this._isServer = false;
2057
- this._redirects = 0;
2058
- if (protocols === void 0) protocols = [];
2059
- else if (!Array.isArray(protocols)) if (typeof protocols === "object" && protocols !== null) {
2060
- options = protocols;
2061
- protocols = [];
2062
- } else protocols = [protocols];
2063
- initAsClient(this, address, protocols, options);
2064
- } else {
2065
- this._autoPong = options.autoPong;
2066
- this._closeTimeout = options.closeTimeout;
2067
- this._isServer = true;
2068
- }
2069
- }
2070
- /**
2071
- * For historical reasons, the custom "nodebuffer" type is used by the default
2072
- * instead of "blob".
2073
- *
2074
- * @type {String}
2075
- */
2076
- get binaryType() {
2077
- return this._binaryType;
2078
- }
2079
- set binaryType(type) {
2080
- if (!BINARY_TYPES.includes(type)) return;
2081
- this._binaryType = type;
2082
- if (this._receiver) this._receiver._binaryType = type;
2083
- }
2084
- /**
2085
- * @type {Number}
2086
- */
2087
- get bufferedAmount() {
2088
- if (!this._socket) return this._bufferedAmount;
2089
- return this._socket._writableState.length + this._sender._bufferedBytes;
2090
- }
2091
- /**
2092
- * @type {String}
2093
- */
2094
- get extensions() {
2095
- return Object.keys(this._extensions).join();
2096
- }
2097
- /**
2098
- * @type {Boolean}
2099
- */
2100
- get isPaused() {
2101
- return this._paused;
2102
- }
2103
- /**
2104
- * @type {Function}
2105
- */
2106
- /* istanbul ignore next */
2107
- get onclose() {
2108
- return null;
2109
- }
2110
- /**
2111
- * @type {Function}
2112
- */
2113
- /* istanbul ignore next */
2114
- get onerror() {
2115
- return null;
2116
- }
2117
- /**
2118
- * @type {Function}
2119
- */
2120
- /* istanbul ignore next */
2121
- get onopen() {
2122
- return null;
2123
- }
2124
- /**
2125
- * @type {Function}
2126
- */
2127
- /* istanbul ignore next */
2128
- get onmessage() {
2129
- return null;
2130
- }
2131
- /**
2132
- * @type {String}
2133
- */
2134
- get protocol() {
2135
- return this._protocol;
2136
- }
2137
- /**
2138
- * @type {Number}
2139
- */
2140
- get readyState() {
2141
- return this._readyState;
2142
- }
2143
- /**
2144
- * @type {String}
2145
- */
2146
- get url() {
2147
- return this._url;
2148
- }
2149
- /**
2150
- * Set up the socket and the internal resources.
2151
- *
2152
- * @param {Duplex} socket The network socket between the server and client
2153
- * @param {Buffer} head The first packet of the upgraded stream
2154
- * @param {Object} options Options object
2155
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2156
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2157
- * multiple times in the same tick
2158
- * @param {Function} [options.generateMask] The function used to generate the
2159
- * masking key
2160
- * @param {Number} [options.maxPayload=0] The maximum allowed message size
2161
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2162
- * not to skip UTF-8 validation for text and close messages
2163
- * @private
2164
- */
2165
- setSocket(socket, head, options) {
2166
- const receiver = new Receiver({
2167
- allowSynchronousEvents: options.allowSynchronousEvents,
2168
- binaryType: this.binaryType,
2169
- extensions: this._extensions,
2170
- isServer: this._isServer,
2171
- maxPayload: options.maxPayload,
2172
- skipUTF8Validation: options.skipUTF8Validation
2173
- });
2174
- const sender = new Sender(socket, this._extensions, options.generateMask);
2175
- this._receiver = receiver;
2176
- this._sender = sender;
2177
- this._socket = socket;
2178
- receiver[kWebSocket] = this;
2179
- sender[kWebSocket] = this;
2180
- socket[kWebSocket] = this;
2181
- receiver.on("conclude", receiverOnConclude);
2182
- receiver.on("drain", receiverOnDrain);
2183
- receiver.on("error", receiverOnError);
2184
- receiver.on("message", receiverOnMessage);
2185
- receiver.on("ping", receiverOnPing);
2186
- receiver.on("pong", receiverOnPong);
2187
- sender.onerror = senderOnError;
2188
- if (socket.setTimeout) socket.setTimeout(0);
2189
- if (socket.setNoDelay) socket.setNoDelay();
2190
- if (head.length > 0) socket.unshift(head);
2191
- socket.on("close", socketOnClose);
2192
- socket.on("data", socketOnData);
2193
- socket.on("end", socketOnEnd);
2194
- socket.on("error", socketOnError);
2195
- this._readyState = WebSocket.OPEN;
2196
- this.emit("open");
2197
- }
2198
- /**
2199
- * Emit the `'close'` event.
2200
- *
2201
- * @private
2202
- */
2203
- emitClose() {
2204
- if (!this._socket) {
2205
- this._readyState = WebSocket.CLOSED;
2206
- this.emit("close", this._closeCode, this._closeMessage);
2207
- return;
2208
- }
2209
- if (this._extensions[PerMessageDeflate.extensionName]) this._extensions[PerMessageDeflate.extensionName].cleanup();
2210
- this._receiver.removeAllListeners();
2211
- this._readyState = WebSocket.CLOSED;
2212
- this.emit("close", this._closeCode, this._closeMessage);
2213
- }
2214
- /**
2215
- * Start a closing handshake.
2216
- *
2217
- * +----------+ +-----------+ +----------+
2218
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2219
- * | +----------+ +-----------+ +----------+ |
2220
- * +----------+ +-----------+ |
2221
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2222
- * +----------+ +-----------+ |
2223
- * | | | +---+ |
2224
- * +------------------------+-->|fin| - - - -
2225
- * | +---+ | +---+
2226
- * - - - - -|fin|<---------------------+
2227
- * +---+
2228
- *
2229
- * @param {Number} [code] Status code explaining why the connection is closing
2230
- * @param {(String|Buffer)} [data] The reason why the connection is
2231
- * closing
2232
- * @public
2233
- */
2234
- close(code, data) {
2235
- if (this.readyState === WebSocket.CLOSED) return;
2236
- if (this.readyState === WebSocket.CONNECTING) {
2237
- abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
2238
- return;
2239
- }
2240
- if (this.readyState === WebSocket.CLOSING) {
2241
- if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) this._socket.end();
2242
- return;
2243
- }
2244
- this._readyState = WebSocket.CLOSING;
2245
- this._sender.close(code, data, !this._isServer, (err) => {
2246
- if (err) return;
2247
- this._closeFrameSent = true;
2248
- if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) this._socket.end();
2249
- });
2250
- setCloseTimer(this);
2251
- }
2252
- /**
2253
- * Pause the socket.
2254
- *
2255
- * @public
2256
- */
2257
- pause() {
2258
- if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
2259
- this._paused = true;
2260
- this._socket.pause();
2261
- }
2262
- /**
2263
- * Send a ping.
2264
- *
2265
- * @param {*} [data] The data to send
2266
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2267
- * @param {Function} [cb] Callback which is executed when the ping is sent
2268
- * @public
2269
- */
2270
- ping(data, mask, cb) {
2271
- if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2272
- if (typeof data === "function") {
2273
- cb = data;
2274
- data = mask = void 0;
2275
- } else if (typeof mask === "function") {
2276
- cb = mask;
2277
- mask = void 0;
2278
- }
2279
- if (typeof data === "number") data = data.toString();
2280
- if (this.readyState !== WebSocket.OPEN) {
2281
- sendAfterClose(this, data, cb);
2282
- return;
2283
- }
2284
- if (mask === void 0) mask = !this._isServer;
2285
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2286
- }
2287
- /**
2288
- * Send a pong.
2289
- *
2290
- * @param {*} [data] The data to send
2291
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2292
- * @param {Function} [cb] Callback which is executed when the pong is sent
2293
- * @public
2294
- */
2295
- pong(data, mask, cb) {
2296
- if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2297
- if (typeof data === "function") {
2298
- cb = data;
2299
- data = mask = void 0;
2300
- } else if (typeof mask === "function") {
2301
- cb = mask;
2302
- mask = void 0;
2303
- }
2304
- if (typeof data === "number") data = data.toString();
2305
- if (this.readyState !== WebSocket.OPEN) {
2306
- sendAfterClose(this, data, cb);
2307
- return;
2308
- }
2309
- if (mask === void 0) mask = !this._isServer;
2310
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2311
- }
2312
- /**
2313
- * Resume the socket.
2314
- *
2315
- * @public
2316
- */
2317
- resume() {
2318
- if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
2319
- this._paused = false;
2320
- if (!this._receiver._writableState.needDrain) this._socket.resume();
2321
- }
2322
- /**
2323
- * Send a data message.
2324
- *
2325
- * @param {*} data The message to send
2326
- * @param {Object} [options] Options object
2327
- * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2328
- * text
2329
- * @param {Boolean} [options.compress] Specifies whether or not to compress
2330
- * `data`
2331
- * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2332
- * last one
2333
- * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2334
- * @param {Function} [cb] Callback which is executed when data is written out
2335
- * @public
2336
- */
2337
- send(data, options, cb) {
2338
- if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2339
- if (typeof options === "function") {
2340
- cb = options;
2341
- options = {};
2342
- }
2343
- if (typeof data === "number") data = data.toString();
2344
- if (this.readyState !== WebSocket.OPEN) {
2345
- sendAfterClose(this, data, cb);
2346
- return;
2347
- }
2348
- const opts = {
2349
- binary: typeof data !== "string",
2350
- mask: !this._isServer,
2351
- compress: true,
2352
- fin: true,
2353
- ...options
2354
- };
2355
- if (!this._extensions[PerMessageDeflate.extensionName]) opts.compress = false;
2356
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
2357
- }
2358
- /**
2359
- * Forcibly close the connection.
2360
- *
2361
- * @public
2362
- */
2363
- terminate() {
2364
- if (this.readyState === WebSocket.CLOSED) return;
2365
- if (this.readyState === WebSocket.CONNECTING) {
2366
- abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
2367
- return;
2368
- }
2369
- if (this._socket) {
2370
- this._readyState = WebSocket.CLOSING;
2371
- this._socket.destroy();
2372
- }
2373
- }
2374
- };
2375
- /**
2376
- * @constant {Number} CONNECTING
2377
- * @memberof WebSocket
2378
- */
2379
- Object.defineProperty(WebSocket, "CONNECTING", {
2380
- enumerable: true,
2381
- value: readyStates.indexOf("CONNECTING")
2382
- });
2383
- /**
2384
- * @constant {Number} CONNECTING
2385
- * @memberof WebSocket.prototype
2386
- */
2387
- Object.defineProperty(WebSocket.prototype, "CONNECTING", {
2388
- enumerable: true,
2389
- value: readyStates.indexOf("CONNECTING")
2390
- });
2391
- /**
2392
- * @constant {Number} OPEN
2393
- * @memberof WebSocket
2394
- */
2395
- Object.defineProperty(WebSocket, "OPEN", {
2396
- enumerable: true,
2397
- value: readyStates.indexOf("OPEN")
2398
- });
2399
- /**
2400
- * @constant {Number} OPEN
2401
- * @memberof WebSocket.prototype
2402
- */
2403
- Object.defineProperty(WebSocket.prototype, "OPEN", {
2404
- enumerable: true,
2405
- value: readyStates.indexOf("OPEN")
2406
- });
2407
- /**
2408
- * @constant {Number} CLOSING
2409
- * @memberof WebSocket
2410
- */
2411
- Object.defineProperty(WebSocket, "CLOSING", {
2412
- enumerable: true,
2413
- value: readyStates.indexOf("CLOSING")
2414
- });
2415
- /**
2416
- * @constant {Number} CLOSING
2417
- * @memberof WebSocket.prototype
2418
- */
2419
- Object.defineProperty(WebSocket.prototype, "CLOSING", {
2420
- enumerable: true,
2421
- value: readyStates.indexOf("CLOSING")
2422
- });
2423
- /**
2424
- * @constant {Number} CLOSED
2425
- * @memberof WebSocket
2426
- */
2427
- Object.defineProperty(WebSocket, "CLOSED", {
2428
- enumerable: true,
2429
- value: readyStates.indexOf("CLOSED")
2430
- });
2431
- /**
2432
- * @constant {Number} CLOSED
2433
- * @memberof WebSocket.prototype
2434
- */
2435
- Object.defineProperty(WebSocket.prototype, "CLOSED", {
2436
- enumerable: true,
2437
- value: readyStates.indexOf("CLOSED")
2438
- });
2439
- [
2440
- "binaryType",
2441
- "bufferedAmount",
2442
- "extensions",
2443
- "isPaused",
2444
- "protocol",
2445
- "readyState",
2446
- "url"
2447
- ].forEach((property) => {
2448
- Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
2449
- });
2450
- [
2451
- "open",
2452
- "error",
2453
- "close",
2454
- "message"
2455
- ].forEach((method) => {
2456
- Object.defineProperty(WebSocket.prototype, `on${method}`, {
2457
- enumerable: true,
2458
- get() {
2459
- for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) return listener[kListener];
2460
- return null;
2461
- },
2462
- set(handler) {
2463
- for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) {
2464
- this.removeListener(method, listener);
2465
- break;
2466
- }
2467
- if (typeof handler !== "function") return;
2468
- this.addEventListener(method, handler, { [kForOnEventAttribute]: true });
2469
- }
2470
- });
2471
- });
2472
- WebSocket.prototype.addEventListener = addEventListener;
2473
- WebSocket.prototype.removeEventListener = removeEventListener;
2474
- module.exports = WebSocket;
2475
- /**
2476
- * Initialize a WebSocket client.
2477
- *
2478
- * @param {WebSocket} websocket The client to initialize
2479
- * @param {(String|URL)} address The URL to which to connect
2480
- * @param {Array} protocols The subprotocols
2481
- * @param {Object} [options] Connection options
2482
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
2483
- * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
2484
- * times in the same tick
2485
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
2486
- * automatically send a pong in response to a ping
2487
- * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait
2488
- * for the closing handshake to finish after `websocket.close()` is called
2489
- * @param {Function} [options.finishRequest] A function which can be used to
2490
- * customize the headers of each http request before it is sent
2491
- * @param {Boolean} [options.followRedirects=false] Whether or not to follow
2492
- * redirects
2493
- * @param {Function} [options.generateMask] The function used to generate the
2494
- * masking key
2495
- * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
2496
- * handshake request
2497
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
2498
- * size
2499
- * @param {Number} [options.maxRedirects=10] The maximum number of redirects
2500
- * allowed
2501
- * @param {String} [options.origin] Value of the `Origin` or
2502
- * `Sec-WebSocket-Origin` header
2503
- * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
2504
- * permessage-deflate
2505
- * @param {Number} [options.protocolVersion=13] Value of the
2506
- * `Sec-WebSocket-Version` header
2507
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2508
- * not to skip UTF-8 validation for text and close messages
2509
- * @private
2510
- */
2511
- function initAsClient(websocket, address, protocols, options) {
2512
- const opts = {
2513
- allowSynchronousEvents: true,
2514
- autoPong: true,
2515
- closeTimeout: CLOSE_TIMEOUT,
2516
- protocolVersion: protocolVersions[1],
2517
- maxPayload: 100 * 1024 * 1024,
2518
- skipUTF8Validation: false,
2519
- perMessageDeflate: true,
2520
- followRedirects: false,
2521
- maxRedirects: 10,
2522
- ...options,
2523
- socketPath: void 0,
2524
- hostname: void 0,
2525
- protocol: void 0,
2526
- timeout: void 0,
2527
- method: "GET",
2528
- host: void 0,
2529
- path: void 0,
2530
- port: void 0
2531
- };
2532
- websocket._autoPong = opts.autoPong;
2533
- websocket._closeTimeout = opts.closeTimeout;
2534
- if (!protocolVersions.includes(opts.protocolVersion)) throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);
2535
- let parsedUrl;
2536
- if (address instanceof URL) parsedUrl = address;
2537
- else try {
2538
- parsedUrl = new URL(address);
2539
- } catch {
2540
- throw new SyntaxError(`Invalid URL: ${address}`);
2541
- }
2542
- if (parsedUrl.protocol === "http:") parsedUrl.protocol = "ws:";
2543
- else if (parsedUrl.protocol === "https:") parsedUrl.protocol = "wss:";
2544
- websocket._url = parsedUrl.href;
2545
- const isSecure = parsedUrl.protocol === "wss:";
2546
- const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2547
- let invalidUrlMessage;
2548
- if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) invalidUrlMessage = "The URL's protocol must be one of \"ws:\", \"wss:\", \"http:\", \"https:\", or \"ws+unix:\"";
2549
- else if (isIpcUrl && !parsedUrl.pathname) invalidUrlMessage = "The URL's pathname is empty";
2550
- else if (parsedUrl.hash) invalidUrlMessage = "The URL contains a fragment identifier";
2551
- if (invalidUrlMessage) {
2552
- const err = new SyntaxError(invalidUrlMessage);
2553
- if (websocket._redirects === 0) throw err;
2554
- else {
2555
- emitErrorAndClose(websocket, err);
2556
- return;
2557
- }
2558
- }
2559
- const defaultPort = isSecure ? 443 : 80;
2560
- const key = randomBytes(16).toString("base64");
2561
- const request = isSecure ? https.request : http$1.request;
2562
- const protocolSet = /* @__PURE__ */ new Set();
2563
- let perMessageDeflate;
2564
- opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2565
- opts.defaultPort = opts.defaultPort || defaultPort;
2566
- opts.port = parsedUrl.port || defaultPort;
2567
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2568
- opts.headers = {
2569
- ...opts.headers,
2570
- "Sec-WebSocket-Version": opts.protocolVersion,
2571
- "Sec-WebSocket-Key": key,
2572
- Connection: "Upgrade",
2573
- Upgrade: "websocket"
2574
- };
2575
- opts.path = parsedUrl.pathname + parsedUrl.search;
2576
- opts.timeout = opts.handshakeTimeout;
2577
- if (opts.perMessageDeflate) {
2578
- perMessageDeflate = new PerMessageDeflate({
2579
- ...opts.perMessageDeflate,
2580
- isServer: false,
2581
- maxPayload: opts.maxPayload
2582
- });
2583
- opts.headers["Sec-WebSocket-Extensions"] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() });
2584
- }
2585
- if (protocols.length) {
2586
- for (const protocol of protocols) {
2587
- if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) throw new SyntaxError("An invalid or duplicated subprotocol was specified");
2588
- protocolSet.add(protocol);
2589
- }
2590
- opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2591
- }
2592
- if (opts.origin) if (opts.protocolVersion < 13) opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2593
- else opts.headers.Origin = opts.origin;
2594
- if (parsedUrl.username || parsedUrl.password) opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2595
- if (isIpcUrl) {
2596
- const parts = opts.path.split(":");
2597
- opts.socketPath = parts[0];
2598
- opts.path = parts[1];
2599
- }
2600
- let req;
2601
- if (opts.followRedirects) {
2602
- if (websocket._redirects === 0) {
2603
- websocket._originalIpc = isIpcUrl;
2604
- websocket._originalSecure = isSecure;
2605
- websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2606
- const headers = options && options.headers;
2607
- options = {
2608
- ...options,
2609
- headers: {}
2610
- };
2611
- if (headers) for (const [key, value] of Object.entries(headers)) options.headers[key.toLowerCase()] = value;
2612
- } else if (websocket.listenerCount("redirect") === 0) {
2613
- const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2614
- if (!isSameHost || websocket._originalSecure && !isSecure) {
2615
- delete opts.headers.authorization;
2616
- delete opts.headers.cookie;
2617
- if (!isSameHost) delete opts.headers.host;
2618
- opts.auth = void 0;
2619
- }
2620
- }
2621
- if (opts.auth && !options.headers.authorization) options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2622
- req = websocket._req = request(opts);
2623
- if (websocket._redirects) websocket.emit("redirect", websocket.url, req);
2624
- } else req = websocket._req = request(opts);
2625
- if (opts.timeout) req.on("timeout", () => {
2626
- abortHandshake(websocket, req, "Opening handshake has timed out");
2627
- });
2628
- req.on("error", (err) => {
2629
- if (req === null || req[kAborted]) return;
2630
- req = websocket._req = null;
2631
- emitErrorAndClose(websocket, err);
2632
- });
2633
- req.on("response", (res) => {
2634
- const location = res.headers.location;
2635
- const statusCode = res.statusCode;
2636
- if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2637
- if (++websocket._redirects > opts.maxRedirects) {
2638
- abortHandshake(websocket, req, "Maximum redirects exceeded");
2639
- return;
2640
- }
2641
- req.abort();
2642
- let addr;
2643
- try {
2644
- addr = new URL(location, address);
2645
- } catch (e) {
2646
- emitErrorAndClose(websocket, /* @__PURE__ */ new SyntaxError(`Invalid URL: ${location}`));
2647
- return;
2648
- }
2649
- initAsClient(websocket, addr, protocols, options);
2650
- } else if (!websocket.emit("unexpected-response", req, res)) abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
2651
- });
2652
- req.on("upgrade", (res, socket, head) => {
2653
- websocket.emit("upgrade", res);
2654
- if (websocket.readyState !== WebSocket.CONNECTING) return;
2655
- req = websocket._req = null;
2656
- const upgrade = res.headers.upgrade;
2657
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2658
- abortHandshake(websocket, socket, "Invalid Upgrade header");
2659
- return;
2660
- }
2661
- const digest = createHash$1("sha1").update(key + GUID).digest("base64");
2662
- if (res.headers["sec-websocket-accept"] !== digest) {
2663
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2664
- return;
2665
- }
2666
- const serverProt = res.headers["sec-websocket-protocol"];
2667
- let protError;
2668
- if (serverProt !== void 0) {
2669
- if (!protocolSet.size) protError = "Server sent a subprotocol but none was requested";
2670
- else if (!protocolSet.has(serverProt)) protError = "Server sent an invalid subprotocol";
2671
- } else if (protocolSet.size) protError = "Server sent no subprotocol";
2672
- if (protError) {
2673
- abortHandshake(websocket, socket, protError);
2674
- return;
2675
- }
2676
- if (serverProt) websocket._protocol = serverProt;
2677
- const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2678
- if (secWebSocketExtensions !== void 0) {
2679
- if (!perMessageDeflate) {
2680
- abortHandshake(websocket, socket, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
2681
- return;
2682
- }
2683
- let extensions;
2684
- try {
2685
- extensions = parse(secWebSocketExtensions);
2686
- } catch (err) {
2687
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
2688
- return;
2689
- }
2690
- const extensionNames = Object.keys(extensions);
2691
- if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2692
- abortHandshake(websocket, socket, "Server indicated an extension that was not requested");
2693
- return;
2694
- }
2695
- try {
2696
- perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2697
- } catch (err) {
2698
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
2699
- return;
2700
- }
2701
- websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2702
- }
2703
- websocket.setSocket(socket, head, {
2704
- allowSynchronousEvents: opts.allowSynchronousEvents,
2705
- generateMask: opts.generateMask,
2706
- maxPayload: opts.maxPayload,
2707
- skipUTF8Validation: opts.skipUTF8Validation
2708
- });
2709
- });
2710
- if (opts.finishRequest) opts.finishRequest(req, websocket);
2711
- else req.end();
2712
- }
2713
- /**
2714
- * Emit the `'error'` and `'close'` events.
2715
- *
2716
- * @param {WebSocket} websocket The WebSocket instance
2717
- * @param {Error} The error to emit
2718
- * @private
2719
- */
2720
- function emitErrorAndClose(websocket, err) {
2721
- websocket._readyState = WebSocket.CLOSING;
2722
- websocket._errorEmitted = true;
2723
- websocket.emit("error", err);
2724
- websocket.emitClose();
2725
- }
2726
- /**
2727
- * Create a `net.Socket` and initiate a connection.
2728
- *
2729
- * @param {Object} options Connection options
2730
- * @return {net.Socket} The newly created socket used to start the connection
2731
- * @private
2732
- */
2733
- function netConnect(options) {
2734
- options.path = options.socketPath;
2735
- return net.connect(options);
2736
- }
2737
- /**
2738
- * Create a `tls.TLSSocket` and initiate a connection.
2739
- *
2740
- * @param {Object} options Connection options
2741
- * @return {tls.TLSSocket} The newly created socket used to start the connection
2742
- * @private
2743
- */
2744
- function tlsConnect(options) {
2745
- options.path = void 0;
2746
- if (!options.servername && options.servername !== "") options.servername = net.isIP(options.host) ? "" : options.host;
2747
- return tls.connect(options);
2748
- }
2749
- /**
2750
- * Abort the handshake and emit an error.
2751
- *
2752
- * @param {WebSocket} websocket The WebSocket instance
2753
- * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
2754
- * abort or the socket to destroy
2755
- * @param {String} message The error message
2756
- * @private
2757
- */
2758
- function abortHandshake(websocket, stream, message) {
2759
- websocket._readyState = WebSocket.CLOSING;
2760
- const err = new Error(message);
2761
- Error.captureStackTrace(err, abortHandshake);
2762
- if (stream.setHeader) {
2763
- stream[kAborted] = true;
2764
- stream.abort();
2765
- if (stream.socket && !stream.socket.destroyed) stream.socket.destroy();
2766
- process.nextTick(emitErrorAndClose, websocket, err);
2767
- } else {
2768
- stream.destroy(err);
2769
- stream.once("error", websocket.emit.bind(websocket, "error"));
2770
- stream.once("close", websocket.emitClose.bind(websocket));
2771
- }
2772
- }
2773
- /**
2774
- * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
2775
- * when the `readyState` attribute is `CLOSING` or `CLOSED`.
2776
- *
2777
- * @param {WebSocket} websocket The WebSocket instance
2778
- * @param {*} [data] The data to send
2779
- * @param {Function} [cb] Callback
2780
- * @private
2781
- */
2782
- function sendAfterClose(websocket, data, cb) {
2783
- if (data) {
2784
- const length = isBlob(data) ? data.size : toBuffer(data).length;
2785
- if (websocket._socket) websocket._sender._bufferedBytes += length;
2786
- else websocket._bufferedAmount += length;
2787
- }
2788
- if (cb) {
2789
- const err = /* @__PURE__ */ new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);
2790
- process.nextTick(cb, err);
2791
- }
2792
- }
2793
- /**
2794
- * The listener of the `Receiver` `'conclude'` event.
2795
- *
2796
- * @param {Number} code The status code
2797
- * @param {Buffer} reason The reason for closing
2798
- * @private
2799
- */
2800
- function receiverOnConclude(code, reason) {
2801
- const websocket = this[kWebSocket];
2802
- websocket._closeFrameReceived = true;
2803
- websocket._closeMessage = reason;
2804
- websocket._closeCode = code;
2805
- if (websocket._socket[kWebSocket] === void 0) return;
2806
- websocket._socket.removeListener("data", socketOnData);
2807
- process.nextTick(resume, websocket._socket);
2808
- if (code === 1005) websocket.close();
2809
- else websocket.close(code, reason);
2810
- }
2811
- /**
2812
- * The listener of the `Receiver` `'drain'` event.
2813
- *
2814
- * @private
2815
- */
2816
- function receiverOnDrain() {
2817
- const websocket = this[kWebSocket];
2818
- if (!websocket.isPaused) websocket._socket.resume();
2819
- }
2820
- /**
2821
- * The listener of the `Receiver` `'error'` event.
2822
- *
2823
- * @param {(RangeError|Error)} err The emitted error
2824
- * @private
2825
- */
2826
- function receiverOnError(err) {
2827
- const websocket = this[kWebSocket];
2828
- if (websocket._socket[kWebSocket] !== void 0) {
2829
- websocket._socket.removeListener("data", socketOnData);
2830
- process.nextTick(resume, websocket._socket);
2831
- websocket.close(err[kStatusCode]);
2832
- }
2833
- if (!websocket._errorEmitted) {
2834
- websocket._errorEmitted = true;
2835
- websocket.emit("error", err);
2836
- }
2837
- }
2838
- /**
2839
- * The listener of the `Receiver` `'finish'` event.
2840
- *
2841
- * @private
2842
- */
2843
- function receiverOnFinish() {
2844
- this[kWebSocket].emitClose();
2845
- }
2846
- /**
2847
- * The listener of the `Receiver` `'message'` event.
2848
- *
2849
- * @param {Buffer|ArrayBuffer|Buffer[])} data The message
2850
- * @param {Boolean} isBinary Specifies whether the message is binary or not
2851
- * @private
2852
- */
2853
- function receiverOnMessage(data, isBinary) {
2854
- this[kWebSocket].emit("message", data, isBinary);
2855
- }
2856
- /**
2857
- * The listener of the `Receiver` `'ping'` event.
2858
- *
2859
- * @param {Buffer} data The data included in the ping frame
2860
- * @private
2861
- */
2862
- function receiverOnPing(data) {
2863
- const websocket = this[kWebSocket];
2864
- if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
2865
- websocket.emit("ping", data);
2866
- }
2867
- /**
2868
- * The listener of the `Receiver` `'pong'` event.
2869
- *
2870
- * @param {Buffer} data The data included in the pong frame
2871
- * @private
2872
- */
2873
- function receiverOnPong(data) {
2874
- this[kWebSocket].emit("pong", data);
2875
- }
2876
- /**
2877
- * Resume a readable stream
2878
- *
2879
- * @param {Readable} stream The readable stream
2880
- * @private
2881
- */
2882
- function resume(stream) {
2883
- stream.resume();
2884
- }
2885
- /**
2886
- * The `Sender` error event handler.
2887
- *
2888
- * @param {Error} The error
2889
- * @private
2890
- */
2891
- function senderOnError(err) {
2892
- const websocket = this[kWebSocket];
2893
- if (websocket.readyState === WebSocket.CLOSED) return;
2894
- if (websocket.readyState === WebSocket.OPEN) {
2895
- websocket._readyState = WebSocket.CLOSING;
2896
- setCloseTimer(websocket);
2897
- }
2898
- this._socket.end();
2899
- if (!websocket._errorEmitted) {
2900
- websocket._errorEmitted = true;
2901
- websocket.emit("error", err);
2902
- }
2903
- }
2904
- /**
2905
- * Set a timer to destroy the underlying raw socket of a WebSocket.
2906
- *
2907
- * @param {WebSocket} websocket The WebSocket instance
2908
- * @private
2909
- */
2910
- function setCloseTimer(websocket) {
2911
- websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
2912
- }
2913
- /**
2914
- * The listener of the socket `'close'` event.
2915
- *
2916
- * @private
2917
- */
2918
- function socketOnClose() {
2919
- const websocket = this[kWebSocket];
2920
- this.removeListener("close", socketOnClose);
2921
- this.removeListener("data", socketOnData);
2922
- this.removeListener("end", socketOnEnd);
2923
- websocket._readyState = WebSocket.CLOSING;
2924
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
2925
- const chunk = this.read(this._readableState.length);
2926
- websocket._receiver.write(chunk);
2927
- }
2928
- websocket._receiver.end();
2929
- this[kWebSocket] = void 0;
2930
- clearTimeout(websocket._closeTimer);
2931
- if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) websocket.emitClose();
2932
- else {
2933
- websocket._receiver.on("error", receiverOnFinish);
2934
- websocket._receiver.on("finish", receiverOnFinish);
2935
- }
2936
- }
2937
- /**
2938
- * The listener of the socket `'data'` event.
2939
- *
2940
- * @param {Buffer} chunk A chunk of data
2941
- * @private
2942
- */
2943
- function socketOnData(chunk) {
2944
- if (!this[kWebSocket]._receiver.write(chunk)) this.pause();
2945
- }
2946
- /**
2947
- * The listener of the socket `'end'` event.
2948
- *
2949
- * @private
2950
- */
2951
- function socketOnEnd() {
2952
- const websocket = this[kWebSocket];
2953
- websocket._readyState = WebSocket.CLOSING;
2954
- websocket._receiver.end();
2955
- this.end();
2956
- }
2957
- /**
2958
- * The listener of the socket `'error'` event.
2959
- *
2960
- * @private
2961
- */
2962
- function socketOnError() {
2963
- const websocket = this[kWebSocket];
2964
- this.removeListener("error", socketOnError);
2965
- this.on("error", NOOP);
2966
- if (websocket) {
2967
- websocket._readyState = WebSocket.CLOSING;
2968
- this.destroy();
2969
- }
2970
- }
2971
- }));
2972
- //#endregion
2973
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/stream.js
2974
- var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2975
- require_websocket();
2976
- const { Duplex: Duplex$1 } = __require("stream");
2977
- /**
2978
- * Emits the `'close'` event on a stream.
2979
- *
2980
- * @param {Duplex} stream The stream.
2981
- * @private
2982
- */
2983
- function emitClose(stream) {
2984
- stream.emit("close");
2985
- }
2986
- /**
2987
- * The listener of the `'end'` event.
2988
- *
2989
- * @private
2990
- */
2991
- function duplexOnEnd() {
2992
- if (!this.destroyed && this._writableState.finished) this.destroy();
2993
- }
2994
- /**
2995
- * The listener of the `'error'` event.
2996
- *
2997
- * @param {Error} err The error
2998
- * @private
2999
- */
3000
- function duplexOnError(err) {
3001
- this.removeListener("error", duplexOnError);
3002
- this.destroy();
3003
- if (this.listenerCount("error") === 0) this.emit("error", err);
3004
- }
3005
- /**
3006
- * Wraps a `WebSocket` in a duplex stream.
3007
- *
3008
- * @param {WebSocket} ws The `WebSocket` to wrap
3009
- * @param {Object} [options] The options for the `Duplex` constructor
3010
- * @return {Duplex} The duplex stream
3011
- * @public
3012
- */
3013
- function createWebSocketStream(ws, options) {
3014
- let terminateOnDestroy = true;
3015
- const duplex = new Duplex$1({
3016
- ...options,
3017
- autoDestroy: false,
3018
- emitClose: false,
3019
- objectMode: false,
3020
- writableObjectMode: false
3021
- });
3022
- ws.on("message", function message(msg, isBinary) {
3023
- const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3024
- if (!duplex.push(data)) ws.pause();
3025
- });
3026
- ws.once("error", function error(err) {
3027
- if (duplex.destroyed) return;
3028
- terminateOnDestroy = false;
3029
- duplex.destroy(err);
3030
- });
3031
- ws.once("close", function close() {
3032
- if (duplex.destroyed) return;
3033
- duplex.push(null);
3034
- });
3035
- duplex._destroy = function(err, callback) {
3036
- if (ws.readyState === ws.CLOSED) {
3037
- callback(err);
3038
- process.nextTick(emitClose, duplex);
3039
- return;
3040
- }
3041
- let called = false;
3042
- ws.once("error", function error(err) {
3043
- called = true;
3044
- callback(err);
3045
- });
3046
- ws.once("close", function close() {
3047
- if (!called) callback(err);
3048
- process.nextTick(emitClose, duplex);
3049
- });
3050
- if (terminateOnDestroy) ws.terminate();
3051
- };
3052
- duplex._final = function(callback) {
3053
- if (ws.readyState === ws.CONNECTING) {
3054
- ws.once("open", function open() {
3055
- duplex._final(callback);
3056
- });
3057
- return;
3058
- }
3059
- if (ws._socket === null) return;
3060
- if (ws._socket._writableState.finished) {
3061
- callback();
3062
- if (duplex._readableState.endEmitted) duplex.destroy();
3063
- } else {
3064
- ws._socket.once("finish", function finish() {
3065
- callback();
3066
- });
3067
- ws.close();
3068
- }
3069
- };
3070
- duplex._read = function() {
3071
- if (ws.isPaused) ws.resume();
3072
- };
3073
- duplex._write = function(chunk, encoding, callback) {
3074
- if (ws.readyState === ws.CONNECTING) {
3075
- ws.once("open", function open() {
3076
- duplex._write(chunk, encoding, callback);
3077
- });
3078
- return;
3079
- }
3080
- ws.send(chunk, callback);
3081
- };
3082
- duplex.on("end", duplexOnEnd);
3083
- duplex.on("error", duplexOnError);
3084
- return duplex;
3085
- }
3086
- module.exports = createWebSocketStream;
3087
- }));
3088
- //#endregion
3089
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/subprotocol.js
3090
- var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3091
- const { tokenChars } = require_validation();
3092
- /**
3093
- * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
3094
- *
3095
- * @param {String} header The field value of the header
3096
- * @return {Set} The subprotocol names
3097
- * @public
3098
- */
3099
- function parse(header) {
3100
- const protocols = /* @__PURE__ */ new Set();
3101
- let start = -1;
3102
- let end = -1;
3103
- let i = 0;
3104
- for (; i < header.length; i++) {
3105
- const code = header.charCodeAt(i);
3106
- if (end === -1 && tokenChars[code] === 1) {
3107
- if (start === -1) start = i;
3108
- } else if (i !== 0 && (code === 32 || code === 9)) {
3109
- if (end === -1 && start !== -1) end = i;
3110
- } else if (code === 44) {
3111
- if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
3112
- if (end === -1) end = i;
3113
- const protocol = header.slice(start, end);
3114
- if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3115
- protocols.add(protocol);
3116
- start = end = -1;
3117
- } else throw new SyntaxError(`Unexpected character at index ${i}`);
3118
- }
3119
- if (start === -1 || end !== -1) throw new SyntaxError("Unexpected end of input");
3120
- const protocol = header.slice(start, i);
3121
- if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3122
- protocols.add(protocol);
3123
- return protocols;
3124
- }
3125
- module.exports = { parse };
3126
- }));
3127
- //#endregion
3128
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/websocket-server.js
3129
- var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3130
- const EventEmitter = __require("events");
3131
- const http = __require("http");
3132
- const { Duplex } = __require("stream");
3133
- const { createHash } = __require("crypto");
3134
- const extension = require_extension();
3135
- const PerMessageDeflate = require_permessage_deflate();
3136
- const subprotocol = require_subprotocol();
3137
- const WebSocket = require_websocket();
3138
- const { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3139
- const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3140
- const RUNNING = 0;
3141
- const CLOSING = 1;
3142
- const CLOSED = 2;
3143
- /**
3144
- * Class representing a WebSocket server.
3145
- *
3146
- * @extends EventEmitter
3147
- */
3148
- var WebSocketServer = class extends EventEmitter {
3149
- /**
3150
- * Create a `WebSocketServer` instance.
3151
- *
3152
- * @param {Object} options Configuration options
3153
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3154
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3155
- * multiple times in the same tick
3156
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3157
- * automatically send a pong in response to a ping
3158
- * @param {Number} [options.backlog=511] The maximum length of the queue of
3159
- * pending connections
3160
- * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3161
- * track clients
3162
- * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3163
- * wait for the closing handshake to finish after `websocket.close()` is
3164
- * called
3165
- * @param {Function} [options.handleProtocols] A hook to handle protocols
3166
- * @param {String} [options.host] The hostname where to bind the server
3167
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3168
- * size
3169
- * @param {Boolean} [options.noServer=false] Enable no server mode
3170
- * @param {String} [options.path] Accept only connections matching this path
3171
- * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3172
- * permessage-deflate
3173
- * @param {Number} [options.port] The port where to bind the server
3174
- * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3175
- * server to use
3176
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3177
- * not to skip UTF-8 validation for text and close messages
3178
- * @param {Function} [options.verifyClient] A hook to reject connections
3179
- * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3180
- * class to use. It must be the `WebSocket` class or class that extends it
3181
- * @param {Function} [callback] A listener for the `listening` event
3182
- */
3183
- constructor(options, callback) {
3184
- super();
3185
- options = {
3186
- allowSynchronousEvents: true,
3187
- autoPong: true,
3188
- maxPayload: 100 * 1024 * 1024,
3189
- skipUTF8Validation: false,
3190
- perMessageDeflate: false,
3191
- handleProtocols: null,
3192
- clientTracking: true,
3193
- closeTimeout: CLOSE_TIMEOUT,
3194
- verifyClient: null,
3195
- noServer: false,
3196
- backlog: null,
3197
- server: null,
3198
- host: null,
3199
- path: null,
3200
- port: null,
3201
- WebSocket,
3202
- ...options
3203
- };
3204
- if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) throw new TypeError("One and only one of the \"port\", \"server\", or \"noServer\" options must be specified");
3205
- if (options.port != null) {
3206
- this._server = http.createServer((req, res) => {
3207
- const body = http.STATUS_CODES[426];
3208
- res.writeHead(426, {
3209
- "Content-Length": body.length,
3210
- "Content-Type": "text/plain"
3211
- });
3212
- res.end(body);
3213
- });
3214
- this._server.listen(options.port, options.host, options.backlog, callback);
3215
- } else if (options.server) this._server = options.server;
3216
- if (this._server) {
3217
- const emitConnection = this.emit.bind(this, "connection");
3218
- this._removeListeners = addListeners(this._server, {
3219
- listening: this.emit.bind(this, "listening"),
3220
- error: this.emit.bind(this, "error"),
3221
- upgrade: (req, socket, head) => {
3222
- this.handleUpgrade(req, socket, head, emitConnection);
3223
- }
3224
- });
3225
- }
3226
- if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3227
- if (options.clientTracking) {
3228
- this.clients = /* @__PURE__ */ new Set();
3229
- this._shouldEmitClose = false;
3230
- }
3231
- this.options = options;
3232
- this._state = RUNNING;
3233
- }
3234
- /**
3235
- * Returns the bound address, the address family name, and port of the server
3236
- * as reported by the operating system if listening on an IP socket.
3237
- * If the server is listening on a pipe or UNIX domain socket, the name is
3238
- * returned as a string.
3239
- *
3240
- * @return {(Object|String|null)} The address of the server
3241
- * @public
3242
- */
3243
- address() {
3244
- if (this.options.noServer) throw new Error("The server is operating in \"noServer\" mode");
3245
- if (!this._server) return null;
3246
- return this._server.address();
3247
- }
3248
- /**
3249
- * Stop the server from accepting new connections and emit the `'close'` event
3250
- * when all existing connections are closed.
3251
- *
3252
- * @param {Function} [cb] A one-time listener for the `'close'` event
3253
- * @public
3254
- */
3255
- close(cb) {
3256
- if (this._state === CLOSED) {
3257
- if (cb) this.once("close", () => {
3258
- cb(/* @__PURE__ */ new Error("The server is not running"));
3259
- });
3260
- process.nextTick(emitClose, this);
3261
- return;
3262
- }
3263
- if (cb) this.once("close", cb);
3264
- if (this._state === CLOSING) return;
3265
- this._state = CLOSING;
3266
- if (this.options.noServer || this.options.server) {
3267
- if (this._server) {
3268
- this._removeListeners();
3269
- this._removeListeners = this._server = null;
3270
- }
3271
- if (this.clients) if (!this.clients.size) process.nextTick(emitClose, this);
3272
- else this._shouldEmitClose = true;
3273
- else process.nextTick(emitClose, this);
3274
- } else {
3275
- const server = this._server;
3276
- this._removeListeners();
3277
- this._removeListeners = this._server = null;
3278
- server.close(() => {
3279
- emitClose(this);
3280
- });
3281
- }
3282
- }
3283
- /**
3284
- * See if a given request should be handled by this server instance.
3285
- *
3286
- * @param {http.IncomingMessage} req Request object to inspect
3287
- * @return {Boolean} `true` if the request is valid, else `false`
3288
- * @public
3289
- */
3290
- shouldHandle(req) {
3291
- if (this.options.path) {
3292
- const index = req.url.indexOf("?");
3293
- if ((index !== -1 ? req.url.slice(0, index) : req.url) !== this.options.path) return false;
3294
- }
3295
- return true;
3296
- }
3297
- /**
3298
- * Handle a HTTP Upgrade request.
3299
- *
3300
- * @param {http.IncomingMessage} req The request object
3301
- * @param {Duplex} socket The network socket between the server and client
3302
- * @param {Buffer} head The first packet of the upgraded stream
3303
- * @param {Function} cb Callback
3304
- * @public
3305
- */
3306
- handleUpgrade(req, socket, head, cb) {
3307
- socket.on("error", socketOnError);
3308
- const key = req.headers["sec-websocket-key"];
3309
- const upgrade = req.headers.upgrade;
3310
- const version = +req.headers["sec-websocket-version"];
3311
- if (req.method !== "GET") {
3312
- abortHandshakeOrEmitwsClientError(this, req, socket, 405, "Invalid HTTP method");
3313
- return;
3314
- }
3315
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3316
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Upgrade header");
3317
- return;
3318
- }
3319
- if (key === void 0 || !keyRegex.test(key)) {
3320
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Key header");
3321
- return;
3322
- }
3323
- if (version !== 13 && version !== 8) {
3324
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Version header", { "Sec-WebSocket-Version": "13, 8" });
3325
- return;
3326
- }
3327
- if (!this.shouldHandle(req)) {
3328
- abortHandshake(socket, 400);
3329
- return;
3330
- }
3331
- const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3332
- let protocols = /* @__PURE__ */ new Set();
3333
- if (secWebSocketProtocol !== void 0) try {
3334
- protocols = subprotocol.parse(secWebSocketProtocol);
3335
- } catch (err) {
3336
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Sec-WebSocket-Protocol header");
3337
- return;
3338
- }
3339
- const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3340
- const extensions = {};
3341
- if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3342
- const perMessageDeflate = new PerMessageDeflate({
3343
- ...this.options.perMessageDeflate,
3344
- isServer: true,
3345
- maxPayload: this.options.maxPayload
3346
- });
3347
- try {
3348
- const offers = extension.parse(secWebSocketExtensions);
3349
- if (offers[PerMessageDeflate.extensionName]) {
3350
- perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
3351
- extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3352
- }
3353
- } catch (err) {
3354
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
3355
- return;
3356
- }
3357
- }
3358
- if (this.options.verifyClient) {
3359
- const info = {
3360
- origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3361
- secure: !!(req.socket.authorized || req.socket.encrypted),
3362
- req
3363
- };
3364
- if (this.options.verifyClient.length === 2) {
3365
- this.options.verifyClient(info, (verified, code, message, headers) => {
3366
- if (!verified) return abortHandshake(socket, code || 401, message, headers);
3367
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3368
- });
3369
- return;
3370
- }
3371
- if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3372
- }
3373
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3374
- }
3375
- /**
3376
- * Upgrade the connection to WebSocket.
3377
- *
3378
- * @param {Object} extensions The accepted extensions
3379
- * @param {String} key The value of the `Sec-WebSocket-Key` header
3380
- * @param {Set} protocols The subprotocols
3381
- * @param {http.IncomingMessage} req The request object
3382
- * @param {Duplex} socket The network socket between the server and client
3383
- * @param {Buffer} head The first packet of the upgraded stream
3384
- * @param {Function} cb Callback
3385
- * @throws {Error} If called more than once with the same socket
3386
- * @private
3387
- */
3388
- completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3389
- if (!socket.readable || !socket.writable) return socket.destroy();
3390
- if (socket[kWebSocket]) throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");
3391
- if (this._state > RUNNING) return abortHandshake(socket, 503);
3392
- const headers = [
3393
- "HTTP/1.1 101 Switching Protocols",
3394
- "Upgrade: websocket",
3395
- "Connection: Upgrade",
3396
- `Sec-WebSocket-Accept: ${createHash("sha1").update(key + GUID).digest("base64")}`
3397
- ];
3398
- const ws = new this.options.WebSocket(null, void 0, this.options);
3399
- if (protocols.size) {
3400
- const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3401
- if (protocol) {
3402
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3403
- ws._protocol = protocol;
3404
- }
3405
- }
3406
- if (extensions[PerMessageDeflate.extensionName]) {
3407
- const params = extensions[PerMessageDeflate.extensionName].params;
3408
- const value = extension.format({ [PerMessageDeflate.extensionName]: [params] });
3409
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
3410
- ws._extensions = extensions;
3411
- }
3412
- this.emit("headers", headers, req);
3413
- socket.write(headers.concat("\r\n").join("\r\n"));
3414
- socket.removeListener("error", socketOnError);
3415
- ws.setSocket(socket, head, {
3416
- allowSynchronousEvents: this.options.allowSynchronousEvents,
3417
- maxPayload: this.options.maxPayload,
3418
- skipUTF8Validation: this.options.skipUTF8Validation
3419
- });
3420
- if (this.clients) {
3421
- this.clients.add(ws);
3422
- ws.on("close", () => {
3423
- this.clients.delete(ws);
3424
- if (this._shouldEmitClose && !this.clients.size) process.nextTick(emitClose, this);
3425
- });
3426
- }
3427
- cb(ws, req);
3428
- }
3429
- };
3430
- module.exports = WebSocketServer;
3431
- /**
3432
- * Add event listeners on an `EventEmitter` using a map of <event, listener>
3433
- * pairs.
3434
- *
3435
- * @param {EventEmitter} server The event emitter
3436
- * @param {Object.<String, Function>} map The listeners to add
3437
- * @return {Function} A function that will remove the added listeners when
3438
- * called
3439
- * @private
3440
- */
3441
- function addListeners(server, map) {
3442
- for (const event of Object.keys(map)) server.on(event, map[event]);
3443
- return function removeListeners() {
3444
- for (const event of Object.keys(map)) server.removeListener(event, map[event]);
3445
- };
3446
- }
3447
- /**
3448
- * Emit a `'close'` event on an `EventEmitter`.
3449
- *
3450
- * @param {EventEmitter} server The event emitter
3451
- * @private
3452
- */
3453
- function emitClose(server) {
3454
- server._state = CLOSED;
3455
- server.emit("close");
3456
- }
3457
- /**
3458
- * Handle socket errors.
3459
- *
3460
- * @private
3461
- */
3462
- function socketOnError() {
3463
- this.destroy();
3464
- }
3465
- /**
3466
- * Close the connection when preconditions are not fulfilled.
3467
- *
3468
- * @param {Duplex} socket The socket of the upgrade request
3469
- * @param {Number} code The HTTP response status code
3470
- * @param {String} [message] The HTTP response body
3471
- * @param {Object} [headers] Additional HTTP response headers
3472
- * @private
3473
- */
3474
- function abortHandshake(socket, code, message, headers) {
3475
- message = message || http.STATUS_CODES[code];
3476
- headers = {
3477
- Connection: "close",
3478
- "Content-Type": "text/html",
3479
- "Content-Length": Buffer.byteLength(message),
3480
- ...headers
3481
- };
3482
- socket.once("finish", socket.destroy);
3483
- socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message);
3484
- }
3485
- /**
3486
- * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
3487
- * one listener for it, otherwise call `abortHandshake()`.
3488
- *
3489
- * @param {WebSocketServer} server The WebSocket server
3490
- * @param {http.IncomingMessage} req The request object
3491
- * @param {Duplex} socket The socket of the upgrade request
3492
- * @param {Number} code The HTTP response status code
3493
- * @param {String} message The HTTP response body
3494
- * @param {Object} [headers] The HTTP response headers
3495
- * @private
3496
- */
3497
- function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3498
- if (server.listenerCount("wsClientError")) {
3499
- const err = new Error(message);
3500
- Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3501
- server.emit("wsClientError", err, socket, req);
3502
- } else abortHandshake(socket, code, message, headers);
3503
- }
3504
- }));
3505
- //#endregion
3506
- //#region ../../node_modules/.bun/ws@8.20.0/node_modules/ws/wrapper.mjs
3507
- var import_stream = /* @__PURE__ */ __toESM(require_stream(), 1);
3508
- var import_extension = /* @__PURE__ */ __toESM(require_extension(), 1);
3509
- var import_permessage_deflate = /* @__PURE__ */ __toESM(require_permessage_deflate(), 1);
3510
- var import_receiver = /* @__PURE__ */ __toESM(require_receiver(), 1);
3511
- var import_sender = /* @__PURE__ */ __toESM(require_sender(), 1);
3512
- var import_subprotocol = /* @__PURE__ */ __toESM(require_subprotocol(), 1);
3513
- var import_websocket = /* @__PURE__ */ __toESM(require_websocket(), 1);
3514
- var import_websocket_server = /* @__PURE__ */ __toESM(require_websocket_server(), 1);
3515
- var wrapper_default = import_websocket.default;
3516
- //#endregion
3517
- var PerMessageDeflate = import_permessage_deflate.default;
3518
- var Receiver = import_receiver.default;
3519
- var Sender = import_sender.default;
3520
- var WebSocket = import_websocket.default;
3521
- var WebSocketServer = import_websocket_server.default;
3522
- var createWebSocketStream = import_stream.default;
3523
- var extension = import_extension.default;
3524
- var subprotocol = import_subprotocol.default;
3525
- export { PerMessageDeflate, Receiver, Sender, WebSocket, WebSocketServer, createWebSocketStream, wrapper_default as default, extension, subprotocol };
3526
-
3527
- //# sourceMappingURL=wrapper-CE6GQ27z.mjs.map