@miqro/core 4.0.1 → 5.0.2

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 (220) hide show
  1. package/build/app.d.ts +15 -11
  2. package/build/app.js +22 -20
  3. package/build/app.js.map +1 -1
  4. package/build/common.d.ts +106 -0
  5. package/build/common.js +477 -0
  6. package/build/common.js.map +1 -0
  7. package/build/lib.d.ts +7 -38
  8. package/build/lib.js +6 -33
  9. package/build/lib.js.map +1 -1
  10. package/build/middleware/body-parser.d.ts +78 -0
  11. package/build/middleware/body-parser.js +552 -0
  12. package/build/middleware/body-parser.js.map +1 -0
  13. package/build/middleware/router.d.ts +114 -0
  14. package/build/middleware/router.js +704 -0
  15. package/build/middleware/router.js.map +1 -0
  16. package/build/middleware/session.d.ts +27 -3
  17. package/build/middleware/session.js +238 -18
  18. package/build/middleware/session.js.map +1 -1
  19. package/build/types.d.ts +309 -0
  20. package/build/types.js +455 -0
  21. package/build/types.js.map +1 -0
  22. package/build/{websocket/cluster.d.ts → websocket.d.ts} +13 -2
  23. package/build/websocket.js +316 -0
  24. package/build/websocket.js.map +1 -0
  25. package/package.json +7 -7
  26. package/src/app.ts +36 -32
  27. package/src/common.ts +528 -0
  28. package/src/lib.ts +63 -101
  29. package/src/middleware/body-parser.ts +597 -0
  30. package/src/middleware/router.ts +840 -0
  31. package/src/middleware/session.ts +249 -19
  32. package/src/types.ts +785 -0
  33. package/src/websocket.ts +356 -0
  34. package/build/api-router.d.ts +0 -34
  35. package/build/api-router.js +0 -48
  36. package/build/api-router.js.map +0 -1
  37. package/build/app-utils.d.ts +0 -13
  38. package/build/app-utils.js +0 -78
  39. package/build/app-utils.js.map +0 -1
  40. package/build/common/api-router-types.d.ts +0 -28
  41. package/build/common/api-router-types.js +0 -24
  42. package/build/common/api-router-types.js.map +0 -1
  43. package/build/common/api-router-utils.d.ts +0 -3
  44. package/build/common/api-router-utils.js +0 -118
  45. package/build/common/api-router-utils.js.map +0 -1
  46. package/build/common/config/config.d.ts +0 -15
  47. package/build/common/config/config.js +0 -38
  48. package/build/common/config/config.js.map +0 -1
  49. package/build/common/config/featuretoggle.d.ts +0 -1
  50. package/build/common/config/featuretoggle.js +0 -6
  51. package/build/common/config/featuretoggle.js.map +0 -1
  52. package/build/common/config/loader.d.ts +0 -13
  53. package/build/common/config/loader.js +0 -64
  54. package/build/common/config/loader.js.map +0 -1
  55. package/build/common/context.d.ts +0 -57
  56. package/build/common/context.js +0 -137
  57. package/build/common/context.js.map +0 -1
  58. package/build/common/error/badrequesterror.d.ts +0 -3
  59. package/build/common/error/badrequesterror.js +0 -7
  60. package/build/common/error/badrequesterror.js.map +0 -1
  61. package/build/common/error/configfilenotfound.d.ts +0 -3
  62. package/build/common/error/configfilenotfound.js +0 -7
  63. package/build/common/error/configfilenotfound.js.map +0 -1
  64. package/build/common/error/forbiddenerror.d.ts +0 -3
  65. package/build/common/error/forbiddenerror.js +0 -7
  66. package/build/common/error/forbiddenerror.js.map +0 -1
  67. package/build/common/error/notfound.d.ts +0 -3
  68. package/build/common/error/notfound.js +0 -7
  69. package/build/common/error/notfound.js.map +0 -1
  70. package/build/common/error/notimplemented.d.ts +0 -3
  71. package/build/common/error/notimplemented.js +0 -7
  72. package/build/common/error/notimplemented.js.map +0 -1
  73. package/build/common/error/unauthorizederror.d.ts +0 -3
  74. package/build/common/error/unauthorizederror.js +0 -7
  75. package/build/common/error/unauthorizederror.js.map +0 -1
  76. package/build/common/logger/constants.d.ts +0 -14
  77. package/build/common/logger/constants.js +0 -22
  78. package/build/common/logger/constants.js.map +0 -1
  79. package/build/common/logger/factory.d.ts +0 -16
  80. package/build/common/logger/factory.js +0 -47
  81. package/build/common/logger/factory.js.map +0 -1
  82. package/build/common/logger/interfaces.d.ts +0 -18
  83. package/build/common/logger/interfaces.js +0 -2
  84. package/build/common/logger/interfaces.js.map +0 -1
  85. package/build/common/logger/logger.d.ts +0 -35
  86. package/build/common/logger/logger.js +0 -95
  87. package/build/common/logger/logger.js.map +0 -1
  88. package/build/common/logger/transport/console.d.ts +0 -5
  89. package/build/common/logger/transport/console.js +0 -37
  90. package/build/common/logger/transport/console.js.map +0 -1
  91. package/build/common/logger/transport/file.d.ts +0 -2
  92. package/build/common/logger/transport/file.js +0 -25
  93. package/build/common/logger/transport/file.js.map +0 -1
  94. package/build/common/parser.d.ts +0 -7
  95. package/build/common/parser.js +0 -44
  96. package/build/common/parser.js.map +0 -1
  97. package/build/common/router-default-logger-factory.d.ts +0 -4
  98. package/build/common/router-default-logger-factory.js +0 -38
  99. package/build/common/router-default-logger-factory.js.map +0 -1
  100. package/build/common/router-handler.d.ts +0 -20
  101. package/build/common/router-handler.js +0 -154
  102. package/build/common/router-handler.js.map +0 -1
  103. package/build/common/router-types.d.ts +0 -63
  104. package/build/common/router-types.js +0 -86
  105. package/build/common/router-types.js.map +0 -1
  106. package/build/common/router-utils.d.ts +0 -3
  107. package/build/common/router-utils.js +0 -46
  108. package/build/common/router-utils.js.map +0 -1
  109. package/build/common/session/common.d.ts +0 -37
  110. package/build/common/session/common.js +0 -2
  111. package/build/common/session/common.js.map +0 -1
  112. package/build/common/session/service.d.ts +0 -26
  113. package/build/common/session/service.js +0 -154
  114. package/build/common/session/service.js.map +0 -1
  115. package/build/common/tokenize-match.d.ts +0 -19
  116. package/build/common/tokenize-match.js +0 -73
  117. package/build/common/tokenize-match.js.map +0 -1
  118. package/build/common/url-utils.d.ts +0 -6
  119. package/build/common/url-utils.js +0 -48
  120. package/build/common/url-utils.js.map +0 -1
  121. package/build/middleware/buffer.d.ts +0 -6
  122. package/build/middleware/buffer.js +0 -78
  123. package/build/middleware/buffer.js.map +0 -1
  124. package/build/middleware/cookie.d.ts +0 -4
  125. package/build/middleware/cookie.js +0 -15
  126. package/build/middleware/cookie.js.map +0 -1
  127. package/build/middleware/cors.d.ts +0 -8
  128. package/build/middleware/cors.js +0 -89
  129. package/build/middleware/cors.js.map +0 -1
  130. package/build/middleware/form.d.ts +0 -6
  131. package/build/middleware/form.js +0 -58
  132. package/build/middleware/form.js.map +0 -1
  133. package/build/middleware/group.d.ts +0 -3
  134. package/build/middleware/group.js +0 -77
  135. package/build/middleware/group.js.map +0 -1
  136. package/build/middleware/json.d.ts +0 -6
  137. package/build/middleware/json.js +0 -55
  138. package/build/middleware/json.js.map +0 -1
  139. package/build/middleware/logger.d.ts +0 -4
  140. package/build/middleware/logger.js +0 -16
  141. package/build/middleware/logger.js.map +0 -1
  142. package/build/middleware/parse.d.ts +0 -14
  143. package/build/middleware/parse.js +0 -88
  144. package/build/middleware/parse.js.map +0 -1
  145. package/build/middleware/result.d.ts +0 -9
  146. package/build/middleware/result.js +0 -62
  147. package/build/middleware/result.js.map +0 -1
  148. package/build/middleware/tag.d.ts +0 -4
  149. package/build/middleware/tag.js +0 -10
  150. package/build/middleware/tag.js.map +0 -1
  151. package/build/middleware/text.d.ts +0 -5
  152. package/build/middleware/text.js +0 -46
  153. package/build/middleware/text.js.map +0 -1
  154. package/build/proxy.d.ts +0 -19
  155. package/build/proxy.js +0 -74
  156. package/build/proxy.js.map +0 -1
  157. package/build/router.d.ts +0 -26
  158. package/build/router.js +0 -116
  159. package/build/router.js.map +0 -1
  160. package/build/static.d.ts +0 -14
  161. package/build/static.js +0 -211
  162. package/build/static.js.map +0 -1
  163. package/build/websocket/cluster.js +0 -114
  164. package/build/websocket/cluster.js.map +0 -1
  165. package/build/websocket/server.d.ts +0 -15
  166. package/build/websocket/server.js +0 -127
  167. package/build/websocket/server.js.map +0 -1
  168. package/build/websocket/types.d.ts +0 -39
  169. package/build/websocket/types.js +0 -2
  170. package/build/websocket/types.js.map +0 -1
  171. package/build/websocket/utils.d.ts +0 -8
  172. package/build/websocket/utils.js +0 -77
  173. package/build/websocket/utils.js.map +0 -1
  174. package/src/api-router.ts +0 -50
  175. package/src/app-utils.ts +0 -82
  176. package/src/common/api-router-types.ts +0 -52
  177. package/src/common/api-router-utils.ts +0 -126
  178. package/src/common/config/config.ts +0 -49
  179. package/src/common/config/featuretoggle.ts +0 -6
  180. package/src/common/config/loader.ts +0 -81
  181. package/src/common/context.ts +0 -192
  182. package/src/common/error/badrequesterror.ts +0 -6
  183. package/src/common/error/configfilenotfound.ts +0 -6
  184. package/src/common/error/forbiddenerror.ts +0 -6
  185. package/src/common/error/notfound.ts +0 -6
  186. package/src/common/error/notimplemented.ts +0 -6
  187. package/src/common/error/unauthorizederror.ts +0 -6
  188. package/src/common/logger/constants.ts +0 -28
  189. package/src/common/logger/factory.ts +0 -53
  190. package/src/common/logger/interfaces.ts +0 -19
  191. package/src/common/logger/logger.ts +0 -136
  192. package/src/common/logger/transport/console.ts +0 -36
  193. package/src/common/logger/transport/file.ts +0 -26
  194. package/src/common/parser.ts +0 -50
  195. package/src/common/router-default-logger-factory.ts +0 -44
  196. package/src/common/router-handler.ts +0 -186
  197. package/src/common/router-types.ts +0 -153
  198. package/src/common/router-utils.ts +0 -47
  199. package/src/common/session/common.ts +0 -40
  200. package/src/common/session/service.ts +0 -175
  201. package/src/common/tokenize-match.ts +0 -98
  202. package/src/common/url-utils.ts +0 -46
  203. package/src/middleware/buffer.ts +0 -82
  204. package/src/middleware/cookie.ts +0 -20
  205. package/src/middleware/cors.ts +0 -98
  206. package/src/middleware/form.ts +0 -61
  207. package/src/middleware/group.ts +0 -74
  208. package/src/middleware/json.ts +0 -57
  209. package/src/middleware/logger.ts +0 -18
  210. package/src/middleware/parse.ts +0 -105
  211. package/src/middleware/result.ts +0 -73
  212. package/src/middleware/tag.ts +0 -15
  213. package/src/middleware/text.ts +0 -47
  214. package/src/proxy.ts +0 -99
  215. package/src/router.ts +0 -140
  216. package/src/static.ts +0 -242
  217. package/src/websocket/cluster.ts +0 -128
  218. package/src/websocket/server.ts +0 -135
  219. package/src/websocket/types.ts +0 -41
  220. package/src/websocket/utils.ts +0 -95
