@graftland/plugin-remote 0.3.3 → 0.4.1

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