@minisylar/express-typed-router 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.
- package/README.md +164 -0
- package/dist/zod-router.cjs +232 -0
- package/dist/zod-router.cjs.map +1 -0
- package/dist/zod-router.d.cts +270 -0
- package/dist/zod-router.d.cts.map +1 -0
- package/dist/zod-router.d.ts +270 -0
- package/dist/zod-router.d.ts.map +1 -0
- package/dist/zod-router.js +205 -0
- package/dist/zod-router.js.map +1 -0
- package/package.json +73 -0
package/README.md
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
# @minisylar/express-typed-router
|
|
2
|
+
|
|
3
|
+
A strongly-typed Express router with Zod validation and automatic type inference for params, body, query, and middleware.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 🚀 **Full TypeScript support** with automatic type inference for route parameters
|
|
8
|
+
- 🛡️ **Zod validation** for request body, query parameters, and route params
|
|
9
|
+
- 🔗 **Express.js compatibility** - works with Express 4 and Express 5
|
|
10
|
+
- 📝 **JSDoc documentation** with comprehensive examples
|
|
11
|
+
- 📦 **ES Modules** and CommonJS support
|
|
12
|
+
- 🎯 **Zero runtime overhead** for type checking
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install @minisylar/express-typed-router
|
|
18
|
+
# or
|
|
19
|
+
pnpm add @minisylar/express-typed-router
|
|
20
|
+
# or
|
|
21
|
+
yarn add @minisylar/express-typed-router
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Quick Start
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
import express from "express";
|
|
28
|
+
import { z } from "zod";
|
|
29
|
+
import { createTypedRouter } from "@minisylar/express-typed-router";
|
|
30
|
+
|
|
31
|
+
const app = express();
|
|
32
|
+
app.use(express.json());
|
|
33
|
+
|
|
34
|
+
// Create a typed router
|
|
35
|
+
const router = createTypedRouter();
|
|
36
|
+
|
|
37
|
+
// Define routes with automatic type inference
|
|
38
|
+
router.get(
|
|
39
|
+
"/users/:userId",
|
|
40
|
+
{
|
|
41
|
+
params: z.object({
|
|
42
|
+
userId: z.string(),
|
|
43
|
+
}),
|
|
44
|
+
query: z.object({
|
|
45
|
+
include: z.string().optional(),
|
|
46
|
+
}),
|
|
47
|
+
},
|
|
48
|
+
(req, res) => {
|
|
49
|
+
// req.params.userId is automatically typed as string
|
|
50
|
+
// req.query.include is automatically typed as string | undefined
|
|
51
|
+
res.json({
|
|
52
|
+
userId: req.params.userId,
|
|
53
|
+
include: req.query.include,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
router.post(
|
|
59
|
+
"/users",
|
|
60
|
+
{
|
|
61
|
+
body: z.object({
|
|
62
|
+
name: z.string(),
|
|
63
|
+
email: z.string().email(),
|
|
64
|
+
}),
|
|
65
|
+
},
|
|
66
|
+
(req, res) => {
|
|
67
|
+
// req.body is automatically typed as { name: string; email: string }
|
|
68
|
+
const { name, email } = req.body;
|
|
69
|
+
res.json({ id: "123", name, email });
|
|
70
|
+
}
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
app.use("/api", router.getRouter());
|
|
74
|
+
app.listen(3000);
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Advanced Usage
|
|
78
|
+
|
|
79
|
+
### Custom Error Handling
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
import { createTypedRouterWithConfig } from "@minisylar/express-typed-router";
|
|
83
|
+
|
|
84
|
+
const router = createTypedRouterWithConfig({
|
|
85
|
+
errorHandler: (error, req, res, next) => {
|
|
86
|
+
if (error.name === "ZodError") {
|
|
87
|
+
res.status(400).json({
|
|
88
|
+
error: "Validation failed",
|
|
89
|
+
details: error.errors,
|
|
90
|
+
});
|
|
91
|
+
} else {
|
|
92
|
+
next(error);
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### With Middleware
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
import { createTypedRouterWithMiddleware } from "@minisylar/express-typed-router";
|
|
102
|
+
|
|
103
|
+
const authMiddleware = (req, res, next) => {
|
|
104
|
+
// Your auth logic here
|
|
105
|
+
next();
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const router = createTypedRouterWithMiddleware([authMiddleware]);
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Route Parameter Support
|
|
112
|
+
|
|
113
|
+
This library supports all Express.js routing patterns with automatic TypeScript inference:
|
|
114
|
+
|
|
115
|
+
- **Named parameters**: `/users/:userId` → `{ userId: string }`
|
|
116
|
+
- **Multiple parameters**: `/users/:userId/books/:bookId` → `{ userId: string; bookId: string }`
|
|
117
|
+
- **Consecutive parameters**: `/flights/:from-:to` → `{ from: string; to: string }`
|
|
118
|
+
- **Optional parameters (Express 4)**: `/posts/:id?` → `{ id?: string }`
|
|
119
|
+
- **Repeating parameters (Express 5)**: `/files/:path+` → `{ path: string[] }`
|
|
120
|
+
- **Wildcard parameters (Express 5)**: `/files/:path*` → `{ path: string[] }`
|
|
121
|
+
- **Optional segments (Express 5)**: `{/:optional}` → `{ optional?: string }`
|
|
122
|
+
- **Regex constraints**: `/users/:id(\\d+)` → `{ id: string }`
|
|
123
|
+
|
|
124
|
+
## API Reference
|
|
125
|
+
|
|
126
|
+
### `createTypedRouter()`
|
|
127
|
+
|
|
128
|
+
Creates a basic typed router instance.
|
|
129
|
+
|
|
130
|
+
### `createTypedRouterWithConfig(config)`
|
|
131
|
+
|
|
132
|
+
Creates a typed router with custom configuration.
|
|
133
|
+
|
|
134
|
+
### `createTypedRouterWithMiddleware(middleware)`
|
|
135
|
+
|
|
136
|
+
Creates a typed router with pre-applied middleware.
|
|
137
|
+
|
|
138
|
+
### `TypedMiddleware<T>`
|
|
139
|
+
|
|
140
|
+
Type for middleware functions with typed request parameters.
|
|
141
|
+
|
|
142
|
+
## Development
|
|
143
|
+
|
|
144
|
+
```bash
|
|
145
|
+
# Install dependencies
|
|
146
|
+
pnpm install
|
|
147
|
+
|
|
148
|
+
# Build the library
|
|
149
|
+
pnpm build
|
|
150
|
+
|
|
151
|
+
# Run type checking
|
|
152
|
+
pnpm type-check
|
|
153
|
+
|
|
154
|
+
# Build in watch mode
|
|
155
|
+
pnpm build:watch
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## License
|
|
159
|
+
|
|
160
|
+
ISC
|
|
161
|
+
|
|
162
|
+
## Contributing
|
|
163
|
+
|
|
164
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
//#region rolldown:runtime
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
+
key = keys[i];
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
13
|
+
get: ((k) => from[k]).bind(null, key),
|
|
14
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
20
|
+
value: mod,
|
|
21
|
+
enumerable: true
|
|
22
|
+
}) : target, mod));
|
|
23
|
+
|
|
24
|
+
//#endregion
|
|
25
|
+
const express = __toESM(require("express"));
|
|
26
|
+
const zod = __toESM(require("zod"));
|
|
27
|
+
|
|
28
|
+
//#region src/zod-router.ts
|
|
29
|
+
var TypedRouter = class {
|
|
30
|
+
router;
|
|
31
|
+
constructor() {
|
|
32
|
+
this.router = express.default.Router();
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
|
|
36
|
+
* Add typed middleware that extends the request with additional properties
|
|
37
|
+
|
|
38
|
+
*/
|
|
39
|
+
useTypedMiddleware(middleware) {
|
|
40
|
+
this.router.use(middleware);
|
|
41
|
+
return this;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
|
|
45
|
+
* Get the underlying Express router
|
|
46
|
+
|
|
47
|
+
*/
|
|
48
|
+
getRouter() {
|
|
49
|
+
return this.router;
|
|
50
|
+
}
|
|
51
|
+
get(path, optionsOrHandler, handler) {
|
|
52
|
+
return this.registerRoute("get", path, optionsOrHandler, handler);
|
|
53
|
+
}
|
|
54
|
+
post(path, optionsOrHandler, handler) {
|
|
55
|
+
return this.registerRoute("post", path, optionsOrHandler, handler);
|
|
56
|
+
}
|
|
57
|
+
put(path, optionsOrHandler, handler) {
|
|
58
|
+
return this.registerRoute("put", path, optionsOrHandler, handler);
|
|
59
|
+
}
|
|
60
|
+
patch(path, optionsOrHandler, handler) {
|
|
61
|
+
return this.registerRoute("patch", path, optionsOrHandler, handler);
|
|
62
|
+
}
|
|
63
|
+
delete(path, optionsOrHandler, handler) {
|
|
64
|
+
return this.registerRoute("delete", path, optionsOrHandler, handler);
|
|
65
|
+
}
|
|
66
|
+
options(path, optionsOrHandler, handler) {
|
|
67
|
+
return this.registerRoute("options", path, optionsOrHandler, handler);
|
|
68
|
+
}
|
|
69
|
+
head(path, optionsOrHandler, handler) {
|
|
70
|
+
return this.registerRoute("head", path, optionsOrHandler, handler);
|
|
71
|
+
}
|
|
72
|
+
all(path, optionsOrHandler, handler) {
|
|
73
|
+
return this.registerRoute("all", path, optionsOrHandler, handler);
|
|
74
|
+
}
|
|
75
|
+
registerRoute(method, path, optionsOrHandler, handler) {
|
|
76
|
+
const middlewares = [];
|
|
77
|
+
if (typeof optionsOrHandler === "object") {
|
|
78
|
+
const options = optionsOrHandler;
|
|
79
|
+
if (options.middleware) middlewares.push(...options.middleware);
|
|
80
|
+
if (options.bodySchema) middlewares.push(this.createBodyValidationMiddleware(options.bodySchema));
|
|
81
|
+
if (options.querySchema) middlewares.push(this.createQueryValidationMiddleware(options.querySchema));
|
|
82
|
+
middlewares.push(handler);
|
|
83
|
+
} else middlewares.push(optionsOrHandler);
|
|
84
|
+
this.router[method](path, ...middlewares);
|
|
85
|
+
return this;
|
|
86
|
+
}
|
|
87
|
+
createBodyValidationMiddleware(schema) {
|
|
88
|
+
return (req, res, next) => {
|
|
89
|
+
try {
|
|
90
|
+
req.body = schema.parse(req.body);
|
|
91
|
+
next();
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (error instanceof zod.z.ZodError) res.status(400).json({
|
|
94
|
+
error: "Validation failed",
|
|
95
|
+
details: error.errors
|
|
96
|
+
});
|
|
97
|
+
else next(error);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
createQueryValidationMiddleware(schema) {
|
|
102
|
+
return (req, res, next) => {
|
|
103
|
+
try {
|
|
104
|
+
req.query = schema.parse(req.query);
|
|
105
|
+
next();
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (error instanceof zod.z.ZodError) res.status(400).json({
|
|
108
|
+
error: "Validation failed",
|
|
109
|
+
details: error.errors
|
|
110
|
+
});
|
|
111
|
+
else next(error);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
/**
|
|
117
|
+
|
|
118
|
+
* Create a new strongly-typed Express router instance.
|
|
119
|
+
|
|
120
|
+
*
|
|
121
|
+
|
|
122
|
+
* This is the simplest way to get started with @minisylar/express-typed-router.
|
|
123
|
+
|
|
124
|
+
*
|
|
125
|
+
|
|
126
|
+
* @example
|
|
127
|
+
|
|
128
|
+
* import { createTypedRouter } from '@minisylar/express-typed-router';
|
|
129
|
+
|
|
130
|
+
*
|
|
131
|
+
|
|
132
|
+
* // Create a router and add a typed GET route
|
|
133
|
+
|
|
134
|
+
* const router = createTypedRouter();
|
|
135
|
+
|
|
136
|
+
* router.get('/hello/:name', (req, res) => {
|
|
137
|
+
|
|
138
|
+
* // req.params.name is typed as string
|
|
139
|
+
|
|
140
|
+
* res.json({ message: `Hello, ${req.params.name}!` });
|
|
141
|
+
|
|
142
|
+
* });
|
|
143
|
+
|
|
144
|
+
*
|
|
145
|
+
|
|
146
|
+
* // Use with Express
|
|
147
|
+
|
|
148
|
+
* import express from 'express';
|
|
149
|
+
|
|
150
|
+
* const app = express();
|
|
151
|
+
|
|
152
|
+
* app.use('/api', router.getRouter());
|
|
153
|
+
|
|
154
|
+
*/
|
|
155
|
+
function createTypedRouter() {
|
|
156
|
+
return new TypedRouter();
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
|
|
160
|
+
* Create a new typed router with optional configuration.
|
|
161
|
+
|
|
162
|
+
*
|
|
163
|
+
|
|
164
|
+
* Use this if you want to add a global error handler or future global options.
|
|
165
|
+
|
|
166
|
+
*
|
|
167
|
+
|
|
168
|
+
* @param config - Optional configuration for the router (e.g. error handler).
|
|
169
|
+
|
|
170
|
+
* @returns A new TypedRouter instance.
|
|
171
|
+
|
|
172
|
+
*
|
|
173
|
+
|
|
174
|
+
* @example
|
|
175
|
+
|
|
176
|
+
* import { createTypedRouterWithConfig } from '@minisylar/express-typed-router';
|
|
177
|
+
|
|
178
|
+
*
|
|
179
|
+
|
|
180
|
+
* const router = createTypedRouterWithConfig({
|
|
181
|
+
|
|
182
|
+
* errorHandler: (err, req, res, next) => {
|
|
183
|
+
|
|
184
|
+
* res.status(500).json({ error: 'Something went wrong', details: err });
|
|
185
|
+
|
|
186
|
+
* }
|
|
187
|
+
|
|
188
|
+
* });
|
|
189
|
+
|
|
190
|
+
*/
|
|
191
|
+
function createTypedRouterWithConfig(config) {
|
|
192
|
+
const router = new TypedRouter();
|
|
193
|
+
if (config?.errorHandler) router.getRouter().use(config.errorHandler);
|
|
194
|
+
return router;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
|
|
198
|
+
* Create a new typed router with pre-configured middleware.
|
|
199
|
+
|
|
200
|
+
*
|
|
201
|
+
|
|
202
|
+
* This is useful for setting up router-level middleware in a single call.
|
|
203
|
+
|
|
204
|
+
*
|
|
205
|
+
|
|
206
|
+
* @param middleware - One or more TypedMiddleware functions to apply to all routes.
|
|
207
|
+
|
|
208
|
+
* @returns A new TypedRouter instance with the middleware applied.
|
|
209
|
+
|
|
210
|
+
*
|
|
211
|
+
|
|
212
|
+
* @example
|
|
213
|
+
|
|
214
|
+
* import { createTypedRouterWithMiddleware } from '@minisylar/express-typed-router';
|
|
215
|
+
|
|
216
|
+
*
|
|
217
|
+
|
|
218
|
+
* const router = createTypedRouterWithMiddleware(authMiddleware, loggingMiddleware);
|
|
219
|
+
|
|
220
|
+
*/
|
|
221
|
+
function createTypedRouterWithMiddleware(...middleware) {
|
|
222
|
+
let router = new TypedRouter();
|
|
223
|
+
for (const mw of middleware) router = router.useTypedMiddleware(mw);
|
|
224
|
+
return router;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
//#endregion
|
|
228
|
+
exports.TypedRouter = TypedRouter
|
|
229
|
+
exports.createTypedRouter = createTypedRouter
|
|
230
|
+
exports.createTypedRouterWithConfig = createTypedRouterWithConfig
|
|
231
|
+
exports.createTypedRouterWithMiddleware = createTypedRouterWithMiddleware
|
|
232
|
+
//# sourceMappingURL=zod-router.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"zod-router.cjs","names":["middleware: TypedMiddleware<T>","path: string","optionsOrHandler: any","handler?: any","method: HttpMethod","middlewares: any[]","schema: ZodType<any, any, any>","req: Request","res: Response","next: NextFunction","config?: RouterConfig"],"sources":["../src/zod-router.ts"],"sourcesContent":["/**\r\n * @packageDocumentation\r\n * @module @minisylar/express-typed-router\r\n *\r\n * @title @minisylar/express-typed-router\r\n *\r\n * A strongly-typed Express router with Zod validation and automatic type inference for params, body, query, and middleware.\r\n *\r\n * @example\r\n * // Example 1: Basic usage with router-level middleware\r\n * const router = createTypedRouter()\r\n * .useTypedMiddleware(timestampMiddleware)\r\n * .useTypedMiddleware(requestIdMiddleware)\r\n *\r\n * router.get('/posts/:postId', (req, res) => {\r\n * const { postId } = req.params // Typed as { postId: string }\r\n * const { timestamp, requestId } = req // Both properties are now typed correctly!\r\n * res.json({ postId, timestamp, requestId })\r\n * })\r\n *\r\n * @example\r\n * // Example 2: Per-route middleware with automatic type inference\r\n * router.post(\r\n * '/posts',\r\n * {\r\n * bodySchema: CreatePostSchema,\r\n * middleware: [timestampMiddleware, requestIdMiddleware] as const\r\n * },\r\n * (req, res) => {\r\n * const { title, content, tags } = req.body // From schema validation\r\n * const { timestamp, requestId } = req // From middleware - should be automatically typed!\r\n * res.json({ title, content, tags, timestamp, requestId })\r\n * }\r\n * )\r\n *\r\n * @example\r\n * // Example 3: Mixed middleware\r\n * const router = createTypedRouter().useTypedMiddleware(requestIdMiddleware)\r\n * router.get(\r\n * '/posts/:postId',\r\n * {\r\n * middleware: [authMiddleware] as const\r\n * },\r\n * (req, res) => {\r\n * const { postId } = req.params\r\n * const { requestId } = req // From router-level middleware\r\n * const { userId, hasPermission } = req // From per-route middleware\r\n * res.json({ postId, requestId, userId, hasPermission })\r\n * }\r\n * )\r\n *\r\n * @example\r\n * // Example 4: Using factory with pre-configured middleware\r\n * const router = createTypedRouterWithMiddleware(timestampMiddleware, requestIdMiddleware)\r\n * router.get('/simple/:id', (req, res) => {\r\n * const { id } = req.params\r\n * const { timestamp, requestId } = req // Already available from factory setup!\r\n * res.json({ id, timestamp, requestId })\r\n * })\r\n *\r\n * @example\r\n * // Example 5: Demonstrating all HTTP methods\r\n * const router = createTypedRouter().useTypedMiddleware(requestIdMiddleware)\r\n *\r\n * // GET with query validation\r\n * router.get('/posts', { querySchema: QuerySchema }, (req, res) => {\r\n * const { limit, offset } = req.query // Typed from schema\r\n * const { requestId } = req // From router middleware\r\n * res.json({ posts: [], limit, offset, requestId })\r\n * })\r\n *\r\n * // POST with body validation and middleware\r\n * router.post(\r\n * '/posts',\r\n * {\r\n * bodySchema: CreatePostSchema,\r\n * middleware: [timestampMiddleware] as const\r\n * },\r\n * (req, res) => {\r\n * const { title, content } = req.body // From body schema\r\n * const { requestId, timestamp } = req // From middleware\r\n * res.json({ id: 'new-post', title, content, requestId, timestamp })\r\n * }\r\n * )\r\n *\r\n * // PUT for full updates\r\n * router.put(\r\n * '/posts/:postId',\r\n * {\r\n * bodySchema: CreatePostSchema,\r\n * middleware: [authMiddleware] as const\r\n * },\r\n * (req, res) => {\r\n * const { postId } = req.params\r\n * const { title, content } = req.body\r\n * const { requestId, userId, hasPermission } = req\r\n * res.json({ postId, title, content, requestId, userId, hasPermission })\r\n * }\r\n * )\r\n *\r\n * // PATCH for partial updates\r\n * router.patch('/posts/:postId', { bodySchema: UpdatePostSchema }, (req, res) => {\r\n * const { postId } = req.params\r\n * const updates = req.body // Partial update object\r\n * const { requestId } = req\r\n * res.json({ postId, updates, requestId })\r\n * })\r\n *\r\n * // DELETE\r\n * router.delete('/posts/:postId', (req, res) => {\r\n * const { postId } = req.params\r\n * const { requestId } = req\r\n * res.json({ deleted: postId, requestId })\r\n * })\r\n *\r\n * // OPTIONS for CORS preflight\r\n * router.options('/posts/*', (req, res) => {\r\n * res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE')\r\n * res.header('Access-Control-Allow-Headers', 'Content-Type')\r\n * res.status(200).end()\r\n * })\r\n *\r\n * // HEAD for metadata only\r\n * router.head('/posts/:postId', (req, res) => {\r\n * const { postId } = req.params\r\n * res.header('X-Post-ID', postId)\r\n * res.status(200).end()\r\n * })\r\n *\r\n * // ALL method for catch-all routes\r\n * router.all('/debug/*', (req, res) => {\r\n * const { requestId } = req\r\n * res.json({\r\n * method: req.method,\r\n * path: req.path,\r\n * requestId\r\n * })\r\n * })\r\n */\r\n/* eslint-disable @typescript-eslint/no-empty-object-type */\r\nimport express, {\r\n type Request,\r\n type Response,\r\n type NextFunction,\r\n} from \"express\";\r\nimport { z, type ZodType } from \"zod\";\r\n\r\n/**\r\n * Extract route parameters from Express.js route patterns.\r\n *\r\n * Supports all Express.js routing patterns:\r\n * - Named parameters: /users/:userId → { userId: string }\r\n * - Multiple parameters: /users/:userId/books/:bookId → { userId: string; bookId: string }\r\n * - Parameters with separators: /flights/:from-:to → { from: string; to: string }\r\n * - Dot notation: /plantae/:genus.:species → { genus: string; species: string }\r\n * - Regex constraints: /user/:id(\\\\d+) → { id: string }\r\n * - Optional parameters: /posts/:year/:month? → { year: string; month?: string }\r\n * - Wildcard parameters: /files/* → { \"0\": string }\r\n * - Multiple wildcards: /a/star/b/star → { \"0\": string; \"1\": string }\r\n */\r\nexport type ExtractRouteParams<Path extends string> = string extends Path\r\n ? Record<string, string>\r\n : ExtractParams<Path>;\r\n\r\n/**\r\n * Main parameter extraction logic - enhanced for Express 5 support\r\n */\r\ntype ExtractParams<Path extends string> =\r\n // Handle Express 5 braces for optional segments: {/:param} or {/path/:param}\r\n Path extends `${infer Before}{${infer OptionalContent}}${infer After}`\r\n ? ExtractOptionalSegment<OptionalContent> &\r\n ExtractParams<`${Before}${After}`>\r\n : // Handle named parameters :paramName\r\n Path extends `${infer _Before}:${infer Rest}`\r\n ? ExtractSingleParam<Rest> & ExtractParams<RemoveFirstParam<Path>>\r\n : // Handle wildcards *\r\n Path extends `${infer _Before}*${infer After}`\r\n ? { [K in CountWildcards<_Before>]: string } & ExtractParams<After>\r\n : // No more parameters\r\n {};\r\n\r\n/**\r\n * Extract parameters from Express 5 optional segments in braces\r\n * Handles patterns like {/:param}, {.:ext}, {/optional/:param}\r\n */\r\ntype ExtractOptionalSegment<Content extends string> =\r\n // Handle optional parameter patterns like /:param\r\n Content extends `/:${infer Rest}`\r\n ? ExtractOptionalParam<Rest>\r\n : Content extends `.:${infer Rest}`\r\n ? ExtractOptionalParam<Rest>\r\n : Content extends `${infer _Path}:${infer Rest}`\r\n ? ExtractOptionalParam<Rest>\r\n : {};\r\n\r\n/**\r\n * Extract a single optional parameter from brace content\r\n */\r\ntype ExtractOptionalParam<Rest extends string> =\r\n Rest extends `${infer ParamName}/${infer _After}`\r\n ? { [K in ParamName]?: string }\r\n : Rest extends `${infer ParamName}-${infer _After}`\r\n ? { [K in ParamName]?: string }\r\n : Rest extends `${infer ParamName}.${infer _After}`\r\n ? { [K in ParamName]?: string }\r\n : Rest extends `${infer ParamName}`\r\n ? { [K in ParamName]?: string }\r\n : {};\r\n\r\n/**\r\n * Extract a single parameter name from the rest of the path\r\n * Enhanced to handle Express 5 patterns and optional parameters correctly\r\n * Special handling for consecutive parameters like :from-:to\r\n * Order matters: regex constraints must be handled before repeating parameters\r\n */\r\ntype ExtractSingleParam<Rest extends string> =\r\n // Handle regex constraints FIRST (before +, *, ?) to avoid conflicts\r\n Rest extends `${infer ParamName}(${infer _Constraint})${infer _After}`\r\n ? { [K in ParamName]: string } // Handle consecutive parameters with separators first: param-:nextParam\r\n : Rest extends `${infer ParamName}-:${infer _NextParam}`\r\n ? { [K in ParamName]: string }\r\n : Rest extends `${infer ParamName}.:${infer _NextParam}`\r\n ? { [K in ParamName]: string }\r\n : // Handle optional parameters followed by delimiters (before regular delimiters)\r\n Rest extends `${infer ParamName}?/${infer _After}`\r\n ? { [K in ParamName]?: string }\r\n : Rest extends `${infer ParamName}?-${infer _After}`\r\n ? { [K in ParamName]?: string }\r\n : Rest extends `${infer ParamName}?.${infer _After}`\r\n ? { [K in ParamName]?: string }\r\n : Rest extends `${infer ParamName}?#${infer _After}`\r\n ? { [K in ParamName]?: string }\r\n : Rest extends `${infer ParamName}?:${infer _After}`\r\n ? { [K in ParamName]?: string }\r\n : // Then handle regular delimiters (after optional parameter patterns)\r\n Rest extends `${infer ParamName}/${infer _After}`\r\n ? { [K in ParamName]: string }\r\n : Rest extends `${infer ParamName}-${infer _After}`\r\n ? { [K in ParamName]: string }\r\n : Rest extends `${infer ParamName}.${infer _After}`\r\n ? { [K in ParamName]: string }\r\n : Rest extends `${infer ParamName}#${infer _After}`\r\n ? { [K in ParamName]: string }\r\n : Rest extends `${infer ParamName}:${infer _After}`\r\n ? { [K in ParamName]: string }\r\n : // Handle Express 5 repeating parameters (after regular delimiters)\r\n Rest extends `${infer ParamName}+${infer _After}`\r\n ? { [K in ParamName]: string[] }\r\n : Rest extends `${infer ParamName}*${infer _After}`\r\n ? { [K in ParamName]?: string[] }\r\n : // Handle optional parameters with ? (Express 4) - only at the end of a segment\r\n Rest extends `${infer ParamName}?${infer _After}`\r\n ? { [K in ParamName]?: string } // Parameter at absolute end of string\r\n : Rest extends string\r\n ? Rest extends \"\"\r\n ? {}\r\n : Rest extends `${infer ParamName}?`\r\n ? { [K in ParamName]?: string } // ParamName here doesn't include the ?\r\n : Rest extends `${infer ParamName}+`\r\n ? { [K in ParamName]: string[] }\r\n : Rest extends `${infer ParamName}*`\r\n ? { [K in ParamName]?: string[] }\r\n : { [K in Rest]: string }\r\n : {};\r\n\r\n/**\r\n * Remove the first parameter from path to continue parsing\r\n * Enhanced to handle Express 5 patterns and optional parameters\r\n * Handles patterns like :from-:to by removing just :from and keeping -:to\r\n * Order matters: regex constraints must be handled before repeating parameters\r\n */\r\ntype RemoveFirstParam<Path extends string> =\r\n Path extends `${infer Before}:${infer Rest}`\r\n ? // Handle regex constraints FIRST (before +, *, ?) to avoid conflicts\r\n Rest extends `${infer _ParamName}(${infer _Constraint})${infer After}`\r\n ? `${Before}${After}` // Handle consecutive parameters: :param-:nextParam -> -:nextParam\r\n : Rest extends `${infer _ParamName}-:${infer After}`\r\n ? `${Before}-:${After}`\r\n : Rest extends `${infer _ParamName}.:${infer After}`\r\n ? `${Before}.:${After}`\r\n : // Handle optional parameters followed by delimiters (before regular delimiters)\r\n Rest extends `${infer _ParamName}?/${infer After}`\r\n ? `${Before}/${After}`\r\n : Rest extends `${infer _ParamName}?-${infer After}`\r\n ? `${Before}${After}`\r\n : Rest extends `${infer _ParamName}?.${infer After}`\r\n ? `${Before}${After}`\r\n : Rest extends `${infer _ParamName}?#${infer After}`\r\n ? `${Before}${After}`\r\n : Rest extends `${infer _ParamName}?:${infer After}`\r\n ? `${Before}:${After}`\r\n : // Handle regular separators (after optional parameter patterns)\r\n Rest extends `${infer _ParamName}/${infer After}`\r\n ? `${Before}/${After}`\r\n : Rest extends `${infer _ParamName}-${infer After}`\r\n ? `${Before}${After}`\r\n : Rest extends `${infer _ParamName}.${infer After}`\r\n ? `${Before}${After}`\r\n : Rest extends `${infer _ParamName}#${infer After}`\r\n ? `${Before}${After}`\r\n : Rest extends `${infer _ParamName}:${infer After}`\r\n ? `${Before}:${After}`\r\n : // Handle Express 5 repeating parameters (after regular separators)\r\n Rest extends `${infer _ParamName}+${infer After}`\r\n ? `${Before}${After}`\r\n : Rest extends `${infer _ParamName}*${infer After}`\r\n ? `${Before}${After}`\r\n : // Handle optional parameters with ?\r\n Rest extends `${infer _ParamName}?${infer After}`\r\n ? `${Before}${After}`\r\n : Before\r\n : Path;\r\n\r\n/**\r\n * Count wildcards to assign proper numeric indices\r\n */\r\ntype CountWildcards<\r\n Path extends string,\r\n Count extends string = \"0\"\r\n> = Path extends `${infer _Before}*${infer Rest}`\r\n ? CountWildcards<Rest, IncrementWildcard<Count>>\r\n : Count;\r\n\r\n/**\r\n * Helper type to increment wildcard count as string\r\n */\r\ntype IncrementWildcard<T extends string> = T extends \"0\"\r\n ? \"1\"\r\n : T extends \"1\"\r\n ? \"2\"\r\n : T extends \"2\"\r\n ? \"3\"\r\n : T extends \"3\"\r\n ? \"4\"\r\n : T extends \"4\"\r\n ? \"5\"\r\n : T extends \"5\"\r\n ? \"6\"\r\n : T extends \"6\"\r\n ? \"7\"\r\n : T extends \"7\"\r\n ? \"8\"\r\n : T extends \"8\"\r\n ? \"9\"\r\n : \"10\"; // Reasonable limit for wildcards\r\n\r\n/**\r\n * Express middleware that adds custom properties to the request object.\r\n *\r\n * @template T - The shape of the properties added to the request.\r\n * @param req - The Express request object, extended with T.\r\n * @param res - The Express response object.\r\n * @param next - The next middleware function.\r\n */\r\nexport type TypedMiddleware<T extends Record<string, any>> = (\r\n req: Request & T,\r\n res: Response,\r\n next: NextFunction\r\n) => void | Promise<void>;\r\n\r\n// Utility type to infer props from middleware array\r\ntype InferMiddlewareProps<T extends readonly TypedMiddleware<any>[]> =\r\n T extends readonly [infer First, ...infer Rest]\r\n ? First extends TypedMiddleware<infer FirstType>\r\n ? Rest extends readonly TypedMiddleware<any>[]\r\n ? FirstType & InferMiddlewareProps<Rest>\r\n : FirstType\r\n : {}\r\n : {};\r\n\r\n// Enhanced Request type with proper inference\r\nexport type ZodRequest<\r\n Path extends string = string,\r\n BodySchema extends ZodType<any, any, any> | unknown = unknown,\r\n QuerySchema extends ZodType<any, any, any> | unknown = unknown,\r\n MiddlewareProps extends Record<string, any> = {}\r\n> = Omit<Request, \"params\" | \"query\" | \"body\"> & {\r\n params: ExtractRouteParams<Path>;\r\n body: BodySchema extends ZodType<any, any, any>\r\n ? z.infer<BodySchema>\r\n : unknown;\r\n query: QuerySchema extends ZodType<any, any, any>\r\n ? z.infer<QuerySchema>\r\n : unknown;\r\n} & MiddlewareProps;\r\n\r\n// Route handler type\r\nexport type ZodRouteHandler<\r\n Path extends string = string,\r\n BodySchema extends ZodType<any, any, any> | unknown = unknown,\r\n QuerySchema extends ZodType<any, any, any> | unknown = unknown,\r\n MiddlewareProps extends Record<string, any> = {}\r\n> = (\r\n req: ZodRequest<Path, BodySchema, QuerySchema, MiddlewareProps>,\r\n res: Response,\r\n next?: NextFunction\r\n) => void | Promise<void> | Response | Promise<Response>;\r\n\r\n/**\r\n * Options for defining a typed route, including schemas and middleware.\r\n *\r\n * @template BodySchema - Zod schema for request body validation.\r\n * @template QuerySchema - Zod schema for query parameter validation.\r\n * @property bodySchema - Optional Zod schema for validating the request body.\r\n * @property querySchema - Optional Zod schema for validating the query string.\r\n * @property middleware - Optional array of TypedMiddleware for this route.\r\n */\r\nexport interface RouteOptions<\r\n BodySchema extends ZodType<any, any, any> | unknown = unknown,\r\n QuerySchema extends ZodType<any, any, any> | unknown = unknown\r\n> {\r\n bodySchema?: BodySchema extends ZodType<any, any, any> ? BodySchema : never;\r\n querySchema?: QuerySchema extends ZodType<any, any, any>\r\n ? QuerySchema\r\n : never;\r\n middleware?: readonly TypedMiddleware<any>[];\r\n}\r\n\r\n// HTTP methods\r\nexport type HttpMethod =\r\n | \"get\"\r\n | \"post\"\r\n | \"put\"\r\n | \"delete\"\r\n | \"patch\"\r\n | \"options\"\r\n | \"head\"\r\n | \"all\";\r\n\r\n// Main typed router class\r\nexport class TypedRouter<\r\n RouterMiddlewareProps extends Record<string, any> = {}\r\n> {\r\n private router: express.Router;\r\n\r\n constructor() {\r\n this.router = express.Router();\r\n }\r\n\r\n /**\r\n * Add typed middleware that extends the request with additional properties\r\n */\r\n useTypedMiddleware<T extends Record<string, any>>(\r\n middleware: TypedMiddleware<T>\r\n ): TypedRouter<RouterMiddlewareProps & T> {\r\n this.router.use(middleware as any);\r\n return this as any;\r\n }\r\n\r\n /**\r\n * Get the underlying Express router\r\n */\r\n getRouter(): express.Router {\r\n return this.router;\r\n }\r\n\r\n // Method overloads for GET requests with automatic middleware type inference\r\n get<Path extends string>(\r\n path: Path,\r\n handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps>\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n get<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any> | unknown,\r\n QuerySchema extends ZodType<any, any, any> | unknown\r\n >(\r\n path: Path,\r\n options: RouteOptions<BodySchema, QuerySchema>,\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n QuerySchema,\r\n RouterMiddlewareProps\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n // Special overload for middleware type inference\r\n get<Path extends string, Middleware extends readonly TypedMiddleware<any>[]>(\r\n path: Path,\r\n options: { middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n unknown,\r\n unknown,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n // Combined overload for body/query schema + middleware\r\n get<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any> | unknown,\r\n QuerySchema extends ZodType<any, any, any> | unknown,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: RouteOptions<BodySchema, QuerySchema> & { middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n QuerySchema,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n // Implementation\r\n get(\r\n path: string,\r\n optionsOrHandler: any,\r\n handler?: any\r\n ): TypedRouter<RouterMiddlewareProps> {\r\n return this.registerRoute(\"get\", path, optionsOrHandler, handler);\r\n }\r\n\r\n // Combined overload for body/query schema + middleware (most specific first)\r\n post<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any>,\r\n QuerySchema extends ZodType<any, any, any> | unknown,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: {\r\n bodySchema: BodySchema;\r\n querySchema?: QuerySchema;\r\n middleware: Middleware;\r\n },\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n QuerySchema,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n // Body schema only + middleware\r\n post<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any>,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: { bodySchema: BodySchema; middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n unknown,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n // Middleware only\r\n post<Path extends string, Middleware extends readonly TypedMiddleware<any>[]>(\r\n path: Path,\r\n options: { middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n unknown,\r\n unknown,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n // Body + Query schema without middleware\r\n post<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any> | unknown,\r\n QuerySchema extends ZodType<any, any, any> | unknown\r\n >(\r\n path: Path,\r\n options: RouteOptions<BodySchema, QuerySchema>,\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n QuerySchema,\r\n RouterMiddlewareProps\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n // Just handler, no options\r\n post<Path extends string>(\r\n path: Path,\r\n handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps>\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n post(\r\n path: string,\r\n optionsOrHandler: any,\r\n handler?: any\r\n ): TypedRouter<RouterMiddlewareProps> {\r\n return this.registerRoute(\"post\", path, optionsOrHandler, handler);\r\n }\r\n\r\n // PUT method with all the same overloads as POST\r\n put<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any>,\r\n QuerySchema extends ZodType<any, any, any> | unknown,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: {\r\n bodySchema: BodySchema;\r\n querySchema?: QuerySchema;\r\n middleware: Middleware;\r\n },\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n QuerySchema,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n put<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any>,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: { bodySchema: BodySchema; middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n unknown,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n put<Path extends string, Middleware extends readonly TypedMiddleware<any>[]>(\r\n path: Path,\r\n options: { middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n unknown,\r\n unknown,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n put<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any> | unknown,\r\n QuerySchema extends ZodType<any, any, any> | unknown\r\n >(\r\n path: Path,\r\n options: RouteOptions<BodySchema, QuerySchema>,\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n QuerySchema,\r\n RouterMiddlewareProps\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n put<Path extends string>(\r\n path: Path,\r\n handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps>\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n put(\r\n path: string,\r\n optionsOrHandler: any,\r\n handler?: any\r\n ): TypedRouter<RouterMiddlewareProps> {\r\n return this.registerRoute(\"put\", path, optionsOrHandler, handler);\r\n }\r\n\r\n // PATCH method with all the same overloads as POST\r\n patch<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any>,\r\n QuerySchema extends ZodType<any, any, any> | unknown,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: {\r\n bodySchema: BodySchema;\r\n querySchema?: QuerySchema;\r\n middleware: Middleware;\r\n },\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n QuerySchema,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n patch<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any>,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: { bodySchema: BodySchema; middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n unknown,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n patch<\r\n Path extends string,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: { middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n unknown,\r\n unknown,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n patch<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any> | unknown,\r\n QuerySchema extends ZodType<any, any, any> | unknown\r\n >(\r\n path: Path,\r\n options: RouteOptions<BodySchema, QuerySchema>,\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n QuerySchema,\r\n RouterMiddlewareProps\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n patch<Path extends string>(\r\n path: Path,\r\n handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps>\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n patch(\r\n path: string,\r\n optionsOrHandler: any,\r\n handler?: any\r\n ): TypedRouter<RouterMiddlewareProps> {\r\n return this.registerRoute(\"patch\", path, optionsOrHandler, handler);\r\n }\r\n\r\n // DELETE method (typically no body, but can have query params and middleware)\r\n delete<\r\n Path extends string,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: { middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n unknown,\r\n unknown,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n delete<\r\n Path extends string,\r\n QuerySchema extends ZodType<any, any, any> | unknown,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: { querySchema: QuerySchema; middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n unknown,\r\n QuerySchema,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n delete<\r\n Path extends string,\r\n QuerySchema extends ZodType<any, any, any> | unknown\r\n >(\r\n path: Path,\r\n options: { querySchema: QuerySchema },\r\n handler: ZodRouteHandler<Path, unknown, QuerySchema, RouterMiddlewareProps>\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n delete<Path extends string>(\r\n path: Path,\r\n handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps>\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n delete(\r\n path: string,\r\n optionsOrHandler: any,\r\n handler?: any\r\n ): TypedRouter<RouterMiddlewareProps> {\r\n return this.registerRoute(\"delete\", path, optionsOrHandler, handler);\r\n }\r\n\r\n // OPTIONS method (typically no body, used for CORS preflight)\r\n options<\r\n Path extends string,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: { middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n unknown,\r\n unknown,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n options<Path extends string>(\r\n path: Path,\r\n handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps>\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n options(\r\n path: string,\r\n optionsOrHandler: any,\r\n handler?: any\r\n ): TypedRouter<RouterMiddlewareProps> {\r\n return this.registerRoute(\"options\", path, optionsOrHandler, handler);\r\n }\r\n\r\n // HEAD method (like GET but only returns headers)\r\n head<Path extends string, Middleware extends readonly TypedMiddleware<any>[]>(\r\n path: Path,\r\n options: { middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n unknown,\r\n unknown,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n head<\r\n Path extends string,\r\n QuerySchema extends ZodType<any, any, any> | unknown,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: { querySchema: QuerySchema; middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n unknown,\r\n QuerySchema,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n head<\r\n Path extends string,\r\n QuerySchema extends ZodType<any, any, any> | unknown\r\n >(\r\n path: Path,\r\n options: { querySchema: QuerySchema },\r\n handler: ZodRouteHandler<Path, unknown, QuerySchema, RouterMiddlewareProps>\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n head<Path extends string>(\r\n path: Path,\r\n handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps>\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n head(\r\n path: string,\r\n optionsOrHandler: any,\r\n handler?: any\r\n ): TypedRouter<RouterMiddlewareProps> {\r\n return this.registerRoute(\"head\", path, optionsOrHandler, handler);\r\n }\r\n\r\n // ALL method (matches all HTTP methods)\r\n all<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any>,\r\n QuerySchema extends ZodType<any, any, any> | unknown,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: {\r\n bodySchema: BodySchema;\r\n querySchema?: QuerySchema;\r\n middleware: Middleware;\r\n },\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n QuerySchema,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n all<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any>,\r\n Middleware extends readonly TypedMiddleware<any>[]\r\n >(\r\n path: Path,\r\n options: { bodySchema: BodySchema; middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n unknown,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n all<Path extends string, Middleware extends readonly TypedMiddleware<any>[]>(\r\n path: Path,\r\n options: { middleware: Middleware },\r\n handler: ZodRouteHandler<\r\n Path,\r\n unknown,\r\n unknown,\r\n RouterMiddlewareProps & InferMiddlewareProps<Middleware>\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n all<\r\n Path extends string,\r\n BodySchema extends ZodType<any, any, any> | unknown,\r\n QuerySchema extends ZodType<any, any, any> | unknown\r\n >(\r\n path: Path,\r\n options: RouteOptions<BodySchema, QuerySchema>,\r\n handler: ZodRouteHandler<\r\n Path,\r\n BodySchema,\r\n QuerySchema,\r\n RouterMiddlewareProps\r\n >\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n all<Path extends string>(\r\n path: Path,\r\n handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps>\r\n ): TypedRouter<RouterMiddlewareProps>;\r\n\r\n all(\r\n path: string,\r\n optionsOrHandler: any,\r\n handler?: any\r\n ): TypedRouter<RouterMiddlewareProps> {\r\n return this.registerRoute(\"all\", path, optionsOrHandler, handler);\r\n }\r\n\r\n // Helper method to register routes\r\n private registerRoute(\r\n method: HttpMethod,\r\n path: string,\r\n optionsOrHandler: any,\r\n handler?: any\r\n ): TypedRouter<RouterMiddlewareProps> {\r\n const middlewares: any[] = [];\r\n\r\n if (typeof optionsOrHandler === \"object\") {\r\n const options = optionsOrHandler as RouteOptions<any, any>;\r\n\r\n // Add per-route middleware first\r\n if (options.middleware) {\r\n middlewares.push(...options.middleware);\r\n }\r\n\r\n // Add schema validation middleware\r\n if (options.bodySchema) {\r\n middlewares.push(\r\n this.createBodyValidationMiddleware(options.bodySchema)\r\n );\r\n }\r\n if (options.querySchema) {\r\n middlewares.push(\r\n this.createQueryValidationMiddleware(options.querySchema)\r\n );\r\n }\r\n\r\n // Add the main handler\r\n middlewares.push(handler);\r\n } else {\r\n // Direct handler without options\r\n middlewares.push(optionsOrHandler);\r\n }\r\n\r\n // Register with Express router\r\n (this.router as any)[method](path, ...middlewares);\r\n\r\n return this;\r\n }\r\n\r\n private createBodyValidationMiddleware(schema: ZodType<any, any, any>) {\r\n return (req: Request, res: Response, next: NextFunction) => {\r\n try {\r\n req.body = schema.parse(req.body);\r\n next();\r\n } catch (error) {\r\n if (error instanceof z.ZodError) {\r\n res.status(400).json({\r\n error: \"Validation failed\",\r\n details: error.errors,\r\n });\r\n } else {\r\n next(error);\r\n }\r\n }\r\n };\r\n }\r\n\r\n private createQueryValidationMiddleware(schema: ZodType<any, any, any>) {\r\n return (req: Request, res: Response, next: NextFunction) => {\r\n try {\r\n req.query = schema.parse(req.query);\r\n next();\r\n } catch (error) {\r\n if (error instanceof z.ZodError) {\r\n res.status(400).json({\r\n error: \"Validation failed\",\r\n details: error.errors,\r\n });\r\n } else {\r\n next(error);\r\n }\r\n }\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Create a new strongly-typed Express router instance.\r\n *\r\n * This is the simplest way to get started with @minisylar/express-typed-router.\r\n *\r\n * @example\r\n * import { createTypedRouter } from '@minisylar/express-typed-router';\r\n *\r\n * // Create a router and add a typed GET route\r\n * const router = createTypedRouter();\r\n * router.get('/hello/:name', (req, res) => {\r\n * // req.params.name is typed as string\r\n * res.json({ message: `Hello, ${req.params.name}!` });\r\n * });\r\n *\r\n * // Use with Express\r\n * import express from 'express';\r\n * const app = express();\r\n * app.use('/api', router.getRouter());\r\n */\r\nexport function createTypedRouter<\r\n RouterMiddlewareProps extends Record<string, any> = {}\r\n>(): TypedRouter<RouterMiddlewareProps> {\r\n return new TypedRouter<RouterMiddlewareProps>();\r\n}\r\n\r\n// Option 2: Factory with optional configuration\r\n\r\n/**\r\n * Configuration options for createTypedRouterWithConfig.\r\n *\r\n * @property validateInput - (Future) Whether to enable global input validation.\r\n * @property errorHandler - Optional global error handler middleware for the router.\r\n */\r\nexport interface RouterConfig {\r\n validateInput?: boolean;\r\n errorHandler?: (\r\n error: any,\r\n req: Request,\r\n res: Response,\r\n next: NextFunction\r\n ) => void;\r\n}\r\n\r\n/**\r\n * Create a new typed router with optional configuration.\r\n *\r\n * Use this if you want to add a global error handler or future global options.\r\n *\r\n * @param config - Optional configuration for the router (e.g. error handler).\r\n * @returns A new TypedRouter instance.\r\n *\r\n * @example\r\n * import { createTypedRouterWithConfig } from '@minisylar/express-typed-router';\r\n *\r\n * const router = createTypedRouterWithConfig({\r\n * errorHandler: (err, req, res, next) => {\r\n * res.status(500).json({ error: 'Something went wrong', details: err });\r\n * }\r\n * });\r\n */\r\nexport function createTypedRouterWithConfig<\r\n RouterMiddlewareProps extends Record<string, any> = {}\r\n>(config?: RouterConfig): TypedRouter<RouterMiddlewareProps> {\r\n const router = new TypedRouter<RouterMiddlewareProps>();\r\n if (config?.errorHandler) {\r\n router.getRouter().use(config.errorHandler);\r\n }\r\n return router;\r\n}\r\n\r\n// Option 3: Factory with pre-configured middleware\r\n\r\n/**\r\n * Create a new typed router with pre-configured middleware.\r\n *\r\n * This is useful for setting up router-level middleware in a single call.\r\n *\r\n * @param middleware - One or more TypedMiddleware functions to apply to all routes.\r\n * @returns A new TypedRouter instance with the middleware applied.\r\n *\r\n * @example\r\n * import { createTypedRouterWithMiddleware } from '@minisylar/express-typed-router';\r\n *\r\n * const router = createTypedRouterWithMiddleware(authMiddleware, loggingMiddleware);\r\n */\r\nexport function createTypedRouterWithMiddleware<T extends Record<string, any>>(\r\n ...middleware: TypedMiddleware<any>[]\r\n): TypedRouter<T> {\r\n let router = new TypedRouter() as any;\r\n for (const mw of middleware) {\r\n router = router.useTypedMiddleware(mw);\r\n }\r\n return router;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8aA,IAAa,cAAb,MAEE;CACA;CAEA,cAAc;AACZ,OAAK,SAAS,gBAAQ,QAAQ;CAC/B;;;;;;CAKD,mBACEA,YACwC;AACxC,OAAK,OAAO,IAAI,WAAkB;AAClC,SAAO;CACR;;;;;;CAKD,YAA4B;AAC1B,SAAO,KAAK;CACb;CAqDD,IACEC,MACAC,kBACAC,SACoC;AACpC,SAAO,KAAK,cAAc,OAAO,MAAM,kBAAkB,QAAQ;CAClE;CAyED,KACEF,MACAC,kBACAC,SACoC;AACpC,SAAO,KAAK,cAAc,QAAQ,MAAM,kBAAkB,QAAQ;CACnE;CAqED,IACEF,MACAC,kBACAC,SACoC;AACpC,SAAO,KAAK,cAAc,OAAO,MAAM,kBAAkB,QAAQ;CAClE;CAwED,MACEF,MACAC,kBACAC,SACoC;AACpC,SAAO,KAAK,cAAc,SAAS,MAAM,kBAAkB,QAAQ;CACpE;CA8CD,OACEF,MACAC,kBACAC,SACoC;AACpC,SAAO,KAAK,cAAc,UAAU,MAAM,kBAAkB,QAAQ;CACrE;CAsBD,QACEF,MACAC,kBACAC,SACoC;AACpC,SAAO,KAAK,cAAc,WAAW,MAAM,kBAAkB,QAAQ;CACtE;CA2CD,KACEF,MACAC,kBACAC,SACoC;AACpC,SAAO,KAAK,cAAc,QAAQ,MAAM,kBAAkB,QAAQ;CACnE;CAqED,IACEF,MACAC,kBACAC,SACoC;AACpC,SAAO,KAAK,cAAc,OAAO,MAAM,kBAAkB,QAAQ;CAClE;CAGD,cACEC,QACAH,MACAC,kBACAC,SACoC;EACpC,MAAME,cAAqB,CAAE;AAE7B,aAAW,qBAAqB,UAAU;GACxC,MAAM,UAAU;AAGhB,OAAI,QAAQ,WACV,aAAY,KAAK,GAAG,QAAQ,WAAW;AAIzC,OAAI,QAAQ,WACV,aAAY,KACV,KAAK,+BAA+B,QAAQ,WAAW,CACxD;AAEH,OAAI,QAAQ,YACV,aAAY,KACV,KAAK,gCAAgC,QAAQ,YAAY,CAC1D;AAIH,eAAY,KAAK,QAAQ;EAC1B,MAEC,aAAY,KAAK,iBAAiB;AAInC,OAAK,OAAe,QAAQ,MAAM,GAAG,YAAY;AAElD,SAAO;CACR;CAED,+BAAuCC,QAAgC;AACrE,SAAO,CAACC,KAAcC,KAAeC,SAAuB;AAC1D,OAAI;AACF,QAAI,OAAO,OAAO,MAAM,IAAI,KAAK;AACjC,UAAM;GACP,SAAQ,OAAO;AACd,QAAI,iBAAiB,MAAE,SACrB,KAAI,OAAO,IAAI,CAAC,KAAK;KACnB,OAAO;KACP,SAAS,MAAM;IAChB,EAAC;QAEF,MAAK,MAAM;GAEd;EACF;CACF;CAED,gCAAwCH,QAAgC;AACtE,SAAO,CAACC,KAAcC,KAAeC,SAAuB;AAC1D,OAAI;AACF,QAAI,QAAQ,OAAO,MAAM,IAAI,MAAM;AACnC,UAAM;GACP,SAAQ,OAAO;AACd,QAAI,iBAAiB,MAAE,SACrB,KAAI,OAAO,IAAI,CAAC,KAAK;KACnB,OAAO;KACP,SAAS,MAAM;IAChB,EAAC;QAEF,MAAK,MAAM;GAEd;EACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBD,SAAgB,oBAEwB;AACtC,QAAO,IAAI;AACZ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCD,SAAgB,4BAEdC,QAA2D;CAC3D,MAAM,SAAS,IAAI;AACnB,KAAI,QAAQ,aACV,QAAO,WAAW,CAAC,IAAI,OAAO,aAAa;AAE7C,QAAO;AACR;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBD,SAAgB,gCACd,GAAG,YACa;CAChB,IAAI,SAAS,IAAI;AACjB,MAAK,MAAM,MAAM,WACf,UAAS,OAAO,mBAAmB,GAAG;AAExC,QAAO;AACR"}
|