@veloxts/validation 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +398 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +36 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware.d.ts +174 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/middleware.js +274 -0
- package/dist/middleware.js.map +1 -0
- package/dist/schemas/common.d.ts +168 -0
- package/dist/schemas/common.d.ts.map +1 -0
- package/dist/schemas/common.js +211 -0
- package/dist/schemas/common.js.map +1 -0
- package/dist/schemas/pagination.d.ts +287 -0
- package/dist/schemas/pagination.d.ts.map +1 -0
- package/dist/schemas/pagination.js +202 -0
- package/dist/schemas/pagination.js.map +1 -0
- package/dist/types.d.ts +159 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +78 -0
- package/dist/types.js.map +1 -0
- package/package.json +62 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 VeloxTS Framework Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
# @veloxts/validation
|
|
2
|
+
|
|
3
|
+
Type-safe validation using Zod schemas for the VeloxTS framework.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @veloxts/validation
|
|
9
|
+
# or
|
|
10
|
+
pnpm add @veloxts/validation
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Note: Zod is a peer dependency and will be installed automatically if not already present.
|
|
14
|
+
|
|
15
|
+
## Quick Start
|
|
16
|
+
|
|
17
|
+
```typescript
|
|
18
|
+
import { z, parse, InferOutput } from '@veloxts/validation';
|
|
19
|
+
|
|
20
|
+
// Define a schema
|
|
21
|
+
const UserSchema = z.object({
|
|
22
|
+
id: z.string().uuid(),
|
|
23
|
+
name: z.string().min(1),
|
|
24
|
+
email: z.string().email(),
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
// Infer the TypeScript type
|
|
28
|
+
type User = InferOutput<typeof UserSchema>;
|
|
29
|
+
|
|
30
|
+
// Parse and validate data
|
|
31
|
+
const user = parse(UserSchema, {
|
|
32
|
+
id: '123e4567-e89b-012d-3456-426614174000',
|
|
33
|
+
name: 'Alice',
|
|
34
|
+
email: 'alice@example.com',
|
|
35
|
+
});
|
|
36
|
+
// user is typed as User and validated
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Core API
|
|
40
|
+
|
|
41
|
+
### Validation Functions
|
|
42
|
+
|
|
43
|
+
#### `parse(schema, data)`
|
|
44
|
+
|
|
45
|
+
Parses data against a schema and throws a `ValidationError` if invalid.
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
import { parse, ValidationError } from '@veloxts/validation';
|
|
49
|
+
|
|
50
|
+
try {
|
|
51
|
+
const user = parse(UserSchema, untrustedData);
|
|
52
|
+
// user is valid and typed
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (error instanceof ValidationError) {
|
|
55
|
+
console.log('Validation failed:', error.fields);
|
|
56
|
+
// error.fields contains field-specific error messages
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
#### `safeParse(schema, data)`
|
|
62
|
+
|
|
63
|
+
Parses data and returns a result object instead of throwing.
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
import { safeParse } from '@veloxts/validation';
|
|
67
|
+
|
|
68
|
+
const result = safeParse(UserSchema, untrustedData);
|
|
69
|
+
|
|
70
|
+
if (result.success) {
|
|
71
|
+
console.log('Valid user:', result.data);
|
|
72
|
+
} else {
|
|
73
|
+
console.log('Validation errors:', result.error.issues);
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Common Schemas
|
|
78
|
+
|
|
79
|
+
The package provides pre-built schemas for common use cases:
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
import {
|
|
83
|
+
uuidSchema,
|
|
84
|
+
emailSchema,
|
|
85
|
+
urlSchema,
|
|
86
|
+
nonEmptyStringSchema,
|
|
87
|
+
datetimeSchema,
|
|
88
|
+
idParamSchema,
|
|
89
|
+
timestampFieldsSchema,
|
|
90
|
+
} from '@veloxts/validation';
|
|
91
|
+
|
|
92
|
+
// UUID validation
|
|
93
|
+
const id = parse(uuidSchema, '123e4567-e89b-012d-3456-426614174000');
|
|
94
|
+
|
|
95
|
+
// Email validation
|
|
96
|
+
const email = parse(emailSchema, 'user@example.com');
|
|
97
|
+
|
|
98
|
+
// URL validation
|
|
99
|
+
const website = parse(urlSchema, 'https://example.com');
|
|
100
|
+
|
|
101
|
+
// Non-empty string (trimmed, min 1 char)
|
|
102
|
+
const name = parse(nonEmptyStringSchema, ' Alice '); // "Alice"
|
|
103
|
+
|
|
104
|
+
// ISO datetime string
|
|
105
|
+
const timestamp = parse(datetimeSchema, '2025-01-01T00:00:00Z');
|
|
106
|
+
|
|
107
|
+
// Route parameter validation (e.g., /users/:id)
|
|
108
|
+
const params = parse(idParamSchema, { id: '123e4567-...' });
|
|
109
|
+
|
|
110
|
+
// Standard timestamp fields for entities
|
|
111
|
+
const EntitySchema = z.object({
|
|
112
|
+
id: uuidSchema,
|
|
113
|
+
name: nonEmptyStringSchema,
|
|
114
|
+
}).merge(timestampFieldsSchema);
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Pagination Schemas
|
|
118
|
+
|
|
119
|
+
Built-in support for offset-based and cursor-based pagination:
|
|
120
|
+
|
|
121
|
+
```typescript
|
|
122
|
+
import {
|
|
123
|
+
paginationInputSchema,
|
|
124
|
+
createPaginatedResponseSchema,
|
|
125
|
+
calculatePaginationMeta,
|
|
126
|
+
PAGINATION_DEFAULTS,
|
|
127
|
+
} from '@veloxts/validation';
|
|
128
|
+
|
|
129
|
+
// Input schema for pagination params
|
|
130
|
+
const input = parse(paginationInputSchema, {
|
|
131
|
+
page: 1,
|
|
132
|
+
limit: 20, // default: 10, max: 100
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// Create a paginated response schema
|
|
136
|
+
const UserListSchema = createPaginatedResponseSchema(UserSchema);
|
|
137
|
+
|
|
138
|
+
// Calculate pagination metadata
|
|
139
|
+
const meta = calculatePaginationMeta({
|
|
140
|
+
page: 1,
|
|
141
|
+
limit: 10,
|
|
142
|
+
total: 95,
|
|
143
|
+
});
|
|
144
|
+
// { page: 1, limit: 10, total: 95, totalPages: 10, hasNext: true, hasPrev: false }
|
|
145
|
+
|
|
146
|
+
// Use in procedure definitions
|
|
147
|
+
export const userProcedures = defineProcedures('users', {
|
|
148
|
+
listUsers: procedure()
|
|
149
|
+
.input(paginationInputSchema)
|
|
150
|
+
.output(UserListSchema)
|
|
151
|
+
.query(async ({ input, ctx }) => {
|
|
152
|
+
const skip = (input.page - 1) * input.limit;
|
|
153
|
+
const [data, total] = await Promise.all([
|
|
154
|
+
ctx.db.user.findMany({ skip, take: input.limit }),
|
|
155
|
+
ctx.db.user.count(),
|
|
156
|
+
]);
|
|
157
|
+
|
|
158
|
+
return {
|
|
159
|
+
data,
|
|
160
|
+
meta: calculatePaginationMeta({
|
|
161
|
+
page: input.page,
|
|
162
|
+
limit: input.limit,
|
|
163
|
+
total,
|
|
164
|
+
}),
|
|
165
|
+
};
|
|
166
|
+
}),
|
|
167
|
+
});
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### Schema Utilities
|
|
171
|
+
|
|
172
|
+
#### Field Manipulation
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
import { pickFields, omitFields, makePartial, partialExcept } from '@veloxts/validation';
|
|
176
|
+
|
|
177
|
+
const UserSchema = z.object({
|
|
178
|
+
id: z.string().uuid(),
|
|
179
|
+
name: z.string(),
|
|
180
|
+
email: z.string().email(),
|
|
181
|
+
password: z.string(),
|
|
182
|
+
createdAt: z.string().datetime(),
|
|
183
|
+
updatedAt: z.string().datetime(),
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
// Pick specific fields
|
|
187
|
+
const UserPublicSchema = pickFields(UserSchema, ['id', 'name', 'email']);
|
|
188
|
+
// { id, name, email }
|
|
189
|
+
|
|
190
|
+
// Omit fields
|
|
191
|
+
const UserWithoutPassword = omitFields(UserSchema, ['password']);
|
|
192
|
+
// { id, name, email, createdAt, updatedAt }
|
|
193
|
+
|
|
194
|
+
// Make all fields optional
|
|
195
|
+
const PartialUserSchema = makePartial(UserSchema);
|
|
196
|
+
// All fields are optional
|
|
197
|
+
|
|
198
|
+
// Make all fields optional except specified ones
|
|
199
|
+
const UserUpdateSchema = partialExcept(UserSchema, ['id']);
|
|
200
|
+
// id is required, all other fields are optional
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
#### Type Guards
|
|
204
|
+
|
|
205
|
+
```typescript
|
|
206
|
+
import { createTypeGuard } from '@veloxts/validation';
|
|
207
|
+
|
|
208
|
+
const isUser = createTypeGuard(UserSchema);
|
|
209
|
+
|
|
210
|
+
if (isUser(data)) {
|
|
211
|
+
// data is typed as User
|
|
212
|
+
console.log(data.name);
|
|
213
|
+
}
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### String Coercion Schemas
|
|
217
|
+
|
|
218
|
+
Useful for parsing query parameters and form data:
|
|
219
|
+
|
|
220
|
+
```typescript
|
|
221
|
+
import {
|
|
222
|
+
numberStringSchema,
|
|
223
|
+
integerStringSchema,
|
|
224
|
+
booleanStringSchema,
|
|
225
|
+
} from '@veloxts/validation';
|
|
226
|
+
|
|
227
|
+
// Parse string to number
|
|
228
|
+
const age = parse(numberStringSchema, '25'); // 25 (number)
|
|
229
|
+
|
|
230
|
+
// Parse string to integer
|
|
231
|
+
const count = parse(integerStringSchema, '42'); // 42 (number)
|
|
232
|
+
|
|
233
|
+
// Parse string to boolean
|
|
234
|
+
const enabled = parse(booleanStringSchema, 'true'); // true (boolean)
|
|
235
|
+
// Accepts: "true", "false", "1", "0", "yes", "no"
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
## Using with Procedures
|
|
239
|
+
|
|
240
|
+
Validation schemas integrate seamlessly with VeloxTS procedures:
|
|
241
|
+
|
|
242
|
+
```typescript
|
|
243
|
+
import { procedure, defineProcedures } from '@veloxts/router';
|
|
244
|
+
import { z, emailSchema, nonEmptyStringSchema } from '@veloxts/validation';
|
|
245
|
+
|
|
246
|
+
const CreateUserInput = z.object({
|
|
247
|
+
name: nonEmptyStringSchema,
|
|
248
|
+
email: emailSchema,
|
|
249
|
+
age: z.number().int().min(18).optional(),
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
export const userProcedures = defineProcedures('users', {
|
|
253
|
+
createUser: procedure()
|
|
254
|
+
.input(CreateUserInput)
|
|
255
|
+
.output(UserSchema)
|
|
256
|
+
.mutation(async ({ input, ctx }) => {
|
|
257
|
+
// input is automatically validated and typed
|
|
258
|
+
// { name: string, email: string, age?: number }
|
|
259
|
+
return ctx.db.user.create({ data: input });
|
|
260
|
+
}),
|
|
261
|
+
});
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
## Type Inference
|
|
265
|
+
|
|
266
|
+
The package provides type inference utilities for extracting types from schemas:
|
|
267
|
+
|
|
268
|
+
```typescript
|
|
269
|
+
import { InferInput, InferOutput } from '@veloxts/validation';
|
|
270
|
+
|
|
271
|
+
const UserSchema = z.object({
|
|
272
|
+
email: z.string().email(),
|
|
273
|
+
age: z.number().transform((n) => n + 1),
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
// Input type (before transformation)
|
|
277
|
+
type UserInput = InferInput<typeof UserSchema>;
|
|
278
|
+
// { email: string; age: number }
|
|
279
|
+
|
|
280
|
+
// Output type (after transformation)
|
|
281
|
+
type UserOutput = InferOutput<typeof UserSchema>;
|
|
282
|
+
// { email: string; age: number } (age is transformed)
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
## Error Handling
|
|
286
|
+
|
|
287
|
+
Validation errors are automatically formatted with field-level details:
|
|
288
|
+
|
|
289
|
+
```typescript
|
|
290
|
+
import { ValidationError, parse } from '@veloxts/validation';
|
|
291
|
+
|
|
292
|
+
const UserSchema = z.object({
|
|
293
|
+
name: z.string().min(2),
|
|
294
|
+
email: z.string().email(),
|
|
295
|
+
age: z.number().min(18),
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
try {
|
|
299
|
+
parse(UserSchema, {
|
|
300
|
+
name: 'A', // too short
|
|
301
|
+
email: 'invalid', // not an email
|
|
302
|
+
age: 16, // too young
|
|
303
|
+
});
|
|
304
|
+
} catch (error) {
|
|
305
|
+
if (error instanceof ValidationError) {
|
|
306
|
+
console.log(error.message); // "Validation failed"
|
|
307
|
+
console.log(error.statusCode); // 400
|
|
308
|
+
console.log(error.fields);
|
|
309
|
+
// {
|
|
310
|
+
// name: "String must contain at least 2 character(s)",
|
|
311
|
+
// email: "Invalid email",
|
|
312
|
+
// age: "Number must be greater than or equal to 18"
|
|
313
|
+
// }
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
## Advanced Features
|
|
319
|
+
|
|
320
|
+
### Custom Validators
|
|
321
|
+
|
|
322
|
+
Create reusable validation functions:
|
|
323
|
+
|
|
324
|
+
```typescript
|
|
325
|
+
import { createValidator } from '@veloxts/validation';
|
|
326
|
+
|
|
327
|
+
const validateUser = createValidator(UserSchema);
|
|
328
|
+
|
|
329
|
+
// Use in middleware or handlers
|
|
330
|
+
const user = validateUser(request.body);
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
### Schema Composition
|
|
334
|
+
|
|
335
|
+
Build complex schemas from simpler ones:
|
|
336
|
+
|
|
337
|
+
```typescript
|
|
338
|
+
import { timestampFieldsSchema, baseEntitySchema } from '@veloxts/validation';
|
|
339
|
+
import { z } from 'zod';
|
|
340
|
+
|
|
341
|
+
const PostSchema = baseEntitySchema.extend({
|
|
342
|
+
title: z.string().min(1).max(200),
|
|
343
|
+
content: z.string().min(1),
|
|
344
|
+
authorId: z.string().uuid(),
|
|
345
|
+
published: z.boolean().default(false),
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
// baseEntitySchema includes: id (UUID), createdAt, updatedAt
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
## Configuration
|
|
352
|
+
|
|
353
|
+
### Pagination Defaults
|
|
354
|
+
|
|
355
|
+
Customize pagination defaults:
|
|
356
|
+
|
|
357
|
+
```typescript
|
|
358
|
+
import { PAGINATION_DEFAULTS } from '@veloxts/validation';
|
|
359
|
+
|
|
360
|
+
console.log(PAGINATION_DEFAULTS);
|
|
361
|
+
// {
|
|
362
|
+
// page: 1,
|
|
363
|
+
// limit: 10,
|
|
364
|
+
// maxLimit: 100,
|
|
365
|
+
// }
|
|
366
|
+
|
|
367
|
+
// Create custom pagination schema
|
|
368
|
+
const customPaginationSchema = z.object({
|
|
369
|
+
page: z.number().int().min(1).default(1),
|
|
370
|
+
limit: z.number().int().min(1).max(50).default(25), // custom max
|
|
371
|
+
});
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
## Best Practices
|
|
375
|
+
|
|
376
|
+
1. **Define schemas once, reuse everywhere**: Share schemas between frontend and backend for consistent validation.
|
|
377
|
+
|
|
378
|
+
2. **Use common schemas**: Leverage built-in schemas like `emailSchema`, `uuidSchema` for consistency.
|
|
379
|
+
|
|
380
|
+
3. **Compose schemas**: Build complex schemas from simpler ones using `.extend()`, `.merge()`, and `.pick()`.
|
|
381
|
+
|
|
382
|
+
4. **Validate early**: Use `input()` in procedures to validate at the API boundary.
|
|
383
|
+
|
|
384
|
+
5. **Type inference**: Use `InferOutput` to extract TypeScript types instead of manually defining them.
|
|
385
|
+
|
|
386
|
+
## Related Packages
|
|
387
|
+
|
|
388
|
+
- [@veloxts/core](/packages/core) - Core framework with error classes
|
|
389
|
+
- [@veloxts/router](/packages/router) - Procedure definitions using validation schemas
|
|
390
|
+
- [@veloxts/client](/packages/client) - Type-safe API client with inferred types
|
|
391
|
+
|
|
392
|
+
## TypeScript Support
|
|
393
|
+
|
|
394
|
+
All exports are fully typed with comprehensive JSDoc documentation. The package includes type definitions and declaration maps for excellent IDE support.
|
|
395
|
+
|
|
396
|
+
## License
|
|
397
|
+
|
|
398
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @veloxts/validation - Zod integration for runtime validation
|
|
3
|
+
*
|
|
4
|
+
* Provides Zod-based validation with automatic type inference for
|
|
5
|
+
* procedure inputs/outputs and request validation.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { z, parse, InferOutput } from '@veloxts/validation';
|
|
10
|
+
*
|
|
11
|
+
* const UserSchema = z.object({
|
|
12
|
+
* id: z.string().uuid(),
|
|
13
|
+
* name: z.string().min(1),
|
|
14
|
+
* email: z.string().email(),
|
|
15
|
+
* });
|
|
16
|
+
*
|
|
17
|
+
* type User = InferOutput<typeof UserSchema>;
|
|
18
|
+
*
|
|
19
|
+
* const user = parse(UserSchema, data);
|
|
20
|
+
* // user is typed as User
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* @module @veloxts/validation
|
|
24
|
+
*/
|
|
25
|
+
export { ZodError, type ZodType, type ZodTypeDef, z } from 'zod';
|
|
26
|
+
export declare const VALIDATION_VERSION: "0.1.0";
|
|
27
|
+
export type { AnySchema, AnyZodSchema, InferInput, InferOutput, NoInput, ResolveInput, ResolveOutput, SafeParseError, SafeParseResult, SafeParseSuccess, Schema, SchemaLike, UnknownOutput, ValidationIssue, } from './types.js';
|
|
28
|
+
export { isSchema, isZodSchema, wrapSchema } from './types.js';
|
|
29
|
+
export type { Validator } from './middleware.js';
|
|
30
|
+
export { assertSchema, createTypeGuard, createValidator, formatZodErrors, parse, parseAll, safeParse, safeValidate, validate, validateAll, zodErrorToValidationError, } from './middleware.js';
|
|
31
|
+
export type { BaseEntity, IdParam, TimestampFields } from './schemas/common.js';
|
|
32
|
+
export { baseEntitySchema, booleanStringSchema, createIdSchema, datetimeSchema, emailSchema, idParamSchema, integerStringSchema, makePartial, nonEmptyStringSchema, numberStringSchema, omitFields, partialExcept, pickFields, timestampFieldsSchema, urlSchema, uuidSchema, } from './schemas/common.js';
|
|
33
|
+
export type { CursorPaginatedResponse, CursorPaginationInput, CursorPaginationMeta, PaginatedResponse, PaginationInput, PaginationMeta, } from './schemas/pagination.js';
|
|
34
|
+
export { calculateOffset, calculatePaginationMeta, createCursorPaginatedResponseSchema, createPaginatedResponse, createPaginatedResponseSchema, createPaginationSchema, cursorPaginationSchema, PAGINATION_DEFAULTS, paginationInputSchema, } from './schemas/pagination.js';
|
|
35
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAIH,OAAO,EAAE,QAAQ,EAAE,KAAK,OAAO,EAAE,KAAK,UAAU,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGjE,eAAO,MAAM,kBAAkB,EAAG,OAAgB,CAAC;AAMnD,YAAY,EAEV,SAAS,EACT,YAAY,EACZ,UAAU,EACV,WAAW,EACX,OAAO,EACP,YAAY,EACZ,aAAa,EAEb,cAAc,EACd,eAAe,EACf,gBAAgB,EAChB,MAAM,EACN,UAAU,EACV,aAAa,EACb,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAU/D,YAAY,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAGjD,OAAO,EACL,YAAY,EACZ,eAAe,EACf,eAAe,EACf,eAAe,EACf,KAAK,EACL,QAAQ,EACR,SAAS,EACT,YAAY,EACZ,QAAQ,EACR,WAAW,EACX,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAMzB,YAAY,EAAE,UAAU,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAChF,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,WAAW,EACX,aAAa,EACb,mBAAmB,EACnB,WAAW,EACX,oBAAoB,EACpB,kBAAkB,EAClB,UAAU,EACV,aAAa,EACb,UAAU,EACV,qBAAqB,EACrB,SAAS,EACT,UAAU,GACX,MAAM,qBAAqB,CAAC;AAM7B,YAAY,EACV,uBAAuB,EACvB,qBAAqB,EACrB,oBAAoB,EACpB,iBAAiB,EACjB,eAAe,EACf,cAAc,GACf,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,mCAAmC,EACnC,uBAAuB,EACvB,6BAA6B,EAC7B,sBAAsB,EACtB,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,yBAAyB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @veloxts/validation - Zod integration for runtime validation
|
|
3
|
+
*
|
|
4
|
+
* Provides Zod-based validation with automatic type inference for
|
|
5
|
+
* procedure inputs/outputs and request validation.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { z, parse, InferOutput } from '@veloxts/validation';
|
|
10
|
+
*
|
|
11
|
+
* const UserSchema = z.object({
|
|
12
|
+
* id: z.string().uuid(),
|
|
13
|
+
* name: z.string().min(1),
|
|
14
|
+
* email: z.string().email(),
|
|
15
|
+
* });
|
|
16
|
+
*
|
|
17
|
+
* type User = InferOutput<typeof UserSchema>;
|
|
18
|
+
*
|
|
19
|
+
* const user = parse(UserSchema, data);
|
|
20
|
+
* // user is typed as User
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* @module @veloxts/validation
|
|
24
|
+
*/
|
|
25
|
+
// Re-export Zod for convenience
|
|
26
|
+
// Users can import { z } from '@veloxts/validation' instead of installing zod separately
|
|
27
|
+
export { ZodError, z } from 'zod';
|
|
28
|
+
// Version constant
|
|
29
|
+
export const VALIDATION_VERSION = '0.1.0';
|
|
30
|
+
export { isSchema, isZodSchema, wrapSchema } from './types.js';
|
|
31
|
+
// Primary API - parse functions (Zod naming convention)
|
|
32
|
+
// Deprecated aliases for backwards compatibility
|
|
33
|
+
export { assertSchema, createTypeGuard, createValidator, formatZodErrors, parse, parseAll, safeParse, safeValidate, validate, validateAll, zodErrorToValidationError, } from './middleware.js';
|
|
34
|
+
export { baseEntitySchema, booleanStringSchema, createIdSchema, datetimeSchema, emailSchema, idParamSchema, integerStringSchema, makePartial, nonEmptyStringSchema, numberStringSchema, omitFields, partialExcept, pickFields, timestampFieldsSchema, urlSchema, uuidSchema, } from './schemas/common.js';
|
|
35
|
+
export { calculateOffset, calculatePaginationMeta, createCursorPaginatedResponseSchema, createPaginatedResponse, createPaginatedResponseSchema, createPaginationSchema, cursorPaginationSchema, PAGINATION_DEFAULTS, paginationInputSchema, } from './schemas/pagination.js';
|
|
36
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,gCAAgC;AAChC,yFAAyF;AACzF,OAAO,EAAE,QAAQ,EAAiC,CAAC,EAAE,MAAM,KAAK,CAAC;AAEjE,mBAAmB;AACnB,MAAM,CAAC,MAAM,kBAAkB,GAAG,OAAgB,CAAC;AAwBnD,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAW/D,wDAAwD;AACxD,iDAAiD;AACjD,OAAO,EACL,YAAY,EACZ,eAAe,EACf,eAAe,EACf,eAAe,EACf,KAAK,EACL,QAAQ,EACR,SAAS,EACT,YAAY,EACZ,QAAQ,EACR,WAAW,EACX,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAOzB,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,WAAW,EACX,aAAa,EACb,mBAAmB,EACnB,WAAW,EACX,oBAAoB,EACpB,kBAAkB,EAClB,UAAU,EACV,aAAa,EACb,UAAU,EACV,qBAAqB,EACrB,SAAS,EACT,UAAU,GACX,MAAM,qBAAqB,CAAC;AAc7B,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,mCAAmC,EACnC,uBAAuB,EACvB,6BAA6B,EAC7B,sBAAsB,EACtB,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,yBAAyB,CAAC"}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validation middleware for VeloxTS procedures and routes
|
|
3
|
+
*
|
|
4
|
+
* Provides middleware utilities for validating request data
|
|
5
|
+
* with proper error handling and type inference.
|
|
6
|
+
*
|
|
7
|
+
* @module middleware
|
|
8
|
+
*/
|
|
9
|
+
import { ValidationError } from '@veloxts/core';
|
|
10
|
+
import { ZodError, type ZodType, type ZodTypeDef } from 'zod';
|
|
11
|
+
import type { AnySchema, AnyZodSchema, SafeParseResult } from './types.js';
|
|
12
|
+
/**
|
|
13
|
+
* Transforms Zod validation issues into a field-error map
|
|
14
|
+
*
|
|
15
|
+
* @param issues - Array of Zod validation issues
|
|
16
|
+
* @returns Record mapping field paths to error messages
|
|
17
|
+
*/
|
|
18
|
+
export declare function formatZodErrors(issues: readonly {
|
|
19
|
+
path: readonly (string | number)[];
|
|
20
|
+
message: string;
|
|
21
|
+
}[]): Record<string, string>;
|
|
22
|
+
/**
|
|
23
|
+
* Transforms a ZodError into a VeloxTSValidationError
|
|
24
|
+
*
|
|
25
|
+
* @param error - ZodError from failed validation
|
|
26
|
+
* @param customMessage - Optional custom error message
|
|
27
|
+
* @returns ValidationError with field-specific errors
|
|
28
|
+
*/
|
|
29
|
+
export declare function zodErrorToValidationError(error: ZodError, customMessage?: string): ValidationError;
|
|
30
|
+
/**
|
|
31
|
+
* Parses and validates data against a schema, throwing ValidationError on failure
|
|
32
|
+
*
|
|
33
|
+
* Follows Zod's naming convention for consistency with the ecosystem.
|
|
34
|
+
*
|
|
35
|
+
* @template T - The validated output type
|
|
36
|
+
* @param schema - Zod schema or Schema wrapper
|
|
37
|
+
* @param data - Data to validate
|
|
38
|
+
* @param errorMessage - Optional custom error message
|
|
39
|
+
* @returns Validated data with proper type
|
|
40
|
+
* @throws ValidationError if validation fails
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```typescript
|
|
44
|
+
* const UserSchema = z.object({ name: z.string(), email: z.string().email() });
|
|
45
|
+
*
|
|
46
|
+
* const user = parse(UserSchema, request.body);
|
|
47
|
+
* // user is typed as { name: string; email: string }
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
export declare function parse<T>(schema: ZodType<T, ZodTypeDef, unknown> | AnySchema, data: unknown, errorMessage?: string): T;
|
|
51
|
+
/**
|
|
52
|
+
* @deprecated Use `parse` instead. This alias will be removed in v1.0.
|
|
53
|
+
*/
|
|
54
|
+
export declare const validate: typeof parse;
|
|
55
|
+
/**
|
|
56
|
+
* Safely parses data without throwing
|
|
57
|
+
*
|
|
58
|
+
* Follows Zod's naming convention for consistency with the ecosystem.
|
|
59
|
+
*
|
|
60
|
+
* @template T - The validated output type
|
|
61
|
+
* @param schema - Zod schema or Schema wrapper
|
|
62
|
+
* @param data - Data to validate
|
|
63
|
+
* @returns Safe parse result with success discriminator
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```typescript
|
|
67
|
+
* const result = safeParse(UserSchema, request.body);
|
|
68
|
+
* if (result.success) {
|
|
69
|
+
* console.log(result.data.name);
|
|
70
|
+
* } else {
|
|
71
|
+
* console.log(result.error);
|
|
72
|
+
* }
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
export declare function safeParse<T>(schema: ZodType<T, ZodTypeDef, unknown> | AnySchema, data: unknown): SafeParseResult<T>;
|
|
76
|
+
/**
|
|
77
|
+
* @deprecated Use `safeParse` instead. This alias will be removed in v1.0.
|
|
78
|
+
*/
|
|
79
|
+
export declare const safeValidate: typeof safeParse;
|
|
80
|
+
/**
|
|
81
|
+
* Creates a reusable validator function from a schema
|
|
82
|
+
*
|
|
83
|
+
* @template TOutput - The validated output type
|
|
84
|
+
* @template TInput - The input type (defaults to unknown)
|
|
85
|
+
* @param schema - Zod schema for validation
|
|
86
|
+
* @returns Object with parse and safeParse methods
|
|
87
|
+
*
|
|
88
|
+
* @example
|
|
89
|
+
* ```typescript
|
|
90
|
+
* const userValidator = createValidator(UserSchema);
|
|
91
|
+
*
|
|
92
|
+
* // In a handler
|
|
93
|
+
* const user = userValidator.parse(request.body);
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
export declare function createValidator<TOutput, TInput = unknown>(schema: ZodType<TOutput, ZodTypeDef, TInput>): Validator<TOutput>;
|
|
97
|
+
/**
|
|
98
|
+
* Validator interface for type-safe validation
|
|
99
|
+
*/
|
|
100
|
+
export interface Validator<T> {
|
|
101
|
+
/** Parses data, throwing ValidationError on failure */
|
|
102
|
+
parse(data: unknown): T;
|
|
103
|
+
/** Safely parses data without throwing */
|
|
104
|
+
safeParse(data: unknown): SafeParseResult<T>;
|
|
105
|
+
/** @deprecated Use `parse` instead */
|
|
106
|
+
validate(data: unknown): T;
|
|
107
|
+
/** @deprecated Use `safeParse` instead */
|
|
108
|
+
safeValidate(data: unknown): SafeParseResult<T>;
|
|
109
|
+
/** The underlying Zod schema */
|
|
110
|
+
schema: AnyZodSchema;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Parses multiple data sources at once
|
|
114
|
+
*
|
|
115
|
+
* Useful for validating body, query, and params together.
|
|
116
|
+
*
|
|
117
|
+
* @param validations - Object mapping names to schema/data pairs
|
|
118
|
+
* @returns Object with validated data for each key
|
|
119
|
+
* @throws ValidationError with combined errors if any validation fails
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```typescript
|
|
123
|
+
* const { body, query, params } = parseAll({
|
|
124
|
+
* body: [CreateUserSchema, request.body],
|
|
125
|
+
* query: [PaginationSchema, request.query],
|
|
126
|
+
* params: [IdParamSchema, request.params],
|
|
127
|
+
* });
|
|
128
|
+
* ```
|
|
129
|
+
*/
|
|
130
|
+
export declare function parseAll<T extends Record<string, [AnyZodSchema, unknown]>>(validations: T): {
|
|
131
|
+
[K in keyof T]: T[K][0] extends ZodType<infer O, ZodTypeDef, unknown> ? O : never;
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* @deprecated Use `parseAll` instead. This alias will be removed in v1.0.
|
|
135
|
+
*/
|
|
136
|
+
export declare const validateAll: typeof parseAll;
|
|
137
|
+
/**
|
|
138
|
+
* Creates a type guard from a Zod schema
|
|
139
|
+
*
|
|
140
|
+
* @template T - The validated type
|
|
141
|
+
* @param schema - Zod schema to use for checking
|
|
142
|
+
* @returns Type predicate function
|
|
143
|
+
*
|
|
144
|
+
* @example
|
|
145
|
+
* ```typescript
|
|
146
|
+
* const isUser = createTypeGuard(UserSchema);
|
|
147
|
+
*
|
|
148
|
+
* if (isUser(data)) {
|
|
149
|
+
* // data is typed as User
|
|
150
|
+
* console.log(data.name);
|
|
151
|
+
* }
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
export declare function createTypeGuard<T>(schema: ZodType<T, ZodTypeDef, unknown>): (value: unknown) => value is T;
|
|
155
|
+
/**
|
|
156
|
+
* Asserts that a value matches a schema, narrowing the type
|
|
157
|
+
*
|
|
158
|
+
* @template T - The validated type
|
|
159
|
+
* @param schema - Zod schema to validate against
|
|
160
|
+
* @param value - Value to assert
|
|
161
|
+
* @param errorMessage - Optional custom error message
|
|
162
|
+
* @throws ValidationError if assertion fails
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* ```typescript
|
|
166
|
+
* function processUser(data: unknown) {
|
|
167
|
+
* assertSchema(UserSchema, data);
|
|
168
|
+
* // data is now typed as User
|
|
169
|
+
* console.log(data.name);
|
|
170
|
+
* }
|
|
171
|
+
* ```
|
|
172
|
+
*/
|
|
173
|
+
export declare function assertSchema<T>(schema: ZodType<T, ZodTypeDef, unknown>, value: unknown, errorMessage?: string): asserts value is T;
|
|
174
|
+
//# sourceMappingURL=middleware.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAAA;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