barejs 0.1.54 → 0.1.56

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.
@@ -47,7 +47,10 @@ export const typebox = (schema: any): Middleware => {
47
47
 
48
48
  if (isCtx) (ctx as any).body = body;
49
49
  return next ? next() : undefined;
50
- } catch {
50
+ } catch (e: any) {
51
+ if (e?.status === 413) {
52
+ return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
53
+ }
51
54
  return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
52
55
  }
53
56
  };
@@ -59,48 +62,30 @@ export const typebox = (schema: any): Middleware => {
59
62
  * Native Engine (n)
60
63
  */
61
64
  export const native = (schema: any): Middleware => {
62
- const props = schema.properties || {};
63
- const keys = Object.keys(props);
64
- const kLen = keys.length;
65
- const reqSet = Array.isArray(schema.required) ? new Set<string>(schema.required) : null;
65
+ const check = compileNativeCheck(schema);
66
66
 
67
67
  const mw: Middleware = async (ctx: any, next?: any) => {
68
68
  try {
69
69
  const isCtx = ctx instanceof Object && 'req' in ctx;
70
70
  const body = isCtx ? await ctx.jsonBody() : await ctx.json();
71
71
 
72
- if (!body || typeof body !== 'object' || Array.isArray(body)) {
73
- return errorJSON({ status: 'error', message: 'Invalid JSON object payload' });
74
- }
75
-
76
- for (let i = 0; i < kLen; i++) {
77
- const k = keys[i]!;
78
- const hasKey = Object.hasOwn(body, k) && body[k] !== undefined;
79
- if (!hasKey) {
80
- if (!reqSet || reqSet.has(k)) {
81
- return errorJSON({
82
- status: 'error',
83
- code: 'TYPE_MISMATCH',
84
- message: `Field '${k}' must be of type ${props[k]?.type}`,
85
- field: k
86
- });
87
- }
88
- continue;
89
- }
90
- if (typeof body[k] !== props[k]?.type) {
91
- return errorJSON({
92
- status: 'error',
93
- code: 'TYPE_MISMATCH',
94
- message: `Field '${k}' must be of type ${props[k]?.type}`,
95
- field: k
96
- });
97
- }
72
+ const res = check(body);
73
+ if (!res.ok) {
74
+ return errorJSON({
75
+ status: 'error',
76
+ code: res.error?.code || 'TYPE_MISMATCH',
77
+ message: res.error?.message || 'Validation failed',
78
+ ...(res.error?.path ? { field: res.error.path } : {})
79
+ });
98
80
  }
99
81
 
100
- if (isCtx) (ctx as any).body = body;
82
+ if (isCtx) (ctx as any).body = res.data;
101
83
 
102
84
  return next ? next() : undefined;
103
- } catch {
85
+ } catch (e: any) {
86
+ if (e?.status === 413) {
87
+ return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
88
+ }
104
89
  return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
105
90
  }
106
91
  };
@@ -130,7 +115,10 @@ export const zod = (schema: z.ZodSchema): Middleware => {
130
115
  if (isCtx) (ctx as any).body = result.data;
131
116
 
132
117
  return next ? next() : undefined;
133
- } catch {
118
+ } catch (e: any) {
119
+ if (e?.status === 413) {
120
+ return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
121
+ }
134
122
  return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
135
123
  }
136
124
  };
@@ -143,9 +131,16 @@ export const zod = (schema: z.ZodSchema): Middleware => {
143
131
  */
144
132
  export const validate = (schema: any): Middleware => {
145
133
  if (schema && '_def' in schema) return zod(schema);
146
- if (schema && (schema.kind || schema.type || schema[Symbol.for('TypeBox.Kind')])) {
134
+ if (schema && (schema.kind || schema[Symbol.for('TypeBox.Kind')])) {
147
135
  return typebox(schema);
148
136
  }
137
+ if (schema && schema.type) {
138
+ try {
139
+ return typebox(schema);
140
+ } catch {
141
+ return native(schema);
142
+ }
143
+ }
149
144
  return native(schema);
150
145
  };
151
146
 
@@ -169,6 +164,279 @@ export interface RouteSchemas {
169
164
  maxBodySize?: number;
170
165
  }
171
166
 
167
+ const matchesJsonType = (val: any, expected: string | string[] | undefined): boolean => {
168
+ if (expected === undefined) return true;
169
+ if (Array.isArray(expected)) return expected.some((t) => matchesJsonType(val, t));
170
+ if (expected === 'array') return Array.isArray(val);
171
+ if (expected === 'integer') return typeof val === 'number' && Number.isInteger(val);
172
+ if (expected === 'number') return typeof val === 'number' && Number.isFinite(val);
173
+ if (expected === 'object') return val !== null && typeof val === 'object' && !Array.isArray(val);
174
+ if (expected === 'null') return val === null;
175
+ return typeof val === expected;
176
+ };
177
+
178
+ const jsonDeepEqual = (a: any, b: any): boolean => {
179
+ if (a === b) return true;
180
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
181
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
182
+ if (Array.isArray(a)) {
183
+ if (a.length !== b.length) return false;
184
+ for (let i = 0; i < a.length; i++) if (!jsonDeepEqual(a[i], b[i])) return false;
185
+ return true;
186
+ }
187
+ const ka = Object.keys(a);
188
+ if (ka.length !== Object.keys(b).length) return false;
189
+ for (let i = 0; i < ka.length; i++) {
190
+ const k = ka[i]!;
191
+ if (!Object.hasOwn(b, k) || !jsonDeepEqual(a[k], b[k])) return false;
192
+ }
193
+ return true;
194
+ };
195
+
196
+ const validateJsonSchemaNode = (
197
+ val: any,
198
+ schema: any,
199
+ path: string,
200
+ requireAllPropsIfOmitted: boolean
201
+ ): { ok: boolean; error?: any } => {
202
+ if (!schema || typeof schema !== 'object') return { ok: true };
203
+
204
+ if (Object.hasOwn(schema, 'const') && !jsonDeepEqual(val, schema.const)) {
205
+ return { ok: false, error: { message: `Value at '${path || 'root'}' must equal ${JSON.stringify(schema.const)}`, path } };
206
+ }
207
+ if (Array.isArray(schema.enum) && !schema.enum.some((e: any) => jsonDeepEqual(e, val))) {
208
+ return { ok: false, error: { message: `Value at '${path || 'root'}' must be one of enum values`, path } };
209
+ }
210
+ if (schema.not && typeof schema.not === 'object' && validateJsonSchemaNode(val, schema.not, path, false).ok) {
211
+ return { ok: false, error: { message: `Value at '${path || 'root'}' must not match the 'not' schema`, path } };
212
+ }
213
+ if (Array.isArray(schema.allOf)) {
214
+ for (let i = 0; i < schema.allOf.length; i++) {
215
+ const r = validateJsonSchemaNode(val, schema.allOf[i], path, false);
216
+ if (!r.ok) return r;
217
+ }
218
+ }
219
+ if (Array.isArray(schema.anyOf)) {
220
+ let matched = false;
221
+ for (let i = 0; i < schema.anyOf.length; i++) {
222
+ if (validateJsonSchemaNode(val, schema.anyOf[i], path, false).ok) {
223
+ matched = true;
224
+ break;
225
+ }
226
+ }
227
+ if (!matched) {
228
+ return { ok: false, error: { message: `Value at '${path || 'root'}' failed anyOf constraint`, path } };
229
+ }
230
+ }
231
+ if (Array.isArray(schema.oneOf)) {
232
+ let count = 0;
233
+ for (let i = 0; i < schema.oneOf.length; i++) {
234
+ if (validateJsonSchemaNode(val, schema.oneOf[i], path, false).ok) count++;
235
+ }
236
+ if (count !== 1) {
237
+ return { ok: false, error: { message: `Value at '${path || 'root'}' must match exactly one schema in oneOf`, path } };
238
+ }
239
+ }
240
+
241
+ if (!matchesJsonType(val, schema.type)) {
242
+ return { ok: false, error: { message: path ? `Field '${path}' must be of type ${schema.type}` : `Expected type ${schema.type}`, path } };
243
+ }
244
+
245
+ if (typeof val === 'number') {
246
+ if (typeof schema.minimum === 'number' && val < schema.minimum) {
247
+ return { ok: false, error: { message: `Field '${path}' must be >= ${schema.minimum}`, path } };
248
+ }
249
+ if (typeof schema.maximum === 'number' && val > schema.maximum) {
250
+ return { ok: false, error: { message: `Field '${path}' must be <= ${schema.maximum}`, path } };
251
+ }
252
+ if (typeof schema.multipleOf === 'number' && schema.multipleOf > 0) {
253
+ const q = val / schema.multipleOf;
254
+ if (Math.abs(q - Math.round(q)) > 1e-9 * Math.max(1, Math.abs(q))) {
255
+ return { ok: false, error: { message: `Field '${path}' must be a multiple of ${schema.multipleOf}`, path } };
256
+ }
257
+ }
258
+ if (typeof schema.exclusiveMinimum === 'number' && val <= schema.exclusiveMinimum) {
259
+ return { ok: false, error: { message: `Field '${path}' must be > ${schema.exclusiveMinimum}`, path } };
260
+ }
261
+ if (typeof schema.exclusiveMaximum === 'number' && val >= schema.exclusiveMaximum) {
262
+ return { ok: false, error: { message: `Field '${path}' must be < ${schema.exclusiveMaximum}`, path } };
263
+ }
264
+ }
265
+
266
+ if (typeof val === 'string') {
267
+ if (typeof schema.minLength === 'number' && val.length < schema.minLength) {
268
+ return { ok: false, error: { message: `Field '${path}' length must be >= ${schema.minLength}`, path } };
269
+ }
270
+ if (typeof schema.maxLength === 'number' && val.length > schema.maxLength) {
271
+ return { ok: false, error: { message: `Field '${path}' length must be <= ${schema.maxLength}`, path } };
272
+ }
273
+ if (typeof schema.pattern === 'string') {
274
+ try {
275
+ if (!new RegExp(schema.pattern).test(val)) {
276
+ return { ok: false, error: { message: `Field '${path}' does not match pattern`, path } };
277
+ }
278
+ } catch { /* ignore invalid regex */ }
279
+ }
280
+ }
281
+
282
+ if (Array.isArray(val)) {
283
+ if (typeof schema.minItems === 'number' && val.length < schema.minItems) {
284
+ return { ok: false, error: { message: `Field '${path}' must have at least ${schema.minItems} items`, path } };
285
+ }
286
+ if (typeof schema.maxItems === 'number' && val.length > schema.maxItems) {
287
+ return { ok: false, error: { message: `Field '${path}' must have at most ${schema.maxItems} items`, path } };
288
+ }
289
+ if (schema.uniqueItems === true) {
290
+ for (let i = 1; i < val.length; i++) {
291
+ for (let j = 0; j < i; j++) {
292
+ if (jsonDeepEqual(val[i], val[j])) {
293
+ return { ok: false, error: { message: `Field '${path}' must have unique items`, path } };
294
+ }
295
+ }
296
+ }
297
+ }
298
+ if (Array.isArray(schema.items)) {
299
+ const n = Math.min(val.length, schema.items.length);
300
+ for (let i = 0; i < n; i++) {
301
+ const r = validateJsonSchemaNode(val[i], schema.items[i], path ? `${path}[${i}]` : `[${i}]`, false);
302
+ if (!r.ok) return r;
303
+ }
304
+ } else if (schema.items && typeof schema.items === 'object') {
305
+ for (let i = 0; i < val.length; i++) {
306
+ const r = validateJsonSchemaNode(val[i], schema.items, path ? `${path}[${i}]` : `[${i}]`, false);
307
+ if (!r.ok) return r;
308
+ }
309
+ }
310
+ }
311
+
312
+ if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
313
+ const props = schema.properties && typeof schema.properties === 'object' ? schema.properties : null;
314
+ const reqList = Array.isArray(schema.required) ? schema.required : null;
315
+ const reqSet = reqList ? new Set<string>(reqList) : null;
316
+
317
+ if (typeof schema.minProperties === 'number' || typeof schema.maxProperties === 'number') {
318
+ const n = Object.keys(val).length;
319
+ if (typeof schema.minProperties === 'number' && n < schema.minProperties) {
320
+ return { ok: false, error: { message: `Object at '${path || 'root'}' must have at least ${schema.minProperties} properties`, path } };
321
+ }
322
+ if (typeof schema.maxProperties === 'number' && n > schema.maxProperties) {
323
+ return { ok: false, error: { message: `Object at '${path || 'root'}' must have at most ${schema.maxProperties} properties`, path } };
324
+ }
325
+ }
326
+
327
+ if (reqList) {
328
+ for (let i = 0; i < reqList.length; i++) {
329
+ const rk = reqList[i]!;
330
+ if (!Object.hasOwn(val, rk) || val[rk] === undefined) {
331
+ const expectedType = props?.[rk]?.type;
332
+ return {
333
+ ok: false,
334
+ error: {
335
+ message: expectedType ? `Field '${rk}' must be of type ${expectedType}` : `Missing required field '${rk}'`,
336
+ path: path ? `${path}.${rk}` : rk
337
+ }
338
+ };
339
+ }
340
+ }
341
+ }
342
+
343
+ if (props) {
344
+ const pKeys = Object.keys(props);
345
+ for (let i = 0; i < pKeys.length; i++) {
346
+ const k = pKeys[i]!;
347
+ const hasKey = Object.hasOwn(val, k) && val[k] !== undefined;
348
+ if (!hasKey) {
349
+ if (requireAllPropsIfOmitted && !reqSet) {
350
+ return {
351
+ ok: false,
352
+ error: {
353
+ message: `Field '${k}' must be of type ${props[k]?.type}`,
354
+ path: path ? `${path}.${k}` : k
355
+ }
356
+ };
357
+ }
358
+ continue;
359
+ }
360
+ const subPath = path ? `${path}.${k}` : k;
361
+ const r = validateJsonSchemaNode(val[k], props[k], subPath, false);
362
+ if (!r.ok) return r;
363
+ }
364
+ }
365
+
366
+ const matchedPatternKeys = new Set<string>();
367
+ if (schema.patternProperties && typeof schema.patternProperties === 'object') {
368
+ const valKeys = Object.keys(val);
369
+ for (const [pat, sub] of Object.entries<any>(schema.patternProperties)) {
370
+ let re: RegExp;
371
+ try { re = new RegExp(pat); } catch { continue; }
372
+ for (let i = 0; i < valKeys.length; i++) {
373
+ const vk = valKeys[i]!;
374
+ if (!re.test(vk)) continue;
375
+ matchedPatternKeys.add(vk);
376
+ const r = validateJsonSchemaNode(val[vk], sub, path ? `${path}.${vk}` : vk, false);
377
+ if (!r.ok) return r;
378
+ }
379
+ }
380
+ }
381
+ if (schema.dependentRequired && typeof schema.dependentRequired === 'object') {
382
+ for (const [dk, deps] of Object.entries<any>(schema.dependentRequired)) {
383
+ if (!Object.hasOwn(val, dk) || !Array.isArray(deps)) continue;
384
+ for (const d of deps) {
385
+ if (!Object.hasOwn(val, d)) {
386
+ return { ok: false, error: { message: `Field '${d}' is required when '${dk}' is present`, path: path ? `${path}.${d}` : d } };
387
+ }
388
+ }
389
+ }
390
+ }
391
+
392
+ if (schema.additionalProperties === false) {
393
+ const valKeys = Object.keys(val);
394
+ for (let i = 0; i < valKeys.length; i++) {
395
+ const vk = valKeys[i]!;
396
+ if ((!props || !Object.hasOwn(props, vk)) && !matchedPatternKeys.has(vk)) {
397
+ return {
398
+ ok: false,
399
+ error: {
400
+ code: 'ADDITIONAL_PROPERTIES',
401
+ message: `Unknown field '${vk}' is not allowed`,
402
+ path: path ? `${path}.${vk}` : vk
403
+ }
404
+ };
405
+ }
406
+ }
407
+ } else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
408
+ const valKeys = Object.keys(val);
409
+ for (let i = 0; i < valKeys.length; i++) {
410
+ const vk = valKeys[i]!;
411
+ if ((!props || !Object.hasOwn(props, vk)) && !matchedPatternKeys.has(vk)) {
412
+ const r = validateJsonSchemaNode(val[vk], schema.additionalProperties, path ? `${path}.${vk}` : vk, false);
413
+ if (!r.ok) return r;
414
+ }
415
+ }
416
+ }
417
+ }
418
+
419
+ return { ok: true };
420
+ };
421
+
422
+ const compileNativeCheck = (schema: any): ((val: any) => { ok: boolean; data?: any; error?: any }) => {
423
+ const hasCombinators = Boolean(schema?.anyOf || schema?.oneOf || schema?.allOf);
424
+ const topRequireAll = !hasCombinators && !Array.isArray(schema?.required) && Boolean(schema?.properties);
425
+ const topExpectsObj = !schema?.type || schema.type === 'object';
426
+ return (val: any) => {
427
+ if (!schema || typeof schema !== 'object') {
428
+ return (!val || typeof val !== 'object' || Array.isArray(val))
429
+ ? { ok: false, error: { message: 'Invalid JSON object payload' } }
430
+ : { ok: true, data: val };
431
+ }
432
+ if (topExpectsObj && (!val || typeof val !== 'object' || Array.isArray(val)) && !hasCombinators) {
433
+ return { ok: false, error: { message: 'Invalid JSON object payload' } };
434
+ }
435
+ const r = validateJsonSchemaNode(val, schema, '', topRequireAll);
436
+ return r.ok ? { ok: true, data: val } : r;
437
+ };
438
+ };
439
+
172
440
  const compileSingleSchema = (schema: any): ((val: any) => { ok: boolean; data?: any; error?: any }) => {
173
441
  if (schema && '_def' in schema) {
174
442
  return (val: any) => {
@@ -176,37 +444,222 @@ const compileSingleSchema = (schema: any): ((val: any) => { ok: boolean; data?:
176
444
  return r.success ? { ok: true, data: r.data } : { ok: false, error: r.error.flatten() };
177
445
  };
178
446
  }
179
- const check = Compiler.TypeCompiler.Compile(schema);
180
- return (val: any) => {
181
- if (check.Check(val)) return { ok: true, data: val };
182
- const first = check.Errors(val).First();
183
- return { ok: false, error: { message: first?.message || 'Invalid input', path: first?.path } };
184
- };
447
+ try {
448
+ const check = Compiler.TypeCompiler.Compile(schema);
449
+ return (val: any) => {
450
+ if (check.Check(val)) return { ok: true, data: val };
451
+ const first = check.Errors(val).First();
452
+ return { ok: false, error: { message: first?.message || 'Invalid input', path: first?.path } };
453
+ };
454
+ } catch {
455
+ return compileNativeCheck(schema);
456
+ }
457
+ };
458
+
459
+ const buildArrayProjectorStmts = (
460
+ itemsSchema: any,
461
+ srcArrVar: string,
462
+ dstAssignPrefix: string,
463
+ depth: number,
464
+ idx: number
465
+ ): string | null => {
466
+ if (!itemsSchema) return null;
467
+ const arrOut = `ar_${depth}_${idx}`;
468
+ const arrIdx = `j_${depth}_${idx}`;
469
+ const itemVar = `ai_${depth}_${idx}`;
470
+ if (itemsSchema.type === 'array' && itemsSchema.items) {
471
+ const innerStmts = buildArrayProjectorStmts(itemsSchema.items, itemVar, `${arrOut}[${arrIdx}] = `, depth + 1, idx + 1);
472
+ if (innerStmts === null) return null;
473
+ return `if (Array.isArray(${srcArrVar})) {\n` +
474
+ ` const ${arrOut} = new Array(${srcArrVar}.length);\n` +
475
+ ` for (let ${arrIdx} = 0; ${arrIdx} < ${srcArrVar}.length; ${arrIdx}++) {\n` +
476
+ ` const ${itemVar} = ${srcArrVar}[${arrIdx}];\n` +
477
+ ` ${innerStmts}\n` +
478
+ ` }\n` +
479
+ ` ${dstAssignPrefix}${arrOut};\n` +
480
+ `} else {\n ${dstAssignPrefix}${srcArrVar};\n}`;
481
+ }
482
+ const itemDst = `ao_${depth}_${idx}`;
483
+ const itemStmts = buildProjectorStatements(itemsSchema, itemVar, itemDst, depth + 1);
484
+ if (itemStmts === null) return null;
485
+ return `if (Array.isArray(${srcArrVar})) {\n` +
486
+ ` const ${arrOut} = new Array(${srcArrVar}.length);\n` +
487
+ ` for (let ${arrIdx} = 0; ${arrIdx} < ${srcArrVar}.length; ${arrIdx}++) {\n` +
488
+ ` const ${itemVar} = ${srcArrVar}[${arrIdx}];\n` +
489
+ ` if (${itemVar} && typeof ${itemVar} === 'object' && !Array.isArray(${itemVar})) {\n` +
490
+ ` const ${itemDst} = {};\n${itemStmts} ${arrOut}[${arrIdx}] = ${itemDst};\n` +
491
+ ` } else {\n ${arrOut}[${arrIdx}] = ${itemVar};\n }\n` +
492
+ ` }\n` +
493
+ ` ${dstAssignPrefix}${arrOut};\n` +
494
+ `} else {\n ${dstAssignPrefix}${srcArrVar};\n}`;
185
495
  };
186
496
 
187
- const buildProjectorExpr = (schema: any, accessor: string): string | null => {
497
+ const buildProjectorStatements = (schema: any, srcVar: string, dstVar: string, depth = 0): string | null => {
188
498
  const props = schema?.properties;
189
499
  if (!props || typeof props !== 'object') return null;
190
- const entries: string[] = [];
500
+ let stmts = '';
501
+ let idx = 0;
191
502
  for (const [k, subSchema] of Object.entries<any>(props)) {
192
503
  if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
193
504
  const keyLit = JSON.stringify(k);
194
- const propAccess = `${accessor}[${keyLit}]`;
195
- const nestedExpr = buildProjectorExpr(subSchema, propAccess);
196
- if (nestedExpr) {
197
- entries.push(`${keyLit}: (${propAccess} && typeof ${propAccess} === 'object' && !Array.isArray(${propAccess})) ? ${nestedExpr} : ${propAccess}`);
505
+ const valVar = `v_${depth}_${idx++}`;
506
+ const nestedDst = `d_${depth}_${idx}`;
507
+ stmts += `const ${valVar} = Object.hasOwn(${srcVar}, ${keyLit}) ? ${srcVar}[${keyLit}] : undefined;\n`;
508
+
509
+ if (subSchema?.type === 'array' && subSchema?.items) {
510
+ const arrBlock = buildArrayProjectorStmts(subSchema.items, valVar, `${dstVar}[${keyLit}] = `, depth, idx);
511
+ if (arrBlock !== null) {
512
+ stmts += `if (${valVar} !== undefined) {\n${arrBlock}\n}\n`;
513
+ continue;
514
+ }
515
+ }
516
+
517
+ const nestedStmts = buildProjectorStatements(subSchema, valVar, nestedDst, depth + 1);
518
+ if (nestedStmts !== null) {
519
+ stmts += `if (${valVar} !== undefined) {\n`;
520
+ stmts += ` if (${valVar} && typeof ${valVar} === 'object' && !Array.isArray(${valVar})) {\n`;
521
+ stmts += ` const ${nestedDst} = {};\n${nestedStmts} ${dstVar}[${keyLit}] = ${nestedDst};\n`;
522
+ stmts += ` } else {\n ${dstVar}[${keyLit}] = ${valVar};\n }\n}\n`;
198
523
  } else {
199
- entries.push(`${keyLit}: ${propAccess}`);
524
+ stmts += `if (${valVar} !== undefined) ${dstVar}[${keyLit}] = ${valVar};\n`;
200
525
  }
201
526
  }
202
- return `{ ${entries.join(', ')} }`;
527
+ return stmts;
528
+ };
529
+
530
+ const schemaNeedsFallbackProjector = (schema: any): boolean => {
531
+ if (!schema || typeof schema !== 'object') return false;
532
+ if (Array.isArray(schema.anyOf) || Array.isArray(schema.oneOf) || Array.isArray(schema.allOf)) return true;
533
+ if (schema.additionalProperties && typeof schema.additionalProperties === 'object') return true;
534
+ if (schema.patternProperties && typeof schema.patternProperties === 'object') return true;
535
+ if (Array.isArray(schema.items)) return true;
536
+ if (schema.type === 'array' && schema.items) return schemaNeedsFallbackProjector(schema.items);
537
+ if (schema.properties && typeof schema.properties === 'object') {
538
+ for (const sub of Object.values<any>(schema.properties)) {
539
+ if (schemaNeedsFallbackProjector(sub)) return true;
540
+ }
541
+ }
542
+ return false;
543
+ };
544
+
545
+ const collectAllOfObjectProps = (schema: any, outProps: Record<string, any>): boolean => {
546
+ let hasProps = false;
547
+ if (schema?.properties && typeof schema.properties === 'object') {
548
+ Object.assign(outProps, schema.properties);
549
+ hasProps = true;
550
+ }
551
+ if (Array.isArray(schema?.allOf)) {
552
+ for (const sub of schema.allOf) {
553
+ if (collectAllOfObjectProps(sub, outProps)) hasProps = true;
554
+ }
555
+ }
556
+ return hasProps;
557
+ };
558
+
559
+ const projectWithSchema = (val: any, schema: any): any => {
560
+ if (!schema || typeof schema !== 'object' || val === null || typeof val !== 'object') return val;
561
+
562
+ if (Array.isArray(val)) {
563
+ if (Array.isArray(schema.items)) {
564
+ return val.map((item, i) => (schema.items[i] ? projectWithSchema(item, schema.items[i]) : item));
565
+ }
566
+ if (schema.items && typeof schema.items === 'object') {
567
+ return val.map((item) => projectWithSchema(item, schema.items));
568
+ }
569
+ return val;
570
+ }
571
+
572
+ const branches = schema.anyOf || schema.oneOf;
573
+ if (Array.isArray(branches) && branches.length > 0) {
574
+ let matchedBranch: any = null;
575
+ for (const b of branches) {
576
+ if (b && typeof b === 'object' && compileSingleSchema(b)(val).ok) {
577
+ matchedBranch = b;
578
+ break;
579
+ }
580
+ }
581
+ if (matchedBranch) {
582
+ if (schema.properties && typeof schema.properties === 'object') {
583
+ const merged = { ...schema.properties, ...(matchedBranch.properties || {}) };
584
+ const out: Record<string, any> = {};
585
+ for (const [k, sub] of Object.entries<any>(merged)) {
586
+ if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
587
+ if (Object.hasOwn(val, k) && val[k] !== undefined) {
588
+ out[k] = projectWithSchema(val[k], sub);
589
+ }
590
+ }
591
+ return out;
592
+ }
593
+ return projectWithSchema(val, matchedBranch);
594
+ }
595
+ if (!schema.properties) return val;
596
+ }
597
+
598
+ if (Array.isArray(schema.allOf)) {
599
+ const mergedProps: Record<string, any> = {};
600
+ if (collectAllOfObjectProps(schema, mergedProps)) {
601
+ const out: Record<string, any> = {};
602
+ for (const [k, sub] of Object.entries<any>(mergedProps)) {
603
+ if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
604
+ if (Object.hasOwn(val, k) && val[k] !== undefined) {
605
+ out[k] = projectWithSchema(val[k], sub);
606
+ }
607
+ }
608
+ return out;
609
+ }
610
+ }
611
+
612
+ const hasProps = Boolean(schema.properties && typeof schema.properties === 'object');
613
+ const hasPatProps = Boolean(schema.patternProperties && typeof schema.patternProperties === 'object');
614
+ const hasAddProps = Boolean(schema.additionalProperties && typeof schema.additionalProperties === 'object');
615
+ if (hasProps || hasPatProps || hasAddProps) {
616
+ const out: Record<string, any> = {};
617
+ const props = hasProps ? schema.properties : null;
618
+ if (props) {
619
+ for (const [k, sub] of Object.entries<any>(props)) {
620
+ if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
621
+ if (Object.hasOwn(val, k) && val[k] !== undefined) {
622
+ out[k] = projectWithSchema(val[k], sub);
623
+ }
624
+ }
625
+ }
626
+ if (hasPatProps || hasAddProps) {
627
+ const patterns = hasPatProps
628
+ ? Object.entries<any>(schema.patternProperties).map(([pat, sub]) => ({ re: new RegExp(pat), sub }))
629
+ : [];
630
+ for (const k of Object.keys(val)) {
631
+ if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
632
+ if (val[k] === undefined || (props && Object.hasOwn(props, k))) continue;
633
+ let matched = false;
634
+ for (let i = 0; i < patterns.length; i++) {
635
+ if (patterns[i]!.re.test(k)) {
636
+ out[k] = projectWithSchema(val[k], patterns[i]!.sub);
637
+ matched = true;
638
+ break;
639
+ }
640
+ }
641
+ if (!matched && hasAddProps) {
642
+ out[k] = projectWithSchema(val[k], schema.additionalProperties);
643
+ }
644
+ }
645
+ }
646
+ return out;
647
+ }
648
+
649
+ return val;
203
650
  };
204
651
 
205
652
  const compileProjector = (schema: any): ((val: any) => any) | null => {
206
653
  if (!schema || '_def' in schema) return null; // Zod safeParse strips unknown keys natively
654
+ if (schemaNeedsFallbackProjector(schema)) {
655
+ return (val: any) => projectWithSchema(val, schema);
656
+ }
207
657
  if (schema.type === 'array' && schema.items) {
208
- const itemExpr = buildProjectorExpr(schema.items, 'item');
209
- if (!itemExpr) return null;
658
+ if (schema.items.type === 'array') {
659
+ return (val: any) => projectWithSchema(val, schema);
660
+ }
661
+ const itemStmts = buildProjectorStatements(schema.items, 'item', 'outItem');
662
+ if (itemStmts === null) return (val: any) => projectWithSchema(val, schema);
210
663
  return new Function(
211
664
  `return function(arr) {
212
665
  if (!Array.isArray(arr)) return arr;
@@ -214,18 +667,26 @@ const compileProjector = (schema: any): ((val: any) => any) | null => {
214
667
  const out = new Array(len);
215
668
  for (let i = 0; i < len; i++) {
216
669
  const item = arr[i];
217
- out[i] = (item && typeof item === 'object' && !Array.isArray(item)) ? ${itemExpr} : item;
670
+ if (item && typeof item === 'object' && !Array.isArray(item)) {
671
+ const outItem = {};
672
+ ${itemStmts}
673
+ out[i] = outItem;
674
+ } else {
675
+ out[i] = item;
676
+ }
218
677
  }
219
678
  return out;
220
679
  }`
221
680
  )();
222
681
  }
223
- const objExpr = buildProjectorExpr(schema, 'o');
224
- if (!objExpr) return null;
682
+ const objStmts = buildProjectorStatements(schema, 'o', 'out');
683
+ if (objStmts === null) return (val: any) => projectWithSchema(val, schema);
225
684
  return new Function(
226
685
  `return function(o) {
227
686
  if (!o || typeof o !== 'object' || Array.isArray(o)) return o;
228
- return ${objExpr};
687
+ const out = {};
688
+ ${objStmts}
689
+ return out;
229
690
  }`
230
691
  )();
231
692
  };
@@ -245,19 +706,40 @@ export const createResponseFilter = (schema: any): ((val: any) => any) => {
245
706
  };
246
707
  };
247
708
 
709
+ const unwrapPropType = (propSchema: any): string | undefined => {
710
+ let cur = propSchema;
711
+ while (cur?._def) {
712
+ const tn = cur._def.typeName;
713
+ if (tn === 'ZodOptional' || tn === 'ZodDefault' || tn === 'ZodNullable') {
714
+ cur = cur._def.innerType;
715
+ } else if (tn === 'ZodEffects') {
716
+ cur = cur._def.schema;
717
+ } else {
718
+ break;
719
+ }
720
+ }
721
+ return cur?.type || cur?._def?.typeName;
722
+ };
723
+
724
+ const NUMERIC_RE = /^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/;
725
+
248
726
  const coerceFields = (obj: Record<string, any>, schema: any): Record<string, any> => {
249
- const props = schema?.properties || (schema?._def?.shape ? (typeof schema._def.shape === 'function' ? schema._def.shape() : schema._def.shape) : null);
727
+ let cur = schema;
728
+ while (cur?._def?.typeName === 'ZodEffects') {
729
+ cur = cur._def.schema;
730
+ }
731
+ const props = cur?.properties || (cur?._def?.shape ? (typeof cur._def.shape === 'function' ? cur._def.shape() : cur._def.shape) : null);
250
732
  if (!props) return obj;
251
733
  const out: Record<string, any> = { ...obj };
252
734
  for (const [k, propSchema] of Object.entries<any>(props)) {
253
735
  if (!Object.hasOwn(out, k)) continue;
254
736
  const val = out[k];
255
737
  if (typeof val !== 'string') continue;
256
- const tType = propSchema?.type || propSchema?._def?.typeName;
738
+ const tType = unwrapPropType(propSchema);
257
739
  if (tType === 'number' || tType === 'integer' || tType === 'ZodNumber') {
258
- if (val.trim() !== '') {
740
+ if (/^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/.test(val)) {
259
741
  const n = Number(val);
260
- if (!Number.isNaN(n)) out[k] = n;
742
+ if (Number.isFinite(n)) out[k] = n;
261
743
  }
262
744
  } else if (tType === 'boolean' || tType === 'ZodBoolean') {
263
745
  if (val === 'true') out[k] = true;
@@ -273,8 +755,38 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
273
755
  const paramsCheck = schemas.params ? compileSingleSchema(schemas.params) : null;
274
756
  const headersCheck = schemas.headers ? compileSingleSchema(schemas.headers) : null;
275
757
  const bodyProjector = schemas.stripUnknown && schemas.body ? compileProjector(schemas.body) : null;
758
+ const queryProjector = schemas.stripUnknown && schemas.query ? compileProjector(schemas.query) : null;
759
+ const paramsProjector = schemas.stripUnknown && schemas.params ? compileProjector(schemas.params) : null;
276
760
  const responseFilter = schemas.response ? createResponseFilter(schemas.response) : null;
277
761
  const maxBodySize = schemas.maxBodySize ?? 1048576;
762
+ const queryArrayKeys: string[] = [];
763
+ const queryArrayNumeric = new Set<string>();
764
+ {
765
+ let qs: any = schemas.query;
766
+ while (qs?._def?.schema) qs = qs._def.schema;
767
+ const qProps = qs?.properties || (qs?._def?.shape ? (typeof qs._def.shape === 'function' ? qs._def.shape() : qs._def.shape) : null);
768
+ const unwrapZod = (node: any): any => {
769
+ let cur = node;
770
+ while (cur?._def) {
771
+ const tn = cur._def.typeName;
772
+ if (tn === 'ZodOptional' || tn === 'ZodDefault' || tn === 'ZodNullable') cur = cur._def.innerType;
773
+ else if (tn === 'ZodEffects') cur = cur._def.schema;
774
+ else break;
775
+ }
776
+ return cur;
777
+ };
778
+ if (qProps) {
779
+ for (const [k, rawPs] of Object.entries<any>(qProps)) {
780
+ const ps = unwrapZod(rawPs);
781
+ const isArr = ps?.type === 'array' || ps?._def?.typeName === 'ZodArray';
782
+ if (!isArr) continue;
783
+ queryArrayKeys.push(k);
784
+ const inner = unwrapZod(ps.items ?? ps._def?.type);
785
+ const it = inner?.type ?? inner?._def?.typeName;
786
+ if (it === 'number' || it === 'integer' || it === 'ZodNumber') queryArrayNumeric.add(k);
787
+ }
788
+ }
789
+ }
278
790
  const hasSyncParts = Boolean(paramsCheck || queryCheck || headersCheck);
279
791
 
280
792
  const validateSyncParts = (ctx: Context): Response | undefined => {
@@ -282,17 +794,26 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
282
794
  const coerced = coerceFields(ctx.params, schemas.params);
283
795
  const r = paramsCheck(coerced);
284
796
  if (!r.ok) return errorJSON({ status: 'error', code: 'PARAMS_INVALID', error: r.error });
285
- ctx.params = r.data;
797
+ ctx.params = paramsProjector ? paramsProjector(r.data) : r.data;
286
798
  }
287
799
  if (queryCheck) {
288
800
  const coerced = coerceFields(ctx.query, schemas.query);
801
+ for (const k of queryArrayKeys) {
802
+ const all = ctx.queryAll(k);
803
+ if (all.length > 0) coerced[k] = all.map((v) => (queryArrayNumeric.has(k) && NUMERIC_RE.test(v) ? Number(v) : v));
804
+ }
289
805
  const r = queryCheck(coerced);
290
806
  if (!r.ok) return errorJSON({ status: 'error', code: 'QUERY_INVALID', error: r.error });
291
- ctx._query = r.data;
807
+ ctx._query = queryProjector ? queryProjector(r.data) : r.data;
292
808
  }
293
809
  if (headersCheck) {
294
810
  const hdrObj: Record<string, string> = {};
295
- ctx.req.headers.forEach((v, k) => { hdrObj[k.toLowerCase()] = v; });
811
+ ctx.req.headers.forEach((v, k) => {
812
+ const lower = k.toLowerCase();
813
+ if (lower !== '__proto__' && lower !== 'constructor' && lower !== 'prototype') {
814
+ hdrObj[lower] = v;
815
+ }
816
+ });
296
817
  const r = headersCheck(hdrObj);
297
818
  if (!r.ok) return errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: r.error });
298
819
  }
@@ -312,26 +833,53 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
312
833
  return syncMw;
313
834
  }
314
835
 
315
- const mw: Middleware = async (ctx: Context, next?: Next) => {
836
+ const isZodBody = Boolean(schemas.body && '_def' in schemas.body);
837
+ const finishBodyValidation = (ctx: Context, body: any, next?: Next): any => {
838
+ let r: { ok: boolean; data?: any; error?: any };
839
+ try {
840
+ r = bodyCheck(body);
841
+ } catch {
842
+ if (isZodBody) {
843
+ return schemas.body.safeParseAsync(body).then((zr: any) => {
844
+ if (!zr.success) return errorJSON({ status: 'error', code: 'VALIDATION_FAILED', error: zr.error.flatten() });
845
+ ctx.body = bodyProjector ? bodyProjector(zr.data) : zr.data;
846
+ return next ? next() : undefined;
847
+ });
848
+ }
849
+ r = { ok: false, error: { message: 'Validation failed' } };
850
+ }
851
+ if (!r.ok) return errorJSON({ status: 'error', code: 'VALIDATION_FAILED', error: r.error });
852
+ ctx.body = bodyProjector ? bodyProjector(r.data) : r.data;
853
+ return next ? next() : undefined;
854
+ };
855
+
856
+ const mw: Middleware = (ctx: Context, next?: Next) => {
316
857
  if (hasSyncParts) {
317
858
  const errRes = validateSyncParts(ctx);
318
859
  if (errRes) return errRes;
319
860
  }
320
861
 
321
- let body: any;
862
+ let bodyOrPromise: any;
322
863
  try {
323
- body = await ctx.jsonBody(maxBodySize);
864
+ bodyOrPromise = (ctx as any).jsonBodySyncOrAsync(maxBodySize);
324
865
  } catch (e: any) {
325
866
  if (e?.status === 413) {
326
867
  return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
327
868
  }
328
869
  return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
329
870
  }
330
- const r = bodyCheck(body);
331
- if (!r.ok) return errorJSON({ status: 'error', code: 'VALIDATION_FAILED', error: r.error });
332
- ctx.body = bodyProjector ? bodyProjector(r.data) : r.data;
333
-
334
- return next ? next() : undefined;
871
+ if (bodyOrPromise && typeof bodyOrPromise.then === 'function') {
872
+ return bodyOrPromise.then(
873
+ (body: any) => finishBodyValidation(ctx, body, next),
874
+ (e: any) => {
875
+ if (e?.status === 413) {
876
+ return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
877
+ }
878
+ return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
879
+ }
880
+ );
881
+ }
882
+ return finishBodyValidation(ctx, bodyOrPromise, next);
335
883
  };
336
884
  (mw as any).__schema = schemas.body;
337
885
  (mw as any).__routeSchemas = schemas;