@naman_deep_singh/server-utils 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,238 +1,281 @@
1
1
  # @naman_deep_singh/server-utils
2
2
 
3
- Extensible server utilities for Express.js microservices with TypeScript. Provides a plugin-based architecture for building consistent and maintainable server applications.
4
-
5
- ## Features
6
-
7
- - 🚀 **Express Server Factory** - Quick server setup with sensible defaults
8
- - 🔌 **Plugin System** - Extensible architecture for custom functionality
9
- - 🏥 **Health Checks** - Built-in health monitoring with custom checks
10
- - 🛑 **Graceful Shutdown** - Proper cleanup and shutdown handling
11
- - 📝 **Logging Middleware** - Request logging with customizable formats
12
- - 🛡️ **Error Handling** - Centralized error handling middleware
13
- - 🆔 **Request ID** - Automatic request ID generation and tracking
3
+ Extensible server utilities for Express.js microservices with multi-protocol support and TypeScript.
14
4
 
15
5
  ## Installation
16
6
 
17
7
  ```bash
18
8
  npm install @naman_deep_singh/server-utils
19
- # or
20
- pnpm add @naman_deep_singh/server-utils
21
9
  ```
22
10
 
11
+ ## Features
12
+
13
+ - ✅ **Multi-protocol support** - HTTP, gRPC, JSON-RPC, WebSockets, Webhooks
14
+ - ✅ **Express.js integration** with middleware collection
15
+ - ✅ **Graceful shutdown** handling
16
+ - ✅ **Health checks** with custom checks support
17
+ - ✅ **TypeScript support** with full type safety
18
+ - ✅ **Hybrid exports** - use named imports or namespace imports
19
+ - ✅ **Plugin architecture** for extensibility
20
+ - ✅ **Built-in middleware** - logging, validation, rate limiting, auth
21
+
23
22
  ## Quick Start
24
23
 
25
- ### Basic Server
24
+ ### Named Imports
26
25
  ```typescript
27
- import { createServer, startServerWithShutdown } from '@naman_deep_singh/server-utils';
26
+ import { createServer } from '@naman_deep_singh/server-utils';
28
27
 
29
- const app = createServer({
28
+ const server = createServer('My API', '1.0.0', {
29
+ port: 3000,
30
30
  cors: true,
31
- helmet: true,
32
- healthCheck: true
31
+ helmet: true
33
32
  });
34
33
 
35
- app.get('/', (req, res) => {
36
- res.json({ message: 'Hello World!' });
34
+ // Add routes
35
+ server.app.get('/users', (req, res) => {
36
+ res.json({ users: [] });
37
37
  });
38
38
 
39
- startServerWithShutdown(app, 3000);
39
+ // Start server
40
+ await server.start();
40
41
  ```
41
42
 
42
- ### Plugin-Based Architecture
43
+ ### Namespace Import
43
44
  ```typescript
44
- import {
45
- createServerWithPlugins,
46
- withHealthCheck,
47
- withLogging,
48
- withErrorHandler,
49
- withGracefulShutdown,
50
- startServerWithShutdown
51
- } from '@naman_deep_singh/server-utils';
52
-
53
- const app = createServerWithPlugins(
54
- { cors: true, helmet: true },
55
- withLogging('detailed'),
56
- withHealthCheck('/health', {
57
- customChecks: [
58
- {
59
- name: 'database',
60
- check: async () => {
61
- // Your database health check
62
- return true;
63
- }
64
- }
65
- ]
66
- }),
67
- withErrorHandler(),
68
- withGracefulShutdown({
69
- timeout: 15000,
70
- onShutdown: async () => {
71
- console.log('Cleaning up resources...');
72
- // Your cleanup logic
73
- }
74
- })
75
- );
76
-
77
- // Add your routes
78
- app.get('/api/users', (req, res) => {
79
- res.json({ users: [] });
80
- });
45
+ import ServerUtils from '@naman_deep_singh/server-utils';
81
46
 
82
- startServerWithShutdown(app, 3000);
47
+ const server = ServerUtils.createServer('My API', '1.0.0');
83
48
  ```
84
49
 
85
- ## API Reference
50
+ ## Multi-Protocol Support
86
51
 
