uwebsockets 1.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,58 +1,52 @@
1
1
  <div align="center">
2
2
  <img src="https://raw.githubusercontent.com/uNetworking/uWebSockets/master/misc/logo.svg" height="180" /><br>
3
- <i>Simple, secure</i><sup><a href="https://github.com/uNetworking/uWebSockets/tree/master/fuzzing#fuzz-testing-of-various-parsers-and-mocked-examples">1</a></sup><i> & standards compliant</i><sup><a href="https://unetworking.github.io/uWebSockets.js/report.pdf">2</a></sup><i> web server for the most demanding</i><sup><a href="https://github.com/uNetworking/uWebSockets/tree/master/benchmarks#benchmark-driven-development">3</a></sup><i> of applications.</i> <a href="https://github.com/uNetworking/uWebSockets#readme">Read more...</a>
3
+ <i>Simple, secure</i><sup><a href="https://github.com/NPM-Package-Jaykumar/uWebSockets/tree/master/fuzzing#fuzz-testing-of-various-parsers-and-mocked-examples">1</a></sup><i> & standards compliant</i><sup><a href="https://unetworking.github.io/uWebSockets.js/report.pdf">2</a></sup><i> web server for the most demanding</i><sup><a href="https://github.com/NPM-Package-Jaykumar/uWebSockets/tree/master/benchmarks#benchmark-driven-development">3</a></sup><i> of applications.</i> <a href="https://github.com/NPM-Package-Jaykumar/uWebSockets#readme">Read more...</a>
4
4
  <br><br>
5
5
 
6
- <a href="https://github.com/uNetworking/uWebSockets.js/releases"><img src="https://img.shields.io/github/v/release/uNetworking/uWebSockets.js"></a> <a href="https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:uwebsockets"><img src="https://oss-fuzz-build-logs.storage.googleapis.com/badges/uwebsockets.svg" /></a> <img src="https://img.shields.io/badge/downloads-70%20million-green" /> <img src="https://img.shields.io/badge/established-in%202016-green" />
6
+ <a href="https://github.com/NPM-Package-Jaykumar/uWebSockets/releases"><img src="https://img.shields.io/github/v/release/uNetworking/uWebSockets.js"></a> <a href="https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:uwebsockets"><img src="https://oss-fuzz-build-logs.storage.googleapis.com/badges/uwebsockets.svg" /></a> <img src="https://img.shields.io/badge/downloads-70%20million-green" /> <img src="https://img.shields.io/badge/established-in%202016-green" />
7
+
7
8
  </div>
8
9
  <br><br>
9
10
 
10
11
  ### :zap: Simple performance
