@oxog/spark 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/LICENSE +21 -0
  3. package/README.md +242 -0
  4. package/dist/LICENSE +21 -0
  5. package/dist/README.md +242 -0
  6. package/dist/core/application.js +957 -0
  7. package/dist/core/context.js +831 -0
  8. package/dist/core/middleware.js +218 -0
  9. package/dist/core/request.js +333 -0
  10. package/dist/core/response.js +375 -0
  11. package/dist/index.js +278 -0
  12. package/dist/middleware/body-parser.js +526 -0
  13. package/dist/middleware/cache.js +171 -0
  14. package/dist/middleware/compression.js +183 -0
  15. package/dist/middleware/cors.js +95 -0
  16. package/dist/middleware/health.js +219 -0
  17. package/dist/middleware/index.js +21 -0
  18. package/dist/middleware/logger.js +195 -0
  19. package/dist/middleware/metrics.js +328 -0
  20. package/dist/middleware/rate-limit.js +320 -0
  21. package/dist/middleware/security.js +333 -0
  22. package/dist/middleware/session.js +530 -0
  23. package/dist/middleware/static.js +299 -0
  24. package/dist/package.json +62 -0
  25. package/dist/router/layer.js +117 -0
  26. package/dist/router/route.js +123 -0
  27. package/dist/router/router.js +756 -0
  28. package/dist/types/index.d.ts +291 -0
  29. package/dist/utils/async-handler.js +145 -0
  30. package/dist/utils/cache.js +441 -0
  31. package/dist/utils/context-pool.js +83 -0
  32. package/dist/utils/error-types.js +132 -0
  33. package/dist/utils/http.js +413 -0
  34. package/dist/utils/regex-validator.js +177 -0
  35. package/package.json +89 -0
  36. package/src/core/application.js +957 -0
  37. package/src/core/context.js +831 -0
  38. package/src/core/middleware.js +218 -0
  39. package/src/core/request.js +333 -0
  40. package/src/core/response.js +375 -0
  41. package/src/index.js +278 -0
  42. package/src/middleware/body-parser.js +526 -0
  43. package/src/middleware/cache.js +171 -0
  44. package/src/middleware/compression.js +183 -0
  45. package/src/middleware/cors.js +95 -0
  46. package/src/middleware/health.js +219 -0
  47. package/src/middleware/index.js +21 -0
  48. package/src/middleware/logger.js +195 -0
  49. package/src/middleware/metrics.js +328 -0
  50. package/src/middleware/rate-limit.js +320 -0
  51. package/src/middleware/security.js +333 -0
  52. package/src/middleware/session.js +530 -0
  53. package/src/middleware/static.js +299 -0
  54. package/src/router/layer.js +117 -0
  55. package/src/router/route.js +123 -0
  56. package/src/router/router.js +756 -0
  57. package/src/utils/async-handler.js +145 -0
  58. package/src/utils/cache.js +441 -0
  59. package/src/utils/context-pool.js +83 -0
  60. package/src/utils/error-types.js +132 -0
  61. package/src/utils/http.js +413 -0
  62. package/src/utils/regex-validator.js +177 -0
  63. package/types/index.d.ts +291 -0
