@kevisual/router 0.2.3 → 0.2.5

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.
@@ -0,0 +1,749 @@
1
+ var __create = Object.create;
2
+ var __getProtoOf = Object.getPrototypeOf;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ function __accessProp(key) {
7
+ return this[key];
8
+ }
9
+ var __toESMCache_node;
10
+ var __toESMCache_esm;
11
+ var __toESM = (mod, isNodeMode, target) => {
12
+ var canCache = mod != null && typeof mod === "object";
13
+ if (canCache) {
14
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
15
+ var cached = cache.get(mod);
16
+ if (cached)
17
+ return cached;
18
+ }
19
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
20
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
21
+ for (let key of __getOwnPropNames(mod))
22
+ if (!__hasOwnProp.call(to, key))
23
+ __defProp(to, key, {
24
+ get: __accessProp.bind(mod, key),
25
+ enumerable: true
26
+ });
27
+ if (canCache)
28
+ cache.set(mod, to);
29
+ return to;
30
+ };
31
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
32
+
33
+ // ../../node_modules/.pnpm/path-to-regexp@8.4.0/node_modules/path-to-regexp/dist/index.js
34
+ var require_dist = __commonJS((exports) => {
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.PathError = exports.TokenData = undefined;
37
+ exports.parse = parse;
38
+ exports.compile = compile;
39
+ exports.match = match;
40
+ exports.pathToRegexp = pathToRegexp;
41
+ exports.stringify = stringify;
42
+ var DEFAULT_DELIMITER = "/";
43
+ var NOOP_VALUE = (value) => value;
44
+ var ID_START = /^[$_\p{ID_Start}]$/u;
45
+ var ID_CONTINUE = /^[$\u200c\u200d\p{ID_Continue}]$/u;
46
+ var ID = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
47
+ var SIMPLE_TOKENS = "{}()[]+?!";
48
+ function escapeText(str) {
49
+ return str.replace(/[{}()\[\]+?!:*\\]/g, "\\$&");
50
+ }
51
+ function escape(str) {
52
+ return str.replace(/[.+*?^${}()[\]|/\\]/g, "\\$&");
53
+ }
54
+
55
+ class TokenData {
56
+ constructor(tokens, originalPath) {
57
+ this.tokens = tokens;
58
+ this.originalPath = originalPath;
59
+ }
60
+ }
61
+ exports.TokenData = TokenData;
62
+
63
+ class PathError extends TypeError {
64
+ constructor(message, originalPath) {
65
+ let text = message;
66
+ if (originalPath)
67
+ text += `: ${originalPath}`;
68
+ text += `; visit https://git.new/pathToRegexpError for info`;
69
+ super(text);
70
+ this.originalPath = originalPath;
71
+ }
72
+ }
73
+ exports.PathError = PathError;
74
+ function parse(str, options = {}) {
75
+ const { encodePath = NOOP_VALUE } = options;
76
+ const chars = [...str];
77
+ const tokens = [];
78
+ let index = 0;
79
+ let pos = 0;
80
+ function name() {
81
+ let value = "";
82
+ if (ID_START.test(chars[index])) {
83
+ do {
84
+ value += chars[index++];
85
+ } while (ID_CONTINUE.test(chars[index]));
86
+ } else if (chars[index] === '"') {
87
+ let quoteStart = index;
88
+ while (index < chars.length) {
89
+ if (chars[++index] === '"') {
90
+ index++;
91
+ quoteStart = 0;
92
+ break;
93
+ }
94
+ if (chars[index] === "\\")
95
+ index++;
96
+ value += chars[index];
97
+ }
98
+ if (quoteStart) {
99
+ throw new PathError(`Unterminated quote at index ${quoteStart}`, str);
100
+ }
101
+ }
102
+ if (!value) {
103
+ throw new PathError(`Missing parameter name at index ${index}`, str);
104
+ }
105
+ return value;
106
+ }
107
+ while (index < chars.length) {
108
+ const value = chars[index++];
109
+ if (SIMPLE_TOKENS.includes(value)) {
110
+ tokens.push({ type: value, index, value });
111
+ } else if (value === "\\") {
112
+ tokens.push({ type: "escape", index, value: chars[index++] });
113
+ } else if (value === ":") {
114
+ tokens.push({ type: "param", index, value: name() });
115
+ } else if (value === "*") {
116
+ tokens.push({ type: "wildcard", index, value: name() });
117
+ } else {
118
+ tokens.push({ type: "char", index, value });
119
+ }
120
+ }
121
+ tokens.push({ type: "end", index, value: "" });
122
+ function consumeUntil(endType) {
123
+ const output = [];
124
+ while (true) {
125
+ const token = tokens[pos++];
126
+ if (token.type === endType)
127
+ break;
128
+ if (token.type === "char" || token.type === "escape") {
129
+ let path = token.value;
130
+ let cur = tokens[pos];
131
+ while (cur.type === "char" || cur.type === "escape") {
132
+ path += cur.value;
133
+ cur = tokens[++pos];
134
+ }
135
+ output.push({
136
+ type: "text",
137
+ value: encodePath(path)
138
+ });
139
+ continue;
140
+ }
141
+ if (token.type === "param" || token.type === "wildcard") {
142
+ output.push({
143
+ type: token.type,
144
+ name: token.value
145
+ });
146
+ continue;
147
+ }
148
+ if (token.type === "{") {
149
+ output.push({
150
+ type: "group",
151
+ tokens: consumeUntil("}")
152
+ });
153
+ continue;
154
+ }
155
+ throw new PathError(`Unexpected ${token.type} at index ${token.index}, expected ${endType}`, str);
156
+ }
157
+ return output;
158
+ }
159
+ return new TokenData(consumeUntil("end"), str);
160
+ }
161
+ function compile(path, options = {}) {
162
+ const { encode = encodeURIComponent, delimiter = DEFAULT_DELIMITER } = options;
163
+ const data = typeof path === "object" ? path : parse(path, options);
164
+ const fn = tokensToFunction(data.tokens, delimiter, encode);
165
+ return function path2(params = {}) {
166
+ const [path3, ...missing] = fn(params);
167
+ if (missing.length) {
168
+ throw new TypeError(`Missing parameters: ${missing.join(", ")}`);
169
+ }
170
+ return path3;
171
+ };
172
+ }
173
+ function tokensToFunction(tokens, delimiter, encode) {
174
+ const encoders = tokens.map((token) => tokenToFunction(token, delimiter, encode));
175
+ return (data) => {
176
+ const result = [""];
177
+ for (const encoder of encoders) {
178
+ const [value, ...extras] = encoder(data);
179
+ result[0] += value;
180
+ result.push(...extras);
181
+ }
182
+ return result;
183
+ };
184
+ }
185
+ function tokenToFunction(token, delimiter, encode) {
186
+ if (token.type === "text")
187
+ return () => [token.value];
188
+ if (token.type === "group") {
189
+ const fn = tokensToFunction(token.tokens, delimiter, encode);
190
+ return (data) => {
191
+ const [value, ...missing] = fn(data);
192
+ if (!missing.length)
193
+ return [value];
194
+ return [""];
195
+ };
196
+ }
197
+ const encodeValue = encode || NOOP_VALUE;
198
+ if (token.type === "wildcard" && encode !== false) {
199
+ return (data) => {
200
+ const value = data[token.name];
201
+ if (value == null)
202
+ return ["", token.name];
203
+ if (!Array.isArray(value) || value.length === 0) {
204
+ throw new TypeError(`Expected "${token.name}" to be a non-empty array`);
205
+ }
206
+ return [
207
+ value.map((value2, index) => {
208
+ if (typeof value2 !== "string") {
209
+ throw new TypeError(`Expected "${token.name}/${index}" to be a string`);
210
+ }
211
+ return encodeValue(value2);
212
+ }).join(delimiter)
213
+ ];
214
+ };
215
+ }
216
+ return (data) => {
217
+ const value = data[token.name];
218
+ if (value == null)
219
+ return ["", token.name];
220
+ if (typeof value !== "string") {
221
+ throw new TypeError(`Expected "${token.name}" to be a string`);
222
+ }
223
+ return [encodeValue(value)];
224
+ };
225
+ }
226
+ function match(path, options = {}) {
227
+ const { decode = decodeURIComponent, delimiter = DEFAULT_DELIMITER } = options;
228
+ const { regexp, keys } = pathToRegexp(path, options);
229
+ const decoders = keys.map((key) => {
230
+ if (decode === false)
231
+ return NOOP_VALUE;
232
+ if (key.type === "param")
233
+ return decode;
234
+ return (value) => value.split(delimiter).map(decode);
235
+ });
236
+ return function match2(input) {
237
+ const m = regexp.exec(input);
238
+ if (!m)
239
+ return false;
240
+ const path2 = m[0];
241
+ const params = Object.create(null);
242
+ for (let i = 1;i < m.length; i++) {
243
+ if (m[i] === undefined)
244
+ continue;
245
+ const key = keys[i - 1];
246
+ const decoder = decoders[i - 1];
247
+ params[key.name] = decoder(m[i]);
248
+ }
249
+ return { path: path2, params };
250
+ };
251
+ }
252
+ function pathToRegexp(path, options = {}) {
253
+ const { delimiter = DEFAULT_DELIMITER, end = true, sensitive = false, trailing = true } = options;
254
+ const root = new SourceNode("^");
255
+ const paths = [path];
256
+ let combinations = 0;
257
+ while (paths.length) {
258
+ const path2 = paths.shift();
259
+ if (Array.isArray(path2)) {
260
+ paths.push(...path2);
261
+ continue;
262
+ }
263
+ const data = typeof path2 === "object" ? path2 : parse(path2, options);
264
+ flatten(data.tokens, 0, [], (tokens) => {
265
+ if (combinations++ >= 256) {
266
+ throw new PathError("Too many path combinations", data.originalPath);
267
+ }
268
+ let node = root;
269
+ for (const part of toRegExpSource(tokens, delimiter, data.originalPath)) {
270
+ node = node.add(part.source, part.key);
271
+ }
272
+ node.add("");
273
+ });
274
+ }
275
+ const keys = [];
276
+ let pattern = toRegExp(root, keys);
277
+ if (trailing)
278
+ pattern += "(?:" + escape(delimiter) + "$)?";
279
+ pattern += end ? "$" : "(?=" + escape(delimiter) + "|$)";
280
+ return { regexp: new RegExp(pattern, sensitive ? "" : "i"), keys };
281
+ }
282
+ function toRegExp(node, keys) {
283
+ if (node.key)
284
+ keys.push(node.key);
285
+ const children = Object.keys(node.children);
286
+ const text = children.map((id) => toRegExp(node.children[id], keys)).join("|");
287
+ return node.source + (children.length < 2 ? text : `(?:${text})`);
288
+ }
289
+
290
+ class SourceNode {
291
+ constructor(source, key) {
292
+ this.source = source;
293
+ this.key = key;
294
+ this.children = Object.create(null);
295
+ }
296
+ add(source, key) {
297
+ var _a;
298
+ const id = source + ":" + (key ? key.name : "");
299
+ return (_a = this.children)[id] || (_a[id] = new SourceNode(source, key));
300
+ }
301
+ }
302
+ function flatten(tokens, index, result, callback) {
303
+ while (index < tokens.length) {
304
+ const token = tokens[index++];
305
+ if (token.type === "group") {
306
+ flatten(token.tokens, 0, result.slice(), (seq) => flatten(tokens, index, seq, callback));
307
+ continue;
308
+ }
309
+ result.push(token);
310
+ }
311
+ callback(result);
312
+ }
313
+ function toRegExpSource(tokens, delimiter, originalPath) {
314
+ let result = [];
315
+ let backtrack = "";
316
+ let wildcardBacktrack = "";
317
+ let prevCaptureType = 0;
318
+ let hasSegmentCapture = 0;
319
+ let index = 0;
320
+ function hasInSegment(index2, type) {
321
+ while (index2 < tokens.length) {
322
+ const token = tokens[index2++];
323
+ if (token.type === type)
324
+ return true;
325
+ if (token.type === "text") {
326
+ if (token.value.includes(delimiter))
327
+ break;
328
+ }
329
+ }
330
+ return false;
331
+ }
332
+ function peekText(index2) {
333
+ let result2 = "";
334
+ while (index2 < tokens.length) {
335
+ const token = tokens[index2++];
336
+ if (token.type !== "text")
337
+ break;
338
+ result2 += token.value;
339
+ }
340
+ return result2;
341
+ }
342
+ while (index < tokens.length) {
343
+ const token = tokens[index++];
344
+ if (token.type === "text") {
345
+ result.push({ source: escape(token.value) });
346
+ backtrack += token.value;
347
+ if (prevCaptureType === 2)
348
+ wildcardBacktrack += token.value;
349
+ if (token.value.includes(delimiter))
350
+ hasSegmentCapture = 0;
351
+ continue;
352
+ }
353
+ if (token.type === "param" || token.type === "wildcard") {
354
+ if (prevCaptureType && !backtrack) {
355
+ throw new PathError(`Missing text before "${token.name}" ${token.type}`, originalPath);
356
+ }
357
+ if (token.type === "param") {
358
+ result.push({
359
+ source: hasSegmentCapture ? `(${negate(delimiter, backtrack)}+?)` : hasInSegment(index, "wildcard") ? `(${negate(delimiter, peekText(index))}+?)` : `(${negate(delimiter, "")}+?)`,
360
+ key: token
361
+ });
362
+ hasSegmentCapture |= prevCaptureType = 1;
363
+ } else {
364
+ result.push({
365
+ source: hasSegmentCapture & 2 ? `(${negate(backtrack, "")}+?)` : hasSegmentCapture & 1 ? `(${negate(wildcardBacktrack, "")}+?)` : wildcardBacktrack ? `(${negate(wildcardBacktrack, "")}+?|${negate(delimiter, "")}+?)` : `([^]+?)`,
366
+ key: token
367
+ });
368
+ wildcardBacktrack = "";
369
+ hasSegmentCapture |= prevCaptureType = 2;
370
+ }
371
+ backtrack = "";
372
+ continue;
373
+ }
374
+ throw new TypeError(`Unknown token type: ${token.type}`);
375
+ }
376
+ return result;
377
+ }
378
+ function negate(a, b) {
379
+ if (b.length > a.length)
380
+ return negate(b, a);
381
+ if (a === b)
382
+ b = "";
383
+ if (b.length > 1)
384
+ return `(?:(?!${escape(a)}|${escape(b)})[^])`;
385
+ if (a.length > 1)
386
+ return `(?:(?!${escape(a)})[^${escape(b)}])`;
387
+ return `[^${escape(a + b)}]`;
388
+ }
389
+ function stringifyTokens(tokens, index) {
390
+ let value = "";
391
+ while (index < tokens.length) {
392
+ const token = tokens[index++];
393
+ if (token.type === "text") {
394
+ value += escapeText(token.value);
395
+ continue;
396
+ }
397
+ if (token.type === "group") {
398
+ value += "{" + stringifyTokens(token.tokens, 0) + "}";
399
+ continue;
400
+ }
401
+ if (token.type === "param") {
402
+ value += ":" + stringifyName(token.name, tokens[index]);
403
+ continue;
404
+ }
405
+ if (token.type === "wildcard") {
406
+ value += "*" + stringifyName(token.name, tokens[index]);
407
+ continue;
408
+ }
409
+ throw new TypeError(`Unknown token type: ${token.type}`);
410
+ }
411
+ return value;
412
+ }
413
+ function stringify(data) {
414
+ return stringifyTokens(data.tokens, 0);
415
+ }
416
+ function stringifyName(name, next) {
417
+ if (!ID.test(name))
418
+ return JSON.stringify(name);
419
+ if ((next === null || next === undefined ? undefined : next.type) === "text" && ID_CONTINUE.test(next.value[0])) {
420
+ return JSON.stringify(name);
421
+ }
422
+ return name;
423
+ }
424
+ });
425
+
426
+ // src/router-simple.ts
427
+ var import_path_to_regexp = __toESM(require_dist(), 1);
428
+
429
+ // src/server/parse-body.ts
430
+ import url from "node:url";
431
+
432
+ // src/utils/is-engine.ts
433
+ var isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
434
+ var isBrowser = typeof window !== "undefined" && typeof document !== "undefined" && typeof document.createElement === "function";
435
+ var isDeno = typeof Deno !== "undefined" && typeof Deno.version === "object" && typeof Deno.version.deno === "string";
436
+ var isBun = typeof Bun !== "undefined" && typeof Bun.version === "string";
437
+
438
+ // src/server/parse-body.ts
439
+ var parseBody = async (req) => {
440
+ const resolveBody = (body) => {
441
+ const contentType = req.headers["content-type"] || "";
442
+ const resolve = (data) => {
443
+ return data;
444
+ };
445
+ if (contentType.includes("application/json")) {
446
+ return resolve(JSON.parse(body));
447
+ }
448
+ if (contentType.includes("application/x-www-form-urlencoded")) {
449
+ const formData = new URLSearchParams(body);
450
+ const result = {};
451
+ formData.forEach((value, key) => {
452
+ try {
453
+ result[key] = JSON.parse(value);
454
+ } catch {
455
+ result[key] = value;
456
+ }
457
+ });
458
+ return resolve(result);
459
+ }
460
+ try {
461
+ return resolve(JSON.parse(body));
462
+ } catch {
463
+ return resolve({});
464
+ }
465
+ };
466
+ if (isBun) {
467
+ const body = req.body;
468
+ if (body) {
469
+ return resolveBody(body);
470
+ }
471
+ return {};
472
+ }
473
+ return new Promise((resolve, reject) => {
474
+ const arr = [];
475
+ req.on("data", (chunk) => {
476
+ arr.push(chunk);
477
+ });
478
+ req.on("end", () => {
479
+ try {
480
+ const body = Buffer.concat(arr).toString();
481
+ resolve(resolveBody(body));
482
+ } catch (e) {
483
+ resolve({});
484
+ }
485
+ });
486
+ });
487
+ };
488
+ var parseSearch = (req) => {
489
+ const parsedUrl = url.parse(req.url, true);
490
+ return parsedUrl.query;
491
+ };
492
+ var parseSearchValue = (value, opts) => {
493
+ if (!value)
494
+ return {};
495
+ const decode = opts?.decode ?? false;
496
+ if (decode) {
497
+ value = decodeURIComponent(value);
498
+ }
499
+ try {
500
+ return JSON.parse(value);
501
+ } catch (e) {
502
+ return {};
503
+ }
504
+ };
505
+
506
+ // src/router-simple.ts
507
+ class SimpleRouter {
508
+ routes = [];
509
+ exclude = [];
510
+ constructor(opts) {
511
+ this.exclude = opts?.exclude || ["/api/router"];
512
+ }
513
+ getBody(req) {
514
+ return parseBody(req);
515
+ }
516
+ getSearch(req) {
517
+ return parseSearch(req);
518
+ }
519
+ parseSearchValue = parseSearchValue;
520
+ use(method, route, ...fns) {
521
+ const handlers = Array.isArray(fns) ? fns.flat() : [];
522
+ const pattern = import_path_to_regexp.pathToRegexp(route);
523
+ this.routes.push({ method: method.toLowerCase(), regexp: pattern.regexp, keys: pattern.keys, handlers });
524
+ return this;
525
+ }
526
+ get(route, ...fns) {
527
+ return this.use("get", route, ...fns);
528
+ }
529
+ post(route, ...fns) {
530
+ return this.use("post", route, ...fns);
531
+ }
532
+ sse(route, ...fns) {
533
+ return this.use("sse", route, ...fns);
534
+ }
535
+ all(route, ...fns) {
536
+ this.use("post", route, ...fns);
537
+ this.use("get", route, ...fns);
538
+ this.use("sse", route, ...fns);
539
+ return this;
540
+ }
541
+ getJson(v) {
542
+ if (typeof v === "object") {
543
+ return v;
544
+ }
545
+ try {
546
+ return JSON.parse(v);
547
+ } catch (e) {
548
+ return {};
549
+ }
550
+ }
551
+ isSse(req) {
552
+ const { headers } = req;
553
+ if (!headers)
554
+ return false;
555
+ if (headers["accept"] && headers["accept"].includes("text/event-stream")) {
556
+ return true;
557
+ }
558
+ if (headers["content-type"] && headers["content-type"].includes("text/event-stream")) {
559
+ return true;
560
+ }
561
+ return false;
562
+ }
563
+ parse(req, res) {
564
+ const { pathname } = new URL(req.url, "http://localhost");
565
+ let method = req.method.toLowerCase();
566
+ if (this.exclude.includes(pathname)) {
567
+ return "is_exclude";
568
+ }
569
+ const isSse = this.isSse(req);
570
+ if (isSse)
571
+ method = "sse";
572
+ const route = this.routes.find((route2) => {
573
+ const matchResult = route2.regexp.exec(pathname);
574
+ if (matchResult && route2.method === method) {
575
+ const params = {};
576
+ route2.keys.forEach((key, i) => {
577
+ params[key.name] = matchResult[i + 1];
578
+ });
579
+ req.params = params;
580
+ return true;
581
+ }
582
+ });
583
+ if (route) {
584
+ const { handlers } = route;
585
+ return handlers.reduce((promiseChain, handler) => promiseChain.then(() => Promise.resolve(handler(req, res))), Promise.resolve());
586
+ }
587
+ return "not_found";
588
+ }
589
+ chain(req, res) {
590
+ const chain = new HttpChain({ req, res, simpleRouter: this });
591
+ return chain;
592
+ }
593
+ static Chain(opts) {
594
+ return new HttpChain(opts);
595
+ }
596
+ }
597
+
598
+ class HttpChain {
599
+ req;
600
+ res;
601
+ simpleRouter;
602
+ server;
603
+ hasSetHeader = false;
604
+ isSseSet = false;
605
+ constructor(opts) {
606
+ if (opts?.res) {
607
+ this.res = opts.res;
608
+ }
609
+ if (opts?.req) {
610
+ this.req = opts.req;
611
+ }
612
+ this.simpleRouter = opts?.simpleRouter;
613
+ }
614
+ setReq(req) {
615
+ this.req = req;
616
+ return this;
617
+ }
618
+ setRes(res) {
619
+ this.res = res;
620
+ return this;
621
+ }
622
+ setRouter(router) {
623
+ this.simpleRouter = router;
624
+ return this;
625
+ }
626
+ setServer(server) {
627
+ this.server = server;
628
+ return this;
629
+ }
630
+ status(status) {
631
+ if (!this.res)
632
+ return this;
633
+ if (this.hasSetHeader) {
634
+ return this;
635
+ }
636
+ this.hasSetHeader = true;
637
+ this.res.writeHead(status);
638
+ return this;
639
+ }
640
+ writeHead(status) {
641
+ if (!this.res)
642
+ return this;
643
+ if (this.hasSetHeader) {
644
+ return this;
645
+ }
646
+ this.hasSetHeader = true;
647
+ this.res.writeHead(status);
648
+ return this;
649
+ }
650
+ json(data) {
651
+ if (!this.res)
652
+ return this;
653
+ this.res.end(JSON.stringify(data));
654
+ return this;
655
+ }
656
+ end(data) {
657
+ if (!this.res)
658
+ return this;
659
+ if (typeof data === "object") {
660
+ this.res.end(JSON.stringify(data));
661
+ } else if (typeof data === "string") {
662
+ this.res.end(data);
663
+ } else {
664
+ this.res.end("nothing");
665
+ }
666
+ return this;
667
+ }
668
+ listen(opts, callback) {
669
+ this.server.listen(opts, callback);
670
+ return this;
671
+ }
672
+ parse(opts) {
673
+ const { listenOptions, listenCallBack } = opts || {};
674
+ if (!this.server || !this.simpleRouter) {
675
+ throw new Error("Server and SimpleRouter must be set before calling parse");
676
+ }
677
+ const that = this;
678
+ const listener = (req, res) => {
679
+ try {
680
+ that.simpleRouter.parse(req, res);
681
+ } catch (error) {
682
+ console.error("Error parsing request:", error);
683
+ if (!res.headersSent) {
684
+ res.writeHead(500);
685
+ res.end(JSON.stringify({ code: 500, message: "Internal Server Error" }));
686
+ }
687
+ }
688
+ };
689
+ if (listenOptions) {
690
+ this.server.listen(listenOptions, listenCallBack);
691
+ }
692
+ this.server.on("request", listener);
693
+ return () => {
694
+ that.server.removeListener("request", listener);
695
+ };
696
+ }
697
+ getString(value) {
698
+ if (typeof value === "string") {
699
+ return value;
700
+ }
701
+ return JSON.stringify(value);
702
+ }
703
+ sse(value) {
704
+ const res = this.res;
705
+ const req = this.req;
706
+ if (!res || !req)
707
+ return;
708
+ const data = this.getString(value);
709
+ if (this.isSseSet) {
710
+ res.write(`data: ${data}
711
+
712
+ `);
713
+ return this;
714
+ }
715
+ const headersMap = new Map([
716
+ ["Content-Type", "text/event-stream"],
717
+ ["Cache-Control", "no-cache"],
718
+ ["Connection", "keep-alive"]
719
+ ]);
720
+ this.isSseSet = true;
721
+ let intervalId;
722
+ if (!this.hasSetHeader) {
723
+ this.hasSetHeader = true;
724
+ res.setHeaders(headersMap);
725
+ setInterval(() => {
726
+ res.write(`
727
+ `);
728
+ }, 3000);
729
+ req.on("close", () => {
730
+ clearInterval(intervalId);
731
+ res.end();
732
+ });
733
+ }
734
+ this.res.write(`data: ${data}
735
+
736
+ `);
737
+ return this;
738
+ }
739
+ close() {
740
+ if (this.req?.destroy) {
741
+ this.req.destroy();
742
+ }
743
+ return this;
744
+ }
745
+ }
746
+ export {
747
+ SimpleRouter,
748
+ HttpChain
749
+ };