validator.ts
This file
Path
src/validator/validator.ts
151 lines · 4.6 KiB · TypeScript
Last changed by
fix(validator): Fixed a bug in hono/validator where URL Encoded Data could not be validated if the Content-Type included charset. (#3297)uttkbefore adoptionc378dd9
History of this fileTake it
The walk stopped after 200 commits: lines older than 7ee829b point at it.
v4.4.7Yusuke Wadabefore adoption7ee829b
lines 1–25why, one step back1import type { Context } from '../context'2import { getCookie } from '../helper/cookie'3import { HTTPException } from '../http-exception'4import type { Env, MiddlewareHandler, TypedResponse, ValidationTargets } from '../types'5import type { BodyData } from '../utils/body'6import { bufferToFormData } from '../utils/buffer'78type ValidationTargetKeysWithBody = 'form' | 'json'9type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.10 ? Exclude<keyof ValidationTargets, ValidationTargetKeysWithBody>11 : keyof ValidationTargets1213export type ValidationFunction<14 InputType,15 OutputType,16 E extends Env = {},17 P extends string = string18> = (19 value: InputType,20 c: Context<E, P>21) => OutputType | Response | Promise<OutputType> | Promise<Response>2223// eslint-disable-next-line @typescript-eslint/no-explicit-any24type ExcludeResponseType<T> = T extends Response & TypedResponse<any> ? never : T25fix(validator): support `application/json` with a charset (#3199)Yusuke Wadabefore adoptioncdd48f4
line 26why, one step back26const jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/fix(validator): support multipart headers without a space separating boundary (#3286)Ernest Badubefore adoption81a1f07
line 27why, one step back27const multipartRegex = /^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/fix(validator): Fixed a bug in hono/validator where URL Encoded Data could not be validated if the Content-Type included charset. (#3297)uttkbefore adoptionc378dd9
line 28why, one step back28const urlencodedRegex = /^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/fix(validator): allow content-type mismatches (#3165)Yusuke Wadabefore adoption4171896
line 29why, one step back29v4.4.7Yusuke Wadabefore adoption7ee829b
lines 30–73why, one step back30export const validator = <31 InputType,32 P extends string,33 M extends string,34 U extends ValidationTargetByMethod<M>,35 OutputType = ValidationTargets[U],36 OutputTypeExcludeResponseType = ExcludeResponseType<OutputType>,37 P2 extends string = P,38 V extends {39 in: {40 [K in U]: K extends 'json'41 ? unknown extends InputType42 ? OutputTypeExcludeResponseType43 : InputType44 : { [K2 in keyof OutputTypeExcludeResponseType]: ValidationTargets[K][K2] }45 }46 out: { [K in U]: OutputTypeExcludeResponseType }47 } = {48 in: {49 [K in U]: K extends 'json'50 ? unknown extends InputType51 ? OutputTypeExcludeResponseType52 : InputType53 : { [K2 in keyof OutputTypeExcludeResponseType]: ValidationTargets[K][K2] }54 }55 out: { [K in U]: OutputTypeExcludeResponseType }56 },57 // eslint-disable-next-line @typescript-eslint/no-explicit-any58 E extends Env = any59>(60 target: U,61 validationFunc: ValidationFunction<62 unknown extends InputType ? ValidationTargets[U] : InputType,63 OutputType,64 E,65 P266 >67): MiddlewareHandler<E, P, V> => {68 return async (c, next) => {69 let value = {}70 const contentType = c.req.header('Content-Type')7172 switch (target) {73 case 'json':fix(validator): allow content-type mismatches (#3165)Yusuke Wadabefore adoption4171896
lines 74–75why, one step back74 if (!contentType || !jsonRegex.test(contentType)) {75 breakv4.4.7Yusuke Wadabefore adoption7ee829b
lines 76–84why, one step back76 }77 try {78 value = await c.req.json()79 } catch {80 const message = 'Malformed JSON in request body'81 throw new HTTPException(400, { message })82 }83 break84 case 'form': {fix(validator): allow content-type mismatches (#3165)Yusuke Wadabefore adoption4171896
lines 85–88why, one step back85 if (86 !contentType ||87 !(multipartRegex.test(contentType) || urlencodedRegex.test(contentType))88 ) {v4.4.7Yusuke Wadabefore adoption7ee829b
lines 89–91why, one step back89 break90 }91fix(validator): don't return a FormData if formData is cached (#3067)Yusuke Wadabefore adoption2d452f2
lines 92–93why, one step back92 let formData: FormData93v4.4.7Yusuke Wadabefore adoption7ee829b
line 94why, one step back94 if (c.req.bodyCache.formData) {fix(validator): don't return a FormData if formData is cached (#3067)Yusuke Wadabefore adoption2d452f2
lines 95–105why, one step back95 formData = await c.req.bodyCache.formData96 } else {97 try {98 const arrayBuffer = await c.req.arrayBuffer()99 formData = await bufferToFormData(arrayBuffer, contentType)100 c.req.bodyCache.formData = formData101 } catch (e) {102 let message = 'Malformed FormData request.'103 message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`104 throw new HTTPException(400, { message })105 }v4.4.7Yusuke Wadabefore adoption7ee829b
lines 106–107why, one step back106 }107fix(validator): don't return a FormData if formData is cached (#3067)Yusuke Wadabefore adoption2d452f2
lines 108–110why, one step back108 const form: BodyData<{ all: true }> = {}109 formData.forEach((value, key) => {110 if (key.endsWith('[]')) {fix(validator): Allow form data will mutliple values appended (#3273)Nick Randallbefore adoption0c1e899
lines 111–115why, one step back111 ;((form[key] ??= []) as unknown[]).push(value)112 } else if (Array.isArray(form[key])) {113 ;(form[key] as unknown[]).push(value)114 } else if (key in form) {115 form[key] = [form[key] as string | File, value]fix(validator): don't return a FormData if formData is cached (#3067)Yusuke Wadabefore adoption2d452f2
lines 116–120why, one step back116 } else {117 form[key] = value118 }119 })120 value = formv4.4.7Yusuke Wadabefore adoption7ee829b
lines 121–151why, one step back121 break122 }123 case 'query':124 value = Object.fromEntries(125 Object.entries(c.req.queries()).map(([k, v]) => {126 return v.length === 1 ? [k, v[0]] : [k, v]127 })128 )129 break130 case 'param':131 value = c.req.param() as Record<string, string>132 break133 case 'header':134 value = c.req.header()135 break136 case 'cookie':137 value = getCookie(c)138 break139 }140141 const res = await validationFunc(value as never, c as never)142143 if (res instanceof Response) {144 return res145 }146147 c.req.addValidatedData(target, res as never)148149 await next()150 }151}