87
- ### Server Factory
52
+ ### HTTP + Express Routes
53
+ ```typescript
54
+ const server = createServer('Multi-Protocol Server', '1.0.0');
88
55
 
89
- #### `createServer(config?: ServerConfig)`
90
- Creates an Express application with default middleware.
56
+ server.app.get('/api/users', (req, res) => {
57
+ res.json({ users: [] });
58
+ });
91
59
 
92
- ```typescript
93
- interface ServerConfig {
94
- port?: number;
95
- cors?: boolean | CorsOptions;
96
- helmet?: boolean;
97
- json?: boolean;
98
- customMiddleware?: express.RequestHandler[];
99
- healthCheck?: boolean | string;
100
- gracefulShutdown?: boolean;
101
- }
60
+ await server.start();
102
61
  ```
103
62
 
104
- #### `createServerWithPlugins(config, ...plugins)`
105
- Creates a server and applies multiple plugins.
63
+ ### gRPC Support
64
+ ```typescript
65
+ // Add gRPC service (requires @grpc/grpc-js)
66
+ server.addGrpcService(userProto.UserService.service, {
67
+ getUser: (call, callback) => {
68
+ callback(null, { id: call.request.id, name: 'John' });
69
+ }
70
+ }, 50051); // Custom port
71
+ ```
106
72
 
107
- ### Health Checks
73
+ ### JSON-RPC Support
74
+ ```typescript
75
+ // Add JSON-RPC methods (requires jayson)
76
+ server.addRpcMethods({
77
+ add: (params, callback) => {
78
+ callback(null, params[0] + params[1]);
79
+ },
80
+ getUser: (id, callback) => {
81
+ callback(null, { id, name: 'John' });
82
+ }
83
+ }, '/rpc'); // Custom path
84
+ ```
108
85
 
109
- #### `withHealthCheck(path?, config?)`
110
- Adds health check endpoint as a plugin.
86
+ ### WebSocket Support
87
+ ```typescript
88
+ // Add Socket.IO (requires socket.io)
89
+ const io = server.addSocketIO({
90
+ cors: true,
91
+ onConnection: (socket) => {
92
+ console.log('Client connected:', socket.id);
93
+
94
+ socket.on('message', (data) => {
95
+ socket.broadcast.emit('message', data);
96
+ });
97
+ },
98
+ onDisconnection: (socket, reason) => {
99
+ console.log('Client disconnected:', socket.id, reason);
100
+ }
101
+ });
102
+ ```
111
103
 
104
+ ### Webhook Support
112
105
  ```typescript