11
- µWebSockets.js is a web server bypass for Node.js that reimplements eventing, networking, encryption, web protocols, routing and pub/sub in highly optimized C++. As such, µWebSockets.js delivers web serving for Node.js, **[8.5x that of Fastify](https://alexhultman.medium.com/serving-100k-requests-second-from-a-fanless-raspberry-pi-4-over-ethernet-fdd2c2e05a1e)** and at least **[10x that of Socket.IO](https://medium.com/swlh/100k-secure-websockets-with-raspberry-pi-4-1ba5d2127a23)**. It is also the built-in **[web server of Bun](https://bun.sh/)**.
12
12
 
13
- * We *recommend, for simplicity* installing with `bun install uNetworking/uWebSockets.js#v20.33.0` or any such [release](https://github.com/uNetworking/uWebSockets.js/releases). Use [official builds](https://nodejs.org/en/download) of Node.js LTS.
13
+ µWebSockets.js is a web server bypass for Node.js that reimplements eventing, networking, encryption, web protocols, routing and pub/sub in highly optimized C++. As such, µWebSockets.js delivers web serving for Node.js, **[8.5x that of Fastify](https://alexhultman.medium.com/serving-100k-requests-second-from-a-fanless-raspberry-pi-4-over-ethernet-fdd2c2e05a1e)** and at least **[10x that of Socket.IO](https://medium.com/swlh/100k-secure-websockets-with-raspberry-pi-4-1ba5d2127a23)**. It is also the built-in **[web server of Bun](https://bun.sh/)**.
14
14
 
15
- * Browse the [documentation](https://unetworking.github.io/uWebSockets.js/generated/) and see the [main repo](https://github.com/uNetworking/uWebSockets). There are tons of [examples](examples) but here's the gist of it all:
15
+ - Browse the [documentation](https://unetworking.github.io/uWebSockets.js/generated/) and see the [main repo](https://github.com/NPM-Package-Jaykumar/uWebSockets). There are tons of [examples](examples) but here's the gist of it all:
16
16
 
17
17
  ```javascript
18
18
  /* Non-SSL is simply App() */
19
- require('uWebSockets.js').SSLApp({
20
-
21
- /* There are more SSL options, cut for brevity */
22
- key_file_name: 'misc/key.pem',
23
- cert_file_name: 'misc/cert.pem',
24
-
25
- }).ws('/*', {
26
-
27
- /* There are many common helper features */
28
- idleTimeout: 32,
29
- maxBackpressure: 1024,
30
- maxPayloadLength: 512,
31
- compression: DEDICATED_COMPRESSOR_3KB,
32
-
33
- /* For brevity we skip the other events (upgrade, open, ping, pong, close) */
34
- message: (ws, message, isBinary) => {
35
- /* You can do app.publish('sensors/home/temperature', '22C') kind of pub/sub as well */
36
-
37
- /* Here we echo the message back, using compression if available */
38
- let ok = ws.send(message, isBinary, true);
39
- }
40
-
41
- }).get('/*', (res, req) => {
42
-
43
- /* It does Http as well */
44
- res.writeStatus('200 OK').writeHeader('IsExample', 'Yes').end('Hello there!');
45
-
46
- }).listen(9001, (listenSocket) => {
47
-
48
- if (listenSocket) {
49
- console.log('Listening to port 9001');
50
- }
51
-
52
- });
19
+ require("uWebSockets.js")
20
+ .SSLApp({
21
+ /* There are more SSL options, cut for brevity */
22
+ key_file_name: "misc/key.pem",
23
+ cert_file_name: "misc/cert.pem",
24
+ })
25
+ .ws("/*", {
26
+ /* There are many common helper features */
27
+ idleTimeout: 32,
28
+ maxBackpressure: 1024,
29
+ maxPayloadLength: 512,
30
+ compression: DEDICATED_COMPRESSOR_3KB,
31
+
32
+ /* For brevity we skip the other events (upgrade, open, ping, pong, close) */
33
+ message: (ws, message, isBinary) => {
34
+ /* You can do app.publish('sensors/home/temperature', '22C') kind of pub/sub as well */
35
+
36
+ /* Here we echo the message back, using compression if available */
37
+ let ok = ws.send(message, isBinary, true);
38
+ },
39
+ })
40
+ .get("/*", (res, req) => {
41
+ /* It does Http as well */
42
+ res
43
+ .writeStatus("200 OK")
44
+ .writeHeader("IsExample", "Yes")
45
+ .end("Hello there!");
46
+ })
47
+ .listen(9001, (listenSocket) => {
48
+ if (listenSocket) {
49
+ console.log("Listening to port 9001");
50
+ }
51
+ });
53
52
  ```
54
-
55
- ### :handshake: Permissively licensed
56
- Intellectual property, all rights reserved.
57
-
58
- Where such explicit notice is given, source code is licensed Apache License 2.0 which is a permissive OSI-approved license with very few limitations. Modified "forks" should be of nothing but licensed source code, and be made available under another product name. If you're uncertain about any of this, please ask before assuming.
package/index.d.ts ADDED
@@ -0,0 +1,362 @@
1
+ /*
2
+ * Authored by Alex Hultman, 2018-2021.
3
+ * Intellectual property of third-party.
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ * http://www.apache.org/licenses/LICENSE-2.0
8
+ * Unless required by applicable law or agreed to in writing, software
9
+ * distributed under the License is distributed on an "AS IS" BASIS,
10
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ * See the License for the specific language governing permissions and
12
+ * limitations under the License.
13
+ */
14
+
15
+ /** Native type representing a raw uSockets struct us_listen_socket_t.
16
+ * Careful with this one, it is entirely unchecked and native so invalid usage will blow up.
17
+ */
18
+ export interface us_listen_socket {
19
+
20
+ }
21
+
22
+ /** Native type representing a raw uSockets struct us_socket_t.
23
+ * Careful with this one, it is entirely unchecked and native so invalid usage will blow up.
24
+ */
25
+ export interface us_socket {
26
+
27
+ }
28
+
29
+ /** Native type representing a raw uSockets struct us_socket_context_t.
30
+ * Used while upgrading a WebSocket manually. */
31
+ export interface us_socket_context_t {
32
+
33
+ }
34
+
35
+ /** Recognized string types, things C++ can read and understand as strings.
36
+ * "String" does not have to mean "text", it can also be "binary".
37
+ *
38
+ * Ironically, JavaScript strings are the least performant of all options, to pass or receive to/from C++.
39
+ * This because we expect UTF-8, which is packed in 8-byte chars. JavaScript strings are UTF-16 internally meaning extra copies and reinterpretation are required.
40
+ *
41
+ * That's why all events pass data by ArrayBuffer and not JavaScript strings, as they allow zero-copy data passing.
42
+ *
43
+ * You can always do Buffer.from(arrayBuffer).toString(), but keeping things binary and as ArrayBuffer is preferred.
44
+ */
45
+ export type RecognizedString = string | ArrayBuffer | Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array;
46
+
47
+ /** A WebSocket connection that is valid from open to close event.
48
+ * Read more about this in the user manual.
49
+ */
50
+ export interface WebSocket {
51
+ /** Sends a message. Make sure to check getBufferedAmount() before sending. Returns true for success, false for built up backpressure that will drain when time is given.
52
+ * Returning false does not mean nothing was sent, it only means backpressure was built up. This you can check by calling getBufferedAmount() afterwards.
53
+ *
54
+ * Make sure you properly understand the concept of backpressure. Check the backpressure example file.
55
+ */
56
+ send(message: RecognizedString, isBinary?: boolean, compress?: boolean) : boolean;
57
+
58
+ /** Returns the bytes buffered in backpressure. This is similar to the bufferedAmount property in the browser counterpart.
59
+ * Check backpressure example.
60
+ */
61
+ getBufferedAmount() : number;
62
+
63
+ /** Gracefully closes this WebSocket. Immediately calls the close handler.
64
+ * A WebSocket close message is sent with code and shortMessage.
65
+ */
66
+ end(code?: number, shortMessage?: RecognizedString) : WebSocket;
67
+
68
+ /** Forcefully closes this WebSocket. Immediately calls the close handler.
69
+ * No WebSocket close message is sent.
70
+ */
71
+ close() : WebSocket;
72
+
73
+ /** Sends a ping control message. Returns true on success in similar ways as WebSocket.send does (regarding backpressure). This helper function correlates to WebSocket::send(message, uWS::OpCode::PING, ...) in C++. */
74
+ ping(message?: RecognizedString) : boolean;
75
+
76
+ /** Subscribe to a topic in MQTT syntax.
77
+ *
78
+ * MQTT syntax includes things like "root/child/+/grandchild" where "+" is a
79
+ * wildcard and "root/#" where "#" is a terminating wildcard.
80
+ *
81
+ * Read more about MQTT.
82
+ */
83
+ subscribe(topic: RecognizedString) : boolean;
84
+
85
+ /** Unsubscribe from a topic. Returns true on success, if the WebSocket was subscribed. */
86
+ unsubscribe(topic: RecognizedString) : boolean;
87
+
88
+ /** Returns whether this websocket is subscribed to topic. */
89
+ isSubscribed(topic: RecognizedString) : boolean;
90
+
91
+ /** Returns a list of topics this websocket is subscribed to. */
92
+ getTopics() : string[];
93
+
94
+ /** Publish a message to a topic in MQTT syntax. You cannot publish using wildcards, only fully specified topics. Just like with MQTT.
95
+ *
96
+ * "parent/child" kind of tree is allowed, but not "parent/#" kind of wildcard publishing.
97
+ *
98
+ * The pub/sub system does not guarantee order between what you manually send using WebSocket.send
99
+ * and what you publish using WebSocket.publish. WebSocket messages are perfectly atomic, but the order in which they appear can get scrambled if you mix the two sending functions on the same socket.
100
+ * This shouldn't matter in most applications. Order is guaranteed relative to other calls to WebSocket.publish.
101
+ *
102
+ * Also keep in mind that backpressure will be automatically managed with pub/sub, meaning some outgoing messages may be dropped if backpressure is greater than specified maxBackpressure.
103
+ */
104
+ publish(topic: RecognizedString, message: RecognizedString, isBinary?: boolean, compress?: boolean) : boolean;
105
+
106
+ /** See HttpResponse.cork. Takes a function in which the socket is corked (packing many sends into one single syscall/SSL block) */
107
+ cork(cb: () => void) : void;
108
+
109
+ /** Returns the remote IP address. Note that the returned IP is binary, not text.
110
+ *
111
+ * IPv4 is 4 byte long and can be converted to text by printing every byte as a digit between 0 and 255.
112
+ * IPv6 is 16 byte long and can be converted to text in similar ways, but you typically print digits in HEX.
113
+ *
114
+ * See getRemoteAddressAsText() for a text version.
115
+ */
116
+ getRemoteAddress() : ArrayBuffer;
117
+
118
+ /** Returns the remote IP address as text. See RecognizedString. */
119
+ getRemoteAddressAsText() : ArrayBuffer;
120
+
121
+ /** Arbitrary user data may be attached to this object. In C++ this is done by using getUserData(). */
122
+ [key: string]: any;
123
+ }
124
+
125
+ /** An HttpResponse is valid until either onAborted callback or any of the .end/.tryEnd calls succeed. You may attach user data to this object. */
126
+ export interface HttpResponse {
127
+ /** Writes the HTTP status message such as "200 OK".
128
+ * This has to be called first in any response, otherwise
129
+ * it will be called automatically with "200 OK".
130
+ *
131
+ * If you want to send custom headers in a WebSocket
132
+ * upgrade response, you have to call writeStatus with
133
+ * "101 Switching Protocols" before you call writeHeader,
134
+ * otherwise your first call to writeHeader will call
135
+ * writeStatus with "200 OK" and the upgrade will fail.
136
+ *
137
+ * As you can imagine, we format outgoing responses in a linear
138
+ * buffer, not in a hash table. You can read about this in
139
+ * the user manual under "corking".
140
+ */
141
+ writeStatus(status: RecognizedString) : HttpResponse;
142
+ /** Writes key and value to HTTP response.
143
+ * See writeStatus and corking.
144
+ */
145
+ writeHeader(key: RecognizedString, value: RecognizedString) : HttpResponse;
146
+ /** Enters or continues chunked encoding mode. Writes part of the response. End with zero length write. */
147
+ write(chunk: RecognizedString) : HttpResponse;
148
+ /** Ends this response by copying the contents of body. */
149
+ end(body?: RecognizedString, closeConnection?: boolean) : HttpResponse;
150
+ /** Ends this response, or tries to, by streaming appropriately sized chunks of body. Use in conjunction with onWritable. Returns tuple [ok, hasResponded].*/
151
+ tryEnd(fullBodyOrChunk: RecognizedString, totalSize: number) : [boolean, boolean];
152
+
153
+ /** Immediately force closes the connection. Any onAborted callback will run. */
154
+ close() : HttpResponse;
155
+
156
+ /** Returns the global byte write offset for this response. Use with onWritable. */
157
+ getWriteOffset() : number;
158
+
159
+ /** Registers a handler for writable events. Continue failed write attempts in here.
160
+ * You MUST return true for success, false for failure.
161
+ * Writing nothing is always success, so by default you must return true.
162
+ */
163
+ onWritable(handler: (offset: number) => boolean) : HttpResponse;
164
+
165
+ /** Every HttpResponse MUST have an attached abort handler IF you do not respond
166
+ * to it immediately inside of the callback. Returning from an Http request handler
167
+ * without attaching (by calling onAborted) an abort handler is ill-use and will termiante.
168
+ * When this event emits, the response has been aborted and may not be used. */
169
+ onAborted(handler: () => void) : HttpResponse;
170
+
171
+ /** Handler for reading data from POST and such requests. You MUST copy the data of chunk if isLast is not true. We Neuter ArrayBuffers on return, making it zero length.*/
172
+ onData(handler: (chunk: ArrayBuffer, isLast: boolean) => void) : HttpResponse;
173
+
174
+ /** Returns the remote IP address in binary format (4 or 16 bytes). */
175
+ getRemoteAddress() : ArrayBuffer;
176
+
177
+ /** Returns the remote IP address as text. */
178
+ getRemoteAddressAsText() : ArrayBuffer;
179
+
180
+ /** Returns the remote IP address in binary format (4 or 16 bytes), as reported by the PROXY Protocol v2 compatible proxy. */
181
+ getProxiedRemoteAddress() : ArrayBuffer;
182
+
183
+ /** Returns the remote IP address as text, as reported by the PROXY Protocol v2 compatible proxy. */
184
+ getProxiedRemoteAddressAsText() : ArrayBuffer;
185
+
186
+ /** Corking a response is a performance improvement in both CPU and network, as you ready the IO system for writing multiple chunks at once.
187
+ * By default, you're corked in the immediately executing top portion of the route handler. In all other cases, such as when returning from
188
+ * await, or when being called back from an async database request or anything that isn't directly executing in the route handler, you'll want
189
+ * to cork before calling writeStatus, writeHeader or just write. Corking takes a callback in which you execute the writeHeader, writeStatus and
190
+ * such calls, in one atomic IO operation. This is important, not only for TCP but definitely for TLS where each write would otherwise result
191
+ * in one TLS block being sent off, each with one send syscall.
192
+ *
193
+ * Example usage:
194
+ *
195
+ * res.cork(() => {
196
+ * res.writeStatus("200 OK").writeHeader("Some", "Value").write("Hello world!");
197
+ * });
198
+ */
199
+ cork(cb: () => void) : void;
200
+
201
+ /** Upgrades a HttpResponse to a WebSocket. See UpgradeAsync, UpgradeSync example files. */
202
+ upgrade<T>(userData : T, secWebSocketKey: RecognizedString, secWebSocketProtocol: RecognizedString, secWebSocketExtensions: RecognizedString, context: us_socket_context_t) : void;
203
+
204
+ /** Arbitrary user data may be attached to this object */
205
+ [key: string]: any;
206
+ }
207
+
208
+ /** An HttpRequest is stack allocated and only accessible during the callback invocation. */
209
+ export interface HttpRequest {
210
+ /** Returns the lowercased header value or empty string. */
211
+ getHeader(lowerCaseKey: RecognizedString) : string;
212
+ /** Returns the parsed parameter at index. Corresponds to route. */
213
+ getParameter(index: number) : string;
214
+ /** Returns the URL including initial /slash */
215
+ getUrl() : string;
216
+ /** Returns the HTTP method, useful for "any" routes. */
217
+ getMethod() : string;
218
+ /** Returns the raw querystring (the part of URL after ? sign) or empty string. */
219
+ getQuery() : string;
220
+ /** Returns a decoded query parameter value or empty string. */
221
+ getQuery(key: string) : string;
222
+ /** Loops over all headers. */
223
+ forEach(cb: (key: string, value: string) => void) : void;
224
+ /** Setting yield to true is to say that this route handler did not handle the route, causing the router to continue looking for a matching route handler, or fail. */
225
+ setYield(yield: boolean) : HttpRequest;
226
+ }
227
+
228
+ /** A structure holding settings and handlers for a WebSocket URL route handler. */
229
+ export interface WebSocketBehavior {
230
+ /** Maximum length of received message. If a client tries to send you a message larger than this, the connection is immediately closed. Defaults to 16 * 1024. */
231
+ maxPayloadLength?: number;
232
+ /** Maximum amount of seconds that may pass without sending or getting a message. Connection is closed if this timeout passes. Resolution (granularity) for timeouts are typically 4 seconds, rounded to closest.
233
+ * Disable by using 0. Defaults to 120.
234
+ */
235
+ idleTimeout?: number;
236
+ /** What permessage-deflate compression to use. uWS.DISABLED, uWS.SHARED_COMPRESSOR or any of the uWS.DEDICATED_COMPRESSOR_xxxKB. Defaults to uWS.DISABLED. */
237
+ compression?: CompressOptions;
238
+ /** Maximum length of allowed backpressure per socket when publishing or sending messages. Slow receivers with too high backpressure will be skipped until they catch up or timeout. Defaults to 1024 * 1024. */
239
+ maxBackpressure?: number;
240
+ /** Upgrade handler used to intercept HTTP upgrade requests and potentially upgrade to WebSocket.
241
+ * See UpgradeAsync and UpgradeSync example files.
242
+ */
243
+ upgrade?: (res: HttpResponse, req: HttpRequest, context: us_socket_context_t) => void;
244
+ /** Handler for new WebSocket connection. WebSocket is valid from open to close, no errors. */
245
+ open?: (ws: WebSocket) => void;
246
+ /** Handler for a WebSocket message. Messages are given as ArrayBuffer no matter if they are binary or not. Given ArrayBuffer is valid during the lifetime of this callback (until first await or return) and will be neutered. */
247
+ message?: (ws: WebSocket, message: ArrayBuffer, isBinary: boolean) => void;
248
+ /** Handler for when WebSocket backpressure drains. Check ws.getBufferedAmount(). Use this to guide / drive your backpressure throttling. */
249
+ drain?: (ws: WebSocket) => void;
250
+ /** Handler for close event, no matter if error, timeout or graceful close. You may not use WebSocket after this event. Do not send on this WebSocket from within here, it is closed. */
251
+ close?: (ws: WebSocket, code: number, message: ArrayBuffer) => void;
252
+ /** Handler for received ping control message. You do not need to handle this, pong messages are automatically sent as per the standard. */
253
+ ping?: (ws: WebSocket, message: ArrayBuffer) => void;
254
+ /** Handler for received pong control message. */
255
+ pong?: (ws: WebSocket, message: ArrayBuffer) => void;
256
+ }
257
+
258
+ /** Options used when constructing an app. Especially for SSLApp.
259
+ * These are options passed directly to uSockets, C layer.
260
+ */
261
+ export interface AppOptions {
262
+ key_file_name?: RecognizedString;
263
+ cert_file_name?: RecognizedString;
264
+ passphrase?: RecognizedString;
265
+ dh_params_file_name?: RecognizedString;
266
+ /** This translates to SSL_MODE_RELEASE_BUFFERS */
267
+ ssl_prefer_low_memory_usage?: boolean;
268
+ }
269
+
270
+ export enum ListenOptions {
271
+ LIBUS_LISTEN_DEFAULT = 0,
272
+ LIBUS_LISTEN_EXCLUSIVE_PORT = 1
273
+ }
274
+
275
+ /** TemplatedApp is either an SSL or non-SSL app. See App for more info, read user manual. */
276
+ export interface TemplatedApp {
277
+ /** Listens to hostname & port. Callback hands either false or a listen socket. */
278
+ listen(host: RecognizedString, port: number, cb: (listenSocket: us_listen_socket) => void): TemplatedApp;
279
+ /** Listens to port. Callback hands either false or a listen socket. */
280
+ listen(port: number, cb: (listenSocket: any) => void): TemplatedApp;
281
+ /** Listens to port and sets Listen Options. Callback hands either false or a listen socket. */
282
+ listen(port: number, options: ListenOptions, cb: (listenSocket: us_listen_socket | false) => void): TemplatedApp;
283
+ /** Registers an HTTP GET handler matching specified URL pattern. */
284
+ get(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void) : TemplatedApp;
285
+ /** Registers an HTTP POST handler matching specified URL pattern. */
286
+ post(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void) : TemplatedApp;
287
+ /** Registers an HTTP OPTIONS handler matching specified URL pattern. */
288
+ options(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void) : TemplatedApp;
289
+ /** Registers an HTTP DELETE handler matching specified URL pattern. */
290
+ del(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void) : TemplatedApp;
291
+ /** Registers an HTTP PATCH handler matching specified URL pattern. */
292
+ patch(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void) : TemplatedApp;
293
+ /** Registers an HTTP PUT handler matching specified URL pattern. */
294
+ put(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void) : TemplatedApp;
295
+ /** Registers an HTTP HEAD handler matching specified URL pattern. */
296
+ head(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void) : TemplatedApp;
297
+ /** Registers an HTTP CONNECT handler matching specified URL pattern. */
298
+ connect(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void) : TemplatedApp;
299
+ /** Registers an HTTP TRACE handler matching specified URL pattern. */
300
+ trace(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void) : TemplatedApp;
301
+ /** Registers an HTTP handler matching specified URL pattern on any HTTP method. */
302
+ any(pattern: RecognizedString, handler: (res: HttpResponse, req: HttpRequest) => void) : TemplatedApp;
303
+ /** Registers a handler matching specified URL pattern where WebSocket upgrade requests are caught. */
304
+ ws(pattern: RecognizedString, behavior: WebSocketBehavior) : TemplatedApp;
305
+ /** Publishes a message under topic, for all WebSockets under this app. See WebSocket.publish. */
306
+ publish(topic: RecognizedString, message: RecognizedString, isBinary?: boolean, compress?: boolean) : boolean;
307
+ /** Returns number of subscribers for this topic. */
308
+ numSubscribers(topic: RecognizedString) : number;
309
+ /** Adds a server name. */
310
+ addServerName(hostname: string, options: AppOptions): TemplatedApp;
311
+ /** Removes a server name. */
312
+ removeServerName(hostname: string): TemplatedApp;
313
+ /** Registers a synchronous callback on missing server names. See /examples/ServerName.js. */
314
+ missingServerName(cb: (hostname: string) => void): TemplatedApp;
315
+ }
316
+
317
+ /** Constructs a non-SSL app. An app is your starting point where you attach behavior to URL routes.
318
+ * This is also where you listen and run your app, set any SSL options (in case of SSLApp) and the like.
319
+ */
320
+ export function App(options?: AppOptions): TemplatedApp;
321
+
322
+ /** Constructs an SSL app. See App. */
323
+ export function SSLApp(options: AppOptions): TemplatedApp;
324
+
325
+ /** Closes a uSockets listen socket. */
326
+ export function us_listen_socket_close(listenSocket: us_listen_socket): void;
327
+
328
+ /** Gets local port of socket (or listenSocket) or -1. */
329
+ export function us_socket_local_port(socket: us_socket): number;
330
+
331
+ export interface MultipartField {
332
+ data: ArrayBuffer;
333
+ name: string;
334
+ type?: string;
335
+ filename?: string;
336
+ }
337
+
338
+ /** Takes a POSTed body and contentType, and returns an array of parts if the request is a multipart request */
339
+ export function getParts(body: RecognizedString, contentType: RecognizedString): MultipartField[] | undefined;
340
+
341
+ /** WebSocket compression options */
342
+ export type CompressOptions = number;
343
+ /** No compression (always a good idea if you operate using an efficient binary protocol) */
344
+ export var DISABLED: CompressOptions;
345
+ /** Zero memory overhead compression (recommended for pub/sub where same message is sent to many receivers) */
346
+ export var SHARED_COMPRESSOR: CompressOptions;
347
+ /** Sliding dedicated compress window, requires 3KB of memory per socket */
348
+ export var DEDICATED_COMPRESSOR_3KB: CompressOptions;
349
+ /** Sliding dedicated compress window, requires 4KB of memory per socket */
350
+ export var DEDICATED_COMPRESSOR_4KB: CompressOptions;
351
+ /** Sliding dedicated compress window, requires 8KB of memory per socket */
352
+ export var DEDICATED_COMPRESSOR_8KB: CompressOptions;
353
+ /** Sliding dedicated compress window, requires 16KB of memory per socket */
354
+ export var DEDICATED_COMPRESSOR_16KB: CompressOptions;
355
+ /** Sliding dedicated compress window, requires 32KB of memory per socket */
356
+ export var DEDICATED_COMPRESSOR_32KB: CompressOptions;
357
+ /** Sliding dedicated compress window, requires 64KB of memory per socket */
358
+ export var DEDICATED_COMPRESSOR_64KB: CompressOptions;
359
+ /** Sliding dedicated compress window, requires 128KB of memory per socket */
360
+ export var DEDICATED_COMPRESSOR_128KB: CompressOptions;
361
+ /** Sliding dedicated compress window, requires 256KB of memory per socket */
362
+ export var DEDICATED_COMPRESSOR_256KB: CompressOptions;
package/package.json CHANGED
@@ -1,16 +1,9 @@
1
1
  {
2
2
  "name": "uwebsockets",
3
- "version": "1.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "µWebSockets.js is a web server bypass for Node.js that reimplements eventing, networking, encryption, web protocols, routing and pub/sub in highly optimized C++. As such, µWebSockets.js delivers web serving for Node.js, 8.5x that of Fastify and at least 10x that of Socket.IO. It is also the built-in web server of Bun.",
5
- "main": "index.js",
6
- "directories": {
7
- "doc": "docs",
8
- "example": "examples",
9
- "test": "tests"
10
- },
11
- "scripts": {
12
- "test": "echo \"Error: no test specified\" && exit 1"
13
- },
5
+ "main": "uws.js",
6
+ "types": "./index.d.ts",
14
7
  "repository": {
15
8
  "type": "git",
16
9
  "url": "git+https://github.com/NPM-Package-Jaykumar/uWebSockets.git"
package/source_commit ADDED
@@ -0,0 +1 @@
1
+ c70d2e6d2d923183885e991c6cb4189419b521a5
package/uws.js ADDED
@@ -0,0 +1,24 @@
1
+ /*
2
+ * Authored by Alex Hultman, 2018-2021.
3
+ * Intellectual property of third-party.
4
+
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ module.exports = (() => {
19
+ try {
20
+ return require('./uws_' + process.platform + '_' + process.arch + '_' + process.versions.modules + '.node');
21
+ } catch (e) {
22
+ throw new Error('This version of µWS is not compatible with your Node.js build:\n\n' + e.toString());
23
+ }
24
+ })();
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/.gitattributes DELETED
@@ -1,3 +0,0 @@
1
- *.js linguist-vendored
2
- *.pro linguist-vendored
3
- src/* linguist-vendored=false
package/.gitmodules DELETED
@@ -1,3 +0,0 @@
1
- [submodule "uWebSockets"]
2
- path = uWebSockets
3
- url = https://github.com/uNetworking/uWebSockets