@@ -0,0 +1,356 @@
1
+ import { createHash, randomUUID } from "crypto";
2
+ import { Duplex } from "stream";
3
+ import { ConnectionUpgrader, WebSocketClient, WebSocketServerOptions, Request } from "./types.js";
4
+ import { Serializable } from "child_process";
5
+
6
+ export class WebSocketServer implements ConnectionUpgrader {
7
+ public readonly clients: Map<string, WebSocketClient> = new Map();
8
+
9
+ constructor(public readonly options: WebSocketServerOptions) {
10
+ this.onUpgrade = this.onUpgrade.bind(this);
11
+ this.isConnected = this.isConnected.bind(this);
12
+ this.writeTo = this.writeTo.bind(this);
13
+ this.broadcast = this.broadcast.bind(this);
14
+ }
15
+
16
+ public isConnected(clientUUID: string) {
17
+ return this.clients.get(clientUUID) !== undefined;
18
+ }
19
+
20
+ public async broadcast(data: string, fromUUID?: string) {
21
+ const tR = [];
22
+ const clients = this.clients.values();
23
+ for (const client of clients) {
24
+ if (fromUUID === undefined || client.uuid !== fromUUID) {
25
+ tR.push(this.writeTo(client.uuid, data));
26
+ }
27
+ }
28
+ await Promise.all(tR);
29
+ }
30
+
31
+ public async writeTo(clientUUID: string, data: string) {
32
+ const client = this.clients.get(clientUUID);
33
+ if (!client) {
34
+ throw new Error("client not found");
35
+ }
36
+ return new Promise<void>((resolve, reject) => {
37
+ try {
38
+ client.req.socket.write(createFrame(data), function SocketWriteCallback(err?: Error) {
39
+ if (err) {
40
+ reject(err);
41
+ } else {
42
+ resolve();
43
+ }
44
+ })
45
+ } catch (e) {
46
+ reject(e);
47
+ }
48
+ });
49
+ }
50
+
51
+ public async onUpgrade(req: Request, socket: Duplex, head: Buffer) {
52
+ const acceptKey = req.headers["sec-websocket-key"];
53
+ if (
54
+ !socket ||
55
+ (!req.headers.connection || req.headers.connection.indexOf("Upgrade") === -1) ||
56
+ req.headers.upgrade !== "websocket" ||
57
+ req.method !== "GET" ||
58
+ !acceptKey
59
+ ) {
60
+ socket.end("HTTP/1.1 400 Bad Request");
61
+ socket.destroy();
62
+ return;
63
+ } else {
64
+ const validateRet = this.options.validate ? await this.options.validate(req) : true;
65
+ const uuid = typeof validateRet === "boolean" ?
66
+ (validateRet ? randomUUID() : null) :
67
+ (typeof validateRet === "object" ? validateRet.uuid :
68
+ validateRet ? randomUUID() : null
69
+ );
70
+ const extraHeaders = typeof validateRet === "object" ? validateRet.headers : undefined;
71
+ if (!uuid) {
72
+ socket.end("HTTP/1.1 403 Forbidden");
73
+ socket.destroy();
74
+ return;
75
+ } else {
76
+ if (this.options.maxConnections !== undefined && this.clients.size >= this.options.maxConnections) {
77
+ socket.end("HTTP/1.1 403 Forbidden");
78
+ socket.destroy();
79
+ return;
80
+ }
81
+ const client: WebSocketClient = {
82
+ uuid,
83
+ head,
84
+ req,
85
+ socket
86
+ };
87
+ this.options.logger?.debug("upgrading connection");
88
+
89
+ socket.write(createUpgradeHeaders(acceptKey, extraHeaders));
90
+
91
+ socket.on("data", (data: Buffer) => {
92
+ const frame = parseFrame(data);
93
+ if (frame !== null) {
94
+ if (!this.options.onMessage) {
95
+ socket.end();
96
+ socket.destroy();
97
+ } else {
98
+ try {
99
+ this.options.onMessage(client, frame);
100
+ } catch (e) {
101
+ this.options.logger?.error(e);
102
+ }
103
+ }
104
+ }
105
+ });
106
+
107
+ socket.on("end", () => {
108
+ this.options.logger?.debug("upgraded connection disconnected!");
109
+ this.clients.delete(uuid);
110
+ if (this.options.onDisconnect) {
111
+ try {
112
+ this.options.onDisconnect(client);
113
+ } catch (e) {
114
+ this.options.logger?.error(e);
115
+ }
116
+ }
117
+ });
118
+
119
+ this.options.logger?.debug("connection upgraded");
120
+ this.clients.set(uuid, client);
121
+ if (this.options.onConnection) {
122
+ try {
123
+ this.options.onConnection(client);
124
+ } catch (e) {
125
+ this.options.logger?.error(e);
126
+ }
127
+ }
128
+ return;
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ const ClusterWebSocketServerMessageType = "ClusterWebSocketServerMessage";
135
+
136
+ export interface ClusterWebSocketServerMessage {
137
+ type: typeof ClusterWebSocketServerMessageType;
138
+ action: "connection" | "disconnection" | "sendMessage";
139
+ clientUUID?: string;
140
+ fromUUID?: string;
141
+ payload?: Serializable;
142
+ }
143
+
144
+ export class ClusterWebSocketServer extends WebSocketServer {
145
+ public static instance: ClusterWebSocketServer;
146
+ public remoteClients: Set<string> = new Set();
147
+ public constructor(options: WebSocketServerOptions) {
148
+ super({
149
+ ...options,
150
+ validate: (req) => {
151
+ if (
152
+ this.options.maxConnections !== undefined &&
153
+ this.clients.size + this.remoteClients.size >= this.options.maxConnections
154
+ ) {
155
+ return false;
156
+ } else {
157
+ return options.validate ? options.validate(req) : true;
158
+ }
159
+ },
160
+ onConnection: (req) => {
161
+ if (process.send) {
162
+ process.send({
163
+ type: ClusterWebSocketServerMessageType,
164
+ action: "connection",
165
+ clientUUID: req.uuid
166
+ } as ClusterWebSocketServerMessage);
167
+ }
168
+ if (options.onConnection) {
169
+ options.onConnection(req);
170
+ }
171
+ },
172
+ onDisconnect: (req) => {
173
+ if (process.send) {
174
+ process.send({
175
+ type: ClusterWebSocketServerMessageType,
176
+ action: "disconnection",
177
+ clientUUID: req.uuid
178
+ } as ClusterWebSocketServerMessage);
179
+ }
180
+ if (options.onDisconnect) {
181
+ options.onDisconnect(req);
182
+ }
183
+ }
184
+ });
185
+ if (ClusterWebSocketServer.instance) {
186
+ throw new Error("cannot create more than one instance");
187
+ }
188
+ ClusterWebSocketServer.instance = this;
189
+ if (process.send) {
190
+ process.on("message", (data) => {
191
+ const msg = (data as ClusterWebSocketServerMessage);
192
+ if (
193
+ msg &&
194
+ msg.type === ClusterWebSocketServerMessageType &&
195
+ msg.action) {
196
+ // receive message from cluster workers
197
+ switch (msg.action) {
198
+ case "connection":
199
+ if (!msg.clientUUID) {
200
+ throw new Error(`action [${msg.action}] without clientUUID`);
201
+ }
202
+ this.remoteClients.add(msg.clientUUID);
203
+ break;
204
+ case "disconnection":
205
+ if (!msg.clientUUID) {
206
+ throw new Error(`action [${msg.action}] without clientUUID`);
207
+ }
208
+ this.remoteClients.delete(msg.clientUUID);
209
+ break;
210
+ case "sendMessage": {
211
+ const data = String(msg.payload);
212
+ if (msg.clientUUID && this.isConnected(msg.clientUUID)) {
213
+ // write if local client
214
+ super.writeTo(msg.clientUUID, data);
215
+ } else {
216
+ super.broadcast(data, msg.fromUUID);
217
+ }
218
+ break;
219
+ }
220
+ default:
221
+ throw new Error(`action [${msg.action}] not supported`);
222
+ }
223
+ }
224
+ });
225
+ }
226
+ }
227
+
228
+ public async broadcast(payload: string, fromUUID?: string): Promise<void> {
229
+ if (process.send) {
230
+ process.send({
231
+ type: ClusterWebSocketServerMessageType,
232
+ action: "sendMessage",
233
+ payload,
234
+ fromUUID
235
+ } as ClusterWebSocketServerMessage);
236
+ }
237
+ super.broadcast(payload, fromUUID);
238
+ }
239
+
240
+ public async writeTo(clientUUID: string, payload: string): Promise<void> {
241
+ if (this.remoteClients.has(clientUUID)) {
242
+ // write to remote client via IPC
243
+ if (process.send) {
244
+ process.send({
245
+ type: ClusterWebSocketServerMessageType,
246
+ action: "sendMessage",
247
+ clientUUID,
248
+ payload
249
+ } as ClusterWebSocketServerMessage);
250
+ return;
251
+ }
252
+ } else {
253
+ // write to local client
254
+ super.writeTo(clientUUID, payload);
255
+ }
256
+ }
257
+ }
258
+
259
+ /**
260
+ * Private
261
+ */
262
+
263
+
264
+ const OPCODES = { text: 0x01, close: 0x08 };
265
+ const GUID: string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
266
+ //Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly
267
+ function createUpgradeHeaders(acceptKey: string, extraHeaders?: {
268
+ name: string;
269
+ value: string;
270
+ }[]) {
271
+ const acceptValue = createHash('sha1')
272
+ .update(acceptKey + GUID, 'binary')
273
+ .digest('base64');
274
+ let extra = extraHeaders && extraHeaders.length > 0 ? `\r\n${extraHeaders.map(h => `${h.name}: ${h.value}`).join("\r\n")}` : "";
275
+ return `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptValue}${extra}\r\n\r\n`;
276
+ }
277
+
278
+ function parseFrame(buffer: Buffer) {
279
+ const firstByte = buffer.readUInt8(0);
280
+ const opCode = firstByte & 0b00001111; // get last 4 bits of a byte
281
+
282
+ if (opCode === OPCODES.close) {
283
+ //this.emit('close');
284
+ return null;
285
+ } else if (opCode !== OPCODES.text) {
286
+ return;
287
+ }
288
+
289
+ const secondByte = buffer.readUInt8(1); // start with a payload length
290
+
291
+ let offset = 2;
292
+ let payloadLength = secondByte & 0b01111111; // get last 7 bits of a second byte
293
+
294
+ if (payloadLength === 126) {
295
+ offset += 2;
296
+ } else if (payloadLength === 127) {
297
+ offset += 8;
298
+ }
299
+
300
+ const isMasked = Boolean((secondByte >>> 7) & 0x1); // get first bit of a second byte
301
+
302
+ if (isMasked) {
303
+ const maskingKey = buffer.readUInt32BE(offset); // read 4-byte mask
304
+ offset += 4;
305
+ const payload = buffer.subarray(offset);
306
+ const result = unmask(payload, maskingKey);
307
+ return result.toString('utf-8');
308
+ }
309
+
310
+ return buffer.subarray(offset).toString('utf-8');
311
+ }
312
+
313
+ function unmask(payload: Buffer, maskingKey: number) {
314
+ const result = Buffer.alloc(payload.byteLength);
315
+
316
+ for (let i = 0; i < payload.byteLength; ++i) {
317
+ const j = i % 4;
318
+ const maskingKeyByteShift = j === 3 ? 0 : (3 - j) << 3;
319
+ const maskingKeyByte = (maskingKeyByteShift === 0 ? maskingKey : maskingKey >>> maskingKeyByteShift) & 0b11111111;
320
+ const transformedByte = maskingKeyByte ^ payload.readUInt8(i);
321
+ result.writeUInt8(transformedByte, i);
322
+ }
323
+
324
+ return result;
325
+ }
326
+
327
+ function createFrame(payload: string) {
328
+
329
+ const payloadByteLength = Buffer.byteLength(payload);
330
+ let payloadBytesOffset = 2;
331
+ let payloadLength = payloadByteLength;
332
+
333
+ if (payloadByteLength > 65535) { // length value cannot fit in 2 bytes
334
+ payloadBytesOffset += 8;
335
+ payloadLength = 127;
336
+ } else if (payloadByteLength > 125) {
337
+ payloadBytesOffset += 2;
338
+ payloadLength = 126;
339
+ }
340
+
341
+ const buffer = Buffer.alloc(payloadBytesOffset + payloadByteLength);
342
+
343
+ // first byte
344
+ buffer.writeUInt8(0b10000001, 0); // [FIN (1), RSV1 (0), RSV2 (0), RSV3 (0), Opode (0x01 - text frame)]
345
+
346
+ buffer[1] = payloadLength; // second byte - actual payload size (if <= 125 bytes) or 126, or 127
347
+
348
+ if (payloadLength === 126) { // write actual payload length as a 16-bit unsigned integer
349
+ buffer.writeUInt16BE(payloadByteLength, 2);
350
+ } else if (payloadByteLength === 127) { // write actual payload length as a 64-bit unsigned integer
351
+ buffer.writeBigUInt64BE(BigInt(payloadByteLength), 2);
352
+ }
353
+
354
+ buffer.write(payload, payloadBytesOffset);
355
+ return buffer;
356
+ }
@@ -1,34 +0,0 @@
1
- import { Logger } from "./common/logger/logger.js";
2
- import { MinimalRouter } from "./common/router-types.js";
3
- import { APIRouterOptions } from "./common/api-router-types.js";
4
- /**
5
- * # APIRouter
6
- *
7
- * src/server.js
8
- * ```typescript
9
- *import { App, APIRouter } from "@miqro/core";
10
- *const app = new App();
11
- *app.use(APIRouter({ dirname: resolve(__dirname, "api") }));
12
- *app.listen(8080);
13
- * ```
14
- *
15
- * src/api/user/post.js
16
- *
17
- * ```typescript
18
- *import { ReadBuffer, JSONParser, APIRoute } from "@miqro/core";
19
- *
20
- *const route: APIRoute = {
21
- * middleware: [ReadBuffer(), JSONParser()]
22
- * query: { ... },
23
- * body: { ... },
24
- * result: { ... },
25
- * handler: async (ctx: Context) => {
26
- * return {
27
- * status: "OK"
28
- * };
29
- * }
30
- *}
31
- *export default route;
32
- * ```
33
- */
34
- export declare function APIRouter(options: APIRouterOptions, logger?: Logger): Promise<MinimalRouter>;
@@ -1,48 +0,0 @@
1
- import { existsSync, lstatSync } from "fs";
2
- import { basename } from "path";
3
- import { traverseAPIRouteDir } from "./common/api-router-utils.js";
4
- import { APIRouterOptionsSchema } from "./common/api-router-types.js";
5
- import { DEFAULT_PARSER, assertNotUndefined } from "./common/parser.js";
6
- /**
7
- * # APIRouter
8
- *
9
- * src/server.js
10
- * ```typescript
11
- *import { App, APIRouter } from "@miqro/core";
12
- *const app = new App();
13
- *app.use(APIRouter({ dirname: resolve(__dirname, "api") }));
14
- *app.listen(8080);
15
- * ```
16
- *
17
- * src/api/user/post.js
18
- *
19
- * ```typescript
20
- *import { ReadBuffer, JSONParser, APIRoute } from "@miqro/core";
21
- *
22
- *const route: APIRoute = {
23
- * middleware: [ReadBuffer(), JSONParser()]
24
- * query: { ... },
25
- * body: { ... },
26
- * result: { ... },
27
- * handler: async (ctx: Context) => {
28
- * return {
29
- * status: "OK"
30
- * };
31
- * }
32
- *}
33
- *export default route;
34
- * ```
35
- */
36
- export async function APIRouter(options, logger) {
37
- const { dirname } = assertNotUndefined(DEFAULT_PARSER.parse(options, APIRouterOptionsSchema, "options"), "bad options");
38
- if (typeof dirname !== "string") {
39
- throw new Error(`options.dirname must be defined!`);
40
- }
41
- if (!existsSync(dirname) || !lstatSync(dirname).isDirectory()) {
42
- throw new Error(`${dirname} not a directory!`);
43
- }
44
- const apiName = options.apiName !== undefined ? options.apiName : basename(dirname);
45
- const apiPath = options.path !== undefined ? options.path : "";
46
- return await traverseAPIRouteDir(apiName.toUpperCase(), dirname, apiPath, undefined, logger);
47
- }
48
- //# sourceMappingURL=api-router.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"api-router.js","sourceRoot":"","sources":["../src/api-router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC;AAChC,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAGnE,OAAO,EAAoB,sBAAsB,EAAE,MAAM,8BAA8B,CAAC;AACxF,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAExE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,OAAyB,EAAE,MAAe;IACxE,MAAM,EAAE,OAAO,EAAE,GAAG,kBAAkB,CAAC,cAAc,CAAC,KAAK,CAAC,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,EAAE,aAAa,CAAC,CAAC;IACxH,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QAC/B,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;KACrD;IACD,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,EAAE;QAC7D,MAAM,IAAI,KAAK,CAAC,GAAG,OAAO,mBAAmB,CAAC,CAAC;KAChD;IACD,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACpF,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;IAC/D,OAAO,MAAM,mBAAmB,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;AAC/F,CAAC"}
@@ -1,13 +0,0 @@
1
- import { ErrorHandler } from "./common/context.js";
2
- export declare const HTML_HEADERS: {
3
- "Content-Type": string;
4
- };
5
- export declare const STATUS: {
6
- ERROR: number;
7
- BAD_REQUEST: number;
8
- NOT_FOUND: number;
9
- NOT_IMPLEMENTED: number;
10
- FORBIDDEN: number;
11
- UNAUTHORIZED: number;
12
- };
13
- export declare function defaultAppErrorHandler(): ErrorHandler<void>;
@@ -1,78 +0,0 @@
1
- export const HTML_HEADERS = {
2
- ["Content-Type"]: "text/html; charset=utf-8"
3
- };
4
- export const STATUS = {
5
- ERROR: 503,
6
- BAD_REQUEST: 400,
7
- NOT_FOUND: 404,
8
- NOT_IMPLEMENTED: 501,
9
- FORBIDDEN: 403,
10
- UNAUTHORIZED: 401,
11
- };
12
- export function defaultAppErrorHandler() {
13
- const isTestEnv = (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test");
14
- return async (e, ctx) => {
15
- if (isTestEnv &&
16
- (!e || !e.name || e.name === "Error")) {
17
- ctx.logger.error(e);
18
- await ctx.end({
19
- headers: HTML_HEADERS,
20
- status: STATUS.ERROR,
21
- body: `${e && e.message ? e.message : String(e)}. You are seeing this message because NODE_ENV === "development" || NODE_ENV === "test"${e && e.stack ? ` ${e.stack}` : ""}`
22
- });
23
- }
24
- else {
25
- ctx.logger.error(e);
26
- const name = e && e.name ? e.name : undefined;
27
- switch (name) {
28
- case "NotFoundError":
29
- await ctx.end({
30
- headers: HTML_HEADERS,
31
- status: STATUS.NOT_FOUND,
32
- body: e.message ? e.message : "NOT FOUND"
33
- });
34
- break;
35
- case "MethodNotImplementedError":
36
- await ctx.end({
37
- headers: HTML_HEADERS,
38
- status: STATUS.NOT_IMPLEMENTED,
39
- body: e.message ? e.message : "NOT IMPLEMENTED"
40
- });
41
- break;
42
- case "ForbiddenError":
43
- await ctx.end({
44
- headers: HTML_HEADERS,
45
- status: STATUS.FORBIDDEN,
46
- body: e.message ? e.message : "FORBIDDEN"
47
- });
48
- break;
49
- case "UnAuthorizedError":
50
- await ctx.end({
51
- headers: HTML_HEADERS,
52
- status: STATUS.UNAUTHORIZED,
53
- body: e.message ? e.message : "UNAUTHORIZED"
54
- });
55
- break;
56
- case "ParseOptionsError":
57
- case "BadRequestError":
58
- case "SequelizeValidationError":
59
- case "SequelizeEagerLoadingError":
60
- case "SequelizeUniqueConstraintError":
61
- await ctx.end({
62
- headers: HTML_HEADERS,
63
- status: STATUS.BAD_REQUEST,
64
- body: e.message ? e.message : "BAD REQUEST"
65
- });
66
- break;
67
- case "ConfigFileNotFoundError":
68
- await ctx.end({
69
- headers: HTML_HEADERS,
70
- status: STATUS.ERROR,
71
- body: e.message ? e.message : "SERVER ERROR"
72
- });
73
- break;
74
- }
75
- }
76
- };
77
- }
78
- //# sourceMappingURL=app-utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"app-utils.js","sourceRoot":"","sources":["../src/app-utils.ts"],"names":[],"mappings":"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"}
@@ -1,28 +0,0 @@
1
- import { Schema } from "@miqro/parser";
2
- import { Handler, Method } from "./context.js";
3
- import { MinimalRouter, RouterHandlerOptions } from "./router-types.js";
4
- /**
5
- * # APIRoute
6
- *
7
- * src/api/comment/get.js
8
- * ```typescript
9
- *import { APIRouter } from "@miqro/core";
10
- *const route: APIRoute = {
11
- * ...
12
- *};
13
- *export default route;
14
- * ```
15
- */
16
- export interface APIRoute extends RouterHandlerOptions {
17
- postFolder?: boolean;
18
- method?: Method | "use" | "USE";
19
- path?: string;
20
- handler: Handler | Array<Handler> | MinimalRouter;
21
- }
22
- export interface APIRouterOptions {
23
- dirname: string;
24
- apiName?: string;
25
- path?: string;
26
- }
27
- export declare const APIRouterOptionsSchema: Schema<APIRouterOptions>;
28
- export declare const APIRouteSchema: Schema<APIRoute>;
@@ -1,24 +0,0 @@
1
- import { MinimalRouterSchema, RouterHandlerOptionsSchema } from "./router-types.js";
2
- export const APIRouterOptionsSchema = {
3
- type: "object",
4
- properties: {
5
- dirname: "string",
6
- apiName: "string?",
7
- path: "string?"
8
- }
9
- };
10
- export const APIRouteSchema = {
11
- type: "object",
12
- properties: {
13
- ...RouterHandlerOptionsSchema.properties,
14
- postFolder: "boolean?",
15
- method: "string?",
16
- path: "string?",
17
- handler: {
18
- type: "function[]!|object",
19
- properties: MinimalRouterSchema.properties,
20
- mode: MinimalRouterSchema.mode
21
- }
22
- }
23
- };
24
- //# sourceMappingURL=api-router-types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"api-router-types.js","sourceRoot":"","sources":["../../src/common/api-router-types.ts"],"names":[],"mappings":"AAEA,OAAO,EAAiB,mBAAmB,EAAwB,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AA2BzH,MAAM,CAAC,MAAM,sBAAsB,GAA6B;IAC9D,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACV,OAAO,EAAE,QAAQ;QACjB,OAAO,EAAE,SAAS;QAClB,IAAI,EAAE,SAAS;KAChB;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,cAAc,GAAqB;IAC9C,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACV,GAAG,0BAA0B,CAAC,UAAU;QACxC,UAAU,EAAE,UAAU;QACtB,MAAM,EAAE,SAAS;QACjB,IAAI,EAAE,SAAS;QACf,OAAO,EAAE;YACP,IAAI,EAAE,oBAAoB;YAC1B,UAAU,EAAE,mBAAmB,CAAC,UAAU;YAC1C,IAAI,EAAE,mBAAmB,CAAC,IAAI;SAC/B;KACF;CACF,CAAC"}
@@ -1,3 +0,0 @@
1
- import { Logger } from "./logger/logger.js";
2
- import { Router } from "../router.js";
3
- export declare function traverseAPIRouteDir(featureName: string, dirname: string, basePath?: string, router?: Router, logger?: Logger): Promise<Router>;