113
- withHealthCheck('/health', {
114
- customChecks: [
115
- {
116
- name: 'redis',
117
- check: async () => await redis.ping()
106
+ // Add secure webhooks
107
+ server.addWebhook({
108
+ path: '/webhooks/github',
109
+ secret: process.env.GITHUB_WEBHOOK_SECRET,
110
+ handler: async (payload, headers) => {
111
+ if (payload.action === 'opened') {
112
+ console.log('New PR opened:', payload.pull_request.title);
118
113
  }
119
- ]
120
- })
114
+ }
115
+ });
116
+
117
+ server.addWebhook({
118
+ path: '/webhooks/stripe',
119
+ secret: process.env.STRIPE_WEBHOOK_SECRET,
120
+ handler: async (payload) => {
121
+ if (payload.type === 'payment_intent.succeeded') {
122
+ // Handle successful payment
123
+ }
124
+ }
125
+ });
121
126
  ```
122
127
 
123
- #### `addHealthCheck(app, path?, config?)`
124
- Directly adds health check to existing app.
128
+ ## Built-in Middleware
125
129
 
126
- ### Graceful Shutdown
130
+ ### Logging Middleware
131
+ ```typescript
132
+ import { createLoggingMiddleware, withLogging } from '@naman_deep_singh/server-utils';
133
+
134
+ // Direct usage
135
+ server.app.use(createLoggingMiddleware('detailed'));
127
136
 
128
- #### `withGracefulShutdown(config?)`
129
- Adds graceful shutdown as a plugin.
137
+ // Plugin usage
138
+ const server = createServerWithPlugins('My API', '1.0.0', [
139
+ withLogging('detailed')
140
+ ]);
141
+ ```
130
142
 
143
+ ### Validation Middleware
131
144
  ```typescript
132
- withGracefulShutdown({
133
- timeout: 10000,
134
- onShutdown: async () => {
135
- await database.close();
136
- await redis.disconnect();
137
- }
138
- })
145
+ import { validateFields } from '@naman_deep_singh/server-utils';
146
+
147
+ server.app.post('/users', validateFields([
148
+ { field: 'email', required: true, type: 'email' },
149
+ { field: 'password', required: true, minLength: 8 },
150
+ { field: 'age', type: 'number', custom: (value) => value >= 18 || 'Must be 18+' }
151
+ ]), (req, res) => {
152
+ // Validation passed
153
+ res.json({ success: true });
154
+ });
139
155
  ```
140
156
 
141
- #### `startServerWithShutdown(app, port, config?)`
142
- Starts server with automatic graceful shutdown setup.
157
+ ### Rate Limiting
158
+ ```typescript
159
+ import { rateLimit } from '@naman_deep_singh/server-utils';
143
160
 
144
- ### Middleware Plugins
161
+ server.app.use('/api', rateLimit({
162
+ windowMs: 15 * 60 * 1000, // 15 minutes
163
+ maxRequests: 100,
164
+ message: 'Too many requests'
165
+ }));
166
+ ```
145
167
 
146
- #### `withLogging(format?)`
147
- Adds request logging middleware.
148
- - `format`: 'simple' | 'detailed'
168
+ ### Authentication Middleware
169
+ ```typescript
170
+ import { requireAuth } from '@naman_deep_singh/server-utils';
149
171
 
150
- #### `withErrorHandler()`
151
- Adds centralized error handling middleware.
172
+ server.app.use('/protected', requireAuth({
173
+ tokenExtractor: (req) => req.headers.authorization?.substring(7),
174
+ tokenValidator: async (token) => {
175
+ // Verify JWT token
176
+ return jwt.verify(token, process.env.JWT_SECRET);
177
+ }
178
+ }));
179
+ ```
152
180
 
153
- #### `withRequestId()`
154
- Adds request ID generation and tracking.
181
+ ## Health Checks
155
182
 
156
- ### Custom Plugins
183
+ ```typescript
184
+ import { addHealthCheck } from '@naman_deep_singh/server-utils';
157
185
 
158
- Create your own plugins:
186
+ addHealthCheck(server.app, '/health', {
187
+ customChecks: [
188
+ {
189
+ name: 'database',
190
+ check: async () => {
191
+ // Check database connection
192
+ return await db.ping();
193
+ }
194
+ },
195
+ {
196
+ name: 'redis',
197
+ check: async () => {
198
+ return await redis.ping() === 'PONG';
199
+ }
200
+ }
201
+ ]
202
+ });
203
+ ```
204
+
205
+ ## Server Management
159
206
 
207
+ ### Server Information
160
208
  ```typescript
161
- import { ServerPlugin } from '@naman_deep_singh/server-utils';
209
+ const info = server.getInfo();
210
+ console.log(info);
211
+ // {
212
+ // name: 'My API',
213
+ // version: '1.0.0',
214
+ // port: 3000,
215
+ // uptime: 12345,
216
+ // status: 'running',
217
+ // startTime: Date
218
+ // }
219
+ ```
162
220
 
163
- const withCustomAuth = (secretKey: string): ServerPlugin => {
164
- return (app, config) => {
165
- app.use((req, res, next) => {
166
- // Your custom auth logic
167
- next();
168
- });
169
- };
170
- };
221
+ ### Graceful Shutdown
222
+ ```typescript
223
+ const server = createServer('My API', '1.0.0', {
224
+ gracefulShutdown: true // Enabled by default
225
+ });
171
226
 
172
- // Use it
173
- const app = createServerWithPlugins(
174
- {},
175
- withCustomAuth('my-secret'),
176
- withLogging()
177
- );
227
+ // Handles SIGINT and SIGTERM
228
+ process.on('SIGINT', async () => {
229
+ await server.stop();
230
+ process.exit(0);
231
+ });
178
232
  ```
179
233
 
180
- ## Examples
234
+ ## Configuration Options
181
235
 
182
- ### Microservice Template
183
236
  ```typescript
184
- import {
185
- createServerWithPlugins,
186
- withHealthCheck,
187
- withLogging,
188
- withErrorHandler,
189
- withRequestId,
190
- startServerWithShutdown
191
- } from '@naman_deep_singh/server-utils';
192
-
193
- const app = createServerWithPlugins(
194
- {
195
- cors: {
196
- origin: process.env.ALLOWED_ORIGINS?.split(',') || '*',
197
- credentials: true
198
- },
199
- helmet: true
200
- },
201
- withRequestId(),
202
- withLogging(process.env.NODE_ENV === 'production' ? 'simple' : 'detailed'),
203
- withHealthCheck('/health', {
204
- customChecks: [
205
- {
206
- name: 'database',
207
- check: async () => {
208
- try {
209
- await prisma.$queryRaw`SELECT 1`;
210
- return true;
211
- } catch {
212
- return false;
213
- }
214
- }
215
- }
216
- ]
217
- }),
218
- withErrorHandler()
219
- );
220
-
221
- // Your routes
222
- app.use('/api', apiRoutes);
223
-
224
- const PORT = Number(process.env.PORT) || 3000;
225
- startServerWithShutdown(app, PORT, {
226
- onShutdown: async () => {
227
- await prisma.$disconnect();
228
- }
229
- });
237
+ interface ServerConfig {
238
+ port?: number; // Default: 3000
239
+ cors?: boolean | CorsOptions; // Default: true
240
+ helmet?: boolean; // Default: true
241
+ json?: boolean; // Default: true
242
+ customMiddleware?: RequestHandler[];
243
+ healthCheck?: boolean | string; // Default: true
244
+ gracefulShutdown?: boolean; // Default: true
245
+ socketIO?: SocketIOConfig;
246
+ }
230
247
  ```
231
248
 
232
- ## TypeScript Support
249
+ ## API Reference
250
+
251
+ ### Core Functions
252
+ - `createServer(name?, version?, config?)` - Create server instance
253
+ - `ExpressServer` - Server class for advanced usage
254
+
255
+ ### Middleware Functions
256
+ - `createLoggingMiddleware(format?)` - Request logging
257
+ - `createErrorHandler()` - Error handling
258
+ - `createValidationMiddleware(rules)` - Input validation
259
+ - `createRateLimitMiddleware(config?)` - Rate limiting
260
+ - `createAuthMiddleware(config)` - Authentication
261
+
262
+ ### Health & Monitoring
263
+ - `createHealthCheck(config?)` - Health check endpoint
264
+ - `addHealthCheck(app, path?, config?)` - Add health check to app
265
+
266
+ ### Graceful Shutdown
267
+ - `createGracefulShutdown(server, config?)` - Setup graceful shutdown
268
+ - `startServerWithShutdown(app, port, config?)` - Start with shutdown handling
233
269
 
234
- Full TypeScript support with comprehensive type definitions for all utilities and plugins.
270
+ ## Dependencies
235
271
 
236
- ## License
272
+ ### Required
273
+ - **express** - Web framework
274
+ - **cors** - CORS middleware
275
+ - **helmet** - Security middleware
276
+ - **cookie-parser** - Cookie parsing
237
277
 
238
- ISC
278
+ ### Optional (for specific features)
279
+ - **@grpc/grpc-js** - For gRPC support
280
+ - **jayson** - For JSON-RPC support
281
+ - **socket.io** - For WebSocket support
package/dist/index.d.ts CHANGED
@@ -1,6 +1,41 @@
1
- export { createServer, withPlugin, createServerWithPlugins } from './server';
1
+ export { ExpressServer, createServer } from './server';
2
+ export type { ServerInstance, ServerInfo, GrpcService, RpcMethod, WebhookConfig } from './server';
2
3
  export { createHealthCheck, withHealthCheck, addHealthCheck } from './health';
3
4
  export { createGracefulShutdown, withGracefulShutdown, startServerWithShutdown } from './shutdown';
4
5
  export { createLoggingMiddleware, createErrorHandler, createRequestIdMiddleware, createValidationMiddleware, createRateLimitMiddleware, createAuthMiddleware, withLogging, withErrorHandler, withRequestId, withValidation, withRateLimit, withAuth, validateFields, rateLimit, requireAuth, type ValidationRule, type RateLimitConfig, type AuthConfig } from './middleware';
5
6
  export { getEnv, getEnvNumber, getEnvBoolean } from './utils';
6
- export type { ServerConfig, HealthCheckConfig, HealthCheck, GracefulShutdownConfig, ServerPlugin } from './types';
7
+ export type { ServerConfig, HealthCheckConfig, HealthCheck, GracefulShutdownConfig, ServerPlugin, SocketIOConfig, SocketInstance } from './types';
8
+ import { ExpressServer, createServer } from './server';
9
+ import { createHealthCheck, withHealthCheck, addHealthCheck } from './health';
10
+ import { createGracefulShutdown, withGracefulShutdown, startServerWithShutdown } from './shutdown';
11
+ import { createLoggingMiddleware, createErrorHandler, createRequestIdMiddleware, createValidationMiddleware, createRateLimitMiddleware, createAuthMiddleware, withLogging, withErrorHandler, withRequestId, withValidation, withRateLimit, withAuth, validateFields, rateLimit, requireAuth } from './middleware';
12
+ import { getEnv, getEnvNumber, getEnvBoolean } from './utils';
13
+ declare const ServerUtils: {
14
+ createServer: typeof createServer;
15
+ ExpressServer: typeof ExpressServer;
16
+ createHealthCheck: typeof createHealthCheck;
17
+ withHealthCheck: typeof withHealthCheck;
18
+ addHealthCheck: typeof addHealthCheck;
19
+ createGracefulShutdown: typeof createGracefulShutdown;
20
+ withGracefulShutdown: typeof withGracefulShutdown;
21
+ startServerWithShutdown: typeof startServerWithShutdown;
22
+ createLoggingMiddleware: typeof createLoggingMiddleware;
23
+ createErrorHandler: typeof createErrorHandler;
24
+ createRequestIdMiddleware: typeof createRequestIdMiddleware;
25
+ createValidationMiddleware: typeof createValidationMiddleware;
26
+ createRateLimitMiddleware: typeof createRateLimitMiddleware;
27
+ createAuthMiddleware: typeof createAuthMiddleware;
28
+ withLogging: typeof withLogging;
29
+ withErrorHandler: typeof withErrorHandler;
30
+ withRequestId: typeof withRequestId;
31
+ withValidation: typeof withValidation;
32
+ withRateLimit: typeof withRateLimit;
33
+ withAuth: typeof withAuth;
34
+ validateFields: typeof validateFields;
35
+ rateLimit: typeof rateLimit;
36
+ requireAuth: typeof requireAuth;
37
+ getEnv: typeof getEnv;
38
+ getEnvNumber: typeof getEnvNumber;
39
+ getEnvBoolean: typeof getEnvBoolean;
40
+ };
41
+ export default ServerUtils;
package/dist/index.js CHANGED
@@ -1,11 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getEnvBoolean = exports.getEnvNumber = exports.getEnv = exports.requireAuth = exports.rateLimit = exports.validateFields = exports.withAuth = exports.withRateLimit = exports.withValidation = exports.withRequestId = exports.withErrorHandler = exports.withLogging = exports.createAuthMiddleware = exports.createRateLimitMiddleware = exports.createValidationMiddleware = exports.createRequestIdMiddleware = exports.createErrorHandler = exports.createLoggingMiddleware = exports.startServerWithShutdown = exports.withGracefulShutdown = exports.createGracefulShutdown = exports.addHealthCheck = exports.withHealthCheck = exports.createHealthCheck = exports.createServerWithPlugins = exports.withPlugin = exports.createServer = void 0;
3
+ exports.getEnvBoolean = exports.getEnvNumber = exports.getEnv = exports.requireAuth = exports.rateLimit = exports.validateFields = exports.withAuth = exports.withRateLimit = exports.withValidation = exports.withRequestId = exports.withErrorHandler = exports.withLogging = exports.createAuthMiddleware = exports.createRateLimitMiddleware = exports.createValidationMiddleware = exports.createRequestIdMiddleware = exports.createErrorHandler = exports.createLoggingMiddleware = exports.startServerWithShutdown = exports.withGracefulShutdown = exports.createGracefulShutdown = exports.addHealthCheck = exports.withHealthCheck = exports.createHealthCheck = exports.createServer = exports.ExpressServer = void 0;
4
4
  // Core server utilities
5
5
  var server_1 = require("./server");
6
+ Object.defineProperty(exports, "ExpressServer", { enumerable: true, get: function () { return server_1.ExpressServer; } });
6
7
  Object.defineProperty(exports, "createServer", { enumerable: true, get: function () { return server_1.createServer; } });
7
- Object.defineProperty(exports, "withPlugin", { enumerable: true, get: function () { return server_1.withPlugin; } });
8
- Object.defineProperty(exports, "createServerWithPlugins", { enumerable: true, get: function () { return server_1.createServerWithPlugins; } });
9
8
  // Health check utilities
10
9
  var health_1 = require("./health");
11
10
  Object.defineProperty(exports, "createHealthCheck", { enumerable: true, get: function () { return health_1.createHealthCheck; } });
@@ -38,3 +37,44 @@ var utils_1 = require("./utils");
38
37
  Object.defineProperty(exports, "getEnv", { enumerable: true, get: function () { return utils_1.getEnv; } });
39
38
  Object.defineProperty(exports, "getEnvNumber", { enumerable: true, get: function () { return utils_1.getEnvNumber; } });
40
39
  Object.defineProperty(exports, "getEnvBoolean", { enumerable: true, get: function () { return utils_1.getEnvBoolean; } });
40
+ // Import all exports for default export
41
+ const server_2 = require("./server");
42
+ const health_2 = require("./health");
43
+ const shutdown_2 = require("./shutdown");
44
+ const middleware_2 = require("./middleware");
45
+ const utils_2 = require("./utils");
46
+ // Default export for namespace usage
47
+ const ServerUtils = {
48
+ // Server creation
49
+ createServer: server_2.createServer,
50
+ ExpressServer: server_2.ExpressServer,
51
+ // Health checks
52
+ createHealthCheck: health_2.createHealthCheck,
53
+ withHealthCheck: health_2.withHealthCheck,
54
+ addHealthCheck: health_2.addHealthCheck,
55
+ // Graceful shutdown
56
+ createGracefulShutdown: shutdown_2.createGracefulShutdown,
57
+ withGracefulShutdown: shutdown_2.withGracefulShutdown,
58
+ startServerWithShutdown: shutdown_2.startServerWithShutdown,
59
+ // Middleware
60
+ createLoggingMiddleware: middleware_2.createLoggingMiddleware,
61
+ createErrorHandler: middleware_2.createErrorHandler,
62
+ createRequestIdMiddleware: middleware_2.createRequestIdMiddleware,
63
+ createValidationMiddleware: middleware_2.createValidationMiddleware,
64
+ createRateLimitMiddleware: middleware_2.createRateLimitMiddleware,
65
+ createAuthMiddleware: middleware_2.createAuthMiddleware,
66
+ withLogging: middleware_2.withLogging,
67
+ withErrorHandler: middleware_2.withErrorHandler,
68
+ withRequestId: middleware_2.withRequestId,
69
+ withValidation: middleware_2.withValidation,
70
+ withRateLimit: middleware_2.withRateLimit,
71
+ withAuth: middleware_2.withAuth,
72
+ validateFields: middleware_2.validateFields,
73
+ rateLimit: middleware_2.rateLimit,
74
+ requireAuth: middleware_2.requireAuth,
75
+ // Utils
76
+ getEnv: utils_2.getEnv,
77
+ getEnvNumber: utils_2.getEnvNumber,
78
+ getEnvBoolean: utils_2.getEnvBoolean
79
+ };
80
+ exports.default = ServerUtils;
@@ -10,7 +10,7 @@ export interface ValidationRule {
10
10
  minLength?: number;
11
11
  maxLength?: number;
12
12
  pattern?: RegExp;
13
- custom?: (value: any) => boolean | string;
13
+ custom?: (value: unknown) => boolean | string;
14
14
  }
15
15
  export declare function createValidationMiddleware(rules: ValidationRule[]): express.RequestHandler;
16
16
  export interface RateLimitConfig {
@@ -22,7 +22,7 @@ export interface RateLimitConfig {
22
22
  export declare function createRateLimitMiddleware(config?: RateLimitConfig): express.RequestHandler;
23
23
  export interface AuthConfig {
24
24
  tokenExtractor?: (req: express.Request) => string | null;
25
- tokenValidator?: (token: string) => Promise<any> | any;
25
+ tokenValidator?: (token: string) => Promise<unknown> | unknown;
26
26
  unauthorizedMessage?: string;
27
27
  }
28
28
  export declare function createAuthMiddleware(config: AuthConfig): express.RequestHandler;
@@ -38,14 +38,16 @@ function createErrorHandler() {
38
38
  if (res.headersSent) {
39
39
  return next(err);
40
40
  }
41
- const status = err.status || err.statusCode || 500;
41
+ // Type guard for error objects
42
+ const errorObj = err;
43
+ const status = errorObj.status || errorObj.statusCode || 500;
42
44
  const message = process.env.NODE_ENV === 'production'
43
45
  ? 'Internal Server Error'
44
- : err.message;
46
+ : errorObj.message || 'Unknown error';
45
47
  res.status(status).json({
46
48
  status: false,
47
49
  message,
48
- ...(process.env.NODE_ENV !== 'production' && { stack: err.stack })
50
+ ...(process.env.NODE_ENV !== 'production' && { stack: errorObj.stack })
49
51
  });
50
52
  };
51
53
  }
package/dist/server.d.ts CHANGED
@@ -1,5 +1,67 @@
1
1
  import express from 'express';
2
- import { ServerConfig, ServerPlugin } from './types';
3
- export declare function createServer(config?: ServerConfig): express.Application;
4
- export declare function withPlugin(app: express.Application, plugin: ServerPlugin, config?: ServerConfig): express.Application;
5
- export declare function createServerWithPlugins(config?: ServerConfig, ...plugins: ServerPlugin[]): express.Application;
2
+ import { Server } from 'http';
3
+ import { ServerConfig, SocketIOConfig } from './types';
4
+ export interface GrpcService {
5
+ service: Record<string, unknown>;
6
+ implementation: Record<string, (...args: unknown[]) => unknown>;
7
+ }
8
+ export interface RpcMethod {
9
+ [key: string]: (params: unknown[], callback: (error: Error | null, result?: unknown) => void) => void;
10
+ }
11
+ export interface WebhookConfig {
12
+ path: string;
13
+ secret?: string;
14
+ handler: (payload: Record<string, unknown>, headers: Record<string, string | string[]>) => void | Promise<void>;
15
+ }
16
+ export interface GrpcServerInstance {
17
+ start(): void;
18
+ forceShutdown(): void;
19
+ addService(service: unknown, implementation: unknown): void;
20
+ bindAsync(address: string, credentials: unknown, callback: () => void): void;
21
+ }
22
+ export interface ServerInstanceConfig extends Required<Omit<ServerConfig, 'socketIO' | 'name' | 'version'>> {
23
+ name: string;
24
+ version: string;
25
+ startTime: Date;
26
+ socketIO?: SocketIOConfig;
27
+ }
28
+ export interface ServerInstance {
29
+ app: express.Application;
30
+ server?: Server;
31
+ config: ServerInstanceConfig;
32
+ start(): Promise<ServerInstance>;
33
+ stop(): Promise<void>;
34
+ getInfo(): ServerInfo;
35
+ addGrpcService(service: Record<string, unknown>, implementation: Record<string, (...args: unknown[]) => unknown>, port?: number): void;
36
+ addRpcMethods(methods: RpcMethod, path?: string): void;
37
+ addWebhook(config: WebhookConfig): void;
38
+ addSocketIO(config?: SocketIOConfig): unknown;
39
+ }
40
+ export interface ServerInfo {
41
+ name: string;
42
+ version: string;
43
+ port: number;
44
+ uptime: number;
45
+ status: 'starting' | 'running' | 'stopping' | 'stopped';
46
+ startTime: Date;
47
+ }
48
+ export declare class ExpressServer implements ServerInstance {
49
+ app: express.Application;
50
+ server?: Server;
51
+ config: ServerInstanceConfig;
52
+ private status;
53
+ private grpcServices;
54
+ private grpcServer?;
55
+ private rpcMethods;
56
+ private socketIO?;
57
+ constructor(name?: string, version?: string, config?: ServerConfig);
58
+ private setupMiddleware;
59
+ start(): Promise<ServerInstance>;
60
+ stop(): Promise<void>;
61
+ getInfo(): ServerInfo;
62
+ addGrpcService(service: Record<string, unknown>, implementation: Record<string, (...args: unknown[]) => unknown>, port?: number): void;
63
+ addRpcMethods(methods: RpcMethod, path?: string): void;
64
+ addWebhook(config: WebhookConfig): void;
65
+ addSocketIO(config?: SocketIOConfig): unknown;
66
+ }
67
+ export declare function createServer(name?: string, version?: string, config?: ServerConfig): ServerInstance;