@minisylar/express-typed-router 1.4.4 → 1.6.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.
@@ -1,320 +0,0 @@
1
- import express, { NextFunction, Request, Response } from "express";
2
- import * as z3 from "zod/v3";
3
- import * as z4 from "zod/v4/core";
4
-
5
- //#region src/zod-router.d.ts
6
-
7
- type AnyZodType = z3.ZodTypeAny | z4.$ZodType;
8
- declare function isZod4Schema(schema: AnyZodType): schema is z4.$ZodType;
9
- type InferOutput<T> = T extends z4.$ZodType ? z4.output<T> : T extends z3.ZodTypeAny ? z3.output<T> : T extends {
10
- _output: infer O;
11
- } ? O : T extends {
12
- _type: infer O;
13
- } ? O : unknown;
14
- type InferInput<T> = T extends z4.$ZodType ? z4.input<T> : T extends z3.ZodTypeAny ? z3.input<T> : T extends {
15
- _input: infer I;
16
- } ? I : T extends {
17
- _type: infer I;
18
- } ? I : unknown;
19
- declare function parseSchema<T extends AnyZodType>(schema: T, data: unknown): InferOutput<T>;
20
- type SafeParseResult<T extends AnyZodType> = T extends z4.$ZodType ? ReturnType<typeof z4.safeParse<T>> : T extends z3.ZodTypeAny ? z3.SafeParseReturnType<z3.input<T>, z3.output<T>> : never;
21
- declare function safeParseSchema<T extends AnyZodType>(schema: T, data: unknown): SafeParseResult<T>;
22
- declare function isZodError(error: unknown): error is z3.ZodError;
23
- /**
24
- * Extract route parameters from Express.js route patterns.
25
- *
26
- * Supports all Express.js routing patterns:
27
- * - Named parameters: /users/:userId → { userId: string }
28
- * - Multiple parameters: /users/:userId/books/:bookId → { userId: string; bookId: string }
29
- * - Parameters with separators: /flights/:from-:to → { from: string; to: string }
30
- * - Dot notation: /plantae/:genus.:species → { genus: string; species: string }
31
- * - Regex constraints: /user/:id(\\d+) → { id: string }
32
- * - Optional parameters: /posts/:year/:month? → { year: string; month?: string }
33
- * - Wildcard parameters: /files/* → { "0": string }
34
- * - Multiple wildcards: /a/star/b/star → { "0": string; "1": string }
35
- */
36
- type ExtractRouteParams<Path extends string> = string extends Path ? Record<string, string> : ExtractParams<Path>;
37
- /**
38
- * Main parameter extraction logic - enhanced for Express 5 support with recursion depth limit
39
- */
40
- type ExtractParams<Path extends string> = Path extends `${infer Before}{${infer OptionalContent}}${infer After}` ? ExtractOptionalSegment<OptionalContent> & ExtractParams<`${Before}${After}`> : Path extends `${infer _Before}:${infer Rest}` ? ExtractSingleParam<Rest> & ExtractParams<RemoveFirstParam<Path>> : Path extends `${infer _Before}*${infer After}` ? { [K in CountWildcards<_Before, "0">]: string } & ExtractParams<After> : {};
41
- /**
42
- * Extract parameters from Express 5 optional segments in braces
43
- * Handles patterns like {/:param}, {.:ext}, {/optional/:param}
44
- */
45
- type ExtractOptionalSegment<Content extends string> = Content extends `/:${infer Rest}` ? ExtractOptionalParam<Rest> : Content extends `.:${infer Rest}` ? ExtractOptionalParam<Rest> : Content extends `${infer _Path}:${infer Rest}` ? ExtractOptionalParam<Rest> : {};
46
- /**
47
- * Extract a single optional parameter from brace content
48
- */
49
- type ExtractOptionalParam<Rest extends string> = Rest extends `${infer ParamName}/${infer _After}` ? { [K in ParamName]?: string } : Rest extends `${infer ParamName}-${infer _After}` ? { [K in ParamName]?: string } : Rest extends `${infer ParamName}.${infer _After}` ? { [K in ParamName]?: string } : Rest extends `${infer ParamName}` ? { [K in ParamName]?: string } : {};
50
- /**
51
- * Extract a single parameter name from the rest of the path
52
- * Enhanced to handle Express 5 patterns and optional parameters correctly
53
- * Special handling for consecutive parameters like :from-:to
54
- * Order matters: regex constraints must be handled before repeating parameters
55
- */
56
- type ExtractSingleParam<Rest extends string> = Rest extends `${infer ParamName}(${infer _Constraint})${infer _After}` ? { [K in ParamName]: string } : Rest extends `${infer ParamName}-:${infer _NextParam}` ? { [K in ParamName]: string } : Rest extends `${infer ParamName}.:${infer _NextParam}` ? { [K in ParamName]: string } : Rest extends `${infer ParamName}?/${infer _After}` ? { [K in ParamName]?: string } : Rest extends `${infer ParamName}?-${infer _After}` ? { [K in ParamName]?: string } : Rest extends `${infer ParamName}?.${infer _After}` ? { [K in ParamName]?: string } : Rest extends `${infer ParamName}?#${infer _After}` ? { [K in ParamName]?: string } : Rest extends `${infer ParamName}?:${infer _After}` ? { [K in ParamName]?: string } : Rest extends `${infer ParamName}/${infer _After}` ? { [K in ParamName]: string } : Rest extends `${infer ParamName}-${infer _After}` ? { [K in ParamName]: string } : Rest extends `${infer ParamName}.${infer _After}` ? { [K in ParamName]: string } : Rest extends `${infer ParamName}#${infer _After}` ? { [K in ParamName]: string } : Rest extends `${infer ParamName}:${infer _After}` ? { [K in ParamName]: string } : Rest extends `${infer ParamName}+${infer _After}` ? { [K in ParamName]: string[] } : Rest extends `${infer ParamName}*${infer _After}` ? { [K in ParamName]?: string[] } : Rest extends `${infer ParamName}?${infer _After}` ? { [K in ParamName]?: string } : Rest extends string ? Rest extends "" ? {} : Rest extends `${infer ParamName}?` ? { [K in ParamName]?: string } : Rest extends `${infer ParamName}+` ? { [K in ParamName]: string[] } : Rest extends `${infer ParamName}*` ? { [K in ParamName]?: string[] } : { [K in Rest]: string } : {};
57
- /**
58
- * Remove the first parameter from path to continue parsing
59
- * Enhanced to handle Express 5 patterns and optional parameters
60
- * Handles patterns like :from-:to by removing just :from and keeping -:to
61
- * Order matters: regex constraints must be handled before repeating parameters
62
- */
63
- type RemoveFirstParam<Path extends string> = Path extends `${infer Before}:${infer Rest}` ? Rest extends `${infer _ParamName}(${infer _Constraint})${infer After}` ? `${Before}${After}` : Rest extends `${infer _ParamName}-:${infer After}` ? `${Before}-:${After}` : Rest extends `${infer _ParamName}.:${infer After}` ? `${Before}.:${After}` : Rest extends `${infer _ParamName}?/${infer After}` ? `${Before}/${After}` : Rest extends `${infer _ParamName}?-${infer After}` ? `${Before}${After}` : Rest extends `${infer _ParamName}?.${infer After}` ? `${Before}${After}` : Rest extends `${infer _ParamName}?#${infer After}` ? `${Before}${After}` : Rest extends `${infer _ParamName}?:${infer After}` ? `${Before}:${After}` : Rest extends `${infer _ParamName}/${infer After}` ? `${Before}/${After}` : Rest extends `${infer _ParamName}-${infer After}` ? `${Before}${After}` : Rest extends `${infer _ParamName}.${infer After}` ? `${Before}${After}` : Rest extends `${infer _ParamName}#${infer After}` ? `${Before}${After}` : Rest extends `${infer _ParamName}:${infer After}` ? `${Before}:${After}` : Rest extends `${infer _ParamName}+${infer After}` ? `${Before}${After}` : Rest extends `${infer _ParamName}*${infer After}` ? `${Before}${After}` : Rest extends `${infer _ParamName}?${infer After}` ? `${Before}${After}` : Before : Path;
64
- /**
65
- * Count wildcards to assign proper numeric indices with recursion depth limit
66
- */
67
- type CountWildcards<Path extends string, Count extends string = "0"> = Path extends `${infer _Before}*${infer Rest}` ? CountWildcards<Rest, IncrementWildcard<Count>> : Count;
68
- /**
69
- * Helper type to increment wildcard count as string
70
- */
71
- type IncrementWildcard<T extends string> = T extends "0" ? "1" : T extends "1" ? "2" : T extends "2" ? "3" : T extends "3" ? "4" : T extends "4" ? "5" : T extends "5" ? "6" : T extends "6" ? "7" : T extends "7" ? "8" : T extends "8" ? "9" : "10";
72
- /**
73
- * Express middleware that adds custom properties to the request object and/or response locals.
74
- *
75
- * @template TReq - The shape of the properties added to the request object.
76
- * @template TLocals - The shape of the properties added to response.locals.
77
- * @param req - The Express request object, extended with TReq.
78
- * @param res - The Express response object with typed locals.
79
- * @param next - The next middleware function.
80
- */
81
- type TypedMiddleware<TReq extends Record<string, any> = {}, TLocals extends Record<string, any> = {}> = (req: Request & TReq, res: Response<any, TLocals>, next: NextFunction) => void | Promise<void>;
82
- /**
83
- * Simplified TypedMiddleware for request-only extensions (backward compatibility)
84
- */
85
- type RequestOnlyMiddleware<TReq extends Record<string, any>> = TypedMiddleware<TReq, {}>;
86
- /**
87
- * Simplified TypedMiddleware for response locals-only extensions
88
- */
89
- type LocalsOnlyMiddleware<TLocals extends Record<string, any>> = TypedMiddleware<{}, TLocals>;
90
- type InferMiddlewareProps<T extends readonly TypedMiddleware<any, any>[]> = T extends readonly [infer First, ...infer Rest] ? First extends TypedMiddleware<infer FirstReq, any> ? Rest extends readonly TypedMiddleware<any, any>[] ? FirstReq & InferMiddlewareProps<Rest> : FirstReq : {} : {};
91
- type InferMiddlewareLocals<T extends readonly TypedMiddleware<any, any>[]> = T extends readonly [infer First, ...infer Rest] ? First extends TypedMiddleware<any, infer FirstLocals> ? Rest extends readonly TypedMiddleware<any, any>[] ? FirstLocals & InferMiddlewareLocals<Rest> : FirstLocals : {} : {};
92
- type ZodRequest<Path extends string = string, BodySchema extends AnyZodType | unknown = unknown, QuerySchema extends AnyZodType | unknown = unknown, MiddlewareProps extends Record<string, any> = {}> = Omit<Request, "params" | "query" | "body"> & {
93
- params: ExtractRouteParams<Path>;
94
- body: BodySchema extends AnyZodType ? InferOutput<BodySchema> : unknown;
95
- query: QuerySchema extends AnyZodType ? InferOutput<QuerySchema> : unknown;
96
- } & MiddlewareProps;
97
- type ZodRouteHandler<Path extends string = string, BodySchema extends AnyZodType | unknown = unknown, QuerySchema extends AnyZodType | unknown = unknown, MiddlewareProps extends Record<string, any> = {}, ResponseLocals extends Record<string, any> = {}> = (req: ZodRequest<Path, BodySchema, QuerySchema, MiddlewareProps>, res: Response<any, ResponseLocals>, next?: NextFunction) => void | Promise<void> | Response | Promise<Response>;
98
- /**
99
- * Options for defining a typed route, including schemas and middleware.
100
- *
101
- * @template BodySchema - Zod schema for request body validation.
102
- * @template QuerySchema - Zod schema for query parameter validation.
103
- * @property bodySchema - Optional Zod schema for validating the request body.
104
- * @property querySchema - Optional Zod schema for validating the query string.
105
- * @property middleware - Optional array of TypedMiddleware for this route.
106
- */
107
- interface RouteOptions<BodySchema extends AnyZodType | unknown = unknown, QuerySchema extends AnyZodType | unknown = unknown> {
108
- bodySchema?: BodySchema;
109
- querySchema?: QuerySchema;
110
- middleware?: TypedMiddleware<any, any>[];
111
- }
112
- type HttpMethod = "get" | "post" | "put" | "delete" | "patch" | "options" | "head" | "all";
113
- declare class TypedRouter<RouterMiddlewareProps extends Record<string, any> = {}, RouterLocals extends Record<string, any> = {}> {
114
- private router;
115
- constructor();
116
- /**
117
- * Add typed middleware that extends the request with additional properties
118
- * and/or adds properties to response.locals
119
- */ /**
120
- * Add typed middleware to the router.
121
- * This middleware will apply to all routes defined after this call.
122
- *
123
- * @template TReq - Type extensions for the request object
124
- * @template TLocals - Type extensions for response.locals
125
- * @param middleware - The typed middleware function
126
- * @returns A new router instance with updated types
127
- */
128
- useMiddleware<TReq extends Record<string, any> = {}, TLocals extends Record<string, any> = {}>(middleware: TypedMiddleware<TReq, TLocals>): TypedRouter<RouterMiddlewareProps & TReq, RouterLocals & TLocals>;
129
- /**
130
- * Get the underlying Express router
131
- */
132
- getRouter(): express.Router;
133
- get<Path extends string>(path: Path, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
134
- get<Path extends string, BodySchema extends AnyZodType | unknown, QuerySchema extends AnyZodType | unknown>(path: Path, options: RouteOptions<BodySchema, QuerySchema>, handler: ZodRouteHandler<Path, BodySchema, QuerySchema, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
135
- get<Path extends string, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
136
- middleware: Middleware;
137
- }, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
138
- get<Path extends string, BodySchema extends AnyZodType | unknown, QuerySchema extends AnyZodType | unknown, M extends TypedMiddleware<any, any>[]>(path: Path, options: RouteOptions<BodySchema, QuerySchema> & {
139
- middleware: [...M];
140
- },
141
- // Using tuple spread pattern
142
- handler: ZodRouteHandler<Path, BodySchema, QuerySchema, RouterMiddlewareProps & InferMiddlewareProps<readonly [...M]>,
143
- // Make it readonly for type inference
144
- // Make it readonly for type inference
145
- RouterLocals & InferMiddlewareLocals<readonly [...M]>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
146
- post<Path extends string, BodySchema extends AnyZodType, QuerySchema extends AnyZodType | unknown, M extends TypedMiddleware<any, any>[]>(path: Path, options: {
147
- bodySchema: BodySchema;
148
- querySchema?: QuerySchema;
149
- middleware: [...M];
150
- }, handler: ZodRouteHandler<Path, BodySchema, QuerySchema, RouterMiddlewareProps & InferMiddlewareProps<readonly [...M]>,
151
- // Make it readonly for type inference
152
- // Make it readonly for type inference
153
- RouterLocals & InferMiddlewareLocals<readonly [...M]>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
154
- post<Path extends string, BodySchema extends AnyZodType, M extends TypedMiddleware<any, any>[]>(path: Path, options: {
155
- bodySchema: BodySchema;
156
- middleware: [...M];
157
- },
158
- // Using tuple spread pattern
159
- handler: ZodRouteHandler<Path, BodySchema, unknown, RouterMiddlewareProps & InferMiddlewareProps<readonly [...M]>,
160
- // Make it readonly for type inference
161
- // Make it readonly for type inference
162
- RouterLocals & InferMiddlewareLocals<readonly [...M]>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
163
- post<Path extends string, M extends TypedMiddleware<any, any>[]>(path: Path, options: {
164
- middleware: [...M];
165
- },
166
- // Using tuple spread pattern
167
- handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps & InferMiddlewareProps<readonly [...M]>,
168
- // Make it readonly for type inference
169
- // Make it readonly for type inference
170
- RouterLocals & InferMiddlewareLocals<readonly [...M]>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
171
- post<Path extends string, BodySchema extends AnyZodType | unknown, QuerySchema extends AnyZodType | unknown>(path: Path, options: RouteOptions<BodySchema, QuerySchema>, handler: ZodRouteHandler<Path, BodySchema, QuerySchema, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
172
- post<Path extends string>(path: Path, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
173
- put<Path extends string, BodySchema extends AnyZodType, QuerySchema extends AnyZodType | unknown, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
174
- bodySchema: BodySchema;
175
- querySchema?: QuerySchema;
176
- middleware: Middleware;
177
- }, handler: ZodRouteHandler<Path, BodySchema, QuerySchema, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
178
- put<Path extends string, BodySchema extends AnyZodType, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
179
- bodySchema: BodySchema;
180
- middleware: Middleware;
181
- }, handler: ZodRouteHandler<Path, BodySchema, unknown, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
182
- put<Path extends string, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
183
- middleware: Middleware;
184
- }, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
185
- put<Path extends string, BodySchema extends AnyZodType | unknown, QuerySchema extends AnyZodType | unknown>(path: Path, options: RouteOptions<BodySchema, QuerySchema>, handler: ZodRouteHandler<Path, BodySchema, QuerySchema, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
186
- put<Path extends string>(path: Path, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
187
- patch<Path extends string, BodySchema extends AnyZodType, QuerySchema extends AnyZodType | unknown, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
188
- bodySchema: BodySchema;
189
- querySchema?: QuerySchema;
190
- middleware: Middleware;
191
- }, handler: ZodRouteHandler<Path, BodySchema, QuerySchema, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
192
- patch<Path extends string, BodySchema extends AnyZodType, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
193
- bodySchema: BodySchema;
194
- middleware: Middleware;
195
- }, handler: ZodRouteHandler<Path, BodySchema, unknown, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
196
- patch<Path extends string, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
197
- middleware: Middleware;
198
- }, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
199
- patch<Path extends string, BodySchema extends AnyZodType | unknown, QuerySchema extends AnyZodType | unknown>(path: Path, options: RouteOptions<BodySchema, QuerySchema>, handler: ZodRouteHandler<Path, BodySchema, QuerySchema, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
200
- patch<Path extends string>(path: Path, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
201
- delete<Path extends string, QuerySchema extends AnyZodType | unknown, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
202
- querySchema: QuerySchema;
203
- middleware: Middleware;
204
- }, handler: ZodRouteHandler<Path, unknown, QuerySchema, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
205
- delete<Path extends string, QuerySchema extends AnyZodType | unknown>(path: Path, options: {
206
- querySchema: QuerySchema;
207
- }, handler: ZodRouteHandler<Path, unknown, QuerySchema, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
208
- delete<Path extends string, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
209
- middleware: Middleware;
210
- }, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
211
- delete<Path extends string>(path: Path, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
212
- options<Path extends string, QuerySchema extends AnyZodType | unknown, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
213
- querySchema: QuerySchema;
214
- middleware: Middleware;
215
- }, handler: ZodRouteHandler<Path, unknown, QuerySchema, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
216
- options<Path extends string, QuerySchema extends AnyZodType | unknown>(path: Path, options: {
217
- querySchema: QuerySchema;
218
- }, handler: ZodRouteHandler<Path, unknown, QuerySchema, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
219
- options<Path extends string, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
220
- middleware: Middleware;
221
- }, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
222
- options<Path extends string>(path: Path, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
223
- head<Path extends string, QuerySchema extends AnyZodType | unknown, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
224
- querySchema: QuerySchema;
225
- middleware: Middleware;
226
- }, handler: ZodRouteHandler<Path, unknown, QuerySchema, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
227
- head<Path extends string, QuerySchema extends AnyZodType | unknown>(path: Path, options: {
228
- querySchema: QuerySchema;
229
- }, handler: ZodRouteHandler<Path, unknown, QuerySchema, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
230
- head<Path extends string, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
231
- middleware: Middleware;
232
- }, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
233
- head<Path extends string>(path: Path, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
234
- all<Path extends string, BodySchema extends AnyZodType, QuerySchema extends AnyZodType | unknown, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
235
- bodySchema: BodySchema;
236
- querySchema?: QuerySchema;
237
- middleware: Middleware;
238
- }, handler: ZodRouteHandler<Path, BodySchema, QuerySchema, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
239
- all<Path extends string, BodySchema extends AnyZodType, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
240
- bodySchema: BodySchema;
241
- middleware: Middleware;
242
- }, handler: ZodRouteHandler<Path, BodySchema, unknown, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
243
- all<Path extends string, QuerySchema extends AnyZodType | unknown, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
244
- querySchema: QuerySchema;
245
- middleware: Middleware;
246
- }, handler: ZodRouteHandler<Path, unknown, QuerySchema, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
247
- all<Path extends string, BodySchema extends AnyZodType | unknown, QuerySchema extends AnyZodType | unknown>(path: Path, options: RouteOptions<BodySchema, QuerySchema>, handler: ZodRouteHandler<Path, BodySchema, QuerySchema, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
248
- all<Path extends string, Middleware extends readonly TypedMiddleware<any, any>[]>(path: Path, options: {
249
- middleware: Middleware;
250
- }, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps & InferMiddlewareProps<Middleware>, RouterLocals & InferMiddlewareLocals<Middleware>>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
251
- all<Path extends string>(path: Path, handler: ZodRouteHandler<Path, unknown, unknown, RouterMiddlewareProps, RouterLocals>): TypedRouter<RouterMiddlewareProps, RouterLocals>;
252
- private registerRoute;
253
- private createBodyValidationMiddleware;
254
- private createQueryValidationMiddleware;
255
- }
256
- /**
257
- * Create a new strongly-typed Express router instance.
258
- *
259
- * This is the simplest way to get started with @minisylar/express-typed-router.
260
- *
261
- * @example
262
- * import { createTypedRouter } from '@minisylar/express-typed-router';
263
- *
264
- * // Create a router and add a typed GET route
265
- * const router = createTypedRouter();
266
- * router.get('/hello/:name', (req, res) => {
267
- * // req.params.name is typed as string
268
- * res.json({ message: `Hello, ${req.params.name}!` });
269
- * });
270
- *
271
- * // Use with Express
272
- * import express from 'express';
273
- * const app = express();
274
- * app.use('/api', router.getRouter());
275
- */
276
- declare function createTypedRouter<RouterMiddlewareProps extends Record<string, any> = {}, RouterLocals extends Record<string, any> = {}>(): TypedRouter<RouterMiddlewareProps, RouterLocals>;
277
- /**
278
- * Configuration options for createTypedRouterWithConfig.
279
- *
280
- * @property validateInput - (Future) Whether to enable global input validation.
281
- * @property errorHandler - Optional global error handler middleware for the router.
282
- */
283
- interface RouterConfig {
284
- validateInput?: boolean;
285
- errorHandler?: (error: any, req: Request, res: Response, next: NextFunction) => void;
286
- }
287
- /**
288
- * Create a new typed router with optional configuration.
289
- *
290
- * Use this if you want to add a global error handler or future global options.
291
- *
292
- * @param config - Optional configuration for the router (e.g. error handler).
293
- * @returns A new TypedRouter instance.
294
- *
295
- * @example
296
- * import { createTypedRouterWithConfig } from '@minisylar/express-typed-router';
297
- *
298
- * const router = createTypedRouterWithConfig({
299
- * errorHandler: (err, req, res, next) => {
300
- * res.status(500).json({ error: 'Something went wrong', details: err });
301
- * }
302
- * });
303
- */
304
- declare function createTypedRouterWithConfig<RouterMiddlewareProps extends Record<string, any> = {}, RouterLocals extends Record<string, any> = {}>(config?: RouterConfig): TypedRouter<RouterMiddlewareProps, RouterLocals>;
305
- /**
306
- * Create a new typed router with pre-configured middleware.
307
- *
308
- * This is useful for setting up router-level middleware in a single call.
309
- *
310
- * @param middleware - One or more TypedMiddleware functions to apply to all routes.
311
- * @returns A new TypedRouter instance with the middleware applied.
312
- *
313
- * @example
314
- * import { createTypedRouterWithMiddleware } from '@minisylar/express-typed-router';
315
- *
316
- * const router = createTypedRouterWithMiddleware(authMiddleware, loggingMiddleware);
317
- */
318
- declare function createTypedRouterWithMiddleware<T extends Record<string, any>>(...middleware: TypedMiddleware<any, any>[]): TypedRouter<T>;
319
- //#endregion
320
- export { AnyZodType, ExtractRouteParams, HttpMethod, InferInput, InferOutput, LocalsOnlyMiddleware, RequestOnlyMiddleware, RouteOptions, RouterConfig, SafeParseResult, TypedMiddleware, ZodRequest, ZodRouteHandler, createTypedRouter, createTypedRouterWithConfig, createTypedRouterWithMiddleware, isZod4Schema, isZodError, parseSchema, safeParseSchema };
@@ -1 +0,0 @@
1
- import e from"express";import*as t from"zod/v3";import*as n from"zod/v4/core";function r(e){return`_zod`in e}function i(e,t){return r(e)?n.parse(e,t):e.parse(t)}function a(e,t){return r(e)?n.safeParse(e,t):e.safeParse(t)}function o(e){return e instanceof t.ZodError||typeof e==`object`&&!!e&&`issues`in e&&Array.isArray(e.issues)}var s=class{router;constructor(){this.router=e.Router()}useMiddleware(e){return this.router.use(e),this}getRouter(){return this.router}get(e,t,n){return this.registerRoute(`get`,e,t,n)}post(e,t,n){return this.registerRoute(`post`,e,t,n)}put(e,t,n){return this.registerRoute(`put`,e,t,n)}patch(e,t,n){return this.registerRoute(`patch`,e,t,n)}delete(e,t,n){return this.registerRoute(`delete`,e,t,n)}options(e,t,n){return this.registerRoute(`options`,e,t,n)}head(e,t,n){return this.registerRoute(`head`,e,t,n)}all(e,t,n){return this.registerRoute(`all`,e,t,n)}registerRoute(e,t,n,r){let i=[];if(typeof n==`object`){let e=n;e.middleware&&i.push(...e.middleware),e.bodySchema&&i.push(this.createBodyValidationMiddleware(e.bodySchema)),e.querySchema&&i.push(this.createQueryValidationMiddleware(e.querySchema)),i.push(r)}else i.push(n);return this.router[e](t,...i),this}createBodyValidationMiddleware(e){return(t,n,r)=>{try{t.body=i(e,t.body),r()}catch(e){o(e)?n.status(400).json({error:`Validation failed`,details:e.errors||e.issues}):r(e)}}}createQueryValidationMiddleware(e){return(t,n,r)=>{try{let n=i(e,t.query);Object.defineProperty(t,`query`,{value:n,writable:!1,enumerable:!0,configurable:!0}),r()}catch(e){o(e)?n.status(400).json({error:`Validation failed`,details:e.errors||e.issues}):r(e)}}}};function c(){return new s}function l(e){let t=new s;return e?.errorHandler&&t.getRouter().use(e.errorHandler),t}function u(...e){let t=new s;for(let n of e)t=t.useMiddleware(n);return t}export{c as createTypedRouter,l as createTypedRouterWithConfig,u as createTypedRouterWithMiddleware,r as isZod4Schema,o as isZodError,i as parseSchema,a as safeParseSchema};