@@ -0,0 +1,291 @@
1
+ declare module '@oxog/spark' {
2
+ // Basic types without Node.js dependencies
3
+ interface IncomingMessage {
4
+ url?: string;
5
+ method?: string;
6
+ headers: Record<string, string | string[] | undefined>;
7
+ }
8
+
9
+ interface ServerResponse {
10
+ statusCode: number;
11
+ setHeader(name: string, value: string | string[]): void;
12
+ writeHead(statusCode: number, headers?: Record<string, string | string[]>): void;
13
+ write(chunk: any): boolean;
14
+ end(chunk?: any): void;
15
+ }
16
+
17
+ interface Server {
18
+ listen(port?: number, hostname?: string, callback?: () => void): void;
19
+ close(callback?: () => void): void;
20
+ address(): { address: string; port: number } | null;
21
+ }
22
+
23
+ export interface AppOptions {
24
+ port?: number;
25
+ host?: string;
26
+ cluster?: boolean;
27
+ compression?: boolean;
28
+ security?: {
29
+ cors?: CorsOptions;
30
+ rateLimit?: RateLimitOptions;
31
+ csrf?: boolean;
32
+ };
33
+ https?: {
34
+ key: string;
35
+ cert: string;
36
+ };
37
+ }
38
+
39
+ export interface Context<TState = any> {
40
+ req: IncomingMessage;
41
+ res: ServerResponse;
42
+ app: Spark;
43
+ method: string;
44
+ url: string;
45
+ path: string;
46
+ query: Record<string, string | string[]>;
47
+ params: Record<string, string>;
48
+ headers: Record<string, string>;
49
+ cookies: Record<string, string>;
50
+ body: any;
51
+ files: Record<string, UploadedFile> | null;
52
+ session: any;
53
+ state: TState;
54
+ responded: boolean;
55
+ statusCode: number;
56
+
57
+ get(headerName: string): string | undefined;
58
+ set(headerName: string, value: string): Context;
59
+ setHeader(name: string, value: string): Context;
60
+ getHeader(name: string): string | undefined;
61
+ removeHeader(name: string): Context;
62
+ status(code: number): Context;
63
+ redirect(url: string, status?: number): Context;
64
+ json(data: any): Context;
65
+ text(data: string): Context;
66
+ html(data: string): Context;
67
+ send(data: any): Context;
68
+ end(data?: any): Context;
69
+ setCookie(name: string, value: string, options?: CookieOptions): Context;
70
+ clearCookie(name: string, options?: CookieOptions): Context;
71
+ }
72
+
73
+ export interface UploadedFile {
74
+ filename: string;
75
+ contentType: string;
76
+ size: number;
77
+ data: any;
78
+ }
79
+
80
+ export interface CookieOptions {
81
+ maxAge?: number;
82
+ expires?: Date;
83
+ path?: string;
84
+ domain?: string;
85
+ secure?: boolean;
86
+ httpOnly?: boolean;
87
+ sameSite?: 'strict' | 'lax' | 'none';
88
+ }
89
+
90
+ export type Middleware<TState = any> = (
91
+ ctx: Context<TState>,
92
+ next: () => Promise<void>
93
+ ) => Promise<void> | void;
94
+
95
+ export interface RouterOptions {
96
+ prefix?: string;
97
+ strict?: boolean;
98
+ sensitive?: boolean;
99
+ }
100
+
101
+ export interface Route {
102
+ method: string;
103
+ path: string;
104
+ middleware: Middleware[];
105
+ }
106
+
107
+ export class Router {
108
+ constructor(options?: RouterOptions);
109
+ use(...middleware: Middleware[]): Router;
110
+ get(path: string, ...middleware: Middleware[]): Router;
111
+ post(path: string, ...middleware: Middleware[]): Router;
112
+ put(path: string, ...middleware: Middleware[]): Router;
113
+ patch(path: string, ...middleware: Middleware[]): Router;
114
+ delete(path: string, ...middleware: Middleware[]): Router;
115
+ head(path: string, ...middleware: Middleware[]): Router;
116
+ options(path: string, ...middleware: Middleware[]): Router;
117
+ all(path: string, ...middleware: Middleware[]): Router;
118
+ prefix(prefix: string): Router;
119
+ group(prefix: string, fn: (router: Router) => void): Router;
120
+ routes(): Middleware;
121
+ middleware(prefix?: string): Middleware;
122
+ }
123
+
124
+ export class Spark {
125
+ constructor(options?: AppOptions);
126
+ options: AppOptions;
127
+ server?: Server;
128
+ listening: boolean;
129
+
130
+ use(path?: string | Middleware, ...middleware: Middleware[]): Spark;
131
+ get(path: string, ...middleware: Middleware[]): Spark;
132
+ post(path: string, ...middleware: Middleware[]): Spark;
133
+ put(path: string, ...middleware: Middleware[]): Spark;
134
+ patch(path: string, ...middleware: Middleware[]): Spark;
135
+ delete(path: string, ...middleware: Middleware[]): Spark;
136
+ head(path: string, ...middleware: Middleware[]): Spark;
137
+ options(path: string, ...middleware: Middleware[]): Spark;
138
+ all(path: string, ...middleware: Middleware[]): Spark;
139
+
140
+ listen(port?: number, host?: string, callback?: () => void): Promise<void>;
141
+ close(): Promise<void>;
142
+ handleError(error: Error, ctx?: Context): void;
143
+ onShutdown(handler: () => Promise<void> | void): void;
144
+
145
+ on(event: 'error', listener: (error: Error, ctx?: Context) => void): Spark;
146
+ on(event: 'listening', listener: () => void): Spark;
147
+ on(event: string, listener: (...args: any[]) => void): Spark;
148
+
149
+ emit(event: 'error', error: Error, ctx?: Context): boolean;
150
+ emit(event: 'listening'): boolean;
151
+ emit(event: string, ...args: any[]): boolean;
152
+ }
153
+
154
+ // Middleware types
155
+ export interface CorsOptions {
156
+ origin?: boolean | string | string[] | ((ctx: Context) => string | boolean);
157
+ credentials?: boolean;
158
+ methods?: string[];
159
+ allowedHeaders?: string[];
160
+ exposedHeaders?: string[];
161
+ maxAge?: number;
162
+ }
163
+
164
+ export interface RateLimitOptions {
165
+ max?: number;
166
+ windowMs?: number;
167
+ message?: string;
168
+ keyGenerator?: (ctx: Context) => string;
169
+ skip?: (ctx: Context) => boolean;
170
+ standardHeaders?: boolean;
171
+ legacyHeaders?: boolean;
172
+ }
173
+
174
+ export interface SessionOptions {
175
+ key?: string;
176
+ secret: string;
177
+ store?: any;
178
+ cookie?: {
179
+ maxAge?: number;
180
+ httpOnly?: boolean;
181
+ secure?: boolean;
182
+ sameSite?: 'strict' | 'lax' | 'none';
183
+ path?: string;
184
+ domain?: string;
185
+ };
186
+ genid?: () => string;
187
+ rolling?: boolean;
188
+ resave?: boolean;
189
+ saveUninitialized?: boolean;
190
+ }
191
+
192
+ export interface StaticOptions {
193
+ root?: string;
194
+ index?: string | string[];
195
+ hidden?: boolean;
196
+ extensions?: string[];
197
+ redirect?: boolean;
198
+ maxAge?: number;
199
+ }
200
+
201
+ export interface CompressionOptions {
202
+ threshold?: number;
203
+ level?: number;
204
+ filter?: (ctx: Context) => boolean;
205
+ }
206
+
207
+ export interface BodyParserOptions {
208
+ json?: boolean;
209
+ urlencoded?: boolean;
210
+ text?: boolean;
211
+ multipart?: boolean;
212
+ limit?: string | number;
213
+ }
214
+
215
+ // Middleware functions
216
+ export function bodyParser(options?: BodyParserOptions): Middleware;
217
+ export function cors(options?: CorsOptions): Middleware;
218
+ export function compression(options?: CompressionOptions): Middleware;
219
+ export function rateLimit(options?: RateLimitOptions): Middleware;
220
+ export function session(options: SessionOptions): Middleware;
221
+ export function security(options?: any): Middleware;
222
+ export function healthCheck(options?: any): Middleware;
223
+ export function metrics(options?: any): Middleware;
224
+ export function logger(options?: any): Middleware;
225
+
226
+ // Main exports
227
+ export const Application: typeof Spark;
228
+ export const App: typeof Spark;
229
+
230
+ // Error handling utilities
231
+ export const errorHandling: {
232
+ asyncHandler: (fn: Middleware) => Middleware;
233
+ errorHandler: () => Middleware;
234
+ createError: (status: number, message: string) => Error;
235
+ errors: {
236
+ badRequest: (message?: string) => Error;
237
+ unauthorized: (message?: string) => Error;
238
+ forbidden: (message?: string) => Error;
239
+ notFound: (message?: string) => Error;
240
+ conflict: (message?: string) => Error;
241
+ tooManyRequests: (message?: string) => Error;
242
+ internalServerError: (message?: string) => Error;
243
+ };
244
+ };
245
+
246
+ // Middleware collection
247
+ export const middleware: {
248
+ bodyParser: typeof bodyParser;
249
+ cors: typeof cors;
250
+ compression: typeof compression;
251
+ static: (root: string, options?: StaticOptions) => Middleware;
252
+ session: typeof session;
253
+ rateLimit: typeof rateLimit;
254
+ security: typeof security;
255
+ helmet: typeof security;
256
+ healthCheck: typeof healthCheck;
257
+ health: typeof healthCheck;
258
+ metrics: typeof metrics;
259
+ logger: typeof logger;
260
+ cache: (options?: any) => Middleware;
261
+ compress: typeof compression;
262
+ };
263
+
264
+ // Utility classes
265
+ export const utils: {
266
+ ContextPool: any;
267
+ RegexValidator: any;
268
+ SafeRegexCache: any;
269
+ };
270
+
271
+ // Default export for ES6 compatibility
272
+ export default {
273
+ Spark,
274
+ App,
275
+ Application,
276
+ Router,
277
+ Context,
278
+ middleware,
279
+ bodyParser,
280
+ cors,
281
+ compression,
282
+ rateLimit,
283
+ session,
284
+ security,
285
+ healthCheck,
286
+ metrics,
287
+ logger,
288
+ errorHandling,
289
+ utils
290
+ };
291
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Wraps async route handlers to properly catch errors
3
+ * @param {Function} fn - Async function to wrap
4
+ * @returns {Function} Wrapped function that catches errors
5
+ */
6
+ function asyncHandler(fn) {
7
+ return (ctx, next) => {
8
+ const result = fn(ctx, next);
9
+
10
+ // If it's a promise, catch any errors
11
+ if (result && typeof result.then === 'function') {
12
+ return result.catch((error) => {
13
+ // Pass error to the next middleware
14
+ return next(error);
15
+ });
16
+ }
17
+
18
+ return result;
19
+ };
20
+ }
21
+
22
+ /**
23
+ * Wraps all methods of a router or controller
24
+ * @param {Object} target - Object with methods to wrap
25
+ * @returns {Object} Object with wrapped methods
26
+ */
27
+ function wrapAsync(target) {
28
+ const wrapped = {};
29
+
30
+ for (const key in target) {
31
+ if (typeof target[key] === 'function') {
32
+ wrapped[key] = asyncHandler(target[key]);
33
+ } else {
34
+ wrapped[key] = target[key];
35
+ }
36
+ }
37
+
38
+ return wrapped;
39
+ }
40
+
41
+ /**
42
+ * Error handler middleware that can work as both regular middleware and error handler
43
+ * @param {Error|Context} errOrCtx - Error object or Context (when used as regular middleware)
44
+ * @param {Context|Function} ctxOrNext - Context or next function
45
+ * @param {Function} [next] - Next middleware function
46
+ */
47
+ function errorHandler(errOrCtx, ctxOrNext, next) {
48
+ // Check if this is being used as error handler (3 args) or regular middleware (2 args)
49
+ if (next && typeof next === 'function') {
50
+ // This is an error handler (err, ctx, next)
51
+ const err = errOrCtx;
52
+ const ctx = ctxOrNext;
53
+
54
+ // Skip if response already sent
55
+ if (ctx.responded) {
56
+ return;
57
+ }
58
+
59
+ // Log error for debugging
60
+ console.error('Error handler caught:', err);
61
+
62
+ // Set status code
63
+ const status = err.status || err.statusCode || 500;
64
+ ctx.status(status);
65
+
66
+ handleErrorResponse(err, ctx, status);
67
+ } else {
68
+ // This is regular middleware (ctx, next)
69
+ const ctx = errOrCtx;
70
+ const nextFn = ctxOrNext;
71
+
72
+ // Just pass through - this shouldn't normally happen
73
+ return nextFn();
74
+ }
75
+ }
76
+
77
+ function handleErrorResponse(err, ctx, status) {
78
+ // Prepare error response
79
+ const isDevelopment = process.env.NODE_ENV !== 'production';
80
+ const errorResponse = {
81
+ error: err.message || 'Internal Server Error',
82
+ status: status
83
+ };
84
+
85
+ // Add stack trace in development
86
+ if (isDevelopment) {
87
+ errorResponse.stack = err.stack;
88
+ }
89
+
90
+ // Add any additional error properties
91
+ if (err.code) {
92
+ errorResponse.code = err.code;
93
+ }
94
+
95
+ if (err.details) {
96
+ errorResponse.details = err.details;
97
+ }
98
+
99
+ // Send error response
100
+ ctx.json(errorResponse);
101
+ }
102
+
103
+ /**
104
+ * Creates a custom error with status code
105
+ * @param {string} message - Error message
106
+ * @param {number} status - HTTP status code
107
+ * @param {string} code - Error code
108
+ * @returns {Error} Custom error object
109
+ */
110
+ function createError(message, status = 500, code = null) {
111
+ const error = new Error(message);
112
+ error.status = status;
113
+ if (code) {
114
+ error.code = code;
115
+ }
116
+ return error;
117
+ }
118
+
119
+ /**
120
+ * Common HTTP errors
121
+ */
122
+ const errors = {
123
+ badRequest: (message = 'Bad Request') => createError(message, 400, 'BAD_REQUEST'),
124
+ unauthorized: (message = 'Unauthorized') => createError(message, 401, 'UNAUTHORIZED'),
125
+ forbidden: (message = 'Forbidden') => createError(message, 403, 'FORBIDDEN'),
126
+ notFound: (message = 'Not Found') => createError(message, 404, 'NOT_FOUND'),
127
+ methodNotAllowed: (message = 'Method Not Allowed') => createError(message, 405, 'METHOD_NOT_ALLOWED'),
128
+ conflict: (message = 'Conflict') => createError(message, 409, 'CONFLICT'),
129
+ gone: (message = 'Gone') => createError(message, 410, 'GONE'),
130
+ unprocessableEntity: (message = 'Unprocessable Entity') => createError(message, 422, 'UNPROCESSABLE_ENTITY'),
131
+ tooManyRequests: (message = 'Too Many Requests') => createError(message, 429, 'TOO_MANY_REQUESTS'),
132
+ internalServerError: (message = 'Internal Server Error') => createError(message, 500, 'INTERNAL_SERVER_ERROR'),
133
+ notImplemented: (message = 'Not Implemented') => createError(message, 501, 'NOT_IMPLEMENTED'),
134
+ badGateway: (message = 'Bad Gateway') => createError(message, 502, 'BAD_GATEWAY'),
135
+ serviceUnavailable: (message = 'Service Unavailable') => createError(message, 503, 'SERVICE_UNAVAILABLE'),
136
+ gatewayTimeout: (message = 'Gateway Timeout') => createError(message, 504, 'GATEWAY_TIMEOUT')
137
+ };
138
+
139
+ module.exports = {
140
+ asyncHandler,
141
+ wrapAsync,
142
+ errorHandler,
143
+ createError,
144
+ errors
145
+ };