tezx 1.0.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.
@@ -0,0 +1,726 @@
1
+ declare class HeadersParser {
2
+ private headers;
3
+ constructor(init?: [string, string][] | Record<string, string>);
4
+ /**
5
+ * Adds multiple headers to the parser.
6
+ * @param headers - Headers as an array of tuples or a record object.
7
+ */
8
+ add(headers: [string, string][] | Record<string, string>): this;
9
+ /**
10
+ * Sets a header value.
11
+ * @param key - Header name.
12
+ * @param value - Header value(s).
13
+ */
14
+ set(key: string, value: string | string[]): this;
15
+ /**
16
+ * Retrieves the first value of a header.
17
+ * @param key - Header name.
18
+ * @returns The first header value or undefined if not found.
19
+ */
20
+ get(key: string): string | undefined;
21
+ /**
22
+ * Retrieves all values of a header.
23
+ * @param key - Header name.
24
+ * @returns An array of header values.
25
+ */
26
+ getAll(key: string): string[];
27
+ /**
28
+ * Checks if a header exists.
29
+ * @param key - Header name.
30
+ * @returns True if the header exists, false otherwise.
31
+ */
32
+ has(key: string): boolean;
33
+ /**
34
+ * Deletes a header.
35
+ * @param key - Header name.
36
+ * @returns True if deleted successfully, false otherwise.
37
+ */
38
+ delete(key: string): boolean;
39
+ /**
40
+ * Appends a value to an existing header or creates a new one.
41
+ * @param key - Header name.
42
+ * @param value - Value to append.
43
+ */
44
+ append(key: string, value: string): this;
45
+ /**
46
+ * Returns an iterator over header entries.
47
+ * @returns IterableIterator of header key-value pairs.
48
+ */
49
+ entries(): IterableIterator<[string, string[]]>;
50
+ /**
51
+ * Returns an iterator over header keys.
52
+ * @returns IterableIterator of header names.
53
+ */
54
+ keys(): IterableIterator<string>;
55
+ /**
56
+ * Returns an iterator over header values.
57
+ * @returns IterableIterator of header values arrays.
58
+ */
59
+ values(): IterableIterator<string[]>;
60
+ /**
61
+ * Iterates over headers and executes a callback function.
62
+ * @param callback - Function to execute for each header.
63
+ */
64
+ forEach(callback: (value: string[], key: string) => void): void;
65
+ /**
66
+ * Converts headers into a plain object.
67
+ * @returns A record of headers where single-value headers are returned as a string.
68
+ */
69
+ toObject(): Record<string, string | string[]>;
70
+ }
71
+
72
+ type UrlRef = {
73
+ hash: string | undefined;
74
+ protocol: string | undefined;
75
+ origin: string | undefined;
76
+ username: string | undefined;
77
+ password: string | undefined;
78
+ hostname: string | undefined;
79
+ port: string | undefined;
80
+ href: string | undefined;
81
+ query: {
82
+ [key: string]: string;
83
+ };
84
+ pathname: string | undefined;
85
+ };
86
+
87
+ type FormDataOptions = {
88
+ maxSize?: number;
89
+ allowedTypes?: string[];
90
+ sanitized?: boolean;
91
+ };
92
+ type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE" | "OPTIONS" | "PATCH" | "HEAD" | "ALL" | "TRACE" | "CONNECT" | string;
93
+ declare class Request$1 {
94
+ #private;
95
+ headers: HeadersParser;
96
+ /**
97
+ * Full request URL including protocol and query string
98
+ * @type {string}
99
+ */
100
+ readonly url: string;
101
+ /**
102
+ * HTTP request method (GET, POST, PUT, DELETE, etc.)
103
+ * @type {HTTPMethod}
104
+ */
105
+ readonly method: HTTPMethod;
106
+ /** Parsed URL reference containing components like query parameters, pathname, etc. */
107
+ readonly urlRef: UrlRef;
108
+ /** Query parameters extracted from the URL */
109
+ readonly query: Record<string, any>;
110
+ /**
111
+ * Retrieve a parameter by name.
112
+ * @param name - The parameter name.
113
+ * @returns The parameter value if found, or undefined.
114
+ */
115
+ readonly params: Record<string, any>;
116
+ constructor(req: any, params: Record<string, any>);
117
+ /**
118
+ * Parses the request body as plain text.
119
+ * @returns {Promise<string>} The text content of the request body.
120
+ */
121
+ text(): Promise<string>;
122
+ /**
123
+ * Parses the request body as JSON.
124
+ * @returns {Promise<Record<string, any>>} The parsed JSON object.
125
+ * If the Content-Type is not 'application/json', it returns an empty object.
126
+ */
127
+ json(): Promise<Record<string, any>>;
128
+ /**
129
+ * Parses the request body based on Content-Type.
130
+ * Supports:
131
+ * - application/json → JSON parsing
132
+ * - application/x-www-form-urlencoded → URL-encoded form parsing
133
+ * - multipart/form-data → Multipart form-data parsing (for file uploads)
134
+ * @returns {Promise<Record<string, any>>} The parsed form data as an object.
135
+ * @throws {Error} If the Content-Type is missing or invalid.
136
+ */
137
+ formData(options?: FormDataOptions): Promise<Record<string, any>>;
138
+ }
139
+
140
+ declare class JetResponse {
141
+ /**
142
+ * Sends a JSON response.
143
+ * @param body - The response data.
144
+ * @param status - (Optional) HTTP status code (default: 200).
145
+ * @param headers - (Optional) Additional response headers.
146
+ * @returns Response object with JSON data.
147
+ */
148
+ static json(body: any, status?: number, headers?: ResponseHeaders): Response;
149
+ static json(body: any, headers?: ResponseHeaders): Response;
150
+ static json(body: any, status?: number): Response;
151
+ /**
152
+ * Sends an HTML response.
153
+ * @param data - The HTML content as a string.
154
+ * @param status - (Optional) HTTP status code (default: 200).
155
+ * @param headers - (Optional) Additional response headers.
156
+ * @returns Response object with HTML data.
157
+ */
158
+ static html(data: string, status?: number, headers?: ResponseHeaders): Response;
159
+ static html(data: string, headers?: ResponseHeaders): Response;
160
+ static html(data: string, status?: number): Response;
161
+ /**
162
+ * Sends a plain text response.
163
+ * @param data - The text content.
164
+ * @param status - (Optional) HTTP status code (default: 200).
165
+ * @param headers - (Optional) Additional response headers.
166
+ * @returns Response object with plain text data.
167
+ */
168
+ static text(data: string, status?: number, headers?: ResponseHeaders): Response;
169
+ static text(data: string, headers?: ResponseHeaders): Response;
170
+ static text(data: string, status?: number): Response;
171
+ /**
172
+ * Sends an XML response.
173
+ * @param data - The XML content.
174
+ * @param status - (Optional) HTTP status code (default: 200).
175
+ * @param headers - (Optional) Additional response headers.
176
+ * @returns Response object with XML data.
177
+ */
178
+ static xml(data: string, status?: number, headers?: ResponseHeaders): Response;
179
+ static xml(data: string, headers?: ResponseHeaders): Response;
180
+ static xml(data: string, status?: number): Response;
181
+ /**
182
+ * Sends a response with any content type.
183
+ * Automatically determines content type if not provided.
184
+ * @param body - The response body.
185
+ * @param status - (Optional) HTTP status code.
186
+ * @param headers - (Optional) Additional response headers.
187
+ * @returns Response object.
188
+ */
189
+ static send(body: any, status?: number, headers?: ResponseHeaders): Response;
190
+ static send(body: any, headers?: ResponseHeaders): Response;
191
+ static send(body: any, status?: number): Response;
192
+ /**
193
+ * Redirects to a given URL.
194
+ * @param url - The target URL.
195
+ * @param status - (Optional) HTTP status code (default: 302).
196
+ * @param headers - (Optional) Additional headers.
197
+ * @returns Response object with redirect.
198
+ */
199
+ static redirect(url: string, status?: number, headers?: ResponseHeaders): Response;
200
+ /**
201
+ * Handles file downloads.
202
+ * @param filePath - The path to the file.
203
+ * @param fileName - The name of the downloaded file.
204
+ * @returns Response object for file download.
205
+ */
206
+ static download(filePath: string, fileName: string): Promise<Response>;
207
+ /**
208
+ * Serves a file to the client.
209
+ * @param filePath - Absolute or relative path to the file.
210
+ * @param fileName - (Optional) The name of the send file.
211
+ * @param headers - (Optional) Additional headers.
212
+ * @returns Response object with the file stream.
213
+ */
214
+ static sendFile(filePath: string, fileName?: string, headers?: ResponseHeaders): Promise<Response>;
215
+ static sendFile(filePath: string, headers?: ResponseHeaders): Promise<Response>;
216
+ static sendFile(filePath: string, fileName?: string): Promise<Response>;
217
+ }
218
+
219
+ /**
220
+ * A simple key-value storage class using Map.
221
+ */
222
+ declare class State {
223
+ private state;
224
+ constructor();
225
+ /**
226
+ * Store a value with a specific key.
227
+ * @param key - The key for the value.
228
+ * @param value - The value to be stored.
229
+ */
230
+ set(key: string, value: any): void;
231
+ /**
232
+ * Retrieve a value by key.
233
+ * @param key - The key of the value to retrieve.
234
+ * @returns The stored value or undefined if not found.
235
+ */
236
+ get(key: string): any | undefined;
237
+ /**
238
+ * Delete a key from storage.
239
+ * @param key - The key to remove.
240
+ * @returns True if the key was deleted, false otherwise.
241
+ */
242
+ delete(key: string): boolean;
243
+ /**
244
+ * Check if a key exists in the storage.
245
+ * @param key - The key to check.
246
+ * @returns True if the key exists, false otherwise.
247
+ */
248
+ has(key: string): boolean;
249
+ /**
250
+ * Get an array of all stored keys.
251
+ * @returns An array of keys.
252
+ */
253
+ keys(): string[];
254
+ /**
255
+ * Get an array of all stored values.
256
+ * @returns An array of values.
257
+ */
258
+ values(): any[];
259
+ /**
260
+ * Get an array of all key-value pairs.
261
+ * @returns An array of [key, value] tuples.
262
+ */
263
+ entries(): [string, any][];
264
+ /**
265
+ * Remove all entries from storage.
266
+ */
267
+ clear(): void;
268
+ }
269
+
270
+ interface CookieOptions {
271
+ expires?: Date;
272
+ path?: string;
273
+ maxAge?: number;
274
+ domain?: string;
275
+ secure?: boolean;
276
+ httpOnly?: boolean;
277
+ sameSite?: 'Strict' | 'Lax' | 'None';
278
+ }
279
+ type ResponseHeaders = Record<string, string>;
280
+ declare class Context<T extends Record<string, any> = {}> {
281
+ #private;
282
+ [key: string]: any;
283
+ /**
284
+ * Environment variables and configuration
285
+ * @type {object}
286
+ */
287
+ env: Record<string, any> & T;
288
+ /**
289
+ * Parser for handling and manipulating HTTP headers
290
+ * @type {HeadersParser}
291
+ */
292
+ headers: HeadersParser;
293
+ /**
294
+ * Parser for handling and manipulating HTTP response
295
+ * @type {Response}
296
+ */
297
+ res: Response;
298
+ /**
299
+ * Request path without query parameters
300
+ * @type {string}
301
+ */
302
+ readonly pathname: string;
303
+ /**
304
+ * Full request URL including protocol and query string
305
+ * @type {string}
306
+ */
307
+ readonly url: string;
308
+ /**
309
+ * HTTP request method (GET, POST, PUT, DELETE, etc.)
310
+ * @type {HTTPMethod}
311
+ */
312
+ readonly method: HTTPMethod;
313
+ /**
314
+ * Public state container for application data
315
+ * state storage for middleware and plugins
316
+ * @type {State}
317
+ */
318
+ state: State;
319
+ /**
320
+ * Flag indicating if the request processing is complete
321
+ * @type {boolean}
322
+ */
323
+ finalized: boolean;
324
+ constructor(req: any);
325
+ /**
326
+ * Cookie handling utility with get/set/delete operations
327
+ * @returns {{
328
+ * get: (name: string) => string | undefined,
329
+ * all: () => Record<string, string>,
330
+ * delete: (name: string, options?: CookieOptions) => void,
331
+ * set: (name: string, value: string, options?: CookieOptions) => void
332
+ * }} Cookie handling interface
333
+ */
334
+ get cookies(): {
335
+ /**
336
+ * Get a specific cookie by name.
337
+ * @param {string} cookie - The name of the cookie to retrieve.
338
+ * @returns {string | undefined} - The cookie value or undefined if not found.
339
+ */
340
+ get: (cookie: string) => string;
341
+ /**
342
+ * Get all cookies as an object.
343
+ * @returns {Record<string, string>} - An object containing all cookies.
344
+ */
345
+ all: () => Record<string, string>;
346
+ /**
347
+ * Delete a cookie by setting its expiration to the past.
348
+ * @param {string} name - The name of the cookie to delete.
349
+ * @param {CookieOptions} [options] - Additional cookie options.
350
+ */
351
+ delete: (name: string, options?: CookieOptions) => void;
352
+ /**
353
+ * Set a new cookie with the given name, value, and options.
354
+ * @param {string} name - The name of the cookie.
355
+ * @param {string} value - The value of the cookie.
356
+ * @param {CookieOptions} [options] - Additional options like expiration.
357
+ */
358
+ set: (name: string, value: string, options?: CookieOptions) => void;
359
+ };
360
+ /**
361
+ * Sends a JSON response.
362
+ * @param body - The response data.
363
+ * @param status - (Optional) HTTP status code (default: 200).
364
+ * @param headers - (Optional) Additional response headers.
365
+ * @returns Response object with JSON data.
366
+ */
367
+ json(body: any, status?: number, headers?: ResponseHeaders): JetResponse;
368
+ json(body: any, headers?: ResponseHeaders): JetResponse;
369
+ json(body: any, status?: number): JetResponse;
370
+ /**
371
+ * Sends a response with any content type.
372
+ * Automatically determines content type if not provided.
373
+ * @param body - The response body.
374
+ * @param status - (Optional) HTTP status code.
375
+ * @param headers - (Optional) Additional response headers.
376
+ * @returns Response object.
377
+ */
378
+ send(body: any, status?: number, headers?: ResponseHeaders): any;
379
+ send(body: any, headers?: ResponseHeaders): any;
380
+ send(body: any, status?: number): any;
381
+ /**
382
+ * Sends an HTML response.
383
+ * @param data - The HTML content as a string.
384
+ * @param status - (Optional) HTTP status code (default: 200).
385
+ * @param headers - (Optional) Additional response headers.
386
+ * @returns Response object with HTML data.
387
+ */
388
+ html(data: string, status?: number, headers?: ResponseHeaders): any;
389
+ html(data: string, headers?: ResponseHeaders): any;
390
+ html(data: string, status?: number): any;
391
+ /**
392
+ * Sends a plain text response.
393
+ * @param data - The text content.
394
+ * @param status - (Optional) HTTP status code (default: 200).
395
+ * @param headers - (Optional) Additional response headers.
396
+ * @returns Response object with plain text data.
397
+ */
398
+ text(data: string, status?: number, headers?: ResponseHeaders): any;
399
+ text(data: string, headers?: ResponseHeaders): any;
400
+ text(data: string, status?: number): any;
401
+ /**
402
+ * Sends an XML response.
403
+ * @param data - The XML content.
404
+ * @param status - (Optional) HTTP status code (default: 200).
405
+ * @param headers - (Optional) Additional response headers.
406
+ * @returns Response object with XML data.
407
+ */
408
+ xml(data: string, status?: number, headers?: ResponseHeaders): any;
409
+ xml(data: string, headers?: ResponseHeaders): any;
410
+ xml(data: string, status?: number): any;
411
+ /**
412
+ * HTTP status code..
413
+ * @param status - number.
414
+ * @returns Response object with context all method.
415
+ */
416
+ status: (status: number) => this;
417
+ /**
418
+ * Redirects to a given URL.
419
+ * @param url - The target URL.
420
+ * @param status - (Optional) HTTP status code (default: 302).
421
+ * @param headers - (Optional) Additional headers.
422
+ * @returns Response object with redirect.
423
+ */
424
+ redirect(url: string, status?: number, headers?: ResponseHeaders): Response;
425
+ /**
426
+ * Handles file downloads.
427
+ * @param filePath - The path to the file.
428
+ * @param fileName - The name of the downloaded file.
429
+ * @returns Response object for file download.
430
+ */
431
+ download(filePath: string, fileName: string): Promise<Response>;
432
+ /**
433
+ * Serves a file to the client.
434
+ * @param filePath - Absolute or relative path to the file.
435
+ * @param fileName - (Optional) The name of the send file.
436
+ * @param headers - (Optional) Additional headers.
437
+ * @returns Response object with the file stream.
438
+ */
439
+ sendFile(filePath: string, fileName?: string, headers?: ResponseHeaders): Promise<Response>;
440
+ sendFile(filePath: string, headers?: ResponseHeaders): Promise<Response>;
441
+ sendFile(filePath: string, fileName?: string): Promise<Response>;
442
+ /**
443
+ * Getter that creates a standardized Request object from internal state
444
+ * @returns {Request} - Normalized request object combining:
445
+ * - Raw platform-specific request
446
+ * - Parsed headers
447
+ * - Route parameters
448
+ *
449
+ * @example
450
+ * // Get standardized request
451
+ * const request = ctx.req;
452
+ * // Access route params
453
+ * const id = request.params.get('id');
454
+ */
455
+ get req(): Request$1;
456
+ protected set params(params: Record<string, any>);
457
+ protected get params(): Record<string, any>;
458
+ }
459
+
460
+ declare class CommonHandler {
461
+ /**
462
+ * Register a custom 404 handler for missing routes
463
+ * @param {Callback} callback - Handler function to execute when no route matches
464
+ * @returns {this} - Returns current instance for chaining
465
+ *
466
+ * @example
467
+ * // Register a custom not-found handler
468
+ * app.notFound((ctx) => {
469
+ * ctx.status(404).text('Custom not found message');
470
+ * });
471
+ */
472
+ notFound(callback: Callback): this;
473
+ onError(callback: <T extends Record<string, any> = {}>(err: string, ctx: ctx<T>) => any): this;
474
+ }
475
+
476
+ declare class TriMiddleware {
477
+ children: Map<string, TriMiddleware>;
478
+ middlewares: Middleware<any>[];
479
+ groupMiddlewares: Map<string, Middleware<any>[]>;
480
+ isOptional: boolean;
481
+ pathname: string;
482
+ constructor(pathname?: string);
483
+ }
484
+ declare class MiddlewareConfigure<T extends Record<string, any> = {}> extends CommonHandler {
485
+ triMiddlewares: TriMiddleware;
486
+ protected basePath: string;
487
+ constructor(basePath?: string);
488
+ protected addMiddleware(pathname: string, middlewares: Middleware<T>[]): void;
489
+ }
490
+
491
+ type NextCallback = () => Promise<any>;
492
+ type ctx<T extends Record<string, any> = {}> = Context<T> & T;
493
+ type Callback<T extends Record<string, any> = {}> = (ctx: ctx<T>) => void;
494
+ type Middleware<T extends Record<string, any> = {}> = (ctx: ctx<T>, next: NextCallback) => void;
495
+ type RouterConfig = {
496
+ env?: Record<string, string | number>;
497
+ basePath?: string;
498
+ };
499
+ declare class TrieRouter {
500
+ children: Map<string, TrieRouter>;
501
+ handlers: Map<HTTPMethod, {
502
+ handlerID?: string;
503
+ callback: Callback<any>;
504
+ middlewares: Middleware<any>[];
505
+ }>;
506
+ pathname: string;
507
+ paramName: any;
508
+ isParam: boolean;
509
+ constructor(pathname?: string);
510
+ }
511
+ declare class Router<T extends Record<string, any> = {}> extends MiddlewareConfigure<T> {
512
+ #private;
513
+ protected routers: Map<string, Map<HTTPMethod, {
514
+ callback: Callback<T>;
515
+ handlerID?: string;
516
+ middlewares: Middleware<T>[];
517
+ }>>;
518
+ protected rootNode: TrieRouter;
519
+ constructor({ basePath, env }?: RouterConfig);
520
+ /**
521
+ * Registers a GET route with optional middleware(s)
522
+ * @param path - URL path pattern (supports route parameters)
523
+ * @param args - Handler callback or middleware(s) + handler
524
+ * @returns Current instance for chaining
525
+ *
526
+ * @example
527
+ * // Simple GET route
528
+ * app.get('/users', (ctx) => { ... });
529
+ *
530
+ * // With middleware
531
+ * app.get('/secure', authMiddleware, (ctx) => { ... });
532
+ *
533
+ * // With multiple middlewares
534
+ * app.get('/admin', [authMiddleware, adminMiddleware], (ctx) => { ... });
535
+ */
536
+ get(path: string, callback: Callback<T>): this;
537
+ get(path: string, middlewares: Middleware<T>[], callback: Callback<T>): this;
538
+ get(path: string, middlewares: Middleware<T>, callback: Callback<T>): this;
539
+ /**
540
+ * Registers a POST route with optional middleware(s)
541
+ * @param path - URL path pattern
542
+ * @param args - Handler callback or middleware(s) + handler
543
+ */
544
+ post(path: string, callback: Callback<T>): this;
545
+ post(path: string, middlewares: Middleware<T>[], callback: Callback<T>): this;
546
+ post(path: string, middlewares: Middleware<T>, callback: Callback<T>): this;
547
+ /**
548
+ * Registers a PUT route with optional middleware(s)
549
+ * @param path - URL path pattern
550
+ * @param args - Handler callback or middleware(s) + handler
551
+ */
552
+ put(path: string, callback: Callback<T>): this;
553
+ put(path: string, middlewares: Middleware<T>[], callback: Callback<T>): this;
554
+ put(path: string, middlewares: Middleware<T>, callback: Callback<T>): this;
555
+ /**
556
+ * Registers a PATCH route with optional middleware(s)
557
+ * @param path - URL path pattern
558
+ * @param args - Handler callback or middleware(s) + handler
559
+ */
560
+ patch(path: string, callback: Callback<T>): this;
561
+ patch(path: string, middlewares: Middleware<T>[], callback: Callback<T>): this;
562
+ patch(path: string, middlewares: Middleware<T>, callback: Callback<T>): this;
563
+ /**
564
+ * Registers a DELETE route with optional middleware(s)
565
+ * @param path - URL path pattern
566
+ * @param args - Handler callback or middleware(s) + handler
567
+ */
568
+ delete(path: string, callback: Callback<T>): this;
569
+ delete(path: string, middlewares: Middleware<T>[], callback: Callback<T>): this;
570
+ delete(path: string, middlewares: Middleware<T>, callback: Callback<T>): this;
571
+ /**
572
+ * Registers an OPTIONS route (primarily for CORS preflight requests)
573
+ * @param path - URL path pattern
574
+ * @param args - Handler callback or middleware(s) + handler
575
+ */
576
+ options(path: string, callback: Callback<T>): this;
577
+ options(path: string, middlewares: Middleware<T>[], callback: Callback<T>): this;
578
+ options(path: string, middlewares: Middleware<T>, callback: Callback<T>): this;
579
+ /**
580
+ * Registers a HEAD route (returns headers only)
581
+ * @param path - URL path pattern
582
+ * @param args - Handler callback or middleware(s) + handler
583
+ */
584
+ head(path: string, callback: Callback<T>): this;
585
+ head(path: string, middlewares: Middleware<T>[], callback: Callback<T>): this;
586
+ head(path: string, middlewares: Middleware<T>, callback: Callback<T>): this;
587
+ /**
588
+ * Registers a route that responds to all HTTP methods
589
+ * @param path - URL path pattern
590
+ * @param args - Handler callback or middleware(s) + handler
591
+ */
592
+ all(path: string, callback: Callback<T>): this;
593
+ all(path: string, middlewares: Middleware<T>[], callback: Callback<T>): this;
594
+ all(path: string, middlewares: Middleware<T>, callback: Callback<T>): this;
595
+ /**
596
+ * Generic method registration for custom HTTP methods
597
+ * @param method - HTTP method name (e.g., 'PURGE')
598
+ * @param path - URL path pattern
599
+ * @param args - Handler callback or middleware(s) + handler
600
+ *
601
+ * @example
602
+ * // Register custom method
603
+ * server.addRoute('PURGE', '/cache', purgeHandler);
604
+ */
605
+ addRoute(method: HTTPMethod, path: string, callback: Callback<T>): this;
606
+ addRoute(method: HTTPMethod, path: string, middlewares: Middleware<T>[], callback: Callback<T>): this;
607
+ addRoute(method: HTTPMethod, path: string, middlewares: Middleware<T>, callback: Callback<T>): this;
608
+ /**
609
+ * Mount a sub-router at specific path prefix
610
+ * @param path - Base path for the sub-router
611
+ * @param router - Router instance to mount
612
+ * @returns Current instance for chaining
613
+ *
614
+ * @example
615
+ * const apiRouter = new Router();
616
+ * apiRouter.get('/users', () => { ... });
617
+ * server.addRouter('/api', apiRouter);
618
+ */
619
+ addRouter(path: string, router: Router<T>): void;
620
+ /**
621
+ * Create route group with shared path prefix
622
+ * @param prefix - Path prefix for the group
623
+ * @param callback - Function that receives group-specific router
624
+ * @returns Current router instance for chaining
625
+ *
626
+ * @example
627
+ * app.group('/v1', (group) => {
628
+ * group.get('/users', v1UserHandler);
629
+ * });
630
+ */
631
+ group(prefix: string, callback: (group: Router<T>) => void): this;
632
+ /**
633
+ * Register middleware with flexible signature
634
+ * @overload
635
+ * @param path - Optional path to scope middleware
636
+ * @param middlewares - Middleware(s) to register
637
+ * @param [callback] - Optional sub-router or handler
638
+ */
639
+ use(path: string, middlewares: Middleware<T>[], callback: Callback<T> | Router<T | any>): this;
640
+ use(path: string, middleware: Middleware<T>, callback: Callback<T> | Router<T | any>): this;
641
+ use(path: string, middlewares: Middleware<T>[]): this;
642
+ use(path: string, middleware: Middleware<T>): this;
643
+ use(path: string, callback: Callback<T> | Router<T | any>): this;
644
+ use(middlewares: Middleware<T>[], callback: Callback<T> | Router<T | any>): this;
645
+ use(middleware: Middleware<T>, callback: Callback<T> | Router<T | any>): this;
646
+ use(middlewares: Middleware<T>[]): this;
647
+ use(middleware: Middleware<T>): this;
648
+ use(callback: Callback<T> | Router<T | any>): this;
649
+ }
650
+
651
+ interface ServeResponse {
652
+ status: number;
653
+ headers: {
654
+ [key: string]: string;
655
+ };
656
+ body: string;
657
+ statusText: string;
658
+ }
659
+ type LoggerFnType = () => {
660
+ request?: (method: HTTPMethod, pathname: string) => void;
661
+ response?: (method: HTTPMethod, pathname: string, status?: number) => void;
662
+ info?: (msg: string, ...args: unknown[]) => void;
663
+ warn?: (msg: string, ...args: unknown[]) => void;
664
+ error?: (msg: string, ...args: unknown[]) => void;
665
+ debug?: (msg: string, ...args: unknown[]) => void;
666
+ success?: (msg: string, ...args: unknown[]) => void;
667
+ };
668
+ type AcceleroConfig = {
669
+ logger?: LoggerFnType;
670
+ middlewareRule?: "follow" | "ignore";
671
+ } & RouterConfig;
672
+ declare class Accelero<T extends Record<string, any> = {}> extends Router<T> {
673
+ #private;
674
+ constructor({ basePath, middlewareRule, env, logger, }?: AcceleroConfig);
675
+ protected findRoute(method: HTTPMethod, pathname: string): {
676
+ callback: any;
677
+ middlewares: Middleware<T>[];
678
+ params: Record<string, string>;
679
+ handlerID?: string;
680
+ } | null;
681
+ serve(req: Request): Promise<ServeResponse | any>;
682
+ }
683
+
684
+ declare function denoAdapter<T extends Record<string, any> = {}>(Accelero: Accelero<T>): {
685
+ listen: (port: number, callback?: (message: string) => void) => any;
686
+ };
687
+ declare function bunAdapter<T extends Record<string, any> = {}>(Accelero: Accelero<T>): {
688
+ listen: (port: number, callback?: (message: string) => void) => any;
689
+ };
690
+ declare function nodeAdapter<T extends Record<string, any> = {}>(Accelero: Accelero<T>): {
691
+ listen: (port: number, callback?: (message: string) => void) => void;
692
+ };
693
+
694
+ /**
695
+ * Loads environment variables from .env files.
696
+ * @param basePath - The base directory where .env files are located.
697
+ */
698
+ declare function loadEnv(basePath?: string): Record<string, string>;
699
+
700
+ type LogLevel = "info" | "warn" | "error" | "debug" | "success";
701
+ /**
702
+ * A universal logger function that measures and logs the processing time of an operation.
703
+ * @param label - A label to identify the operation being logged.
704
+ * @param callback - The operation to measure and execute.
705
+ */
706
+ declare function logger(): {
707
+ request: (method: HTTPMethod, pathname: string) => void;
708
+ response: (method: HTTPMethod, pathname: string, status?: number) => void;
709
+ info: (msg: string, ...args: unknown[]) => void;
710
+ warn: (msg: string, ...args: unknown[]) => void;
711
+ error: (msg: string, ...args: unknown[]) => void;
712
+ debug: (msg: string, ...args: unknown[]) => void;
713
+ success: (msg: string, ...args: unknown[]) => void;
714
+ };
715
+
716
+ type CorsOptions = {
717
+ origin?: string | RegExp | (string | RegExp)[] | ((reqOrigin: string) => boolean);
718
+ methods?: string[];
719
+ allowedHeaders?: string[];
720
+ exposedHeaders?: string[];
721
+ credentials?: boolean;
722
+ maxAge?: number;
723
+ };
724
+ declare function cors(option?: CorsOptions): (ctx: ctx, next: () => Promise<any>) => Promise<any>;
725
+
726
+ export { Accelero, type AcceleroConfig, type Callback, type ctx as Context, type CorsOptions, JetResponse, type LogLevel, type LoggerFnType, type Middleware, type NextCallback, Router, type RouterConfig, type UrlRef, bunAdapter, cors, denoAdapter, loadEnv, logger, nodeAdapter };
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";var P=Object.create;var O=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var H=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var d=(l,e)=>O(l,"name",{value:e,configurable:!0});var I=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of L(e))!z.call(l,n)&&n!==t&&O(l,n,{get:()=>e[n],enumerable:!(s=k(e,n))||s.enumerable});return l};var R=(l,e,t)=>(t=l!=null?P(H(l)):{},I(e||!l||!l.__esModule?O(t,"default",{value:l,enumerable:!0}):t,l));class B{static{d(this,"HeadersParser")}headers=new Map;constructor(e){e&&this.add(e)}add(e){if(Array.isArray(e))for(const[t,s]of e)this.set(t,s);else if(typeof Headers<"u"&&e instanceof Headers)for(const[t,s]of e.entries())this.set(t,s);else if(typeof e=="object")for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.set(t,e[t]);return this}set(e,t){return this.headers.set(e.toLowerCase(),Array.isArray(t)?t:[t]),this}get(e){const t=this.headers.get(e.toLowerCase());return t?t[0]:void 0}getAll(e){return this.headers.get(e.toLowerCase())||[]}has(e){return this.headers.has(e.toLowerCase())}delete(e){return this.headers.delete(e.toLowerCase())}append(e,t){const s=e.toLowerCase();return this.headers.has(s)?this.headers.get(s).push(t):this.headers.set(s,[t]),this}entries(){return this.headers.entries()}keys(){return this.headers.keys()}values(){return this.headers.values()}forEach(e){for(const[t,s]of this.headers)e(s,t)}toObject(){const e={};for(const[t,s]of this.headers.entries())e[t]=s.length>1?s:s[0];return e}}Object.defineProperty(B,"name",{value:"Headers"});class x{static{d(this,"EnvironmentDetector")}static get getEnvironment(){return typeof Bun<"u"?"bun":typeof Deno<"u"?"deno":typeof process<"u"&&process.versions?.node?"node":"unknown"}static detectProtocol(e){try{return this.getEnvironment==="node"?e?.socket?.encrypted?"https":"http":"unknown"}catch{throw new Error("Failed to detect protocol.")}}static getHost(e){try{return e?.get("host")||"unknown"}catch{throw new Error("Failed to get host.")}}}async function F(l){const e=x.getEnvironment;if(e==="node")return new Promise((t,s)=>{let n="";l.on("data",r=>{n+=r.toString()}),l.on("end",()=>{try{t(JSON.parse(n))}catch{s(new Error("Invalid JSON format"))}})});if(e==="deno"||e==="bun")return await l.json();throw new Error("Unsupported environment for multipart parsing")}d(F,"parseJsonBody");async function q(l){const e=x.getEnvironment;if(e==="node")return new Promise((t,s)=>{let n="";l.on("data",r=>{n+=r.toString()}),l.on("end",()=>{try{t(n)}catch{s(new Error("Invalid JSON format"))}})});if(e==="deno"||e==="bun")return await l.text();throw new Error("Unsupported environment for multipart parsing")}d(q,"parseTextBody");async function U(l){const e=x.getEnvironment;if(e==="node")return new Promise((t,s)=>{let n="";l.on("data",r=>{n+=r.toString("binary")}),l.on("end",()=>{try{const r=n.split("&"),i={};r.forEach(o=>{const[a,c]=o.split("=");i[decodeURIComponent(a)]=decodeURIComponent(c||"")}),t(i)}catch{s(new Error("Invalid x-www-form-urlencoded format"))}})});if(e==="deno"||e==="bun"){const t=await l.formData(),s={};for(const[n,r]of t.entries())s[n]=r;return s}else throw new Error("Unsupported environment for multipart parsing")}d(U,"parseUrlEncodedBody");async function W(l,e,t){const s=x.getEnvironment;if(t?.sanitized,s==="node")return new Promise((n,r)=>{let i="";l.on("data",o=>{i+=o.toString("binary")}),l.on("end",()=>{try{const o={};i.split("----------------------------").forEach(h=>{const u=h.match(/name="(.*)"\r\n\r\n(.*)\r\n/);if(u&&u.length===3){const f=u[1],p=u[2];o[f]=p}});const c=i.split(`--${e}`);for(const h of c)if(h.includes("filename")){const u=h.match(/filename="([^"]+)"/),f=h.match(/name="([^"]+)"/),p=h.match(/Content-Type: ([^\r\n]+)/);if(u&&f&&p){let m=u[1];const y=f[1],g=p[1];t?.sanitized&&(m=`${Date.now()}-${m.replace(/\s+/g,"")?.replace(/[^a-zA-Z0-9.-]/g,"-")}`?.toLowerCase()),Array.isArray(t?.allowedTypes)&&!t.allowedTypes?.includes(g)&&r(`Invalid file type: "${g}". Allowed types: ${t.allowedTypes.join(", ")}`);const j=h.indexOf(`\r
2
+ \r
3
+ `)+4,v=Buffer.from(h.substring(j),"binary"),A=v.buffer.slice(v.byteOffset,v.byteOffset+v.byteLength);typeof t?.maxSize<"u"&&v.byteLength>t.maxSize&&r(`File size exceeds the limit: ${v.byteLength} bytes (Max: ${t.maxSize} bytes)`);const T=new File([A],m,{type:g});o[y]?Array.isArray(o[y])?o[y].push(T):o[y]=[o[y],T]:o[y]=T}}n(o)}catch{}})});if(s==="deno"||s==="bun"){const n=await l.formData(),r={};for(const[i,o]of n.entries()){let a=o;if(a instanceof File&&typeof t=="object"){let c=a.name;if(t?.sanitized&&(c=`${Date.now()}-${c.replace(/\s+/g,"")?.replace(/[^a-zA-Z0-9.-]/g,"-")}`?.toLowerCase()),Array.isArray(t?.allowedTypes)&&!t.allowedTypes?.includes(a.type))throw new Error(`Invalid file type: "${a.type}". Allowed types: ${t.allowedTypes.join(", ")}`);if(typeof t?.maxSize<"u"&&a.size>t.maxSize)throw new Error(`File size exceeds the limit: ${a.size} bytes (Max: ${t.maxSize} bytes)`);a=new File([await a.arrayBuffer()],c,{type:a.type})}r[i]?Array.isArray(r[i])?r[i].push(a):r[i]=[r[i],a]:r[i]=a}return r}else throw new Error("Unsupported environment for multipart parsing")}d(W,"parseMultipartBody");function J(l){const e=/^(?:(\w+):\/\/)?(?:([^:@]+)?(?::([^@]+))?@)?([^:/?#]+)?(?::(\d+))?(\/[^?#]*)?(?:\?([^#]*))?(?:#(.*))?$/;let t=l.match(e);const[s,n,r,i,o,a,c,h,u]=t;let f=o;n&&(f=n+"://"+o),a&&(f=f+":"+a);let p=c;p?.endsWith("/")&&p.slice(0,-1);function m(){return h?(decodeURIComponent(h).split("&")?.map(v=>{const[A,T]=v.split("=");return{[A]:T}})).reduce(function(v,A){return{...v,...A}},{}):{}}return d(m,"query"),{pathname:p,hash:u,protocol:n,origin:f,username:r,password:i,hostname:o,href:l,port:a,query:m()}}d(J,"urlParse");class V{static{d(this,"Request")}headers=new B;url;method;urlRef={hash:void 0,protocol:void 0,origin:void 0,username:void 0,password:void 0,hostname:void 0,port:void 0,href:void 0,query:{},pathname:"/"};query;#e;params={};constructor(e,t){if(this.headers=new B(e?.headers),this.method=e?.method?.toUpperCase(),this.params=t,this.#e=e,x.getEnvironment=="node"){const s=x.detectProtocol(e),n=x.getHost(this.headers);this.url=`${s}://${n}${e.url}`}else this.url=e.url;this.urlRef=J(this.url),this.query=this.urlRef.query}async text(){return await q(this.#e)}async json(){return(this.headers.get("content-type")||"").includes("application/json")?await F(this.#e):{}}async formData(e){const t=this.headers.get("content-type")||"";if(!t)throw Error("Invalid Content-Type");if(t.includes("application/json"))return await F(this.#e);if(t.includes("application/x-www-form-urlencoded"))return U(this.#e);if(t.includes("multipart/form-data")){const s=t?.split("; ")?.[1]?.split("=")?.[1];if(!s)throw Error("Boundary not found");return await W(this.#e,s,e)}else return{}}}class M{static{d(this,"JetResponse")}static json(e,...t){let s=200,n={"Content-Type":"application/json; charset=utf-8"};return typeof t[0]=="number"?(s=t[0],typeof t[1]=="object"&&(n={...n,...t[1]})):typeof t[0]=="object"&&(n={...n,...t[0]}),new Response(JSON.stringify(e),{status:s,headers:n})}static html(e,...t){let s=200,n={"Content-Type":"text/html; charset=utf-8"};return typeof t[0]=="number"?(s=t[0],typeof t[1]=="object"&&(n={...n,...t[1]})):typeof t[0]=="object"&&(n={...n,...t[0]}),new Response(e,{status:s,headers:n})}static text(e,...t){let s=200,n={"Content-Type":"text/plain; charset=utf-8"};return typeof t[0]=="number"?(s=t[0],typeof t[1]=="object"&&(n={...n,...t[1]})):typeof t[0]=="object"&&(n={...n,...t[0]}),new Response(e,{status:s,headers:n})}static xml(e,...t){let s=200,n={"Content-Type":"application/xml; charset=utf-8"};return typeof t[0]=="number"?(s=t[0],typeof t[1]=="object"&&(n={...n,...t[1]})):typeof t[0]=="object"&&(n={...n,...t[0]}),new Response(e,{status:s,headers:n})}static send(e,...t){let s=200,n={};return typeof t[0]=="number"?(s=t[0],typeof t[1]=="object"&&(n=t[1])):typeof t[0]=="object"&&(n=t[0]),n["Content-Type"]||(typeof e=="string"?n["Content-Type"]="text/plain;":typeof e=="object"&&e!==null?(n["Content-Type"]="application/json;",e=JSON.stringify(e)):n["Content-Type"]="application/octet-stream"),new Response(e,{status:s,headers:n})}static redirect(e,t=302,s){return new Response(null,{status:t,headers:{Location:e}})}static async download(e,t){try{let s=!1;const n=x.getEnvironment;if(n==="node"){const{existsSync:i}=await import("fs");s=i(e)}else if(n==="bun")s=Bun.file(e).exists();else if(n==="deno")try{await Deno.stat(e),s=!0}catch{s=!1}if(!s)throw Error("File not found");let r;if(n==="node"){const{readFileSync:i}=await import("fs");r=await i(e)}else n==="bun"?r=await Bun.file(e).arrayBuffer().then(i=>new Uint8Array(i)):n==="deno"&&(r=await Deno.readFile(e));return new Response(r,{status:200,headers:{"Content-Disposition":`attachment; filename="${t}"`,"Content-Type":"application/octet-stream","Content-Length":r.byteLength.toString()}})}catch(s){throw Error("Internal Server Error"+s?.message)}}static async sendFile(e,...t){try{const s=x.getEnvironment,n=e;let r=!1;if(s==="node"){const{existsSync:p}=await import("fs");r=p(n)}else if(s==="bun")r=Bun.file(n).exists();else if(s==="deno")try{await Deno.stat(n),r=!0}catch{r=!1}if(!r)throw Error("File not found");let i=0;if(s==="node"){const{statSync:p}=await import("fs");i=p(n).size}else s==="bun"?i=(await Bun.file(n).arrayBuffer()).byteLength:s==="deno"&&(i=(await Deno.stat(n)).size);const o={html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",pdf:"application/pdf",txt:"text/plain",xml:"application/xml",mp4:"video/mp4",webm:"video/webm",ogg:"audio/ogg",mp3:"audio/mpeg",wav:"audio/wav",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar"},a=e.split(".").pop()?.toLowerCase()||"",c=o[a]||"application/octet-stream";let h;if(s==="node"){const{createReadStream:p}=await import("fs");h=p(n)}else s==="bun"?h=Bun.file(n).stream():s==="deno"&&(h=(await Deno.open(n,{read:!0})).readable);let u={"Content-Type":c,"Content-Length":i.toString()},f="";return typeof t[0]=="string"?(f=t[0],typeof t[1]=="object"&&(u={...u,...t[1]})):typeof t[0]=="object"&&(u={...u,...t[0]}),f&&(u["Content-Disposition"]=`attachment; filename="${f}"`),new Response(h,{status:200,headers:u})}catch(s){throw Error("Internal Server Error"+s?.message)}}}class G{static{d(this,"State")}state;constructor(){this.state=new Map}set(e,t){this.state.set(e,t)}get(e){return this.state.get(e)}delete(e){return this.state.delete(e)}has(e){return this.state.has(e)}keys(){return Array.from(this.state.keys())}values(){return Array.from(this.state.values())}entries(){return Array.from(this.state.entries())}clear(){this.state.clear()}}const N={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};class Z{static{d(this,"Context")}#e;env={};headers=new B;res=new Response;pathname;url;method;#t=200;state=new G;#n={};#r;finalized=!1;#s;#o;#i;#a;#l=!0;#c;#d;#f;#u;#h;constructor(e){this.#e=e,this.method=e?.method?.toUpperCase(),this.pathname=this.req.urlRef.pathname,this.url=this.req.url}get cookies(){const e=this.headers.getAll("cookie");let t={};if(Array.isArray(e)&&e.length!=0){const s=e.join("; ").split(";");for(const n of s){const[r,i]=n?.trim()?.split("=");t[r]=decodeURIComponent(i)}}else if(typeof e=="string"){const s=e.split(";");for(const n of s){const[r,i]=n?.trim()?.split("=");t[r]=decodeURIComponent(i)}}return{get:d(s=>t?.[s],"get"),all:d(()=>t,"all"),delete:d((s,n)=>{const r="",i={...n,expires:new Date(0)},o=`${s}=${r};${D(i)}`;this.headers.set("Set-Cookie",o)},"delete"),set:d((s,n,r)=>{const i=`${s}=${n};${D(r||{})}`;this.headers.set("Set-Cookie",i)},"set")}}json(e,...t){let s=this.#t,n={"Content-Type":"application/json; charset=utf-8"};return typeof t[0]=="number"?(s=t[0],typeof t[1]=="object"&&(n={...n,...t[1]})):typeof t[0]=="object"&&(n={...n,...t[0]}),new Response(JSON.stringify(e),{status:s,headers:n})}send(e,...t){let s=this.#t,n={};return typeof t[0]=="number"?(s=t[0],typeof t[1]=="object"&&(n=t[1])):typeof t[0]=="object"&&(n=t[0]),n["Content-Type"]||(typeof e=="string"?n["Content-Type"]="text/plain;":typeof e=="object"&&e!==null?(n["Content-Type"]="application/json;",e=JSON.stringify(e)):n["Content-Type"]="application/octet-stream"),new Response(e,{status:s,headers:n})}html(e,...t){let s=this.#t,n={"Content-Type":"text/html; charset=utf-8"};return typeof t[0]=="number"?(s=t[0],typeof t[1]=="object"&&(n={...n,...t[1]})):typeof t[0]=="object"&&(n={...n,...t[0]}),new Response(e,{status:s,headers:n})}text(e,...t){let s=this.#t,n={"Content-Type":"text/plain; charset=utf-8"};return typeof t[0]=="number"?(s=t[0],typeof t[1]=="object"&&(n={...n,...t[1]})):typeof t[0]=="object"&&(n={...n,...t[0]}),new Response(e,{status:s,headers:n})}xml(e,...t){let s=this.#t,n={"Content-Type":"application/xml; charset=utf-8"};return typeof t[0]=="number"?(s=t[0],typeof t[1]=="object"&&(n={...n,...t[1]})):typeof t[0]=="object"&&(n={...n,...t[0]}),new Response(e,{status:s,headers:n})}status=d(e=>(this.#t=e,this),"status");redirect(e,t=302,s){return M.redirect(e,t,s)}async download(e,t){return await M.download(e,t)}async sendFile(e,...t){return await M.sendFile(e,...t)}get req(){return new V(this.#e,this.params)}set params(e){this.#n=e}get params(){return this.#n}}function D(l){const e=[];return l.maxAge&&e.push(`Max-Age=${l.maxAge}`),l.expires&&e.push(`Expires=${l.expires.toUTCString()}`),l.path&&e.push(`Path=${l.path}`),l.domain&&e.push(`Domain=${l.domain}`),l.secure&&e.push("Secure"),l.httpOnly&&e.push("HttpOnly"),l.sameSite&&e.push(`SameSite=${l.sameSite}`),e.join("; ")}d(D,"serializeOptions");let b=class{static{d(this,"GlobalConfig")}static middlewareRule="ignore";static env;static notFound=d(l=>{const{method:e,urlRef:{pathname:t}}=l.req;return new Response(`${e}: '${t}' could not find
4
+ `,{headers:{"Content-Type":"text/plain"},status:404})},"notFound");static onError=d((l,e)=>{throw Error(l)},"onError");static loggerFn=d(()=>({}),"loggerFn")};function _(l){async function e(s,n){console.log(n.addr);const r=await l.serve(s);return r instanceof Response?r:new Response(r.body,{status:r.status,statusText:r.statusText||N[r?.status],headers:new Headers(r.headers)})}d(e,"handleRequest");function t(s,n){const r=typeof Deno<"u";try{const i=r?Deno.serve({port:s},e):null;if(!i)throw new Error("Deno is not find");const a=`\x1B[1m\u{1F680} Deno Accelero Server running at \x1B[1;34mhttp\x1B[0m://localhost:${s}/\x1B[0m`;if(typeof n=="function")n(a);else{const c=b.loggerFn();c.success&&c.success(a)}return i}catch(i){throw new Error(i?.message)}}return d(t,"listen"),{listen:t}}d(_,"denoAdapter");function K(l){function e(t,s){const n=typeof Bun<"u"?Bun.serve:null;try{if(!n)throw new Error("Bun is not find");const r=n({port:t,async fetch(a){console.log(r.requestIP(a));const c=await l.serve(a);return c instanceof Response?c:new Response(c.body,{status:c.status,statusText:c.statusText||N[c?.status],headers:new Headers(c.headers)})}}),o=`\x1B[1m Bun \u{1F680}Accelero Server running at \x1B[1;34mhttp\x1B[0m://localhost:${t}/\x1B[0m`;if(typeof s=="function")s(o);else{const a=b.loggerFn();a.success&&a.success(o)}return r}catch(r){throw new Error(r?.message)}}return d(e,"listen"),{listen:e}}d(K,"bunAdapter");function Q(l){function e(t,s){import("http").then(n=>{let r=n.createServer(async(i,o)=>{const a=await l.serve(i);console.log(i.socket.remoteAddress);const c=a?.statusText;if(!(a instanceof Response))throw new Error("Invalid response from Accelero.serve");const h=Object.fromEntries(await a.headers.entries());c&&(o.statusMessage=c),o.writeHead(a.status,h);const{Readable:u}=await import("stream");if(a.body instanceof u)a.body.pipe(o);else{const f=await a.arrayBuffer();o.end(Buffer.from(f))}});r.listen(t,()=>{const o=`\x1B[1m NodeJS \u{1F680}Accelero Server running at \x1B[1;34mhttp\x1B[0m://localhost:${t}/\x1B[0m`;if(typeof s=="function")s(o);else{const a=b.loggerFn();a.success&&a.success(o)}return r})}).catch(n=>{throw Error(n.message)})}return d(e,"listen"),{listen:e}}d(Q,"nodeAdapter");class X{static{d(this,"CommonHandler")}notFound(e){return b.notFound=e,this}onError(e){return b.onError=e,this}}class ${static{d(this,"TriMiddleware")}children=new Map;middlewares=[];groupMiddlewares=new Map;isOptional=!1;pathname;constructor(e="/"){this.pathname=e}}class Y extends X{static{d(this,"MiddlewareConfigure")}triMiddlewares=new $;basePath;constructor(e="/"){super(),this.basePath=e}addMiddleware(e,t){const s=`${this.basePath}/${e}`?.split("/").filter(Boolean);let n=this.triMiddlewares;for(const r of s)if(r.startsWith("*"))n.children.has("*")||n.children.set("*",new $),n=n.children.get("*");else if(r.startsWith(":")){const i=r?.endsWith("?");if(i){n.isOptional=i;continue}n.children.has(":")||n.children.set(":",new $),n=n.children.get(":")}else n.children.has(r)||n.children.set(r,new $),n=n.children.get(r);n.middlewares.push(...t)}}class S{static{d(this,"TrieRouter")}children=new Map;handlers=new Map;pathname;paramName;isParam=!1;constructor(e="/"){this.children=new Map,this.pathname=e}}class E extends Y{static{d(this,"Router")}routers=new Map;rootNode;constructor({basePath:e="/",env:t={}}={}){super(e),this.basePath=e,b.env={...b.env,...t},this.rootNode=new S(e),this.get.bind(this),this.post.bind(this),this.put.bind(this),this.delete.bind(this),this.all.bind(this),this.#s.bind(this),this.addRouter.bind(this),this.group.bind(this)}get(e,...t){return this.#e("GET",e,...t),this}post(e,...t){return this.#e("POST",e,...t),this}put(e,...t){return this.#e("PUT",e,...t),this}patch(e,...t){return this.#e("PATCH",e,...t),this}delete(e,...t){return this.#e("DELETE",e,...t),this}options(e,...t){return this.#e("OPTIONS",e,...t),this}head(e,...t){return this.#e("HEAD",e,...t),this}all(e,...t){return this.#e("ALL",e,...t),this}addRoute(e,t,...s){return this.#e(e,t,...s),this}addRouter(e,t){return this.#s(e,t)}group(e,t){const s=new E({basePath:e,env:b.env});return t(s),this.#s("/",s),this}use(...e){let t="/",s=[],n;return typeof e[0]=="string"?(t=e[0],Array.isArray(e[1])?(s=e[1],n=e[2]):typeof e[1]=="function"?(s=[e[1]],n=e[2]):n=e[1]):typeof e[0]=="function"?e.length===1?s=[e[0]]:(s=[e[0]],n=e[1]):Array.isArray(e[0])?(s=e[0],n=e[1]):e[0]instanceof E&&(n=e[0]),this.#n(t,s),n&&n instanceof E&&this.addRouter(t,n),this}#e(e,t,...s){if(s.length===0)throw new Error("At least one handler is required.");let n=[],r;if(s.length>1?(Array.isArray(s[0])?n=s[0]:typeof s[0]=="function"&&(n=[s[0]]),r=s[s.length-1]):r=s[0],typeof r!="function")throw new Error("Route callback function is missing or invalid.");if(!n.every(i=>typeof i=="function"))throw new Error("Middleware must be a function or an array of functions.");this.#t(e,t,r,n)}#t(e,t,s,n){const r=`${this.basePath}/${t}`.replace(/\\/g,"")?.split("/").filter(Boolean);let i=r.join("/");if(/(\/\*|\?)/.test(i)){let a=this.routers.get(i);return a?a.set(e,{callback:s,middlewares:n}):(a=new Map,a.set(e,{callback:s,middlewares:n}),this.routers.set(i,a))}let o=this.rootNode;for(const a of r)a.startsWith(":")?(o.children.has(":")||o.children.set(":",new S),o=o.children.get(":"),o.isParam=!0,o.paramName||(o.paramName=a.slice(1))):(o.children.has(a)||o.children.set(a,new S),o=o.children.get(a));o.handlers.set(e,{callback:s,middlewares:n}),o.pathname=t}#n(e,t){this.addMiddleware(e,t)}#r(){return`HNDLR-${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}#s(e,t){const s=`${this.basePath}/${e}`.replace(/\\/g,"")?.split("/").filter(Boolean);let n;if(b.middlewareRule=="ignore"&&(n=this.#r()),t.routers.size)for(const[o,a]of t.routers){let c=o;if(s.length!==0&&(c=s?.join("/")+"/"+o),this.routers.has(c)){const h=this.routers.get(c);for(const[u,f]of a)f.handlerID=n,h.set(u,f);continue}if(n)for(const[h,u]of a)u.handlerID=n;this.routers.set(c,a)}let r=this.rootNode,i=this.triMiddlewares;if(s.length==0)this.#o(r,i,t,n);else{for(const o of s)o.startsWith(":")?(r.children.has(":")||r.children.set(":",new S),r=r.children.get(":"),r.isParam=!0,r.paramName||(r.paramName=o.slice(1))):(r.children.has(o)||r.children.set(o,new S),r=r.children.get(o));for(const o of s)if(o.startsWith("*"))i.children.has("*")||i.children.set("*",new $),i=i.children.get("*");else if(o.startsWith(":")){const a=o?.endsWith("?");if(a){i.isOptional=a;continue}i.children.has(":")||i.children.set(":",new $),i=i.children.get(":")}else i.children.has(o)||i.children.set(o,new $),i=i.children.get(o);this.#o(r,i,t,n)}}#o(e,t,s,n){function r(c,h){let u=h;for(const f of c)if(u.children.has(f[0])){let p=u.children.get(f[0]);for(const[m,y]of f[1].handlers){let g={...y,handlerID:n};p.handlers.set(m,g)}f[1].children.size&&r(f[1].children,p)}else{if(n){let p=d(function(m){for(const[y,g]of m.handlers)g.handlerID=n;for(const[y,g]of m.children)p(g)},"assignHandlerIDs2");p(f[1])}u.children.set(f[0],f[1])}}d(r,"addSubRouter");function i(c,h){let u=h;for(const[f,p]of c)if(u.children.has(f)){let m=u.children.get(f);if(n){let y=[...p.middlewares];m.groupMiddlewares.set(n,y)}else m.middlewares.push(...p.middlewares);p.children.size&&i(p.children,m)}else{if(n){let m=d(function(y){let g=[...y.middlewares];y.groupMiddlewares.set(n,g);for(const[,j]of y.children)m(j)},"assignHandlerIDs2");m(p)}u.children.set(f,p)}}d(i,"addMiddleware");let o=s.rootNode;const a=s.triMiddlewares;for(const[c,h]of o.handlers){let u={...h,handlerID:n};e.handlers.set(c,u)}o.children.size>0&&r(o.children,e),n?t.groupMiddlewares.set(n,[...a.middlewares]):t.middlewares.push(...a.middlewares),a.children.size>0&&i(a.children,t)}}function ee({path:l,urlPattern:e}){let t={};l=l.replace(/^\/+|\/+$/g,""),e=e.replace(/^\/+|\/+$/g,"");const s=l?l.split("/"):[],n=e?e.split("/"):[],r=s.length,i=n.length;if(r>i&&!e.includes("*"))return{success:!1,params:{}};let o=0;for(let a=0;a<i;a++){const c=n[a];if(c?.startsWith("*")){const u=n.slice(a+1);let f=c.length==1?"*":c?.slice(1);if(u.length>0){const p=u.join("/"),m=s.slice(r-u.length).join("/"),y=s.slice(o,r-u.length).join("/");return p!==m||!y?{success:!1,params:{}}:(t[f]=y,{success:!0,params:t})}else{const p=s.slice(o).join("/");return p?(t[f]=p,{success:!0,params:t}):{success:!1,params:{}}}}if(c.startsWith(":")&&c.endsWith("?")){const u=c.slice(1,-1),f=n[a+1];if(f&&!f.startsWith(":")&&f!=="*"&&o<r&&s[o]===f){t[u]=null;continue}const m=n.slice(a+1).filter(g=>!(g.startsWith(":")&&g.endsWith("?"))).length;r-o===m?t[u]=null:o<r?(t[u]=s[o],o++):t[u]=null;continue}if(c.startsWith(":")){const u=c.slice(1);if(!/^[a-zA-Z0-9_]+$/.test(u))return{success:!1,params:{}};if(o<r)t[u]=s[o],o++;else return{success:!1,params:{}};continue}const h=s[o];if(c!==h)return{success:!1,params:{}};o++}return o<r?{success:!1,params:{}}:{success:!0,params:t}}d(ee,"useParams");class te extends E{static{d(this,"Accelero")}constructor({basePath:e="/",middlewareRule:t="follow",env:s={},logger:n=void 0}={}){super({basePath:e,env:s}),b.middlewareRule=t,n&&(b.loggerFn=n),this.serve=this.serve.bind(this)}#e(e,t){const s=this.routers;for(let n of this.routers.keys()){const{success:r,params:i}=ee({path:t,urlPattern:n}),o=s.get(n)?.get(e)||s.get(n)?.get("ALL");if(r&&o)return{handlerID:o.handlerID,callback:o.callback,middlewares:o.middlewares,params:i}}return null}#t(e,t){const s=t.split("/").filter(Boolean),n={};let r=this.rootNode;for(let i of s)if(r.children.has(i))r=r.children.get(i);else if(r.children.has(":"))r=r.children.get(":"),r.paramName&&(n[r.paramName]=i);else return null;if(r?.handlers?.size&&r?.pathname){const i=r.handlers.get(e)||r.handlers.get("ALL");return i?{handlerID:i?.handlerID,middlewares:i.middlewares,callback:i.callback,params:n}:null}return null}findRoute(e,t){return this.#t(e,t)||this.#e(e,t)}#n(e,t){return async s=>{let n=0;const r=d(async()=>n<e.length?e[n++](s,r):await t(s),"next");return await r()}}#r(e,t){const s=e.split("/").filter(Boolean);let n=[],r=this.triMiddlewares;for(let i of s){if(r.children.has(i))r=r.children.get(i);else if(r.children.has("*"))r=r.children.get("*");else if(r.children.has(":"))r=r.children.get(":");else break;t?n.push(...r.groupMiddlewares.get(t)||[]):n.push(...r.middlewares)}return n}async#s(e){let t=new Z(e);const s=t.req.urlRef,{pathname:n}=s;let r=this.#r(n);t.env=b.env;const i=b.loggerFn();i.request&&i.request(t.method,t.pathname);try{return await this.#n([...this.triMiddlewares.middlewares,...r],async o=>{const a=this.findRoute(o.req.method,n);if(a?.callback){o.params=a.params;const c=a.callback,h=a.handlerID;let u=[...a.middlewares];h&&u.push(...this.#r(n,h));const f=await this.#n(u,c)(o);f?.headers&&o.headers.add(f.headers);const p=f?.statusText||N[f?.status]||"",m=f.status||200;let y=o.headers.toObject();return i.response&&i.response(o.method,o.pathname,m),f instanceof Response?new Response(f.body,{status:m,statusText:p,headers:y}):new Response(f.body,{status:m,statusText:p,headers:y})}else return i.response&&i.response(o.method,o.pathname,404),b.notFound(o)})(t)}catch(o){let a=o;return o instanceof Error&&(a=o.message),i.error&&i.error(`${N[500]}: ${a} `),b.onError(a,t)}}async serve(e){return this.#s(e)}}function ne(l,e){try{let t=!1,s=x.getEnvironment;if(s==="node"||s==="bun"){const{existsSync:i}=require("fs");t=i(l)}else if(s==="deno")try{Deno.statSync(l),t=!0}catch{t=!1}if(!t)return;let n="";if(s==="node"||s==="bun"){const{readFileSync:i}=require("fs");n=i(l,"utf8")}else s==="deno"&&(n=new TextDecoder("utf-8").decode(Deno.readFileSync(l)));const r=n.split(`
5
+ `);for(const i of r){const o=i.trim();if(!o||o.startsWith("#"))continue;const[a,c]=o.split("=",2).map(h=>h.trim());if(a&&c){const h=c.replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1");e[a]=h,s==="node"||s==="bun"?process.env[a]=h:s==="deno"&&Deno.env.set(a,h)}}}catch(t){console.error(`[dotenv] Error parsing file: ${l}`,t)}}d(ne,"parseEnvFile");function se(l="./"){const e={},t=[".env",".env.local",`.env.${process?.env?.NODE_ENV||"development"}`,`.env.${process?.env?.NODE_ENV||"development"}.local`];for(const s of t)ne(`${l}${s}`,e);return e}d(se,"loadEnv");const w={reset:"\x1B[0m",bold:"\x1B[1m",gray:"\x1B[90m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m"},C=d((l,e,...t)=>{const s=new Date().toISOString(),n={info:w.blue,warn:w.yellow,error:w.red,debug:w.cyan,success:w.green},r=`${w.gray}[${s}]${w.reset}`,i=`${n[l]}[${l.toUpperCase()}]${w.reset}`;console.log(`${r} ${i} ${e}`,...t?.flat())},"loggerOutput");function re(){const l=performance.now();return{request:d((e,t)=>{console.log(`${w.bold}<-- ${w.reset}${w.bgMagenta} ${e} ${w.reset} ${t}`)},"request"),response:d((e,t,s)=>{const n=performance.now()-l;console.log(`${w.bold}--> ${w.reset}${w.bgBlue} ${e} ${w.reset} ${t} ${w.yellow}${s}${w.reset} ${w.magenta}${n.toFixed(2)}ms${w.reset}`)},"response"),info:d((e,...t)=>C("info",e,...t),"info"),warn:d((e,...t)=>C("warn",e,...t),"warn"),error:d((e,...t)=>C("error",e,...t),"error"),debug:d((e,...t)=>C("debug",e,...t),"debug"),success:d((e,...t)=>C("success",e,...t),"success")}}d(re,"logger");function oe(l={}){const{methods:e,allowedHeaders:t,credentials:s,exposedHeaders:n,maxAge:r,origin:i}=l;return async(o,a)=>{const c=o.req.headers.get("origin")||"";let h="*";return typeof i=="string"?h=i:i instanceof RegExp?h=i.test(c)?c:"":Array.isArray(i)?h=i.some(f=>{if(typeof f=="string")return f===c;if(f instanceof RegExp)return f.test(c)})?c:"":typeof i=="function"&&(h=i(c)?c:""),o.headers.set("Access-Control-Allow-Origin",h),o.headers.set("Access-Control-Allow-Methods",(e||["GET","POST","PUT","DELETE"]).join(", ")),o.headers.set("Access-Control-Allow-Headers",(t||["Content-Type","Authorization"]).join(", ")),n&&o.headers.set("Access-Control-Expose-Headers",n.join(", ")),s&&o.headers.set("Access-Control-Allow-Credentials","true"),r&&o.headers.set("Access-Control-Max-Age",r.toString()),o.req.method==="OPTIONS"?new Response(null,{status:204,headers:o.headers.toObject()}):await a()}}d(oe,"cors"),exports.Accelero=te,exports.JetResponse=M,exports.Router=E,exports.bunAdapter=K,exports.cors=oe,exports.denoAdapter=_,exports.loadEnv=se,exports.logger=re,exports.nodeAdapter=Q;
package/dist/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ var D=Object.defineProperty;var d=(l,t)=>D(l,"name",{value:t,configurable:!0});import{createRequire as P}from"node:module";const N=P(import.meta.url);class j{static{d(this,"HeadersParser")}headers=new Map;constructor(t){t&&this.add(t)}add(t){if(Array.isArray(t))for(const[e,s]of t)this.set(e,s);else if(typeof Headers<"u"&&t instanceof Headers)for(const[e,s]of t.entries())this.set(e,s);else if(typeof t=="object")for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&this.set(e,t[e]);return this}set(t,e){return this.headers.set(t.toLowerCase(),Array.isArray(e)?e:[e]),this}get(t){const e=this.headers.get(t.toLowerCase());return e?e[0]:void 0}getAll(t){return this.headers.get(t.toLowerCase())||[]}has(t){return this.headers.has(t.toLowerCase())}delete(t){return this.headers.delete(t.toLowerCase())}append(t,e){const s=t.toLowerCase();return this.headers.has(s)?this.headers.get(s).push(e):this.headers.set(s,[e]),this}entries(){return this.headers.entries()}keys(){return this.headers.keys()}values(){return this.headers.values()}forEach(t){for(const[e,s]of this.headers)t(s,e)}toObject(){const t={};for(const[e,s]of this.headers.entries())t[e]=s.length>1?s:s[0];return t}}Object.defineProperty(j,"name",{value:"Headers"});class x{static{d(this,"EnvironmentDetector")}static get getEnvironment(){return typeof Bun<"u"?"bun":typeof Deno<"u"?"deno":typeof process<"u"&&process.versions?.node?"node":"unknown"}static detectProtocol(t){try{return this.getEnvironment==="node"?t?.socket?.encrypted?"https":"http":"unknown"}catch{throw new Error("Failed to detect protocol.")}}static getHost(t){try{return t?.get("host")||"unknown"}catch{throw new Error("Failed to get host.")}}}async function O(l){const t=x.getEnvironment;if(t==="node")return new Promise((e,s)=>{let n="";l.on("data",r=>{n+=r.toString()}),l.on("end",()=>{try{e(JSON.parse(n))}catch{s(new Error("Invalid JSON format"))}})});if(t==="deno"||t==="bun")return await l.json();throw new Error("Unsupported environment for multipart parsing")}d(O,"parseJsonBody");async function k(l){const t=x.getEnvironment;if(t==="node")return new Promise((e,s)=>{let n="";l.on("data",r=>{n+=r.toString()}),l.on("end",()=>{try{e(n)}catch{s(new Error("Invalid JSON format"))}})});if(t==="deno"||t==="bun")return await l.text();throw new Error("Unsupported environment for multipart parsing")}d(k,"parseTextBody");async function L(l){const t=x.getEnvironment;if(t==="node")return new Promise((e,s)=>{let n="";l.on("data",r=>{n+=r.toString("binary")}),l.on("end",()=>{try{const r=n.split("&"),i={};r.forEach(o=>{const[a,c]=o.split("=");i[decodeURIComponent(a)]=decodeURIComponent(c||"")}),e(i)}catch{s(new Error("Invalid x-www-form-urlencoded format"))}})});if(t==="deno"||t==="bun"){const e=await l.formData(),s={};for(const[n,r]of e.entries())s[n]=r;return s}else throw new Error("Unsupported environment for multipart parsing")}d(L,"parseUrlEncodedBody");async function H(l,t,e){const s=x.getEnvironment;if(e?.sanitized,s==="node")return new Promise((n,r)=>{let i="";l.on("data",o=>{i+=o.toString("binary")}),l.on("end",()=>{try{const o={};i.split("----------------------------").forEach(h=>{const u=h.match(/name="(.*)"\r\n\r\n(.*)\r\n/);if(u&&u.length===3){const f=u[1],p=u[2];o[f]=p}});const c=i.split(`--${t}`);for(const h of c)if(h.includes("filename")){const u=h.match(/filename="([^"]+)"/),f=h.match(/name="([^"]+)"/),p=h.match(/Content-Type: ([^\r\n]+)/);if(u&&f&&p){let m=u[1];const y=f[1],g=p[1];e?.sanitized&&(m=`${Date.now()}-${m.replace(/\s+/g,"")?.replace(/[^a-zA-Z0-9.-]/g,"-")}`?.toLowerCase()),Array.isArray(e?.allowedTypes)&&!e.allowedTypes?.includes(g)&&r(`Invalid file type: "${g}". Allowed types: ${e.allowedTypes.join(", ")}`);const C=h.indexOf(`\r
2
+ \r
3
+ `)+4,v=Buffer.from(h.substring(C),"binary"),E=v.buffer.slice(v.byteOffset,v.byteOffset+v.byteLength);typeof e?.maxSize<"u"&&v.byteLength>e.maxSize&&r(`File size exceeds the limit: ${v.byteLength} bytes (Max: ${e.maxSize} bytes)`);const T=new File([E],m,{type:g});o[y]?Array.isArray(o[y])?o[y].push(T):o[y]=[o[y],T]:o[y]=T}}n(o)}catch{}})});if(s==="deno"||s==="bun"){const n=await l.formData(),r={};for(const[i,o]of n.entries()){let a=o;if(a instanceof File&&typeof e=="object"){let c=a.name;if(e?.sanitized&&(c=`${Date.now()}-${c.replace(/\s+/g,"")?.replace(/[^a-zA-Z0-9.-]/g,"-")}`?.toLowerCase()),Array.isArray(e?.allowedTypes)&&!e.allowedTypes?.includes(a.type))throw new Error(`Invalid file type: "${a.type}". Allowed types: ${e.allowedTypes.join(", ")}`);if(typeof e?.maxSize<"u"&&a.size>e.maxSize)throw new Error(`File size exceeds the limit: ${a.size} bytes (Max: ${e.maxSize} bytes)`);a=new File([await a.arrayBuffer()],c,{type:a.type})}r[i]?Array.isArray(r[i])?r[i].push(a):r[i]=[r[i],a]:r[i]=a}return r}else throw new Error("Unsupported environment for multipart parsing")}d(H,"parseMultipartBody");function z(l){const t=/^(?:(\w+):\/\/)?(?:([^:@]+)?(?::([^@]+))?@)?([^:/?#]+)?(?::(\d+))?(\/[^?#]*)?(?:\?([^#]*))?(?:#(.*))?$/;let e=l.match(t);const[s,n,r,i,o,a,c,h,u]=e;let f=o;n&&(f=n+"://"+o),a&&(f=f+":"+a);let p=c;p?.endsWith("/")&&p.slice(0,-1);function m(){return h?(decodeURIComponent(h).split("&")?.map(v=>{const[E,T]=v.split("=");return{[E]:T}})).reduce(function(v,E){return{...v,...E}},{}):{}}return d(m,"query"),{pathname:p,hash:u,protocol:n,origin:f,username:r,password:i,hostname:o,href:l,port:a,query:m()}}d(z,"urlParse");class I{static{d(this,"Request")}headers=new j;url;method;urlRef={hash:void 0,protocol:void 0,origin:void 0,username:void 0,password:void 0,hostname:void 0,port:void 0,href:void 0,query:{},pathname:"/"};query;#e;params={};constructor(t,e){if(this.headers=new j(t?.headers),this.method=t?.method?.toUpperCase(),this.params=e,this.#e=t,x.getEnvironment=="node"){const s=x.detectProtocol(t),n=x.getHost(this.headers);this.url=`${s}://${n}${t.url}`}else this.url=t.url;this.urlRef=z(this.url),this.query=this.urlRef.query}async text(){return await k(this.#e)}async json(){return(this.headers.get("content-type")||"").includes("application/json")?await O(this.#e):{}}async formData(t){const e=this.headers.get("content-type")||"";if(!e)throw Error("Invalid Content-Type");if(e.includes("application/json"))return await O(this.#e);if(e.includes("application/x-www-form-urlencoded"))return L(this.#e);if(e.includes("multipart/form-data")){const s=e?.split("; ")?.[1]?.split("=")?.[1];if(!s)throw Error("Boundary not found");return await H(this.#e,s,t)}else return{}}}class B{static{d(this,"JetResponse")}static json(t,...e){let s=200,n={"Content-Type":"application/json; charset=utf-8"};return typeof e[0]=="number"?(s=e[0],typeof e[1]=="object"&&(n={...n,...e[1]})):typeof e[0]=="object"&&(n={...n,...e[0]}),new Response(JSON.stringify(t),{status:s,headers:n})}static html(t,...e){let s=200,n={"Content-Type":"text/html; charset=utf-8"};return typeof e[0]=="number"?(s=e[0],typeof e[1]=="object"&&(n={...n,...e[1]})):typeof e[0]=="object"&&(n={...n,...e[0]}),new Response(t,{status:s,headers:n})}static text(t,...e){let s=200,n={"Content-Type":"text/plain; charset=utf-8"};return typeof e[0]=="number"?(s=e[0],typeof e[1]=="object"&&(n={...n,...e[1]})):typeof e[0]=="object"&&(n={...n,...e[0]}),new Response(t,{status:s,headers:n})}static xml(t,...e){let s=200,n={"Content-Type":"application/xml; charset=utf-8"};return typeof e[0]=="number"?(s=e[0],typeof e[1]=="object"&&(n={...n,...e[1]})):typeof e[0]=="object"&&(n={...n,...e[0]}),new Response(t,{status:s,headers:n})}static send(t,...e){let s=200,n={};return typeof e[0]=="number"?(s=e[0],typeof e[1]=="object"&&(n=e[1])):typeof e[0]=="object"&&(n=e[0]),n["Content-Type"]||(typeof t=="string"?n["Content-Type"]="text/plain;":typeof t=="object"&&t!==null?(n["Content-Type"]="application/json;",t=JSON.stringify(t)):n["Content-Type"]="application/octet-stream"),new Response(t,{status:s,headers:n})}static redirect(t,e=302,s){return new Response(null,{status:e,headers:{Location:t}})}static async download(t,e){try{let s=!1;const n=x.getEnvironment;if(n==="node"){const{existsSync:i}=await import("fs");s=i(t)}else if(n==="bun")s=Bun.file(t).exists();else if(n==="deno")try{await Deno.stat(t),s=!0}catch{s=!1}if(!s)throw Error("File not found");let r;if(n==="node"){const{readFileSync:i}=await import("fs");r=await i(t)}else n==="bun"?r=await Bun.file(t).arrayBuffer().then(i=>new Uint8Array(i)):n==="deno"&&(r=await Deno.readFile(t));return new Response(r,{status:200,headers:{"Content-Disposition":`attachment; filename="${e}"`,"Content-Type":"application/octet-stream","Content-Length":r.byteLength.toString()}})}catch(s){throw Error("Internal Server Error"+s?.message)}}static async sendFile(t,...e){try{const s=x.getEnvironment,n=t;let r=!1;if(s==="node"){const{existsSync:p}=await import("fs");r=p(n)}else if(s==="bun")r=Bun.file(n).exists();else if(s==="deno")try{await Deno.stat(n),r=!0}catch{r=!1}if(!r)throw Error("File not found");let i=0;if(s==="node"){const{statSync:p}=await import("fs");i=p(n).size}else s==="bun"?i=(await Bun.file(n).arrayBuffer()).byteLength:s==="deno"&&(i=(await Deno.stat(n)).size);const o={html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",pdf:"application/pdf",txt:"text/plain",xml:"application/xml",mp4:"video/mp4",webm:"video/webm",ogg:"audio/ogg",mp3:"audio/mpeg",wav:"audio/wav",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar"},a=t.split(".").pop()?.toLowerCase()||"",c=o[a]||"application/octet-stream";let h;if(s==="node"){const{createReadStream:p}=await import("fs");h=p(n)}else s==="bun"?h=Bun.file(n).stream():s==="deno"&&(h=(await Deno.open(n,{read:!0})).readable);let u={"Content-Type":c,"Content-Length":i.toString()},f="";return typeof e[0]=="string"?(f=e[0],typeof e[1]=="object"&&(u={...u,...e[1]})):typeof e[0]=="object"&&(u={...u,...e[0]}),f&&(u["Content-Disposition"]=`attachment; filename="${f}"`),new Response(h,{status:200,headers:u})}catch(s){throw Error("Internal Server Error"+s?.message)}}}class q{static{d(this,"State")}state;constructor(){this.state=new Map}set(t,e){this.state.set(t,e)}get(t){return this.state.get(t)}delete(t){return this.state.delete(t)}has(t){return this.state.has(t)}keys(){return Array.from(this.state.keys())}values(){return Array.from(this.state.values())}entries(){return Array.from(this.state.entries())}clear(){this.state.clear()}}const M={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};class U{static{d(this,"Context")}#e;env={};headers=new j;res=new Response;pathname;url;method;#t=200;state=new q;#n={};#r;finalized=!1;#s;#o;#i;#a;#l=!0;#c;#d;#f;#u;#h;constructor(t){this.#e=t,this.method=t?.method?.toUpperCase(),this.pathname=this.req.urlRef.pathname,this.url=this.req.url}get cookies(){const t=this.headers.getAll("cookie");let e={};if(Array.isArray(t)&&t.length!=0){const s=t.join("; ").split(";");for(const n of s){const[r,i]=n?.trim()?.split("=");e[r]=decodeURIComponent(i)}}else if(typeof t=="string"){const s=t.split(";");for(const n of s){const[r,i]=n?.trim()?.split("=");e[r]=decodeURIComponent(i)}}return{get:d(s=>e?.[s],"get"),all:d(()=>e,"all"),delete:d((s,n)=>{const r="",i={...n,expires:new Date(0)},o=`${s}=${r};${F(i)}`;this.headers.set("Set-Cookie",o)},"delete"),set:d((s,n,r)=>{const i=`${s}=${n};${F(r||{})}`;this.headers.set("Set-Cookie",i)},"set")}}json(t,...e){let s=this.#t,n={"Content-Type":"application/json; charset=utf-8"};return typeof e[0]=="number"?(s=e[0],typeof e[1]=="object"&&(n={...n,...e[1]})):typeof e[0]=="object"&&(n={...n,...e[0]}),new Response(JSON.stringify(t),{status:s,headers:n})}send(t,...e){let s=this.#t,n={};return typeof e[0]=="number"?(s=e[0],typeof e[1]=="object"&&(n=e[1])):typeof e[0]=="object"&&(n=e[0]),n["Content-Type"]||(typeof t=="string"?n["Content-Type"]="text/plain;":typeof t=="object"&&t!==null?(n["Content-Type"]="application/json;",t=JSON.stringify(t)):n["Content-Type"]="application/octet-stream"),new Response(t,{status:s,headers:n})}html(t,...e){let s=this.#t,n={"Content-Type":"text/html; charset=utf-8"};return typeof e[0]=="number"?(s=e[0],typeof e[1]=="object"&&(n={...n,...e[1]})):typeof e[0]=="object"&&(n={...n,...e[0]}),new Response(t,{status:s,headers:n})}text(t,...e){let s=this.#t,n={"Content-Type":"text/plain; charset=utf-8"};return typeof e[0]=="number"?(s=e[0],typeof e[1]=="object"&&(n={...n,...e[1]})):typeof e[0]=="object"&&(n={...n,...e[0]}),new Response(t,{status:s,headers:n})}xml(t,...e){let s=this.#t,n={"Content-Type":"application/xml; charset=utf-8"};return typeof e[0]=="number"?(s=e[0],typeof e[1]=="object"&&(n={...n,...e[1]})):typeof e[0]=="object"&&(n={...n,...e[0]}),new Response(t,{status:s,headers:n})}status=d(t=>(this.#t=t,this),"status");redirect(t,e=302,s){return B.redirect(t,e,s)}async download(t,e){return await B.download(t,e)}async sendFile(t,...e){return await B.sendFile(t,...e)}get req(){return new I(this.#e,this.params)}set params(t){this.#n=t}get params(){return this.#n}}function F(l){const t=[];return l.maxAge&&t.push(`Max-Age=${l.maxAge}`),l.expires&&t.push(`Expires=${l.expires.toUTCString()}`),l.path&&t.push(`Path=${l.path}`),l.domain&&t.push(`Domain=${l.domain}`),l.secure&&t.push("Secure"),l.httpOnly&&t.push("HttpOnly"),l.sameSite&&t.push(`SameSite=${l.sameSite}`),t.join("; ")}d(F,"serializeOptions");let b=class{static{d(this,"GlobalConfig")}static middlewareRule="ignore";static env;static notFound=d(l=>{const{method:t,urlRef:{pathname:e}}=l.req;return new Response(`${t}: '${e}' could not find
4
+ `,{headers:{"Content-Type":"text/plain"},status:404})},"notFound");static onError=d((l,t)=>{throw Error(l)},"onError");static loggerFn=d(()=>({}),"loggerFn")};function W(l){async function t(s,n){console.log(n.addr);const r=await l.serve(s);return r instanceof Response?r:new Response(r.body,{status:r.status,statusText:r.statusText||M[r?.status],headers:new Headers(r.headers)})}d(t,"handleRequest");function e(s,n){const r=typeof Deno<"u";try{const i=r?Deno.serve({port:s},t):null;if(!i)throw new Error("Deno is not find");const a=`\x1B[1m\u{1F680} Deno Accelero Server running at \x1B[1;34mhttp\x1B[0m://localhost:${s}/\x1B[0m`;if(typeof n=="function")n(a);else{const c=b.loggerFn();c.success&&c.success(a)}return i}catch(i){throw new Error(i?.message)}}return d(e,"listen"),{listen:e}}d(W,"denoAdapter");function J(l){function t(e,s){const n=typeof Bun<"u"?Bun.serve:null;try{if(!n)throw new Error("Bun is not find");const r=n({port:e,async fetch(a){console.log(r.requestIP(a));const c=await l.serve(a);return c instanceof Response?c:new Response(c.body,{status:c.status,statusText:c.statusText||M[c?.status],headers:new Headers(c.headers)})}}),o=`\x1B[1m Bun \u{1F680}Accelero Server running at \x1B[1;34mhttp\x1B[0m://localhost:${e}/\x1B[0m`;if(typeof s=="function")s(o);else{const a=b.loggerFn();a.success&&a.success(o)}return r}catch(r){throw new Error(r?.message)}}return d(t,"listen"),{listen:t}}d(J,"bunAdapter");function V(l){function t(e,s){import("http").then(n=>{let r=n.createServer(async(i,o)=>{const a=await l.serve(i);console.log(i.socket.remoteAddress);const c=a?.statusText;if(!(a instanceof Response))throw new Error("Invalid response from Accelero.serve");const h=Object.fromEntries(await a.headers.entries());c&&(o.statusMessage=c),o.writeHead(a.status,h);const{Readable:u}=await import("stream");if(a.body instanceof u)a.body.pipe(o);else{const f=await a.arrayBuffer();o.end(Buffer.from(f))}});r.listen(e,()=>{const o=`\x1B[1m NodeJS \u{1F680}Accelero Server running at \x1B[1;34mhttp\x1B[0m://localhost:${e}/\x1B[0m`;if(typeof s=="function")s(o);else{const a=b.loggerFn();a.success&&a.success(o)}return r})}).catch(n=>{throw Error(n.message)})}return d(t,"listen"),{listen:t}}d(V,"nodeAdapter");class G{static{d(this,"CommonHandler")}notFound(t){return b.notFound=t,this}onError(t){return b.onError=t,this}}class R{static{d(this,"TriMiddleware")}children=new Map;middlewares=[];groupMiddlewares=new Map;isOptional=!1;pathname;constructor(t="/"){this.pathname=t}}class _ extends G{static{d(this,"MiddlewareConfigure")}triMiddlewares=new R;basePath;constructor(t="/"){super(),this.basePath=t}addMiddleware(t,e){const s=`${this.basePath}/${t}`?.split("/").filter(Boolean);let n=this.triMiddlewares;for(const r of s)if(r.startsWith("*"))n.children.has("*")||n.children.set("*",new R),n=n.children.get("*");else if(r.startsWith(":")){const i=r?.endsWith("?");if(i){n.isOptional=i;continue}n.children.has(":")||n.children.set(":",new R),n=n.children.get(":")}else n.children.has(r)||n.children.set(r,new R),n=n.children.get(r);n.middlewares.push(...e)}}class A{static{d(this,"TrieRouter")}children=new Map;handlers=new Map;pathname;paramName;isParam=!1;constructor(t="/"){this.children=new Map,this.pathname=t}}class $ extends _{static{d(this,"Router")}routers=new Map;rootNode;constructor({basePath:t="/",env:e={}}={}){super(t),this.basePath=t,b.env={...b.env,...e},this.rootNode=new A(t),this.get.bind(this),this.post.bind(this),this.put.bind(this),this.delete.bind(this),this.all.bind(this),this.#s.bind(this),this.addRouter.bind(this),this.group.bind(this)}get(t,...e){return this.#e("GET",t,...e),this}post(t,...e){return this.#e("POST",t,...e),this}put(t,...e){return this.#e("PUT",t,...e),this}patch(t,...e){return this.#e("PATCH",t,...e),this}delete(t,...e){return this.#e("DELETE",t,...e),this}options(t,...e){return this.#e("OPTIONS",t,...e),this}head(t,...e){return this.#e("HEAD",t,...e),this}all(t,...e){return this.#e("ALL",t,...e),this}addRoute(t,e,...s){return this.#e(t,e,...s),this}addRouter(t,e){return this.#s(t,e)}group(t,e){const s=new $({basePath:t,env:b.env});return e(s),this.#s("/",s),this}use(...t){let e="/",s=[],n;return typeof t[0]=="string"?(e=t[0],Array.isArray(t[1])?(s=t[1],n=t[2]):typeof t[1]=="function"?(s=[t[1]],n=t[2]):n=t[1]):typeof t[0]=="function"?t.length===1?s=[t[0]]:(s=[t[0]],n=t[1]):Array.isArray(t[0])?(s=t[0],n=t[1]):t[0]instanceof $&&(n=t[0]),this.#n(e,s),n&&n instanceof $&&this.addRouter(e,n),this}#e(t,e,...s){if(s.length===0)throw new Error("At least one handler is required.");let n=[],r;if(s.length>1?(Array.isArray(s[0])?n=s[0]:typeof s[0]=="function"&&(n=[s[0]]),r=s[s.length-1]):r=s[0],typeof r!="function")throw new Error("Route callback function is missing or invalid.");if(!n.every(i=>typeof i=="function"))throw new Error("Middleware must be a function or an array of functions.");this.#t(t,e,r,n)}#t(t,e,s,n){const r=`${this.basePath}/${e}`.replace(/\\/g,"")?.split("/").filter(Boolean);let i=r.join("/");if(/(\/\*|\?)/.test(i)){let a=this.routers.get(i);return a?a.set(t,{callback:s,middlewares:n}):(a=new Map,a.set(t,{callback:s,middlewares:n}),this.routers.set(i,a))}let o=this.rootNode;for(const a of r)a.startsWith(":")?(o.children.has(":")||o.children.set(":",new A),o=o.children.get(":"),o.isParam=!0,o.paramName||(o.paramName=a.slice(1))):(o.children.has(a)||o.children.set(a,new A),o=o.children.get(a));o.handlers.set(t,{callback:s,middlewares:n}),o.pathname=e}#n(t,e){this.addMiddleware(t,e)}#r(){return`HNDLR-${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}#s(t,e){const s=`${this.basePath}/${t}`.replace(/\\/g,"")?.split("/").filter(Boolean);let n;if(b.middlewareRule=="ignore"&&(n=this.#r()),e.routers.size)for(const[o,a]of e.routers){let c=o;if(s.length!==0&&(c=s?.join("/")+"/"+o),this.routers.has(c)){const h=this.routers.get(c);for(const[u,f]of a)f.handlerID=n,h.set(u,f);continue}if(n)for(const[h,u]of a)u.handlerID=n;this.routers.set(c,a)}let r=this.rootNode,i=this.triMiddlewares;if(s.length==0)this.#o(r,i,e,n);else{for(const o of s)o.startsWith(":")?(r.children.has(":")||r.children.set(":",new A),r=r.children.get(":"),r.isParam=!0,r.paramName||(r.paramName=o.slice(1))):(r.children.has(o)||r.children.set(o,new A),r=r.children.get(o));for(const o of s)if(o.startsWith("*"))i.children.has("*")||i.children.set("*",new R),i=i.children.get("*");else if(o.startsWith(":")){const a=o?.endsWith("?");if(a){i.isOptional=a;continue}i.children.has(":")||i.children.set(":",new R),i=i.children.get(":")}else i.children.has(o)||i.children.set(o,new R),i=i.children.get(o);this.#o(r,i,e,n)}}#o(t,e,s,n){function r(c,h){let u=h;for(const f of c)if(u.children.has(f[0])){let p=u.children.get(f[0]);for(const[m,y]of f[1].handlers){let g={...y,handlerID:n};p.handlers.set(m,g)}f[1].children.size&&r(f[1].children,p)}else{if(n){let p=d(function(m){for(const[y,g]of m.handlers)g.handlerID=n;for(const[y,g]of m.children)p(g)},"assignHandlerIDs2");p(f[1])}u.children.set(f[0],f[1])}}d(r,"addSubRouter");function i(c,h){let u=h;for(const[f,p]of c)if(u.children.has(f)){let m=u.children.get(f);if(n){let y=[...p.middlewares];m.groupMiddlewares.set(n,y)}else m.middlewares.push(...p.middlewares);p.children.size&&i(p.children,m)}else{if(n){let m=d(function(y){let g=[...y.middlewares];y.groupMiddlewares.set(n,g);for(const[,C]of y.children)m(C)},"assignHandlerIDs2");m(p)}u.children.set(f,p)}}d(i,"addMiddleware");let o=s.rootNode;const a=s.triMiddlewares;for(const[c,h]of o.handlers){let u={...h,handlerID:n};t.handlers.set(c,u)}o.children.size>0&&r(o.children,t),n?e.groupMiddlewares.set(n,[...a.middlewares]):e.middlewares.push(...a.middlewares),a.children.size>0&&i(a.children,e)}}function Z({path:l,urlPattern:t}){let e={};l=l.replace(/^\/+|\/+$/g,""),t=t.replace(/^\/+|\/+$/g,"");const s=l?l.split("/"):[],n=t?t.split("/"):[],r=s.length,i=n.length;if(r>i&&!t.includes("*"))return{success:!1,params:{}};let o=0;for(let a=0;a<i;a++){const c=n[a];if(c?.startsWith("*")){const u=n.slice(a+1);let f=c.length==1?"*":c?.slice(1);if(u.length>0){const p=u.join("/"),m=s.slice(r-u.length).join("/"),y=s.slice(o,r-u.length).join("/");return p!==m||!y?{success:!1,params:{}}:(e[f]=y,{success:!0,params:e})}else{const p=s.slice(o).join("/");return p?(e[f]=p,{success:!0,params:e}):{success:!1,params:{}}}}if(c.startsWith(":")&&c.endsWith("?")){const u=c.slice(1,-1),f=n[a+1];if(f&&!f.startsWith(":")&&f!=="*"&&o<r&&s[o]===f){e[u]=null;continue}const m=n.slice(a+1).filter(g=>!(g.startsWith(":")&&g.endsWith("?"))).length;r-o===m?e[u]=null:o<r?(e[u]=s[o],o++):e[u]=null;continue}if(c.startsWith(":")){const u=c.slice(1);if(!/^[a-zA-Z0-9_]+$/.test(u))return{success:!1,params:{}};if(o<r)e[u]=s[o],o++;else return{success:!1,params:{}};continue}const h=s[o];if(c!==h)return{success:!1,params:{}};o++}return o<r?{success:!1,params:{}}:{success:!0,params:e}}d(Z,"useParams");class K extends ${static{d(this,"Accelero")}constructor({basePath:t="/",middlewareRule:e="follow",env:s={},logger:n=void 0}={}){super({basePath:t,env:s}),b.middlewareRule=e,n&&(b.loggerFn=n),this.serve=this.serve.bind(this)}#e(t,e){const s=this.routers;for(let n of this.routers.keys()){const{success:r,params:i}=Z({path:e,urlPattern:n}),o=s.get(n)?.get(t)||s.get(n)?.get("ALL");if(r&&o)return{handlerID:o.handlerID,callback:o.callback,middlewares:o.middlewares,params:i}}return null}#t(t,e){const s=e.split("/").filter(Boolean),n={};let r=this.rootNode;for(let i of s)if(r.children.has(i))r=r.children.get(i);else if(r.children.has(":"))r=r.children.get(":"),r.paramName&&(n[r.paramName]=i);else return null;if(r?.handlers?.size&&r?.pathname){const i=r.handlers.get(t)||r.handlers.get("ALL");return i?{handlerID:i?.handlerID,middlewares:i.middlewares,callback:i.callback,params:n}:null}return null}findRoute(t,e){return this.#t(t,e)||this.#e(t,e)}#n(t,e){return async s=>{let n=0;const r=d(async()=>n<t.length?t[n++](s,r):await e(s),"next");return await r()}}#r(t,e){const s=t.split("/").filter(Boolean);let n=[],r=this.triMiddlewares;for(let i of s){if(r.children.has(i))r=r.children.get(i);else if(r.children.has("*"))r=r.children.get("*");else if(r.children.has(":"))r=r.children.get(":");else break;e?n.push(...r.groupMiddlewares.get(e)||[]):n.push(...r.middlewares)}return n}async#s(t){let e=new U(t);const s=e.req.urlRef,{pathname:n}=s;let r=this.#r(n);e.env=b.env;const i=b.loggerFn();i.request&&i.request(e.method,e.pathname);try{return await this.#n([...this.triMiddlewares.middlewares,...r],async o=>{const a=this.findRoute(o.req.method,n);if(a?.callback){o.params=a.params;const c=a.callback,h=a.handlerID;let u=[...a.middlewares];h&&u.push(...this.#r(n,h));const f=await this.#n(u,c)(o);f?.headers&&o.headers.add(f.headers);const p=f?.statusText||M[f?.status]||"",m=f.status||200;let y=o.headers.toObject();return i.response&&i.response(o.method,o.pathname,m),f instanceof Response?new Response(f.body,{status:m,statusText:p,headers:y}):new Response(f.body,{status:m,statusText:p,headers:y})}else return i.response&&i.response(o.method,o.pathname,404),b.notFound(o)})(e)}catch(o){let a=o;return o instanceof Error&&(a=o.message),i.error&&i.error(`${M[500]}: ${a} `),b.onError(a,e)}}async serve(t){return this.#s(t)}}function Q(l,t){try{let e=!1,s=x.getEnvironment;if(s==="node"||s==="bun"){const{existsSync:i}=N("fs");e=i(l)}else if(s==="deno")try{Deno.statSync(l),e=!0}catch{e=!1}if(!e)return;let n="";if(s==="node"||s==="bun"){const{readFileSync:i}=N("fs");n=i(l,"utf8")}else s==="deno"&&(n=new TextDecoder("utf-8").decode(Deno.readFileSync(l)));const r=n.split(`
5
+ `);for(const i of r){const o=i.trim();if(!o||o.startsWith("#"))continue;const[a,c]=o.split("=",2).map(h=>h.trim());if(a&&c){const h=c.replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1");t[a]=h,s==="node"||s==="bun"?process.env[a]=h:s==="deno"&&Deno.env.set(a,h)}}}catch(e){console.error(`[dotenv] Error parsing file: ${l}`,e)}}d(Q,"parseEnvFile");function X(l="./"){const t={},e=[".env",".env.local",`.env.${process?.env?.NODE_ENV||"development"}`,`.env.${process?.env?.NODE_ENV||"development"}.local`];for(const s of e)Q(`${l}${s}`,t);return t}d(X,"loadEnv");const w={reset:"\x1B[0m",bold:"\x1B[1m",gray:"\x1B[90m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m"},S=d((l,t,...e)=>{const s=new Date().toISOString(),n={info:w.blue,warn:w.yellow,error:w.red,debug:w.cyan,success:w.green},r=`${w.gray}[${s}]${w.reset}`,i=`${n[l]}[${l.toUpperCase()}]${w.reset}`;console.log(`${r} ${i} ${t}`,...e?.flat())},"loggerOutput");function Y(){const l=performance.now();return{request:d((t,e)=>{console.log(`${w.bold}<-- ${w.reset}${w.bgMagenta} ${t} ${w.reset} ${e}`)},"request"),response:d((t,e,s)=>{const n=performance.now()-l;console.log(`${w.bold}--> ${w.reset}${w.bgBlue} ${t} ${w.reset} ${e} ${w.yellow}${s}${w.reset} ${w.magenta}${n.toFixed(2)}ms${w.reset}`)},"response"),info:d((t,...e)=>S("info",t,...e),"info"),warn:d((t,...e)=>S("warn",t,...e),"warn"),error:d((t,...e)=>S("error",t,...e),"error"),debug:d((t,...e)=>S("debug",t,...e),"debug"),success:d((t,...e)=>S("success",t,...e),"success")}}d(Y,"logger");function ee(l={}){const{methods:t,allowedHeaders:e,credentials:s,exposedHeaders:n,maxAge:r,origin:i}=l;return async(o,a)=>{const c=o.req.headers.get("origin")||"";let h="*";return typeof i=="string"?h=i:i instanceof RegExp?h=i.test(c)?c:"":Array.isArray(i)?h=i.some(f=>{if(typeof f=="string")return f===c;if(f instanceof RegExp)return f.test(c)})?c:"":typeof i=="function"&&(h=i(c)?c:""),o.headers.set("Access-Control-Allow-Origin",h),o.headers.set("Access-Control-Allow-Methods",(t||["GET","POST","PUT","DELETE"]).join(", ")),o.headers.set("Access-Control-Allow-Headers",(e||["Content-Type","Authorization"]).join(", ")),n&&o.headers.set("Access-Control-Expose-Headers",n.join(", ")),s&&o.headers.set("Access-Control-Allow-Credentials","true"),r&&o.headers.set("Access-Control-Max-Age",r.toString()),o.req.method==="OPTIONS"?new Response(null,{status:204,headers:o.headers.toObject()}):await a()}}d(ee,"cors");export{K as Accelero,B as JetResponse,$ as Router,J as bunAdapter,ee as cors,W as denoAdapter,X as loadEnv,Y as logger,V as nodeAdapter};
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "tezx",
3
+ "version": "1.0.0",
4
+ "description": "A high-performance server framework for Node.js, Bun, and Deno",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "typings": "dist/index.d.ts",
9
+ "scripts": {
10
+ "build": "tsc",
11
+ "dev": "nodemon --watch src --exec ts-node src/index.ts",
12
+ "start": "node dist/index.js"
13
+ },
14
+ "files": [
15
+ "dist/",
16
+ "dist/index.js",
17
+ "dist/index.mjs",
18
+ "dist/index.js.map",
19
+ "dist/index.d.ts",
20
+ "dist/index.mjs.map"
21
+ ],
22
+ "keywords": [
23
+ "server",
24
+ "framework",
25
+ "http",
26
+ "middleware",
27
+ "router",
28
+ "high-performance",
29
+ "node",
30
+ "bun",
31
+ "deno"
32
+ ],
33
+ "author": "SRAKIB17",
34
+ "license": "MIT"
35
+ }