@scallywag/validation 1.0.0 → 1.0.1
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.bak +1372 -0
- package/dist/env.d.ts +56 -0
- package/dist/env.d.ts.map +1 -0
- package/dist/env.js +262 -0
- package/dist/env.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware.d.ts +85 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/middleware.js +403 -0
- package/dist/middleware.js.map +1 -0
- package/dist/sanitization.d.ts +41 -0
- package/dist/sanitization.d.ts.map +1 -0
- package/dist/sanitization.js +111 -0
- package/dist/sanitization.js.map +1 -0
- package/dist/schemas.d.ts +231 -0
- package/dist/schemas.d.ts.map +1 -0
- package/dist/schemas.js +245 -0
- package/dist/schemas.js.map +1 -0
- package/dist/types.d.ts +136 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +16 -0
- package/dist/types.js.map +1 -0
- package/dist/validators.d.ts +111 -0
- package/dist/validators.d.ts.map +1 -0
- package/dist/validators.js +324 -0
- package/dist/validators.js.map +1 -0
- package/dist/wrappers.d.ts +117 -0
- package/dist/wrappers.d.ts.map +1 -0
- package/dist/wrappers.js +184 -0
- package/dist/wrappers.js.map +1 -0
- package/dist/zod-schema-converter.d.ts +80 -0
- package/dist/zod-schema-converter.d.ts.map +1 -0
- package/dist/zod-schema-converter.js +97 -0
- package/dist/zod-schema-converter.js.map +1 -0
- package/package.json +36 -1
- package/index.js +0 -1
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validation Utilities
|
|
3
|
+
*
|
|
4
|
+
* Helper functions for validation and sanitization
|
|
5
|
+
*/
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { FractalValidationContext, ValidationError, ValidationOptions, ValidationResult } from './types';
|
|
8
|
+
export { sanitizeString, sanitizeObjectStrings, containsXssPatterns, XSS_PATTERNS, SQL_PATTERNS, HTML_ENTITIES, } from './sanitization';
|
|
9
|
+
/**
|
|
10
|
+
* Validate data against a Zod schema
|
|
11
|
+
*/
|
|
12
|
+
export declare function validateData<T>(schema: z.ZodSchema<T>, data: unknown, options?: ValidationOptions): Promise<ValidationResult<T>>;
|
|
13
|
+
/**
|
|
14
|
+
* Validate and sanitize request data
|
|
15
|
+
*/
|
|
16
|
+
export declare function validateRequest<T>(schema: z.ZodSchema<T>, data: unknown, context?: FractalValidationContext): Promise<ValidationResult<T>>;
|
|
17
|
+
/**
|
|
18
|
+
* Create a validation decorator for class methods
|
|
19
|
+
*/
|
|
20
|
+
export declare function createValidationDecorator<T>(schema: z.ZodSchema<T>, options?: ValidationOptions): (_target: unknown, _propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
|
|
21
|
+
/**
|
|
22
|
+
* Validate environment variables
|
|
23
|
+
*/
|
|
24
|
+
export declare function validateEnv<T>(schema: z.ZodSchema<T>): T;
|
|
25
|
+
/**
|
|
26
|
+
* Create a validator function from a schema
|
|
27
|
+
*/
|
|
28
|
+
export declare function createValidator<T>(schema: z.ZodSchema<T>): (data: unknown) => data is T;
|
|
29
|
+
/**
|
|
30
|
+
* Create an async validator function from a schema
|
|
31
|
+
*/
|
|
32
|
+
export declare function createAsyncValidator<T>(schema: z.ZodSchema<T>): (data: unknown) => Promise<boolean>;
|
|
33
|
+
/**
|
|
34
|
+
* Validate file upload
|
|
35
|
+
*/
|
|
36
|
+
export declare function validateFileUpload(file: File, allowedTypes: string[], maxSize: number): ValidationResult<File>;
|
|
37
|
+
/**
|
|
38
|
+
* Batch validate multiple values
|
|
39
|
+
*/
|
|
40
|
+
export declare function batchValidate<T>(schema: z.ZodSchema<T>, dataArray: unknown[], options?: ValidationOptions): Promise<Array<ValidationResult<T>>>;
|
|
41
|
+
/**
|
|
42
|
+
* Custom error formatter for API responses
|
|
43
|
+
*/
|
|
44
|
+
export declare function formatValidationErrors(errors: ValidationError[]): Record<string, string[]>;
|
|
45
|
+
/**
|
|
46
|
+
* Check if validation result has specific error codes
|
|
47
|
+
*/
|
|
48
|
+
export declare function hasErrorCode(result: ValidationResult<unknown>, code: string): boolean;
|
|
49
|
+
/**
|
|
50
|
+
* Get validation errors for a specific field
|
|
51
|
+
*/
|
|
52
|
+
export declare function getFieldErrors(result: ValidationResult<unknown>, field: string): ValidationError[];
|
|
53
|
+
/**
|
|
54
|
+
* Validate input against a Zod schema synchronously.
|
|
55
|
+
* Throws a structured error on validation failure.
|
|
56
|
+
*
|
|
57
|
+
* Use this at module boundaries where invalid input should be rejected
|
|
58
|
+
* immediately. For non-throwing validation, use `safeValidateInput`.
|
|
59
|
+
*/
|
|
60
|
+
export declare function validateInput<T>(schema: z.ZodSchema<T>, input: unknown): T;
|
|
61
|
+
/**
|
|
62
|
+
* Validate input against a Zod schema synchronously.
|
|
63
|
+
* Returns a discriminated result object instead of throwing.
|
|
64
|
+
*
|
|
65
|
+
* Use this when the caller needs to handle validation failure
|
|
66
|
+
* gracefully without try/catch.
|
|
67
|
+
*/
|
|
68
|
+
export declare function safeValidateInput<T>(schema: z.ZodSchema<T>, input: unknown): {
|
|
69
|
+
success: true;
|
|
70
|
+
data: T;
|
|
71
|
+
} | {
|
|
72
|
+
success: false;
|
|
73
|
+
errors: string[];
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Parse JSON string and validate with Zod schema
|
|
77
|
+
* Combines JSON.parse() with Zod validation for type-safe parsing
|
|
78
|
+
*
|
|
79
|
+
* @param schema - Zod schema to validate against
|
|
80
|
+
* @param jsonString - JSON string to parse and validate
|
|
81
|
+
* @returns Validated and parsed data
|
|
82
|
+
* @throws ZodError if validation fails
|
|
83
|
+
* @throws SyntaxError if JSON parsing fails
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```typescript
|
|
87
|
+
* const UserSchema = z.object({ name: z.string(), age: z.number() });
|
|
88
|
+
* const user = parseAndValidateJSON(UserSchema, '{"name":"John","age":30}');
|
|
89
|
+
* ```
|
|
90
|
+
*/
|
|
91
|
+
export declare function parseAndValidateJSON<T>(schema: z.ZodSchema<T>, jsonString: string): T;
|
|
92
|
+
/**
|
|
93
|
+
* Safely parse JSON string and validate with Zod schema
|
|
94
|
+
* Returns a result object instead of throwing
|
|
95
|
+
*
|
|
96
|
+
* @param schema - Zod schema to validate against
|
|
97
|
+
* @param jsonString - JSON string to parse and validate
|
|
98
|
+
* @returns Validation result with success flag
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```typescript
|
|
102
|
+
* const result = safeParseAndValidateJSON(UserSchema, jsonString);
|
|
103
|
+
* if (result.success) {
|
|
104
|
+
* processData(result.data);
|
|
105
|
+
* } else {
|
|
106
|
+
* handleErrors(result.errors);
|
|
107
|
+
* }
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
110
|
+
export declare function safeParseAndValidateJSON<T>(schema: z.ZodSchema<T>, jsonString: string): ValidationResult<T>;
|
|
111
|
+
//# sourceMappingURL=validators.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validators.d.ts","sourceRoot":"","sources":["../validators.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,wBAAwB,EACxB,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EACjB,MAAM,SAAS,CAAC;AAiBjB,OAAO,EACL,cAAc,EACd,qBAAqB,EACrB,mBAAmB,EACnB,YAAY,EACZ,YAAY,EACZ,aAAa,GACd,MAAM,gBAAgB,CAAC;AAExB;;GAEG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAClC,MAAM,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EACtB,IAAI,EAAE,OAAO,EACb,OAAO,GAAE,iBAAsB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC,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sanitization
|
|
5
|
+
*/
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { sanitizeObjectStrings } from './sanitization';
|
|
8
|
+
/**
|
|
9
|
+
* Convert a ZodError into an array of ValidationError objects.
|
|
10
|
+
* Shared between parseAndValidateJSON and safeParseAndValidateJSON.
|
|
11
|
+
*/
|
|
12
|
+
function zodErrorToValidationErrors(error) {
|
|
13
|
+
return error.issues.map((err) => ({
|
|
14
|
+
field: err.path.join('.'),
|
|
15
|
+
message: err.message,
|
|
16
|
+
code: err.code,
|
|
17
|
+
value: 'received' in err ? err.received : undefined,
|
|
18
|
+
}));
|
|
19
|
+
}
|
|
20
|
+
// Re-export sanitization utilities for consumers
|
|
21
|
+
export { sanitizeString, sanitizeObjectStrings, containsXssPatterns, XSS_PATTERNS, SQL_PATTERNS, HTML_ENTITIES, } from './sanitization';
|
|
22
|
+
/**
|
|
23
|
+
* Validate data against a Zod schema
|
|
24
|
+
*/
|
|
25
|
+
export async function validateData(schema, data, options = {}) {
|
|
26
|
+
try {
|
|
27
|
+
const result = options.async
|
|
28
|
+
? await schema.parseAsync(data)
|
|
29
|
+
: schema.parse(data);
|
|
30
|
+
return {
|
|
31
|
+
success: true,
|
|
32
|
+
data: result,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error instanceof z.ZodError) {
|
|
37
|
+
return {
|
|
38
|
+
success: false,
|
|
39
|
+
errors: zodErrorToValidationErrors(error),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
success: false,
|
|
44
|
+
errors: [
|
|
45
|
+
{
|
|
46
|
+
field: 'unknown',
|
|
47
|
+
message: 'Validation failed with unknown error',
|
|
48
|
+
code: 'unknown_error',
|
|
49
|
+
value: data,
|
|
50
|
+
},
|
|
51
|
+
],
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Validate and sanitize request data
|
|
57
|
+
*/
|
|
58
|
+
export async function validateRequest(schema, data, context) {
|
|
59
|
+
// Pre-sanitization for string fields
|
|
60
|
+
if (typeof data === 'object' && data !== null) {
|
|
61
|
+
const sanitizedData = sanitizeObjectStrings(data);
|
|
62
|
+
return validateData(schema, sanitizedData, {
|
|
63
|
+
strict: (context === null || context === void 0 ? void 0 : context.securityLevel) === 'critical',
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return validateData(schema, data, {
|
|
67
|
+
strict: (context === null || context === void 0 ? void 0 : context.securityLevel) === 'critical',
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Create a validation decorator for class methods
|
|
72
|
+
*/
|
|
73
|
+
export function createValidationDecorator(schema, options = {}) {
|
|
74
|
+
return function (_target, _propertyKey, descriptor) {
|
|
75
|
+
const originalMethod = descriptor.value;
|
|
76
|
+
descriptor.value = async function (...args) {
|
|
77
|
+
// Validate the first argument (typically request data)
|
|
78
|
+
const dataToValidate = args[0];
|
|
79
|
+
const validationResult = await validateData(schema, dataToValidate, options);
|
|
80
|
+
if (!validationResult.success) {
|
|
81
|
+
throw new Error(`Validation failed: ${JSON.stringify(validationResult.errors)}`);
|
|
82
|
+
}
|
|
83
|
+
// Replace the first argument with validated data
|
|
84
|
+
args[0] = validationResult.data;
|
|
85
|
+
return originalMethod.apply(this, args);
|
|
86
|
+
};
|
|
87
|
+
return descriptor;
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Validate environment variables
|
|
92
|
+
*/
|
|
93
|
+
export function validateEnv(schema) {
|
|
94
|
+
try {
|
|
95
|
+
return schema.parse(process.env);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (error instanceof z.ZodError) {
|
|
99
|
+
const errorMessage = error.issues
|
|
100
|
+
.map((err) => `${err.path.join('.')}: ${err.message}`)
|
|
101
|
+
.join('\n');
|
|
102
|
+
throw new Error(`Environment validation failed:\n${errorMessage}`);
|
|
103
|
+
}
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Create a validator function from a schema
|
|
109
|
+
*/
|
|
110
|
+
export function createValidator(schema) {
|
|
111
|
+
return (data) => {
|
|
112
|
+
try {
|
|
113
|
+
schema.parse(data);
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
catch (_a) {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Create an async validator function from a schema
|
|
123
|
+
*/
|
|
124
|
+
export function createAsyncValidator(schema) {
|
|
125
|
+
return async (data) => {
|
|
126
|
+
try {
|
|
127
|
+
await schema.parseAsync(data);
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
catch (_a) {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Validate file upload
|
|
137
|
+
*/
|
|
138
|
+
export function validateFileUpload(file, allowedTypes, maxSize) {
|
|
139
|
+
const errors = [];
|
|
140
|
+
if (!file) {
|
|
141
|
+
errors.push({
|
|
142
|
+
field: 'file',
|
|
143
|
+
message: 'File is required',
|
|
144
|
+
code: 'required',
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
if (file && !allowedTypes.includes(file.type)) {
|
|
148
|
+
errors.push({
|
|
149
|
+
field: 'type',
|
|
150
|
+
message: `File type not allowed. Allowed types: ${allowedTypes.join(', ')}`,
|
|
151
|
+
code: 'invalid_type',
|
|
152
|
+
value: file.type,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
if (file && file.size > maxSize) {
|
|
156
|
+
errors.push({
|
|
157
|
+
field: 'size',
|
|
158
|
+
message: `File too large. Maximum size: ${maxSize} bytes`,
|
|
159
|
+
code: 'too_large',
|
|
160
|
+
value: file.size,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
if (errors.length === 0) {
|
|
164
|
+
return {
|
|
165
|
+
success: true,
|
|
166
|
+
data: file,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
return {
|
|
171
|
+
success: false,
|
|
172
|
+
errors,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Batch validate multiple values
|
|
178
|
+
*/
|
|
179
|
+
export async function batchValidate(schema, dataArray, options = {}) {
|
|
180
|
+
return Promise.all(dataArray.map((data) => validateData(schema, data, options)));
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Custom error formatter for API responses
|
|
184
|
+
*/
|
|
185
|
+
export function formatValidationErrors(errors) {
|
|
186
|
+
var _a;
|
|
187
|
+
// @preflight-ignore:in-memory Temporary local object for building API response, not persistent storage.
|
|
188
|
+
const formatted = {};
|
|
189
|
+
for (const error of errors) {
|
|
190
|
+
const fieldErrors = (_a = formatted[error.field]) !== null && _a !== void 0 ? _a : [];
|
|
191
|
+
fieldErrors.push(error.message);
|
|
192
|
+
formatted[error.field] = fieldErrors;
|
|
193
|
+
}
|
|
194
|
+
return formatted;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Check if validation result has specific error codes
|
|
198
|
+
*/
|
|
199
|
+
export function hasErrorCode(result, code) {
|
|
200
|
+
if (!result.success && result.errors) {
|
|
201
|
+
return result.errors.some((error) => error.code === code);
|
|
202
|
+
}
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Get validation errors for a specific field
|
|
207
|
+
*/
|
|
208
|
+
export function getFieldErrors(result, field) {
|
|
209
|
+
if (!result.success && result.errors) {
|
|
210
|
+
return result.errors.filter((error) => error.field === field);
|
|
211
|
+
}
|
|
212
|
+
return [];
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Validate input against a Zod schema synchronously.
|
|
216
|
+
* Throws a structured error on validation failure.
|
|
217
|
+
*
|
|
218
|
+
* Use this at module boundaries where invalid input should be rejected
|
|
219
|
+
* immediately. For non-throwing validation, use `safeValidateInput`.
|
|
220
|
+
*/
|
|
221
|
+
export function validateInput(schema, input) {
|
|
222
|
+
const result = schema.safeParse(input);
|
|
223
|
+
if (!result.success) {
|
|
224
|
+
const errors = result.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`);
|
|
225
|
+
throw new Error(`Validation failed: ${errors.join('; ')}`);
|
|
226
|
+
}
|
|
227
|
+
return result.data;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Validate input against a Zod schema synchronously.
|
|
231
|
+
* Returns a discriminated result object instead of throwing.
|
|
232
|
+
*
|
|
233
|
+
* Use this when the caller needs to handle validation failure
|
|
234
|
+
* gracefully without try/catch.
|
|
235
|
+
*/
|
|
236
|
+
export function safeValidateInput(schema, input) {
|
|
237
|
+
const result = schema.safeParse(input);
|
|
238
|
+
if (!result.success) {
|
|
239
|
+
return {
|
|
240
|
+
success: false,
|
|
241
|
+
errors: result.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`),
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
return { success: true, data: result.data };
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Parse JSON string and validate with Zod schema
|
|
248
|
+
* Combines JSON.parse() with Zod validation for type-safe parsing
|
|
249
|
+
*
|
|
250
|
+
* @param schema - Zod schema to validate against
|
|
251
|
+
* @param jsonString - JSON string to parse and validate
|
|
252
|
+
* @returns Validated and parsed data
|
|
253
|
+
* @throws ZodError if validation fails
|
|
254
|
+
* @throws SyntaxError if JSON parsing fails
|
|
255
|
+
*
|
|
256
|
+
* @example
|
|
257
|
+
* ```typescript
|
|
258
|
+
* const UserSchema = z.object({ name: z.string(), age: z.number() });
|
|
259
|
+
* const user = parseAndValidateJSON(UserSchema, '{"name":"John","age":30}');
|
|
260
|
+
* ```
|
|
261
|
+
*/
|
|
262
|
+
export function parseAndValidateJSON(schema, jsonString) {
|
|
263
|
+
const parsed = JSON.parse(jsonString);
|
|
264
|
+
return schema.parse(parsed);
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Safely parse JSON string and validate with Zod schema
|
|
268
|
+
* Returns a result object instead of throwing
|
|
269
|
+
*
|
|
270
|
+
* @param schema - Zod schema to validate against
|
|
271
|
+
* @param jsonString - JSON string to parse and validate
|
|
272
|
+
* @returns Validation result with success flag
|
|
273
|
+
*
|
|
274
|
+
* @example
|
|
275
|
+
* ```typescript
|
|
276
|
+
* const result = safeParseAndValidateJSON(UserSchema, jsonString);
|
|
277
|
+
* if (result.success) {
|
|
278
|
+
* processData(result.data);
|
|
279
|
+
* } else {
|
|
280
|
+
* handleErrors(result.errors);
|
|
281
|
+
* }
|
|
282
|
+
* ```
|
|
283
|
+
*/
|
|
284
|
+
export function safeParseAndValidateJSON(schema, jsonString) {
|
|
285
|
+
try {
|
|
286
|
+
const parsed = JSON.parse(jsonString);
|
|
287
|
+
const validated = schema.parse(parsed);
|
|
288
|
+
return {
|
|
289
|
+
success: true,
|
|
290
|
+
data: validated,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
if (error instanceof SyntaxError) {
|
|
295
|
+
return {
|
|
296
|
+
success: false,
|
|
297
|
+
errors: [
|
|
298
|
+
{
|
|
299
|
+
field: 'json',
|
|
300
|
+
message: `Invalid JSON: ${error.message}`,
|
|
301
|
+
code: 'invalid_json',
|
|
302
|
+
},
|
|
303
|
+
],
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
if (error instanceof z.ZodError) {
|
|
307
|
+
return {
|
|
308
|
+
success: false,
|
|
309
|
+
errors: zodErrorToValidationErrors(error),
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
return {
|
|
313
|
+
success: false,
|
|
314
|
+
errors: [
|
|
315
|
+
{
|
|
316
|
+
field: 'unknown',
|
|
317
|
+
message: 'Unknown error during parsing/validation',
|
|
318
|
+
code: 'unknown_error',
|
|
319
|
+
},
|
|
320
|
+
],
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
//# sourceMappingURL=validators.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validators.js","sourceRoot":"","sources":["../validators.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAOxB,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAEvD;;;GAGG;AACH,SAAS,0BAA0B,CAAC,KAAiB;IACnD,OAAO,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAe,EAAE,EAAE,CAAC,CAAC;QAC5C,KAAK,EAAE,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;QACzB,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,KAAK,EAAE,UAAU,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS;KACpD,CAAC,CAAC,CAAC;AACN,CAAC;AAED,iDAAiD;AACjD,OAAO,EACL,cAAc,EACd,qBAAqB,EACrB,mBAAmB,EACnB,YAAY,EACZ,YAAY,EACZ,aAAa,GACd,MAAM,gBAAgB,CAAC;AAExB;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,MAAsB,EACtB,IAAa,EACb,UAA6B,EAAE;IAE/B,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK;YAC1B,CAAC,CAAC,MAAM,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC;YAC/B,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAEvB,OAAO;YACL,OAAO,EAAE,IAAI;YACb,IAAI,EAAE,MAAM;SACb,CAAC;IACJ,CAAC;IAAC,O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
|
|
3
|
+
*
|
|
4
|
+
* High-level wrapper functions for common validation patterns.
|
|
5
|
+
* These provide ergonomic APIs for JSON parsing with schema validation
|
|
6
|
+
* and type-safe assertion helpers.
|
|
7
|
+
*/
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
import type { ValidationError } from './types';
|
|
10
|
+
/**
|
|
11
|
+
* Error thrown when JSON parsing fails
|
|
12
|
+
*/
|
|
13
|
+
export declare class JsonParseError extends Error {
|
|
14
|
+
readonly code: "JSON_PARSE_ERROR";
|
|
15
|
+
readonly rawInput: string;
|
|
16
|
+
constructor(message: string, rawInput: string, cause?: Error);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Error thrown when schema validation fails
|
|
20
|
+
*/
|
|
21
|
+
export declare class SchemaValidationError extends Error {
|
|
22
|
+
readonly code: "SCHEMA_VALIDATION_ERROR";
|
|
23
|
+
readonly errors: ValidationError[];
|
|
24
|
+
readonly value: unknown;
|
|
25
|
+
constructor(message: string, errors: ValidationError[], value: unknown);
|
|
26
|
+
/**
|
|
27
|
+
* Get a formatted summary of validation errors
|
|
28
|
+
*/
|
|
29
|
+
getErrorSummary(): string;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Parse a JSON string and validate it against a Zod schema.
|
|
33
|
+
*
|
|
34
|
+
* Combines JSON.parse() with Zod validation in a single operation,
|
|
35
|
+
* providing type-safe parsing with clear error types.
|
|
36
|
+
*
|
|
37
|
+
* @param json - The JSON string to parse
|
|
38
|
+
* @param schema - The Zod schema to validate against
|
|
39
|
+
* @returns The parsed and validated data with full type inference
|
|
40
|
+
* @throws JsonParseError if the JSON string is malformed
|
|
41
|
+
* @throws SchemaValidationError if the parsed data fails schema validation
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* const UserSchema = z.object(\{
|
|
45
|
+
* id: z.string().uuid(),
|
|
46
|
+
* name: z.string().min(1),
|
|
47
|
+
* email: z.string().email(),
|
|
48
|
+
* \});
|
|
49
|
+
*
|
|
50
|
+
* // Fully typed: user is \{ id: string; name: string; email: string \}
|
|
51
|
+
* const user = parseJsonWithSchema(jsonString, UserSchema);
|
|
52
|
+
*
|
|
53
|
+
* // Error handling - catch JsonParseError for invalid JSON
|
|
54
|
+
* // and SchemaValidationError for validation failures
|
|
55
|
+
*/
|
|
56
|
+
export declare function parseJsonWithSchema<T>(json: string, schema: z.ZodSchema<T>): T;
|
|
57
|
+
/**
|
|
58
|
+
* Assert that a value conforms to a Zod schema, narrowing the type.
|
|
59
|
+
*
|
|
60
|
+
* This is a type assertion function that throws if validation fails,
|
|
61
|
+
* allowing TypeScript to narrow the type after the assertion.
|
|
62
|
+
*
|
|
63
|
+
* @param value - The value to validate
|
|
64
|
+
* @param schema - The Zod schema to validate against
|
|
65
|
+
* @throws SchemaValidationError if validation fails
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* const ConfigSchema = z.object(\{ port: z.number(), host: z.string() \});
|
|
69
|
+
*
|
|
70
|
+
* function loadConfig(rawConfig: unknown): void \{
|
|
71
|
+
* // After this line, TypeScript knows rawConfig is \{ port: number; host: string \}
|
|
72
|
+
* assertSchema(rawConfig, ConfigSchema);
|
|
73
|
+
* // Type-safe access to rawConfig.host and rawConfig.port
|
|
74
|
+
* \}
|
|
75
|
+
*/
|
|
76
|
+
export declare function assertSchema<T>(value: unknown, schema: z.ZodSchema<T>): asserts value is T;
|
|
77
|
+
/**
|
|
78
|
+
* Type guard version of assertSchema that returns a boolean instead of throwing.
|
|
79
|
+
*
|
|
80
|
+
* Useful when you want to check if a value matches a schema without throwing,
|
|
81
|
+
* while still getting type narrowing in the true branch.
|
|
82
|
+
*
|
|
83
|
+
* @param value - The value to check
|
|
84
|
+
* @param schema - The Zod schema to validate against
|
|
85
|
+
* @returns True if the value matches the schema, false otherwise
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* function handleMessage(msg: unknown): void \{
|
|
89
|
+
* if (isSchema(msg, TextMessageSchema)) \{
|
|
90
|
+
* // msg is typed as TextMessage here
|
|
91
|
+
* \} else if (isSchema(msg, ImageMessageSchema)) \{
|
|
92
|
+
* // msg is typed as ImageMessage here
|
|
93
|
+
* \}
|
|
94
|
+
* \}
|
|
95
|
+
*/
|
|
96
|
+
export declare function isSchema<T>(value: unknown, schema: z.ZodSchema<T>): value is T;
|
|
97
|
+
/**
|
|
98
|
+
* Parse JSON string safely, returning the parsed value or a default.
|
|
99
|
+
*
|
|
100
|
+
* Use this when you need to parse JSON before applying a Zod schema,
|
|
101
|
+
* or when the schema is determined dynamically.
|
|
102
|
+
*
|
|
103
|
+
* @param json - The JSON string to parse
|
|
104
|
+
* @param defaultValue - Value to return if parsing fails
|
|
105
|
+
* @returns The parsed value as unknown, or the default value
|
|
106
|
+
*
|
|
107
|
+
* @example
|
|
108
|
+
* ```typescript
|
|
109
|
+
* // Parse request body, defaulting to empty object on failure
|
|
110
|
+
* const body = safeParseJson(text, {});
|
|
111
|
+
*
|
|
112
|
+
* // Then validate with a schema
|
|
113
|
+
* const validated = MySchema.parse(body);
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
export declare function safeParseJson(json: string, defaultValue?: unknown): unknown;
|
|
117
|
+
//# sourceMappingURL=wrappers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wrappers.d.ts","sourceRoot":"","sources":["../wrappers.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/C;;GAEG;AACH,qBAAa,cAAe,SAAQ,KAAK;IACvC,SAAgB,IAAI,EAAG,kBAAkB,CAAU;IACnD,SAAgB,QAAQ,EAAE,MAAM,CAAC;gBAErB,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK;CAgB7D;AAED;;GAEG;AAC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