Skip to content
Myr

refactor(types): refactor and add tests for checking Types (#615)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* refactor(types): refactor and add tests for checking Types * remove unused * uncomment * use `Handler` in validator middleware * remove unused * create `src/validator` dir and move some files into it * add the case that the context is in `validator` * rename `D` to `S`

authored by Yusuke Wada · committed by GitHub · parent 77b0815 · Browse files · 39 files+2505 added−2289 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

39 files+2505 added−2289 removed

  • tests:+971 added−799 removed
  • other:+1534 added−1490 removed

39 files+2505 added−2289 removed

modified:deno_dist/middleware/serve-static/serve-static.ts+3 added-4 removed
modified:deno_dist/middleware/validator/middleware.ts+20 added-72 removed
1import type { Context } from '../../context.ts'2import type { Environment, Next, ValidatedData } from '../../hono.ts'2import type { Environment, MiddlewareHandler } from '../../hono.ts'3import { getStatusText } from '../../utils/http-status.ts'4import { mergeObjects } from '../../utils/object.ts'5import { VBase, Validator, VObjectBase } from './validator.ts'6import type {7 VString,8 VNumber,9 VBoolean,10 VObject,11 VNumberArray,12 VStringArray,13 VBooleanArray,14 ValidateResult,15 VArray,16} from './validator.ts'5import type { Schema } from '../../validator/schema.ts'6import type { ValidateResult } from '../../validator/validator.ts'7import { Validator, VBase, VObjectBase } from '../../validator/validator.ts'818export type Schema = {19 [key: string]:20 | VString21 | VNumber22 | VBoolean23 | VStringArray24 | VNumberArray25 | VBooleanArray26 | Schema27 | VObject<Schema>28 | VArray<Schema>29}3031type SchemaToProp<T> = {32 [K in keyof T]: T[K] extends VNumberArray33 ? number[]34 : T[K] extends VBooleanArray35 ? boolean[]36 : T[K] extends VStringArray37 ? string[]38 : T[K] extends VNumber39 ? number40 : T[K] extends VBoolean41 ? boolean42 : T[K] extends VString43 ? string44 : T[K] extends VObjectBase<Schema>45 ? T[K]['container'] extends VNumber46 ? number47 : T[K]['container'] extends VString48 ? string49 : T[K]['container'] extends VBoolean50 ? boolean51 : T[K] extends VArray<Schema>52 ? SchemaToProp<ReadonlyArray<T[K]['container']>>53 : T[K] extends VObject<Schema>54 ? SchemaToProp<T[K]['container']>55 : T[K] extends Schema56 ? SchemaToProp<T[K]>57 : never58 : SchemaToProp<T[K]>59}609type ResultSet = {10 hasError: boolean11 messages: string[]12 results: ValidateResult[]13}1467type Done<Env extends Partial<Environment>> = (15type Done<P extends string, E extends Partial<Environment> = Environment> = (16 resultSet: ResultSet,69 context: Context<string, Env>17 c: Context<P, E>18) => Response | void1972type ValidationFunction<T, Env extends Partial<Environment>> = (73 v: Validator,74 c: Context<string, Env>75) => T20type ValidationFunction<21 P extends string,22 E extends Partial<Environment> = Environment,23 S extends Schema = Schema24> = (v: Validator, c: Context<P, E>) => S2577type MiddlewareHandler<78 Data extends ValidatedData = ValidatedData,79 Env extends Partial<Environment> = Environment80> = (c: Context<string, Env, Data>, next: Next) => Promise<void> | Promise<Response | undefined>8182export const validatorMiddleware = <T extends Schema, Env extends Partial<Environment>>(83 validationFunction: ValidationFunction<T, Env>,84 options?: { done?: Done<Env> }26export const validatorMiddleware = <27 P extends string,28 E extends Partial<Environment> = Environment,29 S extends Schema = Schema30>(31 validationFunction: ValidationFunction<P, E, S>,32 options?: { done?: Done<P, E> }33) => {34 const v = new Validator()87 const handler: MiddlewareHandler<SchemaToProp<T>, Env> = async (c, next) => {35 const handler: MiddlewareHandler<string, E, S> = async (c, next) => {36 const resultSet: ResultSet = {37 hasError: false,38 messages: [],39 results: [],
5 unmodified lines
4546 for (const [keys, validator] of validatorList) {47 let results: ValidateResult[]48 try {101 results = await validator.validate(c.req)49 results = await validator.validate(c.req as Request)50 } catch (e) {51 // Invalid JSON request52 return c.text(getStatusText(400), 400)53 }
78 unmodified lines
deleted:deno_dist/middleware/validator/rule.ts-83 removed
1// Some validation rules is are based on Validator.js2// Validator.js3// License (MIT)4// Copyright (c) 2018 Chris O'Hara <cohara87@gmail.com>5// https://github.com/validatorjs/validator.js67export const rule = {8 // string9 isEmpty(10 value: string,11 options: {12 ignore_whitespace: boolean13 } = { ignore_whitespace: false }14 ): boolean {15 return (options.ignore_whitespace ? value.trim().length : value.length) === 016 },1718 isLength: (19 value: string,20 options: Partial<{ min: number; max: number }> | number,21 arg2?: number22 ) => {23 let min: number24 let max: number | undefined25 if (typeof options === 'object') {26 min = options.min || 027 max = options.max28 } else {29 // backwards compatibility: isLength(str, min [, max])30 min = options || 031 max = arg232 }33 const presentationSequences = value.match(/(\uFE0F|\uFE0E)/g) || []34 const surrogatePairs = value.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []35 const len = value.length - presentationSequences.length - surrogatePairs.length36 return len >= min && (typeof max === 'undefined' || len <= max)37 },3839 isAlpha: (value: string): boolean => {40 return /^[A-Z]+$/i.test(value)41 },4243 isNumeric: (value: string): boolean => {44 return /^[0-9]+$/.test(value)45 },4647 contains: (48 value: string,49 elem: string,50 options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {51 ignoreCase: false,52 minOccurrences: 1,53 }54 ): boolean => {55 options.ignoreCase ||= false56 options.minOccurrences ||= 157 if (options.ignoreCase) {58 return value.toLowerCase().split(elem.toLowerCase()).length > options.minOccurrences59 }60 return value.split(elem).length > options.minOccurrences61 },6263 isIn: (value: string, options: string[]): boolean => {64 if (typeof options === 'object') {65 for (const elem of options) {66 if (elem === value) return true67 }68 }69 return false70 },7172 match: (value: string, regExp: RegExp): boolean => {73 return regExp.test(value)74 },7576 // number77 isGte: (value: number, min: number) => min <= value,78 isLte: (value: number, max: number) => value <= max,7980 // boolean81 isTrue: (value: boolean) => value === true,82 isFalse: (value: boolean) => value === false,83}
deleted:deno_dist/middleware/validator/sanitizer.ts-3 removed
deleted:deno_dist/middleware/validator/validator.ts-492 removed
1import { JSONPathCopy } from '../../utils/json.ts'2import type { JSONObject, JSONPrimitive, JSONArray } from '../../utils/json.ts'3import type { Schema } from './middleware.ts'4import { rule } from './rule.ts'5import { sanitizer } from './sanitizer.ts'67type Target = 'query' | 'header' | 'body' | 'json'8type Type = JSONPrimitive | JSONObject | JSONArray | File9type RuleFunc = (value: Type) => boolean10type Rule = {11 name: string12 func: RuleFunc13 customMessage?: string14 type: 'type' | 'value'15}16type Sanitizer = (value: Type) => Type1718export type ValidateResult = {19 isValid: boolean20 message: string | undefined21 target: Target22 key: string23 value: Type24 ruleName: string25 ruleType: 'type' | 'value'26 jsonData?: JSONObject27}2829export abstract class VObjectBase<T extends Schema> {30 container: T31 keys: string[] = []32 protected _isOptional: boolean = false33 constructor(container: T, key: string) {34 this.container = container35 if (this instanceof VArray) {36 this.keys.push(key, '[*]')37 } else if (this instanceof VObject) {38 this.keys.push(key)39 }40 }4142 isOptional() {43 this._isOptional = true44 return this45 }4647 getValidators = (): VBase[] => {48 const validators: VBase[] = []49 const thisKeys: string[] = []50 Object.assign(thisKeys, this.keys)5152 const walk = (container: T, keys: string[], isOptional: boolean) => {53 for (const v of Object.values(container)) {54 if (v instanceof VArray || v instanceof VObject) {55 // eslint-disable-next-line @typescript-eslint/ban-ts-comment56 // @ts-ignore57 isOptional ||= v._isOptional58 keys.push(...v.keys)59 walk(v.container as T, keys, isOptional)60 const tmp: string[] = []61 Object.assign(tmp, thisKeys)62 keys = tmp63 } else if (v instanceof VBase) {64 if (isOptional) v.isOptional()65 v.baseKeys.push(...keys)66 validators.push(v)67 }68 }69 }7071 walk(this.container, this.keys, this._isOptional)7273 return validators74 }75}7677export class VObject<T extends Schema> extends VObjectBase<T> {78 constructor(container: T, key: string) {79 super(container, key)80 }81}8283export class VArray<T extends Schema> extends VObjectBase<T> {84 type: 'array' = 'array'85 constructor(container: T, key: string) {86 super(container, key)87 }88}8990export class Validator {91 isArray: boolean = false92 query = (key: string): VString => new VString({ target: 'query', key: key })93 header = (key: string): VString => new VString({ target: 'header', key: key })94 body = (key: string): VString => new VString({ target: 'body', key: key })95 json = (key: string) => {96 if (this.isArray) {97 return new VStringArray({ target: 'json', key: key })98 } else {99 return new VString({ target: 'json', key: key })100 }101 }102 array = <T extends Schema>(path: string, validator: (v: Validator) => T): VArray<T> => {103 this.isArray = true104 const res = validator(this)105 const arr = new VArray(res, path)106 return arr107 }108 object = <T extends Schema>(path: string, validator: (v: Validator) => T): VObject<T> => {109 this.isArray = false110 const res = validator(this)111 const obj = new VObject(res, path)112 return obj113 }114}115116type VOptions = {117 target: Target118 key: string119 type?: 'string' | 'number' | 'boolean' | 'object'120 isArray?: boolean121}122123export abstract class VBase {124 type: 'string' | 'number' | 'boolean' | 'object'125 target: Target126 baseKeys: string[] = []127 key: string128 rules: Rule[]129 sanitizers: Sanitizer[]130 isArray: boolean131 private _optional: boolean132 constructor(options: VOptions) {133 this.target = options.target134 this.key = options.key135 this.type = options.type || 'string'136 this.rules = [137 {138 name: this.getTypeRuleName(),139 type: 'type',140 func: this.validateType,141 },142 ]143 this.sanitizers = []144 this._optional = false145 this.isArray = options.isArray || false146 }147148 private _nested = () => (this.baseKeys.length ? true : false)149150 addRule(func: RuleFunc): this151 addRule(name: string, func: RuleFunc): this152 addRule(arg: string | RuleFunc, func?: RuleFunc) {153 if (typeof arg === 'string' && func) {154 this.rules.push({ name: arg, func, type: 'value' })155 } else if (arg instanceof Function) {156 this.rules.push({ name: arg.name, func: arg, type: 'value' })157 }158 return this159 }160161 addSanitizer = (sanitizer: Sanitizer) => {162 this.sanitizers.push(sanitizer)163 return this164 }165166 message = (text: string) => {167 const len = this.rules.length168 if (len >= 1) {169 this.rules[len - 1].customMessage = text170 }171 return this172 }173174 isRequired = () => {175 return this.addRule('isRequired', (value: unknown) => {176 if (value !== undefined && value !== null && value !== '') return true177 return false178 })179 }180181 isOptional = () => {182 this._optional = true183 return this.addRule('isOptional', () => true)184 }185186 isEqual = (comparison: unknown) => {187 return this.addRule('isEqual', (value: unknown) => {188 return value === comparison189 })190 }191192 asNumber = (): VNumber | VNumberArray => {193 const newVNumber = new VNumber({ ...this, type: 'number' })194 if (this.isArray) return newVNumber.asArray()195 return newVNumber196 }197198 asBoolean = (): VBoolean | VBooleanArray => {199 const newVBoolean = new VBoolean({ ...this, type: 'boolean' })200 if (this.isArray) return newVBoolean.asArray()201 return newVBoolean202 }203204 get(value: string) {205 const len = this.rules.length206 if (len > 0) {207 this.rules[this.rules.length - 1].customMessage = value208 }209 return this210 }211212 validate = async (req: Request): Promise<ValidateResult[]> => {213 let value: Type = undefined214 let jsonData: JSONObject | undefined = undefined215216 if (this.target === 'query') {217 value = req.query(this.key)218 }219 if (this.target === 'header') {220 value = req.header(this.key)221 }222 if (this.target === 'body') {223 const body = await req.parseBody()224 value = body[this.key]225 }226 if (this.target === 'json') {227 if (this._nested()) {228 this.key = `${this.baseKeys.join('.')}.${this.key}`229 }230 let obj = {}231 try {232 obj = (await req.json()) as JSONObject233 } catch (e) {234 throw new Error('Malformed JSON in request body')235 }236 const dst = {}237 value = JSONPathCopy(obj, dst, this.key)238 if (this._nested()) jsonData = dst239 }240241 const results: ValidateResult[] = []242243 let typeRule = this.rules.shift()244245 for (const rule of this.rules) {246 if (rule.type === 'type') {247 typeRule = rule248 } else if (rule.type === 'value') {249 const result = this.validateRule(rule, value)250 result.jsonData ||= jsonData251 results.push(result)252 }253 }254255 if (typeRule) {256 const typeResult = this.validateRule(typeRule, value)257 typeResult.jsonData ||= jsonData258 results.unshift(typeResult)259 }260261 return results262 }263264 protected getTypeRuleName(): string {265 const prefix = 'should be'266 return this.isArray ? `${prefix} "${this.type}[]"` : `${prefix} "${this.type}"`267 }268269 private validateRule(rule: Rule, value: Type): ValidateResult {270 let isValid: boolean = false271272 if (this._nested() && this.target != 'json') {273 isValid = false274 } else if (rule.type === 'value') {275 isValid = this.validateValue(rule.func, value)276 } else if (rule.type === 'type') {277 isValid = this.validateType(value)278 }279280 const message = isValid281 ? undefined282 : rule.customMessage || this.getMessage({ ruleName: rule.name, value })283 const result = {284 isValid: isValid,285 message: message,286 target: this.target,287 key: this.key,288 value,289 ruleName: rule.name,290 ruleType: rule.type,291 }292 return result293 }294295 private validateType = (value: Type): boolean => {296 if (this.isArray) {297 if (!Array.isArray(value)) {298 return false299 }300 for (const val of value) {301 if (typeof val === 'undefined' && this._nested()) {302 value.pop()303 }304 for (const val of value) {305 if (typeof val !== this.type) {306 // Value is of wrong type here307 // If it is not optional and not undefined, return false308 if (!this._optional || typeof val !== 'undefined') return false309 }310 }311 }312 } else {313 if (typeof value !== this.type) {314 if (this._optional && (typeof value === 'undefined' || Array.isArray(value))) {315 // Do nothing.316 // If it is optional it's OK to be `undefined` or Array317 } else {318 return false319 }320 }321 }322 return true323 }324325 private validateValue = (func: (value: Type) => boolean, value: Type): boolean => {326 if (this._optional && typeof value === 'undefined') return true327328 if (Array.isArray(value)) {329 // Sanitize330 for (const sanitizer of this.sanitizers) {331 value = value.map((innerVal: any) => sanitizer(innerVal)) as JSONArray332 }333 for (const val of value) {334 if (!func(val)) {335 return false336 }337 }338 return true339 } else {340 // Sanitize341 for (const sanitizer of this.sanitizers) {342 value = sanitizer(value)343 }344 if (!func(value)) {345 return false346 }347 return true348 }349 }350351 private getMessage = (opts: { ruleName: string; value: Type }): string => {352 let keyText: string353 const valueText = Array.isArray(opts.value)354 ? `${opts.value355 .map((val) =>356 val === undefined ? 'undefined' : typeof val === 'string' ? `"${val}"` : val357 )358 .join(', ')}`359 : opts.value360 switch (this.target) {361 case 'query':362 keyText = `the query parameter "${this.key}"`363 break364 case 'header':365 keyText = `the request header "${this.key}"`366 break367 case 'body':368 keyText = `the request body "${this.key}"`369 break370 case 'json':371 keyText = `the JSON body "${this.key}"`372 break373 }374 return `Invalid Value [${valueText}]: ${keyText} is invalid - ${opts.ruleName}`375 }376}377378export class VString extends VBase {379 constructor(options: VOptions) {380 super(options)381 this.type = 'string'382 }383384 asArray = () => {385 return new VStringArray(this)386 }387388 isEmpty = (389 options: {390 ignore_whitespace: boolean391 } = { ignore_whitespace: false }392 ) => {393 return this.addRule('isEmpty', (value) => rule.isEmpty(value as string, options))394 }395396 isLength = (options: Partial<{ min: number; max: number }> | number, arg2?: number) => {397 return this.addRule('isLength', (value) => rule.isLength(value as string, options, arg2))398 }399400 isAlpha = () => {401 return this.addRule('isAlpha', (value) => rule.isAlpha(value as string))402 }403404 isNumeric = () => {405 return this.addRule('isNumeric', (value) => rule.isNumeric(value as string))406 }407408 contains = (409 elem: string,410 options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {411 ignoreCase: false,412 minOccurrences: 1,413 }414 ) => {415 return this.addRule('contains', (value) => rule.contains(value as string, elem, options))416 }417418 isIn = (options: string[]) => {419 return this.addRule('isIn', (value) => rule.isIn(value as string, options))420 }421422 match = (regExp: RegExp) => {423 return this.addRule('match', (value) => rule.match(value as string, regExp))424 }425426 trim = () => {427 return this.addSanitizer((value) => sanitizer.trim(value as string))428 }429}430431export class VNumber extends VBase {432 constructor(options: VOptions) {433 super(options)434 this.type = 'number'435 }436437 asArray = () => {438 return new VNumberArray(this)439 }440441 isGte = (min: number) => {442 return this.addRule('isGte', (value) => rule.isGte(value as number, min))443 }444445 isLte = (min: number) => {446 return this.addRule('isLte', (value) => rule.isLte(value as number, min))447 }448}449450export class VBoolean extends VBase {451 constructor(options: VOptions) {452 super(options)453 this.type = 'boolean'454 }455456 asArray = () => {457 return new VBooleanArray(this)458 }459460 isTrue = () => {461 return this.addRule('isTrue', (value) => rule.isTrue(value as boolean))462 }463464 isFalse = () => {465 return this.addRule('isFalse', (value) => rule.isFalse(value as boolean))466 }467}468469export class VNumberArray extends VNumber {470 isArray: true471 constructor(options: VOptions) {472 super(options)473 this.isArray = true474 this.rules[0].name = this.getTypeRuleName()475 }476}477export class VStringArray extends VString {478 isArray: true479 constructor(options: VOptions) {480 super(options)481 this.isArray = true482 this.rules[0].name = this.getTypeRuleName()483 }484}485export class VBooleanArray extends VBoolean {486 isArray: true487 constructor(options: VOptions) {488 super(options)489 this.isArray = true490 this.rules[0].name = this.getTypeRuleName()491 }492}
added:deno_dist/utils/types.ts+5 added
added:deno_dist/validator/rule.ts+83 added
1// Some validation rules is are based on Validator.js2// Validator.js3// License (MIT)4// Copyright (c) 2018 Chris O'Hara <cohara87@gmail.com>5// https://github.com/validatorjs/validator.js67export const rule = {8 // string9 isEmpty(10 value: string,11 options: {12 ignore_whitespace: boolean13 } = { ignore_whitespace: false }14 ): boolean {15 return (options.ignore_whitespace ? value.trim().length : value.length) === 016 },1718 isLength: (19 value: string,20 options: Partial<{ min: number; max: number }> | number,21 arg2?: number22 ) => {23 let min: number24 let max: number | undefined25 if (typeof options === 'object') {26 min = options.min || 027 max = options.max28 } else {29 // backwards compatibility: isLength(str, min [, max])30 min = options || 031 max = arg232 }33 const presentationSequences = value.match(/(\uFE0F|\uFE0E)/g) || []34 const surrogatePairs = value.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []35 const len = value.length - presentationSequences.length - surrogatePairs.length36 return len >= min && (typeof max === 'undefined' || len <= max)37 },3839 isAlpha: (value: string): boolean => {40 return /^[A-Z]+$/i.test(value)41 },4243 isNumeric: (value: string): boolean => {44 return /^[0-9]+$/.test(value)45 },4647 contains: (48 value: string,49 elem: string,50 options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {51 ignoreCase: false,52 minOccurrences: 1,53 }54 ): boolean => {55 options.ignoreCase ||= false56 options.minOccurrences ||= 157 if (options.ignoreCase) {58 return value.toLowerCase().split(elem.toLowerCase()).length > options.minOccurrences59 }60 return value.split(elem).length > options.minOccurrences61 },6263 isIn: (value: string, options: string[]): boolean => {64 if (typeof options === 'object') {65 for (const elem of options) {66 if (elem === value) return true67 }68 }69 return false70 },7172 match: (value: string, regExp: RegExp): boolean => {73 return regExp.test(value)74 },7576 // number77 isGte: (value: number, min: number) => min <= value,78 isLte: (value: number, max: number) => value <= max,7980 // boolean81 isTrue: (value: boolean) => value === true,82 isFalse: (value: boolean) => value === false,83}
added:deno_dist/validator/sanitizer.ts+3 added
added:deno_dist/validator/schema.ts+54 added
added:deno_dist/validator/validator.ts+492 added
1import { JSONPathCopy } from './../utils/json.ts'2import type { JSONObject, JSONPrimitive, JSONArray } from './../utils/json.ts'3import { rule } from './rule.ts'4import { sanitizer } from './sanitizer.ts'5import type { Schema } from './schema.ts'67type Target = 'query' | 'header' | 'body' | 'json'8type Type = JSONPrimitive | JSONObject | JSONArray | File9type RuleFunc = (value: Type) => boolean10type Rule = {11 name: string12 func: RuleFunc13 customMessage?: string14 type: 'type' | 'value'15}16type Sanitizer = (value: Type) => Type1718export type ValidateResult = {19 isValid: boolean20 message: string | undefined21 target: Target22 key: string23 value: Type24 ruleName: string25 ruleType: 'type' | 'value'26 jsonData?: JSONObject27}2829export abstract class VObjectBase<T extends Schema> {30 container: T31 keys: string[] = []32 protected _isOptional: boolean = false33 constructor(container: T, key: string) {34 this.container = container35 if (this instanceof VArray) {36 this.keys.push(key, '[*]')37 } else if (this instanceof VObject) {38 this.keys.push(key)39 }40 }4142 isOptional() {43 this._isOptional = true44 return this45 }4647 getValidators = (): VBase[] => {48 const validators: VBase[] = []49 const thisKeys: string[] = []50 Object.assign(thisKeys, this.keys)5152 const walk = (container: T, keys: string[], isOptional: boolean) => {53 for (const v of Object.values(container)) {54 if (v instanceof VArray || v instanceof VObject) {55 // eslint-disable-next-line @typescript-eslint/ban-ts-comment56 // @ts-ignore57 isOptional ||= v._isOptional58 keys.push(...v.keys)59 walk(v.container as T, keys, isOptional)60 const tmp: string[] = []61 Object.assign(tmp, thisKeys)62 keys = tmp63 } else if (v instanceof VBase) {64 if (isOptional) v.isOptional()65 v.baseKeys.push(...keys)66 validators.push(v)67 }68 }69 }7071 walk(this.container, this.keys, this._isOptional)7273 return validators74 }75}7677export class VObject<T extends Schema> extends VObjectBase<T> {78 constructor(container: T, key: string) {79 super(container, key)80 }81}8283export class VArray<T extends Schema> extends VObjectBase<T> {84 type: 'array' = 'array'85 constructor(container: T, key: string) {86 super(container, key)87 }88}8990export class Validator {91 isArray: boolean = false92 query = (key: string): VString => new VString({ target: 'query', key: key })93 header = (key: string): VString => new VString({ target: 'header', key: key })94 body = (key: string): VString => new VString({ target: 'body', key: key })95 json = (key: string) => {96 if (this.isArray) {97 return new VStringArray({ target: 'json', key: key })98 } else {99 return new VString({ target: 'json', key: key })100 }101 }102 array = <T extends Schema>(path: string, validator: (v: Validator) => T): VArray<T> => {103 this.isArray = true104 const res = validator(this)105 const arr = new VArray(res, path)106 return arr107 }108 object = <T extends Schema>(path: string, validator: (v: Validator) => T): VObject<T> => {109 this.isArray = false110 const res = validator(this)111 const obj = new VObject(res, path)112 return obj113 }114}115116type VOptions = {117 target: Target118 key: string119 type?: 'string' | 'number' | 'boolean' | 'object'120 isArray?: boolean121}122123export abstract class VBase {124 type: 'string' | 'number' | 'boolean' | 'object'125 target: Target126 baseKeys: string[] = []127 key: string128 rules: Rule[]129 sanitizers: Sanitizer[]130 isArray: boolean131 private _optional: boolean132 constructor(options: VOptions) {133 this.target = options.target134 this.key = options.key135 this.type = options.type || 'string'136 this.rules = [137 {138 name: this.getTypeRuleName(),139 type: 'type',140 func: this.validateType,141 },142 ]143 this.sanitizers = []144 this._optional = false145 this.isArray = options.isArray || false146 }147148 private _nested = () => (this.baseKeys.length ? true : false)149150 addRule(func: RuleFunc): this151 addRule(name: string, func: RuleFunc): this152 addRule(arg: string | RuleFunc, func?: RuleFunc) {153 if (typeof arg === 'string' && func) {154 this.rules.push({ name: arg, func, type: 'value' })155 } else if (arg instanceof Function) {156 this.rules.push({ name: arg.name, func: arg, type: 'value' })157 }158 return this159 }160161 addSanitizer = (sanitizer: Sanitizer) => {162 this.sanitizers.push(sanitizer)163 return this164 }165166 message = (text: string) => {167 const len = this.rules.length168 if (len >= 1) {169 this.rules[len - 1].customMessage = text170 }171 return this172 }173174 isRequired = () => {175 return this.addRule('isRequired', (value: unknown) => {176 if (value !== undefined && value !== null && value !== '') return true177 return false178 })179 }180181 isOptional = () => {182 this._optional = true183 return this.addRule('isOptional', () => true)184 }185186 isEqual = (comparison: unknown) => {187 return this.addRule('isEqual', (value: unknown) => {188 return value === comparison189 })190 }191192 asNumber = (): VNumber | VNumberArray => {193 const newVNumber = new VNumber({ ...this, type: 'number' })194 if (this.isArray) return newVNumber.asArray()195 return newVNumber196 }197198 asBoolean = (): VBoolean | VBooleanArray => {199 const newVBoolean = new VBoolean({ ...this, type: 'boolean' })200 if (this.isArray) return newVBoolean.asArray()201 return newVBoolean202 }203204 get(value: string) {205 const len = this.rules.length206 if (len > 0) {207 this.rules[this.rules.length - 1].customMessage = value208 }209 return this210 }211212 validate = async <R extends Request>(req: R): Promise<ValidateResult[]> => {213 let value: Type = undefined214 let jsonData: JSONObject | undefined = undefined215216 if (this.target === 'query') {217 value = req.query(this.key)218 }219 if (this.target === 'header') {220 value = req.header(this.key)221 }222 if (this.target === 'body') {223 const body = await req.parseBody()224 value = body[this.key]225 }226 if (this.target === 'json') {227 if (this._nested()) {228 this.key = `${this.baseKeys.join('.')}.${this.key}`229 }230 let obj = {}231 try {232 obj = (await req.json()) as JSONObject233 } catch (e) {234 throw new Error('Malformed JSON in request body')235 }236 const dst = {}237 value = JSONPathCopy(obj, dst, this.key)238 if (this._nested()) jsonData = dst239 }240241 const results: ValidateResult[] = []242243 let typeRule = this.rules.shift()244245 for (const rule of this.rules) {246 if (rule.type === 'type') {247 typeRule = rule248 } else if (rule.type === 'value') {249 const result = this.validateRule(rule, value)250 result.jsonData ||= jsonData251 results.push(result)252 }253 }254255 if (typeRule) {256 const typeResult = this.validateRule(typeRule, value)257 typeResult.jsonData ||= jsonData258 results.unshift(typeResult)259 }260261 return results262 }263264 protected getTypeRuleName(): string {265 const prefix = 'should be'266 return this.isArray ? `${prefix} "${this.type}[]"` : `${prefix} "${this.type}"`267 }268269 private validateRule(rule: Rule, value: Type): ValidateResult {270 let isValid: boolean = false271272 if (this._nested() && this.target != 'json') {273 isValid = false274 } else if (rule.type === 'value') {275 isValid = this.validateValue(rule.func, value)276 } else if (rule.type === 'type') {277 isValid = this.validateType(value)278 }279280 const message = isValid281 ? undefined282 : rule.customMessage || this.getMessage({ ruleName: rule.name, value })283 const result = {284 isValid: isValid,285 message: message,286 target: this.target,287 key: this.key,288 value,289 ruleName: rule.name,290 ruleType: rule.type,291 }292 return result293 }294295 private validateType = (value: Type): boolean => {296 if (this.isArray) {297 if (!Array.isArray(value)) {298 return false299 }300 for (const val of value) {301 if (typeof val === 'undefined' && this._nested()) {302 value.pop()303 }304 for (const val of value) {305 if (typeof val !== this.type) {306 // Value is of wrong type here307 // If it is not optional and not undefined, return false308 if (!this._optional || typeof val !== 'undefined') return false309 }310 }311 }312 } else {313 if (typeof value !== this.type) {314 if (this._optional && (typeof value === 'undefined' || Array.isArray(value))) {315 // Do nothing.316 // If it is optional it's OK to be `undefined` or Array317 } else {318 return false319 }320 }321 }322 return true323 }324325 private validateValue = (func: (value: Type) => boolean, value: Type): boolean => {326 if (this._optional && typeof value === 'undefined') return true327328 if (Array.isArray(value)) {329 // Sanitize330 for (const sanitizer of this.sanitizers) {331 value = value.map((innerVal: any) => sanitizer(innerVal)) as JSONArray332 }333 for (const val of value) {334 if (!func(val)) {335 return false336 }337 }338 return true339 } else {340 // Sanitize341 for (const sanitizer of this.sanitizers) {342 value = sanitizer(value)343 }344 if (!func(value)) {345 return false346 }347 return true348 }349 }350351 private getMessage = (opts: { ruleName: string; value: Type }): string => {352 let keyText: string353 const valueText = Array.isArray(opts.value)354 ? `${opts.value355 .map((val) =>356 val === undefined ? 'undefined' : typeof val === 'string' ? `"${val}"` : val357 )358 .join(', ')}`359 : opts.value360 switch (this.target) {361 case 'query':362 keyText = `the query parameter "${this.key}"`363 break364 case 'header':365 keyText = `the request header "${this.key}"`366 break367 case 'body':368 keyText = `the request body "${this.key}"`369 break370 case 'json':371 keyText = `the JSON body "${this.key}"`372 break373 }374 return `Invalid Value [${valueText}]: ${keyText} is invalid - ${opts.ruleName}`375 }376}377378export class VString extends VBase {379 constructor(options: VOptions) {380 super(options)381 this.type = 'string'382 }383384 asArray = () => {385 return new VStringArray(this)386 }387388 isEmpty = (389 options: {390 ignore_whitespace: boolean391 } = { ignore_whitespace: false }392 ) => {393 return this.addRule('isEmpty', (value) => rule.isEmpty(value as string, options))394 }395396 isLength = (options: Partial<{ min: number; max: number }> | number, arg2?: number) => {397 return this.addRule('isLength', (value) => rule.isLength(value as string, options, arg2))398 }399400 isAlpha = () => {401 return this.addRule('isAlpha', (value) => rule.isAlpha(value as string))402 }403404 isNumeric = () => {405 return this.addRule('isNumeric', (value) => rule.isNumeric(value as string))406 }407408 contains = (409 elem: string,410 options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {411 ignoreCase: false,412 minOccurrences: 1,413 }414 ) => {415 return this.addRule('contains', (value) => rule.contains(value as string, elem, options))416 }417418 isIn = (options: string[]) => {419 return this.addRule('isIn', (value) => rule.isIn(value as string, options))420 }421422 match = (regExp: RegExp) => {423 return this.addRule('match', (value) => rule.match(value as string, regExp))424 }425426 trim = () => {427 return this.addSanitizer((value) => sanitizer.trim(value as string))428 }429}430431export class VNumber extends VBase {432 constructor(options: VOptions) {433 super(options)434 this.type = 'number'435 }436437 asArray = () => {438 return new VNumberArray(this)439 }440441 isGte = (min: number) => {442 return this.addRule('isGte', (value) => rule.isGte(value as number, min))443 }444445 isLte = (min: number) => {446 return this.addRule('isLte', (value) => rule.isLte(value as number, min))447 }448}449450export class VBoolean extends VBase {451 constructor(options: VOptions) {452 super(options)453 this.type = 'boolean'454 }455456 asArray = () => {457 return new VBooleanArray(this)458 }459460 isTrue = () => {461 return this.addRule('isTrue', (value) => rule.isTrue(value as boolean))462 }463464 isFalse = () => {465 return this.addRule('isFalse', (value) => rule.isFalse(value as boolean))466 }467}468469export class VNumberArray extends VNumber {470 isArray: true471 constructor(options: VOptions) {472 super(options)473 this.isArray = true474 this.rules[0].name = this.getTypeRuleName()475 }476}477export class VStringArray extends VString {478 isArray: true479 constructor(options: VOptions) {480 super(options)481 this.isArray = true482 this.rules[0].name = this.getTypeRuleName()483 }484}485export class VBooleanArray extends VBoolean {486 isArray: true487 constructor(options: VOptions) {488 super(options)489 this.isArray = true490 this.rules[0].name = this.getTypeRuleName()491 }492}
modified:deno_dist/compose.ts+10 added-4 removed
modified:deno_dist/context.ts+21 added-26 removed
1import type {2 Environment,3 NotFoundHandler,4 ContextVariableMap,5 Bindings,6 ValidatedData,7} from './hono.ts'1import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono.ts'2import type { CookieOptions } from './utils/cookie.ts'3import { serialize } from './utils/cookie.ts'4import type { StatusCode } from './utils/http-status.ts'5import type { Schema, SchemaToProp } from './validator/schema.ts'67type HeaderField = [string, string]8type Headers = Record<string, string | string[]>9export type Data = string | ArrayBuffer | ReadableStream1011export interface Context<17 RequestParamKeyType extends string = string,18 E extends Partial<Environment> = any,19 D extends ValidatedData = ValidatedData12 P extends string = string,13 E extends Partial<Environment> = Environment,14 S extends Partial<Schema> = Schema15> {21 req: Request<RequestParamKeyType, D>16 req: Request<P, SchemaToProp<S>>17 env: E['Bindings']18 event: FetchEvent19 executionCtx: ExecutionContext20 finalized: boolean
5 unmodified lines
26 status: (status: StatusCode) => void27 set: {28 <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void29 <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void35 (key: string, value: any): void30 (key: string, value: unknown): void31 }32 get: {33 <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]34 <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]
10 unmodified lines
45 notFound: () => Response | Promise<Response>46}4748export class HonoContext<54 RequestParamKeyType extends string = string,49 P extends string = string,50 E extends Partial<Environment> = Environment,56 D extends ValidatedData = ValidatedData57> implements Context<RequestParamKeyType, E, D>51 S extends Partial<Schema> = Schema52> implements Context<P, E, S>53{59 req: Request<RequestParamKeyType, D>54 req: Request<P, SchemaToProp<S>>55 env: E['Bindings']56 finalized: boolean57 error: Error | undefined = undefined5859 _status: StatusCode = 20060 private _executionCtx: FetchEvent | ExecutionContext | undefined61 private _pretty: boolean = false62 private _prettySpace: number = 268 private _map: Record<string, any> | undefined63 private _map: Record<string, unknown> | undefined64 private _headers: Record<string, string[]> | undefined65 private _res: Response | undefined71 private notFoundHandler: NotFoundHandler<E>66 private notFoundHandler: NotFoundHandler<P, E, S>6768 constructor(74 req: Request<RequestParamKeyType>,75 env: E['Bindings'] | undefined = undefined,69 req: Request<P>,70 env: E['Bindings'] = {},71 executionCtx: FetchEvent | ExecutionContext | undefined = undefined,77 notFoundHandler: NotFoundHandler<E> = () => new Response()72 notFoundHandler: NotFoundHandler<P, E, S> = () => new Response()73 ) {74 this._executionCtx = executionCtx80 this.req = req as Request<RequestParamKeyType, D>75 this.req = req as Request<P, SchemaToProp<S>>76 this.env = env || ({} as Bindings)7778 this.notFoundHandler = notFoundHandler79 this.finalized = false
56 unmodified lines
136 }137138 set<Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void139 set<Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void145 set(key: string, value: any): void146 set(key: string, value: any): void {140 set(key: string, value: unknown): void141 set(key: string, value: unknown): void {142 this._map ||= {}143 this._map[key] = value144 }145146 get<Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]147 get<Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]153 get<T = any>(key: string): T148 get<T>(key: string): T149 get(key: string) {150 if (!this._map) {151 return undefined152 }
74 unmodified lines
227 this.header('set-cookie', cookie, { append: true })228 }229230 notFound(): Response | Promise<Response> {236 return this.notFoundHandler(this as any)231 return this.notFoundHandler(this)232 }233}
modified:deno_dist/hono.ts+67 added-55 removed
8 unmodified lines
9import { SmartRouter } from './router/smart-router/index.ts'10import { StaticRouter } from './router/static-router/index.ts'11import { TrieRouter } from './router/trie-router/index.ts'12import { getPathFromURL, mergePath } from './utils/url.ts'13import type { Schema } from './validator/schema.ts'1415export interface ContextVariableMap {}1617export type Bindings = Record<string, any> // For Cloudflare Workers
2 unmodified lines
20 Bindings: Bindings21 Variables: Variables22}2323export type ValidatedData = Record<string, any> // For validated data2424export type Handler<26 RequestParamKeyType extends string = string,25 P extends string = string,26 E extends Partial<Environment> = Environment,28 D extends ValidatedData = ValidatedData29> = (30 c: Context<RequestParamKeyType, E, D>,31 next: Next32) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined | void>27 S extends Partial<Schema> = Schema28> = (c: Context<P, E, S>, next: Next) => Response | Promise<Response | undefined | void>2934export type MiddlewareHandler = <E extends Partial<Environment> = Environment>(35 c: Context<string, E>,36 next: Next37) => Promise<void> | Promise<Response | undefined>30export type MiddlewareHandler<31 P extends string = string,32 E extends Partial<Environment> = Environment,33 S extends Partial<Schema> = Schema34> = (c: Context<P, E, S>, next: Next) => Promise<Response | undefined | void>3539export type NotFoundHandler<E extends Partial<Environment> = Environment> = (40 c: Context<string, E>41) => Response | Promise<Response>36export type NotFoundHandler<37 P extends string = string,38 E extends Partial<Environment> = Environment,39 S extends Partial<Schema> = Schema40> = (c: Context<P, E, S>) => Response | Promise<Response>4143export type ErrorHandler<E extends Partial<Environment> = Environment> = (44 err: Error,45 c: Context<string, E>46) => Response42export type ErrorHandler<43 P extends string = string,44 E extends Partial<Environment> = Environment,45 S extends Partial<Schema> = Schema46> = (err: Error, c: Context<P, E, S>) => Response4748export type Next = () => Promise<void>4950// eslint-disable-next-line @typescript-eslint/no-unused-vars
8 unmodified lines
59type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`60 ? ParamKey<Component> | ParamKeys<Rest>61 : ParamKey<Path>6263interface HandlerInterface<T extends string, E extends Partial<Environment>, U = Hono<E, T>> {63interface HandlerInterface<64 P extends string,65 E extends Partial<Environment>,66 S extends Partial<Schema>,67 U = Hono<E, P, S>68> {69 // app.get(handler...)65 <Path extends string, Data extends ValidatedData>(70 <Path extends string, Data extends Schema>(71 ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E, Data>[]72 ): U68 (...handlers: Handler<string, E>[]): U73 (...handlers: Handler<string, E, S>[]): U7475 // app.get('/', handler, handler...)70 <Path extends string, Data extends ValidatedData>(76 <Path extends string, Data extends Partial<Schema> = Schema>(77 path: Path,78 ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E, Data>[]79 ): U80 <Path extends string, Data extends Schema>(path: Path, ...handlers: Handler<string, E, Data>[]): U74 (path: string, ...handlers: Handler<string, E>[]): U81 (path: string, ...handlers: Handler<string, E, S>[]): U82}8384type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE8586function defineDynamicClass(): {80 new <E extends Partial<Environment> = Environment, T extends string = string, U = Hono<E, T>>(): {81 [K in Methods]: HandlerInterface<T, E, U>87 new <88 E extends Partial<Environment> = Environment,89 P extends string = string,90 S extends Partial<Schema> = Schema,91 U = Hono<E, P, S>92 >(): {93 [K in Methods]: HandlerInterface<P, E, S, U>94 }95} {84 return class {} as any96 return class {} as never97}9899interface Route<100 P extends string = string,101 E extends Partial<Environment> = Environment,89 D extends ValidatedData = ValidatedData102 S extends Partial<Schema> = Schema103> {104 path: string105 method: string93 handler: Handler<string, E, D>106 handler: Handler<P, E, S>107}108109export class Hono<110 E extends Partial<Environment> = Environment,111 P extends string = '/',99 D extends ValidatedData = ValidatedData100> extends defineDynamicClass()<E, P, Hono<E, P, D>> {101 readonly router: Router<Handler<string, E, D>> = new SmartRouter({112 S extends Partial<Schema> = Schema113> extends defineDynamicClass()<E, P, S, Hono<E, P, S>> {114 readonly router: Router<Handler<P, E, S>> = new SmartRouter({115 routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],116 })117 readonly strict: boolean = true // strict routing - default is true118 private _tempPath: string = ''119 private path: string = '/'120108 routes: Route<E, D>[] = []121 routes: Route<P, E, S>[] = []122123 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {124 super()125126 extendRequestPrototype()127128 const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]129 allMethods.map((method) => {117 this[method] = <Path extends string = ''>(118 args1: Path | Handler<ParamKeys<Path>, E, D>,119 ...args: [Handler<ParamKeys<Path>, E, D>]130 this[method] = <Path extends string, Env extends Environment, Data extends Schema>(131 args1: Path | Handler<ParamKeys<Path>, Env, Data>,132 ...args: [Handler<ParamKeys<Path>, Env, Data>]133 ): this => {134 if (typeof args1 === 'string') {135 this.path = args1136 } else {124 this.addRoute(method, this.path, args1)137 this.addRoute(method, this.path, args1 as unknown as Handler<P, E, S>)138 }139 args.map((handler) => {140 if (typeof handler !== 'string') {128 this.addRoute(method, this.path, handler)141 this.addRoute(method, this.path, handler as unknown as Handler<P, E, S>)142 }143 })144 return this145 }
1 unmodified line
147148 Object.assign(this, init)149 }150138 private notFoundHandler: NotFoundHandler<E> = (c: Context<string, E>) => {151 private notFoundHandler: NotFoundHandler<P, E, S> = (c: Context<P, E, S>) => {152 return c.text('404 Not Found', 404)153 }154142 private errorHandler: ErrorHandler<E> = (err: Error, c: Context<string, E>) => {155 private errorHandler: ErrorHandler<P, E, S> = (err: Error, c: Context<P, E, S>) => {156 console.trace(err.message)157 const message = 'Internal Server Error'158 return c.text(message, 500)159 }160148 route(path: string, app?: Hono<any>): Hono<E, P, D> {161 route(path: string, app?: Hono<E, P, S>) {162 this._tempPath = path163 if (app) {164 app.routes.map((r) => {165 this.addRoute(r.method, r.path, r.handler)166 })167 this._tempPath = ''168 }156169 return this170 }171160 use<Path extends string = string, Data extends ValidatedData = D>(172 use<Path extends string = string, Data extends Partial<Schema> = Schema>(173 ...middleware: Handler<Path, E, Data>[]162 ): Hono<E, Path, Data>163 use<Path extends string = string, Data extends ValidatedData = D>(174 ): Hono<E, Path, S>175 use<Path extends string = string, Data extends Partial<Schema> = Schema>(176 arg1: string,177 ...middleware: Handler<Path, E, Data>[]166 ): Hono<E, Path, D>167 use(arg1: string | Handler<string, E, D>, ...handlers: Handler<string, E, D>[]): Hono<E, P, D> {178 ): Hono<E, Path, S>179 use(arg1: string | Handler<P, E, S>, ...handlers: Handler<P, E, S>[]) {180 if (typeof arg1 === 'string') {181 this.path = arg1182 } else {183 handlers.unshift(arg1)
3 unmodified lines
187 })188 return this189 }190179 onError(handler: ErrorHandler<E>): Hono<E, P, D> {191 onError(handler: ErrorHandler<P, E, S>) {192 this.errorHandler = handler193 return this194 }195184 notFound(handler: NotFoundHandler<E>): Hono<E, P, D> {196 notFound(handler: NotFoundHandler<P, E, S>) {197 this.notFoundHandler = handler198 return this199 }200189 private addRoute(method: string, path: string, handler: Handler<string, E, D>): void {201 private addRoute(method: string, path: string, handler: Handler<P, E, S>): void {202 method = method.toUpperCase()203 if (this._tempPath) {204 path = mergePath(this._tempPath, path)205 }206 this.router.add(method, path, handler)195 const r: Route<E, D> = { path: path, method: method, handler: handler }207 const r: Route<P, E, S> = { path: path, method: method, handler: handler }208 this.routes.push(r)209 }210211 private matchRoute(method: string, path: string) {212 return this.router.match(method, path)213 }214203 private handleError(err: unknown, c: Context) {215 private handleError(err: unknown, c: Context<P, E, S>) {216 if (err instanceof Error) {217 return this.errorHandler(err, c)218 }219 throw err
9 unmodified lines
229230 const result = this.matchRoute(method, path)231 request.paramData = result?.params232221 const c = new HonoContext<string, E, D>(request, env, eventOrExecutionCtx, this.notFoundHandler)233 const c = new HonoContext<P, E, S>(request, env, eventOrExecutionCtx, this.notFoundHandler)234235 // Do not `compose` if it has only one handler236 if (result && result.handlers.length === 1) {237 const handler = result.handlers[0]226 let res: ReturnType<Handler>238 let res: ReturnType<Handler<P>>239240 try {241 res = handler(c, async () => {})242 if (!res) return this.notFoundHandler(c)
17 unmodified lines
260 })()261 }262263 const handlers = result ? result.handlers : [this.notFoundHandler]252 const composed = compose<HonoContext<string, E>, E>(264 const composed = compose<HonoContext<P, E, S>, P, E, S>(265 handlers,266 this.notFoundHandler,267 this.errorHandler268 )
30 unmodified lines
modified:deno_dist/request.ts+6 added-5 removed
34 unmodified lines
35 (): Cookie36 }37 bodyData?: BodyData38 parseBody<BodyType extends BodyData>(): Promise<BodyType>39 // eslint-disable-next-line @typescript-eslint/no-explicit-any40 jsonData?: any40 json<JSONData = any>(): Promise<JSONData>41 json<JSONData = unknown>(): Promise<Partial<JSONData>>42 data: Data43 valid: {43 (key: string | string[], value: any): Data44 (key: string | string[], value: unknown): Data45 (): Data46 }47 }48}
83 unmodified lines
132 }133 return body134 } as InstanceType<typeof Request>['parseBody']135135 Request.prototype.json = async function <JSONData>(this: Request): Promise<JSONData> {136 Request.prototype.json = async function <JSONData = unknown>(this: Request) {137 // Cache the JSON body137 let jsonData: JSONData138 let jsonData: Partial<JSONData>139 if (!this.jsonData) {140 jsonData = JSON.parse(await this.text())141 this.jsonData = jsonData142 } else {
1 unmodified line
144 }145 return jsonData146 } as InstanceType<typeof Request>['jsonData']147147 Request.prototype.valid = function (this: Request, keys?: string | string[], value?: any) {148 Request.prototype.valid = function (this: Request, keys?: string | string[], value?: unknown) {149 if (!this.data) {150 this.data = {}151 }152 if (keys !== undefined) {
12 unmodified lines
modified:src/middleware/serve-static/serve-static.ts+3 added-4 removed
1import type { Context } from '../../context'2import type { Next } from '../../hono'1import type { MiddlewareHandler } from '../../hono'2import { getContentFromKVAsset } from '../../utils/cloudflare'3import { getFilePath } from '../../utils/filepath'4import { getMimeType } from '../../utils/mime'5
6 unmodified lines
1213const DEFAULT_DOCUMENT = 'index.html'1415// This middleware is available only on Cloudflare Workers.17export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {18 return async (c: Context, next: Next) => {16export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {17 return async (c, next) => {18 // Do nothing if Response is already set19 if (c.finalized) {20 await next()21 return
28 unmodified lines
modified:src/middleware/validator/middleware.test.ts+112 added-4 removed
1/* eslint-disable @typescript-eslint/no-unused-vars */2import { Hono } from '../../hono'3import { getStatusText } from '../../utils/http-status'4import type { Expect, Equal } from '../../utils/types'5import type { Schema } from '../../validator/schema'6import { validator } from './index'78describe('Basic - query', () => {9 const app = new Hono()
94 unmodified lines
104 expect(await res.text()).toBe('CUSTOM MESSAGE')105 })106})107105describe('Basic - JSON', () => {108describe('Basic - JSON with type check', () => {109 const app = new Hono()110 // JSON111 app.post(112 '/json',113 validator((v) => ({114 id: v.json('post.author.id').asNumber(),115 name: v.json('post.author.name').isAlpha(),116 })),117 (c) => {118 const { id, name } = c.req.valid()119 type verifyID = Expect<Equal<typeof id, number>>120 type verifyName = Expect<Equal<typeof name, string>>121 return c.text('Valid')122 }123 )124125 it('Should return 200 response - JSON', async () => {126 const json = {127 post: {128 author: {129 id: 123,130 name: 'abcdef',131 },132 },133 }
452 unmodified lines
586 expect(res.status).toBe(400)587 })588})589582describe('Array values', () => {590describe('Array values with type check', () => {591 const app = new Hono()592 app.post(593 '/post',594 validator((v) => ({
3 unmodified lines
598 ids: v.json('post.ids').asNumber().asArray(),599 },600 })),601 (c) => {594 const res = c.req.valid()595 return c.json({ tag1: res.post.tags[0] })602 const { post } = c.req.valid()603604 type verifyTitle = Expect<Equal<typeof post.title, string>>605 type verifyTags = Expect<Equal<typeof post.tags, string[]>>606 type verifyIDs = Expect<Equal<typeof post.ids, number[]>>607608 return c.json({ tag1: post.tags[0] })609 }610 )611612 it('Should return 200 response', async () => {
129 unmodified lines
742 ].join('\n')743 )744 })745})746747describe('Type check in special case', () => {748 it('Should return 200 response with correct types', async () => {749 const app = new Hono()750 app.post(751 '/posts/:id',752 validator((v) => ({753 title: v.body('title').isRequired(),754 })),755 (c) => {756 const res = c.req.valid()757 const id = c.req.param('id')758 type verifyTitle = Expect<Equal<typeof res.title, string>>759 type verifyId = Expect<Equal<typeof id, string>>760 return c.text(`${id} is ${res.title}`)761 }762 )763 const body = new FormData()764 body.append('title', 'Hello')765 const req = new Request('http://localhost/posts/123', {766 method: 'POST',767 body: body,768 })769 const res = await app.request(req)770 expect(res.status).toBe(200)771 expect(await res.text()).toBe('123 is Hello')772 })773774 it('Should return 200 response with correct types - validator and named parameter', async () => {775 const app = new Hono()776777 const vm = validator((v) => ({778 title: v.body('title').isRequired(),779 }))780781 app.post('/posts', vm, (c) => {782 const { title } = c.req.valid()783 type verify = Expect<Equal<typeof title, string>>784 return c.text(title)785 })786787 app.post('/posts/:id', vm, (c) => {788 const id = c.req.param('id')789 const { title } = c.req.valid()790 type verify = Expect<Equal<typeof title, string>>791 return c.text(`${id} is ${title}`)792 })793794 const body = new FormData()795 body.append('title', 'Hello')796797 let res = await app.request('http://localhost/posts', {798 method: 'POST',799 body: body,800 })801 expect(res.status).toBe(200)802 expect(await res.text()).toBe('Hello')803 res = await app.request('http://localhost/posts/123?title=foo', {804 method: 'POST',805 body: body,806 })807 expect(res.status).toBe(200)808 expect(await res.text()).toBe('123 is Hello')809 })810811 it('Should return 200 response with correct types - Context in validator function', async () => {812 type Env = { Bindings: { FOO: 'abc' } }813814 const app = new Hono<Env>()815816 app.get(817 '/search',818 validator(819 (v) => ({820 foo: v.query('foo'),821 }),822 {823 done: (_, c) => {824 type verifyBindings = Expect<Equal<typeof c.env.FOO, 'abc'>>825 },826 }827 ),828 (c) => {829 const { foo } = c.req.valid()830 type verifyBindings = Expect<Equal<typeof c.env.FOO, 'abc'>>831 type verify = Expect<Equal<typeof foo, string>>832 return c.text(foo)833 }834 )835836 const res = await app.request('http://localhost/search?foo=bar')837 expect(res.status).toBe(200)838 expect(await res.text()).toBe('bar')839 })840})
modified:src/middleware/validator/middleware.ts+20 added-72 removed
1import type { Context } from '../../context'2import type { Environment, Next, ValidatedData } from '../../hono'2import type { Environment, MiddlewareHandler } from '../../hono'3import { getStatusText } from '../../utils/http-status'4import { mergeObjects } from '../../utils/object'5import { VBase, Validator, VObjectBase } from './validator'6import type {7 VString,8 VNumber,9 VBoolean,10 VObject,11 VNumberArray,12 VStringArray,13 VBooleanArray,14 ValidateResult,15 VArray,16} from './validator'5import type { Schema } from '../../validator/schema'6import type { ValidateResult } from '../../validator/validator'7import { Validator, VBase, VObjectBase } from '../../validator/validator'818export type Schema = {19 [key: string]:20 | VString21 | VNumber22 | VBoolean23 | VStringArray24 | VNumberArray25 | VBooleanArray26 | Schema27 | VObject<Schema>28 | VArray<Schema>29}3031type SchemaToProp<T> = {32 [K in keyof T]: T[K] extends VNumberArray33 ? number[]34 : T[K] extends VBooleanArray35 ? boolean[]36 : T[K] extends VStringArray37 ? string[]38 : T[K] extends VNumber39 ? number40 : T[K] extends VBoolean41 ? boolean42 : T[K] extends VString43 ? string44 : T[K] extends VObjectBase<Schema>45 ? T[K]['container'] extends VNumber46 ? number47 : T[K]['container'] extends VString48 ? string49 : T[K]['container'] extends VBoolean50 ? boolean51 : T[K] extends VArray<Schema>52 ? SchemaToProp<ReadonlyArray<T[K]['container']>>53 : T[K] extends VObject<Schema>54 ? SchemaToProp<T[K]['container']>55 : T[K] extends Schema56 ? SchemaToProp<T[K]>57 : never58 : SchemaToProp<T[K]>59}609type ResultSet = {10 hasError: boolean11 messages: string[]12 results: ValidateResult[]13}1467type Done<Env extends Partial<Environment>> = (15type Done<P extends string, E extends Partial<Environment> = Environment> = (16 resultSet: ResultSet,69 context: Context<string, Env>17 c: Context<P, E>18) => Response | void1972type ValidationFunction<T, Env extends Partial<Environment>> = (73 v: Validator,74 c: Context<string, Env>75) => T20type ValidationFunction<21 P extends string,22 E extends Partial<Environment> = Environment,23 S extends Schema = Schema24> = (v: Validator, c: Context<P, E>) => S2577type MiddlewareHandler<78 Data extends ValidatedData = ValidatedData,79 Env extends Partial<Environment> = Environment80> = (c: Context<string, Env, Data>, next: Next) => Promise<void> | Promise<Response | undefined>8182export const validatorMiddleware = <T extends Schema, Env extends Partial<Environment>>(83 validationFunction: ValidationFunction<T, Env>,84 options?: { done?: Done<Env> }26export const validatorMiddleware = <27 P extends string,28 E extends Partial<Environment> = Environment,29 S extends Schema = Schema30>(31 validationFunction: ValidationFunction<P, E, S>,32 options?: { done?: Done<P, E> }33) => {34 const v = new Validator()87 const handler: MiddlewareHandler<SchemaToProp<T>, Env> = async (c, next) => {35 const handler: MiddlewareHandler<string, E, S> = async (c, next) => {36 const resultSet: ResultSet = {37 hasError: false,38 messages: [],39 results: [],
5 unmodified lines
4546 for (const [keys, validator] of validatorList) {47 let results: ValidateResult[]48 try {101 results = await validator.validate(c.req)49 results = await validator.validate(c.req as Request)50 } catch (e) {51 // Invalid JSON request52 return c.text(getStatusText(400), 400)53 }
78 unmodified lines
deleted:src/middleware/validator/rule.test.ts-55 removed
1import { rule } from './rule'23describe('Rules', () => {4 // string5 test('isEmpty', () => {6 expect(rule.isEmpty('')).toBeTruthy()7 expect(rule.isEmpty('abcdef')).toBeFalsy()8 expect(rule.isEmpty('')).toBeTruthy()9 expect(rule.isEmpty(' ')).toBeFalsy()10 expect(rule.isEmpty(' ', { ignore_whitespace: true })).toBeTruthy()11 })12 test('isLength', () => {13 expect(rule.isLength('abcde', { min: 1, max: 10 })).toBeTruthy()14 expect(rule.isLength('abcde', { min: 1, max: 4 })).toBeFalsy()15 expect(rule.isLength('abcde', { max: 10 })).toBeTruthy()16 expect(rule.isLength('abcde', { max: 4 })).toBeFalsy()17 expect(rule.isLength('abcde', { min: 10 })).toBeFalsy()18 expect(rule.isLength('abcde', { min: 4 })).toBeTruthy()19 expect(rule.isLength('abcde', 1, 10)).toBeTruthy()20 expect(rule.isLength('abcde', 1, 4)).toBeFalsy()21 })22 test('isAlpha', () => {23 expect(rule.isAlpha('abcdef')).toBeTruthy()24 expect(rule.isAlpha('abc123')).toBeFalsy()25 })26 test('isNumeric', () => {27 expect(rule.isNumeric('01234')).toBeTruthy()28 expect(rule.isNumeric('012abc')).toBeFalsy()29 })30 test('contains', () => {31 expect(rule.contains('barfoobaz', 'foo')).toBeTruthy()32 expect(rule.contains('barfoobaz', 'fooo')).toBeFalsy()33 expect(rule.contains('barfoobaz', 'Foo')).toBeFalsy()34 expect(rule.contains('barfoobaz', 'Foo', { ignoreCase: true })).toBeTruthy()35 })36 test('isIn', () => {37 expect(rule.isIn('foo', ['foo', 'bar'])).toBeTruthy()38 expect(rule.isIn('foo', ['zzz', 'yyy'])).toBeFalsy()39 })40 test('match', () => {41 expect(rule.match('abcdef', /def$/)).toBeTruthy()42 expect(rule.match('abcdef', /^def$/)).toBeFalsy()43 })44 // number45 test('isGte', () => {46 expect(rule.isGte(20, 10)).toBeTruthy()47 expect(rule.isGte(10, 20)).toBeFalsy()48 expect(rule.isGte(10, 10)).toBeTruthy()49 })50 test('isLte', () => {51 expect(rule.isLte(10, 20)).toBeTruthy()52 expect(rule.isLte(20, 10)).toBeFalsy()53 expect(rule.isLte(10, 10)).toBeTruthy()54 })55})
deleted:src/middleware/validator/rule.ts-83 removed
1// Some validation rules is are based on Validator.js2// Validator.js3// License (MIT)4// Copyright (c) 2018 Chris O'Hara <cohara87@gmail.com>5// https://github.com/validatorjs/validator.js67export const rule = {8 // string9 isEmpty(10 value: string,11 options: {12 ignore_whitespace: boolean13 } = { ignore_whitespace: false }14 ): boolean {15 return (options.ignore_whitespace ? value.trim().length : value.length) === 016 },1718 isLength: (19 value: string,20 options: Partial<{ min: number; max: number }> | number,21 arg2?: number22 ) => {23 let min: number24 let max: number | undefined25 if (typeof options === 'object') {26 min = options.min || 027 max = options.max28 } else {29 // backwards compatibility: isLength(str, min [, max])30 min = options || 031 max = arg232 }33 const presentationSequences = value.match(/(\uFE0F|\uFE0E)/g) || []34 const surrogatePairs = value.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []35 const len = value.length - presentationSequences.length - surrogatePairs.length36 return len >= min && (typeof max === 'undefined' || len <= max)37 },3839 isAlpha: (value: string): boolean => {40 return /^[A-Z]+$/i.test(value)41 },4243 isNumeric: (value: string): boolean => {44 return /^[0-9]+$/.test(value)45 },4647 contains: (48 value: string,49 elem: string,50 options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {51 ignoreCase: false,52 minOccurrences: 1,53 }54 ): boolean => {55 options.ignoreCase ||= false56 options.minOccurrences ||= 157 if (options.ignoreCase) {58 return value.toLowerCase().split(elem.toLowerCase()).length > options.minOccurrences59 }60 return value.split(elem).length > options.minOccurrences61 },6263 isIn: (value: string, options: string[]): boolean => {64 if (typeof options === 'object') {65 for (const elem of options) {66 if (elem === value) return true67 }68 }69 return false70 },7172 match: (value: string, regExp: RegExp): boolean => {73 return regExp.test(value)74 },7576 // number77 isGte: (value: number, min: number) => min <= value,78 isLte: (value: number, max: number) => value <= max,7980 // boolean81 isTrue: (value: boolean) => value === true,82 isFalse: (value: boolean) => value === false,83}
deleted:src/middleware/validator/sanitizer.test.ts-7 removed
1import { sanitizer } from './sanitizer'23describe('Sanitizers', () => {4 test('trim', () => {5 expect(sanitizer.trim(' abc ')).toBe('abc')6 })7})
deleted:src/middleware/validator/sanitizer.ts-3 removed
1export const sanitizer = {2 trim: (value: string) => value.trim(),3}
deleted:src/middleware/validator/validator.test.ts-732 removed
1import { extendRequestPrototype } from '../../request'2import { Validator } from './validator'34extendRequestPrototype()56describe('Basic - query', () => {7 const v = new Validator()89 const req = new Request('http://localhost/?q=foo&page=3')1011 it('Should be valid - page', async () => {12 const validator = v.query('page').trim().isNumeric()13 expect(validator.type).toBe('string')14 const results = await validator.validate(req)15 expect(results[0].isValid).toBe(true)16 expect(results[0].message).toBeUndefined()17 expect(results[1].isValid).toBe(true)18 expect(results[1].message).toBeUndefined()19 })2021 it('Should be invalid - q', async () => {22 const validator = v.query('q').isRequired().asNumber()23 expect(validator.type).toBe('number')24 const results = await validator.validate(req)25 expect(results[0].isValid).toBe(false)26 const messages = [27 'Invalid Value [foo]: the query parameter "q" is invalid - should be "number"',28 ]29 expect(results[0].message).toBe(messages.join('\n'))30 })3132 it('Should be invalid - q2', async () => {33 const validator = v.query('q2').isRequired()34 const results = await validator.validate(req)35 expect(results[0].isValid).toBe(false)36 let messages = [37 'Invalid Value [undefined]: the query parameter "q2" is invalid - should be "string"',38 ]39 expect(results[0].message).toBe(messages.join('\n'))40 expect(results[1].isValid).toBe(false)41 messages = ['Invalid Value [undefined]: the query parameter "q2" is invalid - isRequired']42 expect(results[1].message).toBe(messages.join('\n'))43 })44})4546describe('Basic - header', () => {47 const v = new Validator()4849 const req = new Request('http://localhost/', {50 headers: {51 'x-message': 'hello world!',52 'x-number': '12345',53 },54 })5556 it('Should be valid - x-message', async () => {57 const validator = v.header('x-message').isRequired().contains('Hello', { ignoreCase: true })58 const results = await validator.validate(req)59 expect(results[0].isValid).toBe(true)60 expect(results[0].message).toBeUndefined()61 expect(results[1].isValid).toBe(true)62 expect(results[1].message).toBeUndefined()63 expect(results[2].isValid).toBe(true)64 expect(results[2].message).toBeUndefined()65 })6667 it('Should be invalid - x-number', async () => {68 const validator = v.header('x-number').isEqual(12345)69 const results = await validator.validate(req)70 expect(results[0].isValid).toBe(true)71 expect(results[1].isValid).toBe(false)72 const messages = ['Invalid Value [12345]: the request header "x-number" is invalid - isEqual']73 expect(results[1].message).toBe(messages.join('\n'))74 })75})7677describe('Basic - body', () => {78 const v = new Validator()7980 const body = new FormData()81 body.append('title', ' abcdef ')82 body.append('title2', 'abcdef')83 const req = new Request('http://localhost/', {84 method: 'POST',85 body: body,86 })8788 it('Should be valid - title', async () => {89 const validator = v.body('title').trim().isLength({ max: 10 }).isRequired()90 const results = await validator.validate(req)91 expect(results[0].isValid).toBe(true)92 expect(results[0].message).toBeUndefined()93 expect(results[1].isValid).toBe(true)94 expect(results[1].message).toBeUndefined()95 expect(results[2].isValid).toBe(true)96 expect(results[2].message).toBeUndefined()97 })9899 it('Should be invalid - title2', async () => {100 const validator = v.body('title2').isLength({ max: 5 })101 const results = await validator.validate(req)102 expect(results[0].isValid).toBe(true)103 expect(results[0].message).toBeUndefined()104 expect(results[1].isValid).toBe(false)105 const messages = ['Invalid Value [abcdef]: the request body "title2" is invalid - isLength']106 expect(results[1].message).toBe(messages.join('\n'))107 })108})109110describe('Basic - JSON', () => {111 const v = new Validator()112113 const post = {114 id: 1234,115 title: 'This is title',116 author: {117 name: 'Superman',118 age: 20,119 },120 }121122 const req = new Request('http://localhost/', {123 method: 'POST',124 body: JSON.stringify(post),125 })126127 it('Should be valid - id', async () => {128 const validator = v.json('id').asNumber().isEqual(1234)129 const results = await validator.validate(req)130 expect(results[0].isValid).toBe(true)131 expect(results[0].message).toBeUndefined()132 expect(results[1].isValid).toBe(true)133 expect(results[1].message).toBeUndefined()134 })135136 it('Should be valid - author.name', async () => {137 const validator = v.json('author.name').isIn(['Ultra man', 'Superman'])138 const results = await validator.validate(req)139 expect(results[0].isValid).toBe(true)140 expect(results[0].message).toBeUndefined()141 expect(results[1].isValid).toBe(true)142 expect(results[1].message).toBeUndefined()143 })144145 it('Should be invalid - author.age', async () => {146 const validator = v.json('author.age').asNumber().isLte(10)147 const results = await validator.validate(req)148 expect(results[0].isValid).toBe(true)149 expect(results[1].isValid).toBe(false)150 const messages = ['Invalid Value [20]: the JSON body "author.age" is invalid - isLte']151 expect(results[1].message).toBe(messages.join('\n'))152 })153})154155describe('Handle required values', () => {156 const v = new Validator()157158 const req = new Request('http://localhost/', {159 method: 'POST',160 body: JSON.stringify({ comment: null, name: 'John', admin: false }),161 })162163 it('Should be valid - `name` is required', async () => {164 const validator = v.json('name').isRequired()165 const results = await validator.validate(req)166 expect(results[0].isValid).toBe(true)167 expect(results[1].isValid).toBe(true)168 })169170 it('Should be invalid - `comment` is required but missing', async () => {171 const validator = v.json('comment').isRequired()172 const results = await validator.validate(req)173 expect(results[0].isValid).toBe(false)174 expect(results[1].isValid).toBe(false)175 })176177 it('Should be valid - `admin` is required and present, although falsy', async () => {178 const validator = v.json('admin').asBoolean().isRequired()179 const results = await validator.validate(req)180 expect(results[0].isValid).toBe(true)181 expect(results[1].isValid).toBe(true)182 expect(results[1].value).toBe(false)183 })184})185186describe('Handle optional values', () => {187 it('Should be valid - `comment` is optional', async () => {188 const v = new Validator()189 const req = new Request('http://localhost/', {190 method: 'POST',191 })192 const validator = v.body('comment').isOptional()193 const results = await validator.validate(req)194 expect(results[0].isValid).toBe(true)195 })196 it('Should be valid - "isNumeric" but "isOptional"', async () => {197 const v = new Validator()198 const validator = v.query('page').isNumeric().isOptional()199 const req = new Request('http://localhost/')200 const results = await validator.validate(req)201 expect(results[0].isValid).toBe(true)202 expect(results[1].isValid).toBe(true)203 expect(results[1].message).toBeUndefined()204 })205})206207describe('Handling types error', () => {208 const v = new Validator()209210 const post = {211 id: '1234',212 title: 'This is title',213 published: 'true',214 }215216 const req = new Request('http://localhost/', {217 method: 'POST',218 body: JSON.stringify(post),219 })220221 it('Should be invalid - "1234" is not number', async () => {222 const validator = v.json('id').asNumber().isEqual(1234)223 const results = await validator.validate(req)224 expect(results[0].isValid).toBe(false)225 const messages = ['Invalid Value [1234]: the JSON body "id" is invalid - should be "number"']226 expect(results[0].message).toBe(messages.join('\n'))227 })228229 it('Should be invalid - "true" is not boolean', async () => {230 const validator = v.json('published').asBoolean()231 const results = await validator.validate(req)232 expect(results[0].isValid).toBe(false)233 const messages = [234 'Invalid Value [true]: the JSON body "published" is invalid - should be "boolean"',235 ]236 expect(results[0].message).toBe(messages.join('\n'))237 })238})239240describe('Handle array paths', () => {241 const v = new Validator()242243 const body = {244 posts: [245 {246 id: 12411,247 title: 'This is title #1',248 published: true,249 rating: [true, 'cool'],250 awesome: true,251 testing: false,252 },253 {254 id: 12412,255 title: 'This is title #2',256 published: true,257 rating: [false],258 awesome: 'true',259 testing: true,260 },261 {262 id: 12413,263 title: 'This is title #3',264 published: false,265 rating: [true, 'lame'],266 awesome: false,267 },268 ],269 }270271 const req = new Request('http://localhost/', {272 method: 'POST',273 body: JSON.stringify(body),274 })275276 it('Should validate targeted path in array', async () => {277 const validator = v.json('posts[*].published').asArray().asBoolean().isRequired()278 const results = await validator.validate(req)279 expect(results[0].isValid).toBe(true)280 expect(results[1].isValid).toBe(true)281 expect(results[1].message).toBeUndefined()282 expect(results[1].value).toEqual([true, true, false])283 })284285 it('Should allow nested array paths', async () => {286 const validator = v.json('posts[*].rating[0]').asArray().asBoolean().isRequired()287 const results = await validator.validate(req)288 expect(results[0].isValid).toBe(true)289 expect(results[1].isValid).toBe(true)290 expect(results[1].message).toBeUndefined()291 expect(results[1].value).toEqual([true, false, true])292 })293294 it('Should allow optional array paths', async () => {295 const validator = v.json('posts[*].rating[1]').asArray().isOptional()296 const results = await validator.validate(req)297 expect(results[0].isValid).toBe(true)298 expect(results[1].isValid).toBe(true)299 expect(results[1].message).toBeUndefined()300 expect(results[1].value).toEqual(['cool', undefined, 'lame'])301 })302303 it('Should provide error with invalid array paths', async () => {304 const validator = v.json('posts[*].rating[3]').asArray()305 const results = await validator.validate(req)306 expect(results[0].isValid).toBe(false)307 const messages = [308 'Invalid Value [undefined, undefined, undefined]: the JSON body "posts[*].rating[3]" is invalid - should be "string[]"',309 ]310 expect(results[0].message).toBe(messages.join('\n'))311 expect(results[0].value).toEqual([undefined, undefined, undefined])312 })313314 it('Should prevent invalid types within array', async () => {315 const validator = v.json('posts[*].awesome').asArray().asBoolean()316 const results = await validator.validate(req)317 expect(results[0].isValid).toBe(false)318 const messages = [319 'Invalid Value [true, "true", false]: the JSON body "posts[*].awesome" is invalid - should be "boolean[]"',320 ]321 expect(results[0].message).toBe(messages.join('\n'))322 expect(results[0].value).toEqual([true, 'true', false])323 })324325 it('Should allow undefined values when optional', async () => {326 const validator = v.json('posts[*].testing').asArray().asBoolean().isOptional()327 const results = await validator.validate(req)328 expect(results[0].isValid).toBe(true)329 expect(results[0].value).toEqual([false, true, undefined])330 })331})332333describe('Validate with asArray', () => {334 const v = new Validator()335 const json = {336 post: {337 title: ['Hello'],338 flags: [true, false],339 published: [true],340 comments: [341 {342 title: 'abc',343 author: 'John',344 category: 'Heroes',345 flags: [true, false],346 },347 {348 title: 'def',349 author: 'Dave',350 flags: [false, true],351 },352 ],353 },354 pager: {355 prev: true,356 },357 }358359 const req = new Request('http://localhost/', {360 method: 'POST',361 body: JSON.stringify(json),362 })363364 it('Should validate array values', async () => {365 const validator = v.json('post.title').asArray().isAlpha()366 const results = await validator.validate(req)367 expect(results[0].isValid).toBe(true)368 expect(results[1].isValid).toBe(true)369 })370371 it('Should validate array values - specify with `*`', async () => {372 const validator = v.json('post.comments[*].title').asArray().isAlpha()373 const results = await validator.validate(req)374 expect(results[0].isValid).toBe(true)375 expect(results[1].isValid).toBe(true)376 })377378 it('Should return the same result for `.asArray().as{Type}()` and `.as{Type}().asArray()', async () => {379 const validator1 = v.json('post.flags').asArray().asBoolean().isRequired()380 const validator2 = v.json('post.flags').asBoolean().asArray().isRequired()381 const res1 = await validator1.validate(req)382 const res2 = await validator2.validate(req)383384 expect(res1[0].isValid).toBe(true)385 expect(res1[0].message).toBeUndefined()386 expect(res1[0].value).toEqual([true, false])387 expect(res1[1].isValid).toBe(true)388389 // Entire responses should be equal390 expect(res1).toEqual(res2)391 })392393 it('Should fail validation if value is array but `.asArray()` not called', async () => {394 const validator = v.json('post.flags').asBoolean().isRequired()395 const results = await validator.validate(req)396 expect(results[0].isValid).toBe(false)397 const messages = [398 'Invalid Value [true, false]: the JSON body "post.flags" is invalid - should be "boolean"',399 ]400 expect(results[0].message).toBe(messages.join('\n'))401 expect(results[0].value).toEqual([true, false])402 expect(results[1].isValid).toBe(true)403 })404405 it('Should pass validation if `isRequired` and path has no missing entries', async () => {406 const validator = v.json('post.comments[*].author').asArray().isRequired()407 const results = await validator.validate(req)408 expect(results[0].isValid).toBe(true)409 expect(results[1].isValid).toBe(true)410 })411412 it('Should fail validation if `isRequired` and missing entry for path', async () => {413 const validator = v.json('post.comments[*].heroes').asArray().isRequired()414 const results = await validator.validate(req)415 expect(results[0].isValid).toBe(false)416 let messages = [417 'Invalid Value [undefined, undefined]: the JSON body "post.comments[*].heroes" is invalid - should be "string[]"',418 ]419 expect(results[0].message).toBe(messages.join('\n'))420 expect(results[1].isValid).toBe(false)421 messages = [422 'Invalid Value [undefined, undefined]: the JSON body "post.comments[*].heroes" is invalid - isRequired',423 ]424 expect(results[1].message).toBe(messages.join('\n'))425 })426427 it('Should fail validation if value is not array but `asArray` is set', async () => {428 const validator = v.json('pager.prev').asBoolean().asArray()429 const results = await validator.validate(req)430 expect(results[0].isValid).toBe(false)431 const messages = [432 'Invalid Value [true]: the JSON body "pager.prev" is invalid - should be "boolean[]"',433 ]434 expect(results[0].message).toBe(messages.join('\n'))435 })436})437438describe('Invalid HTTP request handling', () => {439 const v = new Validator()440441 it('Should throw malformed error when JSON body absent', async () => {442 const req = new Request('http://localhost/', {443 method: 'POST',444 })445446 let error447 try {448 const validator = v.json('post.title').isRequired()449 await validator.validate(req)450 } catch (e) {451 error = e452 }453 expect(error instanceof Error).toBe(true)454 expect((error as Error).message).toBe('Malformed JSON in request body')455 })456457 it('Should throw malformed error when a JSON body is not valid JSON', async () => {458 const req = new Request('http://localhost/', {459 method: 'POST',460 body: 'Not json!',461 })462463 let error464 try {465 const validator = v.json('post.title').isRequired()466 await validator.validate(req)467 } catch (e) {468 error = e469 }470 expect(error instanceof Error).toBe(true)471 expect((error as Error).message).toBe('Malformed JSON in request body')472 })473})474475describe('Nested objects', () => {476 const json = {477 posts: [478 {479 id: 123,480 title: 'JavaScript',481 authors: [482 {483 name: 'Superman',484 age: 20,485 like: {486 food: 'fish',487 },488 },489 ],490 tags: [491 {492 name: 'Node.js',493 },494 {495 name: 'Deno',496 },497 {498 name: 'Bun',499 },500 ],501 },502 {503 id: 456,504 title: 'Framework',505 tags: [506 {507 name: 'Hono',508 },509 {510 name: 'Express',511 },512 ],513 },514 ],515 pager: {516 prev: true,517 next: false,518 meta: {519 perPage: 10,520 pages: [521 {522 num: 1,523 },524 ],525 },526 },527 }528529 const req = new Request('http://localhost/', {530 method: 'POST',531 body: JSON.stringify(json),532 })533534 it('Should validate nested array values', async () => {535 const v = new Validator()536 const vArray = v.array('posts', (v) => ({537 id: v.json('id').asNumber(),538 title: v.json('title'),539 authors: v540 .array('authors', (v) => ({541 name: v.json('name'),542 age: v.json('age').asNumber(),543 like: v.object('like', (v) => ({544 food: v.json('food').isRequired(),545 })),546 }))547 .isOptional(),548 tags: v549 .array('tags', (v) => ({550 name: v.json('name'),551 }))552 .isOptional(),553 }))554 for (const validator of vArray.getValidators()) {555 const results = await validator.validate(req)556 expect(results[0].isValid).toBe(true)557 expect(results[0].message).toBeUndefined()558 }559 })560561 it('Should validate nested object values', async () => {562 const v = new Validator()563 const vObject = v.object('pager', (v) => ({564 prev: v.json('prev').asBoolean(),565 next: v.json('next').asBoolean(),566 meta: v.object('meta', (v) => ({567 totalCount: v.json('perPage').asNumber(),568 pages: v.array('pages', (v) => ({569 num: v.json('num').asNumber(),570 })),571 })),572 }))573574 for (const validator of vObject.getValidators()) {575 const results = await validator.validate(req)576 expect(results[0].isValid).toBe(true)577 expect(results[0].message).toBeUndefined()578 }579 })580581 it('Should validate nested array values', async () => {582 let v = new Validator()583 const vArray = v.array('posts', (v) => ({584 id: v.json('id'),585 }))586587 for (const validator of vArray.getValidators()) {588 const results = await validator.validate(req)589 expect(results[0].isValid).toBe(false)590 const messages = [591 'Invalid Value [123, 456]: the JSON body "posts.[*].id" is invalid - should be "string[]"',592 ]593 expect(results[0].message).toBe(messages.join('\n'))594 }595596 v = new Validator()597 const vArray2 = v.array('posts', (v) => ({598 optionalProperty: v.json('optional-property').isOptional(),599 }))600 for (const validator of vArray2.getValidators()) {601 const results = await validator.validate(req)602 expect(results[0].isValid).toBe(true)603 expect(results[0].message).toBeUndefined()604 }605 })606607 it('Should validate nested array values with `isOptional`', async () => {608 const v = new Validator()609 const vArray = v.array('posts', (v) => ({610 title: v.json('optional-title').isOptional(),611 comments: v612 .array('comments', (v) => ({613 body: v.json('body'),614 }))615 .isOptional(),616 }))617618 for (const validator of vArray.getValidators()) {619 const results = await validator.validate(req)620 expect(results[0].isValid).toBe(true)621 expect(results[0].message).toBeUndefined()622 }623624 const vArray2 = v625 .array('posts', (v) => ({626 title: v.json('title').asNumber(),627 }))628 .isOptional()629630 for (const validator of vArray2.getValidators()) {631 const results = await validator.validate(req)632 expect(results[0].isValid).toBe(false)633 const messages = [634 'Invalid Value ["JavaScript", "Framework"]: the JSON body "posts.[*].title" is invalid - should be "number[]"',635 ]636 expect(results[0].message).toBe(messages.join('\n'))637 }638 })639640 it('Should validate nested object values with `isOptional`', async () => {641 const v = new Validator()642 const vObject = v.object('pager', (v) => ({643 current: v.json('optional-value').isOptional(),644 method: v645 .object('method', (v) => ({646 name: v.json('name'),647 }))648 .isOptional(),649 }))650651 for (const validator of vObject.getValidators()) {652 const results = await validator.validate(req)653 expect(results[0].isValid).toBe(true)654 expect(results[0].message).toBeUndefined()655 }656 })657658 it('Should only allow `v.json()` in nested array or object', async () => {659 const v = new Validator()660 const vArray = v.array('posts', (v) => ({661 id: v.header('id').asNumber().isRequired(),662 }))663664 for (const validator of vArray.getValidators()) {665 const results = await validator.validate(req)666 expect(results[0].isValid).toBe(false)667 const messages = [668 'Invalid Value [undefined]: the request header "id" is invalid - should be "number"',669 ]670 expect(results[0].message).toBe(messages.join('\n'))671 }672673 const vObject = v.object('pager', (v) => ({674 prev: v.query('prev').asBoolean(),675 next: v.body('next').asBoolean(),676 }))677678 const messages = [679 'Invalid Value [undefined]: the query parameter "prev" is invalid - should be "boolean"',680 'Invalid Value [undefined]: the request body "next" is invalid - should be "boolean"',681 ]682683 for (const [i, validator] of vObject.getValidators().entries()) {684 const results = await validator.validate(req)685 expect(results[0].isValid).toBe(false)686 expect(results[0].message).toBe(`${messages[i]}`)687 }688 })689})690691describe('Custom message', () => {692 const v = new Validator()693694 const json = {695 title: 'foo',696 post: [697 {698 id: 123,699 },700 ],701 }702703 const req = new Request('http://localhost/', {704 method: 'POST',705 body: JSON.stringify(json),706 })707708 it('Should return custom error message - value', async () => {709 const customMessage1 = 'Custom message: not contain!'710 const customMessage2 = 'Custom message: not numeric!'711 const validator = v712 .json('title')713 .contains('bar')714 .message([customMessage1].join('\n'))715 .isNumeric()716 .message([customMessage2].join('\n'))717 const results = await validator.validate(req)718 expect(results[0].isValid).toBe(true)719 expect(results[1].isValid).toBe(false)720 expect(results[1].message).toBe([customMessage1].join('\n'))721 expect(results[2].isValid).toBe(false)722 expect(results[2].message).toBe([customMessage2].join('\n'))723 })724725 it('Should return custom error message - validate type', async () => {726 const customMessage = 'Custom message: not string array!'727 const validator = v.json('post[*].id').message([customMessage].join('\n'))728 const results = await validator.validate(req)729 expect(results[0].isValid).toBe(false)730 expect(results[0].message).toBe([customMessage].join('\n'))731 })732})
deleted:src/middleware/validator/validator.ts-492 removed
1import { JSONPathCopy } from '../../utils/json'2import type { JSONObject, JSONPrimitive, JSONArray } from '../../utils/json'3import type { Schema } from './middleware'4import { rule } from './rule'5import { sanitizer } from './sanitizer'67type Target = 'query' | 'header' | 'body' | 'json'8type Type = JSONPrimitive | JSONObject | JSONArray | File9type RuleFunc = (value: Type) => boolean10type Rule = {11 name: string12 func: RuleFunc13 customMessage?: string14 type: 'type' | 'value'15}16type Sanitizer = (value: Type) => Type1718export type ValidateResult = {19 isValid: boolean20 message: string | undefined21 target: Target22 key: string23 value: Type24 ruleName: string25 ruleType: 'type' | 'value'26 jsonData?: JSONObject27}2829export abstract class VObjectBase<T extends Schema> {30 container: T31 keys: string[] = []32 protected _isOptional: boolean = false33 constructor(container: T, key: string) {34 this.container = container35 if (this instanceof VArray) {36 this.keys.push(key, '[*]')37 } else if (this instanceof VObject) {38 this.keys.push(key)39 }40 }4142 isOptional() {43 this._isOptional = true44 return this45 }4647 getValidators = (): VBase[] => {48 const validators: VBase[] = []49 const thisKeys: string[] = []50 Object.assign(thisKeys, this.keys)5152 const walk = (container: T, keys: string[], isOptional: boolean) => {53 for (const v of Object.values(container)) {54 if (v instanceof VArray || v instanceof VObject) {55 // eslint-disable-next-line @typescript-eslint/ban-ts-comment56 // @ts-ignore57 isOptional ||= v._isOptional58 keys.push(...v.keys)59 walk(v.container as T, keys, isOptional)60 const tmp: string[] = []61 Object.assign(tmp, thisKeys)62 keys = tmp63 } else if (v instanceof VBase) {64 if (isOptional) v.isOptional()65 v.baseKeys.push(...keys)66 validators.push(v)67 }68 }69 }7071 walk(this.container, this.keys, this._isOptional)7273 return validators74 }75}7677export class VObject<T extends Schema> extends VObjectBase<T> {78 constructor(container: T, key: string) {79 super(container, key)80 }81}8283export class VArray<T extends Schema> extends VObjectBase<T> {84 type: 'array' = 'array'85 constructor(container: T, key: string) {86 super(container, key)87 }88}8990export class Validator {91 isArray: boolean = false92 query = (key: string): VString => new VString({ target: 'query', key: key })93 header = (key: string): VString => new VString({ target: 'header', key: key })94 body = (key: string): VString => new VString({ target: 'body', key: key })95 json = (key: string) => {96 if (this.isArray) {97 return new VStringArray({ target: 'json', key: key })98 } else {99 return new VString({ target: 'json', key: key })100 }101 }102 array = <T extends Schema>(path: string, validator: (v: Validator) => T): VArray<T> => {103 this.isArray = true104 const res = validator(this)105 const arr = new VArray(res, path)106 return arr107 }108 object = <T extends Schema>(path: string, validator: (v: Validator) => T): VObject<T> => {109 this.isArray = false110 const res = validator(this)111 const obj = new VObject(res, path)112 return obj113 }114}115116type VOptions = {117 target: Target118 key: string119 type?: 'string' | 'number' | 'boolean' | 'object'120 isArray?: boolean121}122123export abstract class VBase {124 type: 'string' | 'number' | 'boolean' | 'object'125 target: Target126 baseKeys: string[] = []127 key: string128 rules: Rule[]129 sanitizers: Sanitizer[]130 isArray: boolean131 private _optional: boolean132 constructor(options: VOptions) {133 this.target = options.target134 this.key = options.key135 this.type = options.type || 'string'136 this.rules = [137 {138 name: this.getTypeRuleName(),139 type: 'type',140 func: this.validateType,141 },142 ]143 this.sanitizers = []144 this._optional = false145 this.isArray = options.isArray || false146 }147148 private _nested = () => (this.baseKeys.length ? true : false)149150 addRule(func: RuleFunc): this151 addRule(name: string, func: RuleFunc): this152 addRule(arg: string | RuleFunc, func?: RuleFunc) {153 if (typeof arg === 'string' && func) {154 this.rules.push({ name: arg, func, type: 'value' })155 } else if (arg instanceof Function) {156 this.rules.push({ name: arg.name, func: arg, type: 'value' })157 }158 return this159 }160161 addSanitizer = (sanitizer: Sanitizer) => {162 this.sanitizers.push(sanitizer)163 return this164 }165166 message = (text: string) => {167 const len = this.rules.length168 if (len >= 1) {169 this.rules[len - 1].customMessage = text170 }171 return this172 }173174 isRequired = () => {175 return this.addRule('isRequired', (value: unknown) => {176 if (value !== undefined && value !== null && value !== '') return true177 return false178 })179 }180181 isOptional = () => {182 this._optional = true183 return this.addRule('isOptional', () => true)184 }185186 isEqual = (comparison: unknown) => {187 return this.addRule('isEqual', (value: unknown) => {188 return value === comparison189 })190 }191192 asNumber = (): VNumber | VNumberArray => {193 const newVNumber = new VNumber({ ...this, type: 'number' })194 if (this.isArray) return newVNumber.asArray()195 return newVNumber196 }197198 asBoolean = (): VBoolean | VBooleanArray => {199 const newVBoolean = new VBoolean({ ...this, type: 'boolean' })200 if (this.isArray) return newVBoolean.asArray()201 return newVBoolean202 }203204 get(value: string) {205 const len = this.rules.length206 if (len > 0) {207 this.rules[this.rules.length - 1].customMessage = value208 }209 return this210 }211212 validate = async (req: Request): Promise<ValidateResult[]> => {213 let value: Type = undefined214 let jsonData: JSONObject | undefined = undefined215216 if (this.target === 'query') {217 value = req.query(this.key)218 }219 if (this.target === 'header') {220 value = req.header(this.key)221 }222 if (this.target === 'body') {223 const body = await req.parseBody()224 value = body[this.key]225 }226 if (this.target === 'json') {227 if (this._nested()) {228 this.key = `${this.baseKeys.join('.')}.${this.key}`229 }230 let obj = {}231 try {232 obj = (await req.json()) as JSONObject233 } catch (e) {234 throw new Error('Malformed JSON in request body')235 }236 const dst = {}237 value = JSONPathCopy(obj, dst, this.key)238 if (this._nested()) jsonData = dst239 }240241 const results: ValidateResult[] = []242243 let typeRule = this.rules.shift()244245 for (const rule of this.rules) {246 if (rule.type === 'type') {247 typeRule = rule248 } else if (rule.type === 'value') {249 const result = this.validateRule(rule, value)250 result.jsonData ||= jsonData251 results.push(result)252 }253 }254255 if (typeRule) {256 const typeResult = this.validateRule(typeRule, value)257 typeResult.jsonData ||= jsonData258 results.unshift(typeResult)259 }260261 return results262 }263264 protected getTypeRuleName(): string {265 const prefix = 'should be'266 return this.isArray ? `${prefix} "${this.type}[]"` : `${prefix} "${this.type}"`267 }268269 private validateRule(rule: Rule, value: Type): ValidateResult {270 let isValid: boolean = false271272 if (this._nested() && this.target != 'json') {273 isValid = false274 } else if (rule.type === 'value') {275 isValid = this.validateValue(rule.func, value)276 } else if (rule.type === 'type') {277 isValid = this.validateType(value)278 }279280 const message = isValid281 ? undefined282 : rule.customMessage || this.getMessage({ ruleName: rule.name, value })283 const result = {284 isValid: isValid,285 message: message,286 target: this.target,287 key: this.key,288 value,289 ruleName: rule.name,290 ruleType: rule.type,291 }292 return result293 }294295 private validateType = (value: Type): boolean => {296 if (this.isArray) {297 if (!Array.isArray(value)) {298 return false299 }300 for (const val of value) {301 if (typeof val === 'undefined' && this._nested()) {302 value.pop()303 }304 for (const val of value) {305 if (typeof val !== this.type) {306 // Value is of wrong type here307 // If it is not optional and not undefined, return false308 if (!this._optional || typeof val !== 'undefined') return false309 }310 }311 }312 } else {313 if (typeof value !== this.type) {314 if (this._optional && (typeof value === 'undefined' || Array.isArray(value))) {315 // Do nothing.316 // If it is optional it's OK to be `undefined` or Array317 } else {318 return false319 }320 }321 }322 return true323 }324325 private validateValue = (func: (value: Type) => boolean, value: Type): boolean => {326 if (this._optional && typeof value === 'undefined') return true327328 if (Array.isArray(value)) {329 // Sanitize330 for (const sanitizer of this.sanitizers) {331 value = value.map((innerVal: any) => sanitizer(innerVal)) as JSONArray332 }333 for (const val of value) {334 if (!func(val)) {335 return false336 }337 }338 return true339 } else {340 // Sanitize341 for (const sanitizer of this.sanitizers) {342 value = sanitizer(value)343 }344 if (!func(value)) {345 return false346 }347 return true348 }349 }350351 private getMessage = (opts: { ruleName: string; value: Type }): string => {352 let keyText: string353 const valueText = Array.isArray(opts.value)354 ? `${opts.value355 .map((val) =>356 val === undefined ? 'undefined' : typeof val === 'string' ? `"${val}"` : val357 )358 .join(', ')}`359 : opts.value360 switch (this.target) {361 case 'query':362 keyText = `the query parameter "${this.key}"`363 break364 case 'header':365 keyText = `the request header "${this.key}"`366 break367 case 'body':368 keyText = `the request body "${this.key}"`369 break370 case 'json':371 keyText = `the JSON body "${this.key}"`372 break373 }374 return `Invalid Value [${valueText}]: ${keyText} is invalid - ${opts.ruleName}`375 }376}377378export class VString extends VBase {379 constructor(options: VOptions) {380 super(options)381 this.type = 'string'382 }383384 asArray = () => {385 return new VStringArray(this)386 }387388 isEmpty = (389 options: {390 ignore_whitespace: boolean391 } = { ignore_whitespace: false }392 ) => {393 return this.addRule('isEmpty', (value) => rule.isEmpty(value as string, options))394 }395396 isLength = (options: Partial<{ min: number; max: number }> | number, arg2?: number) => {397 return this.addRule('isLength', (value) => rule.isLength(value as string, options, arg2))398 }399400 isAlpha = () => {401 return this.addRule('isAlpha', (value) => rule.isAlpha(value as string))402 }403404 isNumeric = () => {405 return this.addRule('isNumeric', (value) => rule.isNumeric(value as string))406 }407408 contains = (409 elem: string,410 options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {411 ignoreCase: false,412 minOccurrences: 1,413 }414 ) => {415 return this.addRule('contains', (value) => rule.contains(value as string, elem, options))416 }417418 isIn = (options: string[]) => {419 return this.addRule('isIn', (value) => rule.isIn(value as string, options))420 }421422 match = (regExp: RegExp) => {423 return this.addRule('match', (value) => rule.match(value as string, regExp))424 }425426 trim = () => {427 return this.addSanitizer((value) => sanitizer.trim(value as string))428 }429}430431export class VNumber extends VBase {432 constructor(options: VOptions) {433 super(options)434 this.type = 'number'435 }436437 asArray = () => {438 return new VNumberArray(this)439 }440441 isGte = (min: number) => {442 return this.addRule('isGte', (value) => rule.isGte(value as number, min))443 }444445 isLte = (min: number) => {446 return this.addRule('isLte', (value) => rule.isLte(value as number, min))447 }448}449450export class VBoolean extends VBase {451 constructor(options: VOptions) {452 super(options)453 this.type = 'boolean'454 }455456 asArray = () => {457 return new VBooleanArray(this)458 }459460 isTrue = () => {461 return this.addRule('isTrue', (value) => rule.isTrue(value as boolean))462 }463464 isFalse = () => {465 return this.addRule('isFalse', (value) => rule.isFalse(value as boolean))466 }467}468469export class VNumberArray extends VNumber {470 isArray: true471 constructor(options: VOptions) {472 super(options)473 this.isArray = true474 this.rules[0].name = this.getTypeRuleName()475 }476}477export class VStringArray extends VString {478 isArray: true479 constructor(options: VOptions) {480 super(options)481 this.isArray = true482 this.rules[0].name = this.getTypeRuleName()483 }484}485export class VBooleanArray extends VBoolean {486 isArray: true487 constructor(options: VOptions) {488 super(options)489 this.isArray = true490 this.rules[0].name = this.getTypeRuleName()491 }492}
added:src/utils/types.ts+5 added
1export type Expect<T extends true> = T2export type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 23 ? true4 : false5export type NotEqual<X, Y> = true extends Equal<X, Y> ? false : true
added:src/validator/rule.test.ts+55 added
1import { rule } from './rule'23describe('Rules', () => {4 // string5 test('isEmpty', () => {6 expect(rule.isEmpty('')).toBeTruthy()7 expect(rule.isEmpty('abcdef')).toBeFalsy()8 expect(rule.isEmpty('')).toBeTruthy()9 expect(rule.isEmpty(' ')).toBeFalsy()10 expect(rule.isEmpty(' ', { ignore_whitespace: true })).toBeTruthy()11 })12 test('isLength', () => {13 expect(rule.isLength('abcde', { min: 1, max: 10 })).toBeTruthy()14 expect(rule.isLength('abcde', { min: 1, max: 4 })).toBeFalsy()15 expect(rule.isLength('abcde', { max: 10 })).toBeTruthy()16 expect(rule.isLength('abcde', { max: 4 })).toBeFalsy()17 expect(rule.isLength('abcde', { min: 10 })).toBeFalsy()18 expect(rule.isLength('abcde', { min: 4 })).toBeTruthy()19 expect(rule.isLength('abcde', 1, 10)).toBeTruthy()20 expect(rule.isLength('abcde', 1, 4)).toBeFalsy()21 })22 test('isAlpha', () => {23 expect(rule.isAlpha('abcdef')).toBeTruthy()24 expect(rule.isAlpha('abc123')).toBeFalsy()25 })26 test('isNumeric', () => {27 expect(rule.isNumeric('01234')).toBeTruthy()28 expect(rule.isNumeric('012abc')).toBeFalsy()29 })30 test('contains', () => {31 expect(rule.contains('barfoobaz', 'foo')).toBeTruthy()32 expect(rule.contains('barfoobaz', 'fooo')).toBeFalsy()33 expect(rule.contains('barfoobaz', 'Foo')).toBeFalsy()34 expect(rule.contains('barfoobaz', 'Foo', { ignoreCase: true })).toBeTruthy()35 })36 test('isIn', () => {37 expect(rule.isIn('foo', ['foo', 'bar'])).toBeTruthy()38 expect(rule.isIn('foo', ['zzz', 'yyy'])).toBeFalsy()39 })40 test('match', () => {41 expect(rule.match('abcdef', /def$/)).toBeTruthy()42 expect(rule.match('abcdef', /^def$/)).toBeFalsy()43 })44 // number45 test('isGte', () => {46 expect(rule.isGte(20, 10)).toBeTruthy()47 expect(rule.isGte(10, 20)).toBeFalsy()48 expect(rule.isGte(10, 10)).toBeTruthy()49 })50 test('isLte', () => {51 expect(rule.isLte(10, 20)).toBeTruthy()52 expect(rule.isLte(20, 10)).toBeFalsy()53 expect(rule.isLte(10, 10)).toBeTruthy()54 })55})
added:src/validator/rule.ts+83 added
1// Some validation rules is are based on Validator.js2// Validator.js3// License (MIT)4// Copyright (c) 2018 Chris O'Hara <cohara87@gmail.com>5// https://github.com/validatorjs/validator.js67export const rule = {8 // string9 isEmpty(10 value: string,11 options: {12 ignore_whitespace: boolean13 } = { ignore_whitespace: false }14 ): boolean {15 return (options.ignore_whitespace ? value.trim().length : value.length) === 016 },1718 isLength: (19 value: string,20 options: Partial<{ min: number; max: number }> | number,21 arg2?: number22 ) => {23 let min: number24 let max: number | undefined25 if (typeof options === 'object') {26 min = options.min || 027 max = options.max28 } else {29 // backwards compatibility: isLength(str, min [, max])30 min = options || 031 max = arg232 }33 const presentationSequences = value.match(/(\uFE0F|\uFE0E)/g) || []34 const surrogatePairs = value.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []35 const len = value.length - presentationSequences.length - surrogatePairs.length36 return len >= min && (typeof max === 'undefined' || len <= max)37 },3839 isAlpha: (value: string): boolean => {40 return /^[A-Z]+$/i.test(value)41 },4243 isNumeric: (value: string): boolean => {44 return /^[0-9]+$/.test(value)45 },4647 contains: (48 value: string,49 elem: string,50 options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {51 ignoreCase: false,52 minOccurrences: 1,53 }54 ): boolean => {55 options.ignoreCase ||= false56 options.minOccurrences ||= 157 if (options.ignoreCase) {58 return value.toLowerCase().split(elem.toLowerCase()).length > options.minOccurrences59 }60 return value.split(elem).length > options.minOccurrences61 },6263 isIn: (value: string, options: string[]): boolean => {64 if (typeof options === 'object') {65 for (const elem of options) {66 if (elem === value) return true67 }68 }69 return false70 },7172 match: (value: string, regExp: RegExp): boolean => {73 return regExp.test(value)74 },7576 // number77 isGte: (value: number, min: number) => min <= value,78 isLte: (value: number, max: number) => value <= max,7980 // boolean81 isTrue: (value: boolean) => value === true,82 isFalse: (value: boolean) => value === false,83}
added:src/validator/sanitizer.test.ts+7 added
1import { sanitizer } from './sanitizer'23describe('Sanitizers', () => {4 test('trim', () => {5 expect(sanitizer.trim(' abc ')).toBe('abc')6 })7})
added:src/validator/sanitizer.ts+3 added
1export const sanitizer = {2 trim: (value: string) => value.trim(),3}
added:src/validator/schema.ts+54 added
1import type {2 VString,3 VNumber,4 VBoolean,5 VObject,6 VNumberArray,7 VStringArray,8 VBooleanArray,9 VArray,10 VObjectBase,11} from './validator'1213export type Schema = {14 [key: string]:15 | VString16 | VNumber17 | VBoolean18 | VStringArray19 | VNumberArray20 | VBooleanArray21 | Schema22 | VObject<Schema>23 | VArray<Schema>24}2526export type SchemaToProp<T> = {27 [K in keyof T]: T[K] extends VNumberArray28 ? number[]29 : T[K] extends VBooleanArray30 ? boolean[]31 : T[K] extends VStringArray32 ? string[]33 : T[K] extends VNumber34 ? number35 : T[K] extends VBoolean36 ? boolean37 : T[K] extends VString38 ? string39 : T[K] extends VObjectBase<Schema>40 ? T[K]['container'] extends VNumber41 ? number42 : T[K]['container'] extends VString43 ? string44 : T[K]['container'] extends VBoolean45 ? boolean46 : T[K] extends VArray<Schema>47 ? SchemaToProp<ReadonlyArray<T[K]['container']>>48 : T[K] extends VObject<Schema>49 ? SchemaToProp<T[K]['container']>50 : T[K] extends Schema51 ? SchemaToProp<T[K]>52 : never53 : SchemaToProp<T[K]>54}
added:src/validator/validator.test.ts+732 added
1import { extendRequestPrototype } from '../request'2import { Validator } from './validator'34extendRequestPrototype()56describe('Basic - query', () => {7 const v = new Validator()89 const req = new Request('http://localhost/?q=foo&page=3')1011 it('Should be valid - page', async () => {12 const validator = v.query('page').trim().isNumeric()13 expect(validator.type).toBe('string')14 const results = await validator.validate(req)15 expect(results[0].isValid).toBe(true)16 expect(results[0].message).toBeUndefined()17 expect(results[1].isValid).toBe(true)18 expect(results[1].message).toBeUndefined()19 })2021 it('Should be invalid - q', async () => {22 const validator = v.query('q').isRequired().asNumber()23 expect(validator.type).toBe('number')24 const results = await validator.validate(req)25 expect(results[0].isValid).toBe(false)26 const messages = [27 'Invalid Value [foo]: the query parameter "q" is invalid - should be "number"',28 ]29 expect(results[0].message).toBe(messages.join('\n'))30 })3132 it('Should be invalid - q2', async () => {33 const validator = v.query('q2').isRequired()34 const results = await validator.validate(req)35 expect(results[0].isValid).toBe(false)36 let messages = [37 'Invalid Value [undefined]: the query parameter "q2" is invalid - should be "string"',38 ]39 expect(results[0].message).toBe(messages.join('\n'))40 expect(results[1].isValid).toBe(false)41 messages = ['Invalid Value [undefined]: the query parameter "q2" is invalid - isRequired']42 expect(results[1].message).toBe(messages.join('\n'))43 })44})4546describe('Basic - header', () => {47 const v = new Validator()4849 const req = new Request('http://localhost/', {50 headers: {51 'x-message': 'hello world!',52 'x-number': '12345',53 },54 })5556 it('Should be valid - x-message', async () => {57 const validator = v.header('x-message').isRequired().contains('Hello', { ignoreCase: true })58 const results = await validator.validate(req)59 expect(results[0].isValid).toBe(true)60 expect(results[0].message).toBeUndefined()61 expect(results[1].isValid).toBe(true)62 expect(results[1].message).toBeUndefined()63 expect(results[2].isValid).toBe(true)64 expect(results[2].message).toBeUndefined()65 })6667 it('Should be invalid - x-number', async () => {68 const validator = v.header('x-number').isEqual(12345)69 const results = await validator.validate(req)70 expect(results[0].isValid).toBe(true)71 expect(results[1].isValid).toBe(false)72 const messages = ['Invalid Value [12345]: the request header "x-number" is invalid - isEqual']73 expect(results[1].message).toBe(messages.join('\n'))74 })75})7677describe('Basic - body', () => {78 const v = new Validator()7980 const body = new FormData()81 body.append('title', ' abcdef ')82 body.append('title2', 'abcdef')83 const req = new Request('http://localhost/', {84 method: 'POST',85 body: body,86 })8788 it('Should be valid - title', async () => {89 const validator = v.body('title').trim().isLength({ max: 10 }).isRequired()90 const results = await validator.validate(req)91 expect(results[0].isValid).toBe(true)92 expect(results[0].message).toBeUndefined()93 expect(results[1].isValid).toBe(true)94 expect(results[1].message).toBeUndefined()95 expect(results[2].isValid).toBe(true)96 expect(results[2].message).toBeUndefined()97 })9899 it('Should be invalid - title2', async () => {100 const validator = v.body('title2').isLength({ max: 5 })101 const results = await validator.validate(req)102 expect(results[0].isValid).toBe(true)103 expect(results[0].message).toBeUndefined()104 expect(results[1].isValid).toBe(false)105 const messages = ['Invalid Value [abcdef]: the request body "title2" is invalid - isLength']106 expect(results[1].message).toBe(messages.join('\n'))107 })108})109110describe('Basic - JSON', () => {111 const v = new Validator()112113 const post = {114 id: 1234,115 title: 'This is title',116 author: {117 name: 'Superman',118 age: 20,119 },120 }121122 const req = new Request('http://localhost/', {123 method: 'POST',124 body: JSON.stringify(post),125 })126127 it('Should be valid - id', async () => {128 const validator = v.json('id').asNumber().isEqual(1234)129 const results = await validator.validate(req)130 expect(results[0].isValid).toBe(true)131 expect(results[0].message).toBeUndefined()132 expect(results[1].isValid).toBe(true)133 expect(results[1].message).toBeUndefined()134 })135136 it('Should be valid - author.name', async () => {137 const validator = v.json('author.name').isIn(['Ultra man', 'Superman'])138 const results = await validator.validate(req)139 expect(results[0].isValid).toBe(true)140 expect(results[0].message).toBeUndefined()141 expect(results[1].isValid).toBe(true)142 expect(results[1].message).toBeUndefined()143 })144145 it('Should be invalid - author.age', async () => {146 const validator = v.json('author.age').asNumber().isLte(10)147 const results = await validator.validate(req)148 expect(results[0].isValid).toBe(true)149 expect(results[1].isValid).toBe(false)150 const messages = ['Invalid Value [20]: the JSON body "author.age" is invalid - isLte']151 expect(results[1].message).toBe(messages.join('\n'))152 })153})154155describe('Handle required values', () => {156 const v = new Validator()157158 const req = new Request('http://localhost/', {159 method: 'POST',160 body: JSON.stringify({ comment: null, name: 'John', admin: false }),161 })162163 it('Should be valid - `name` is required', async () => {164 const validator = v.json('name').isRequired()165 const results = await validator.validate(req)166 expect(results[0].isValid).toBe(true)167 expect(results[1].isValid).toBe(true)168 })169170 it('Should be invalid - `comment` is required but missing', async () => {171 const validator = v.json('comment').isRequired()172 const results = await validator.validate(req)173 expect(results[0].isValid).toBe(false)174 expect(results[1].isValid).toBe(false)175 })176177 it('Should be valid - `admin` is required and present, although falsy', async () => {178 const validator = v.json('admin').asBoolean().isRequired()179 const results = await validator.validate(req)180 expect(results[0].isValid).toBe(true)181 expect(results[1].isValid).toBe(true)182 expect(results[1].value).toBe(false)183 })184})185186describe('Handle optional values', () => {187 it('Should be valid - `comment` is optional', async () => {188 const v = new Validator()189 const req = new Request('http://localhost/', {190 method: 'POST',191 })192 const validator = v.body('comment').isOptional()193 const results = await validator.validate(req)194 expect(results[0].isValid).toBe(true)195 })196 it('Should be valid - "isNumeric" but "isOptional"', async () => {197 const v = new Validator()198 const validator = v.query('page').isNumeric().isOptional()199 const req = new Request('http://localhost/')200 const results = await validator.validate(req)201 expect(results[0].isValid).toBe(true)202 expect(results[1].isValid).toBe(true)203 expect(results[1].message).toBeUndefined()204 })205})206207describe('Handling types error', () => {208 const v = new Validator()209210 const post = {211 id: '1234',212 title: 'This is title',213 published: 'true',214 }215216 const req = new Request('http://localhost/', {217 method: 'POST',218 body: JSON.stringify(post),219 })220221 it('Should be invalid - "1234" is not number', async () => {222 const validator = v.json('id').asNumber().isEqual(1234)223 const results = await validator.validate(req)224 expect(results[0].isValid).toBe(false)225 const messages = ['Invalid Value [1234]: the JSON body "id" is invalid - should be "number"']226 expect(results[0].message).toBe(messages.join('\n'))227 })228229 it('Should be invalid - "true" is not boolean', async () => {230 const validator = v.json('published').asBoolean()231 const results = await validator.validate(req)232 expect(results[0].isValid).toBe(false)233 const messages = [234 'Invalid Value [true]: the JSON body "published" is invalid - should be "boolean"',235 ]236 expect(results[0].message).toBe(messages.join('\n'))237 })238})239240describe('Handle array paths', () => {241 const v = new Validator()242243 const body = {244 posts: [245 {246 id: 12411,247 title: 'This is title #1',248 published: true,249 rating: [true, 'cool'],250 awesome: true,251 testing: false,252 },253 {254 id: 12412,255 title: 'This is title #2',256 published: true,257 rating: [false],258 awesome: 'true',259 testing: true,260 },261 {262 id: 12413,263 title: 'This is title #3',264 published: false,265 rating: [true, 'lame'],266 awesome: false,267 },268 ],269 }270271 const req = new Request('http://localhost/', {272 method: 'POST',273 body: JSON.stringify(body),274 })275276 it('Should validate targeted path in array', async () => {277 const validator = v.json('posts[*].published').asArray().asBoolean().isRequired()278 const results = await validator.validate(req)279 expect(results[0].isValid).toBe(true)280 expect(results[1].isValid).toBe(true)281 expect(results[1].message).toBeUndefined()282 expect(results[1].value).toEqual([true, true, false])283 })284285 it('Should allow nested array paths', async () => {286 const validator = v.json('posts[*].rating[0]').asArray().asBoolean().isRequired()287 const results = await validator.validate(req)288 expect(results[0].isValid).toBe(true)289 expect(results[1].isValid).toBe(true)290 expect(results[1].message).toBeUndefined()291 expect(results[1].value).toEqual([true, false, true])292 })293294 it('Should allow optional array paths', async () => {295 const validator = v.json('posts[*].rating[1]').asArray().isOptional()296 const results = await validator.validate(req)297 expect(results[0].isValid).toBe(true)298 expect(results[1].isValid).toBe(true)299 expect(results[1].message).toBeUndefined()300 expect(results[1].value).toEqual(['cool', undefined, 'lame'])301 })302303 it('Should provide error with invalid array paths', async () => {304 const validator = v.json('posts[*].rating[3]').asArray()305 const results = await validator.validate(req)306 expect(results[0].isValid).toBe(false)307 const messages = [308 'Invalid Value [undefined, undefined, undefined]: the JSON body "posts[*].rating[3]" is invalid - should be "string[]"',309 ]310 expect(results[0].message).toBe(messages.join('\n'))311 expect(results[0].value).toEqual([undefined, undefined, undefined])312 })313314 it('Should prevent invalid types within array', async () => {315 const validator = v.json('posts[*].awesome').asArray().asBoolean()316 const results = await validator.validate(req)317 expect(results[0].isValid).toBe(false)318 const messages = [319 'Invalid Value [true, "true", false]: the JSON body "posts[*].awesome" is invalid - should be "boolean[]"',320 ]321 expect(results[0].message).toBe(messages.join('\n'))322 expect(results[0].value).toEqual([true, 'true', false])323 })324325 it('Should allow undefined values when optional', async () => {326 const validator = v.json('posts[*].testing').asArray().asBoolean().isOptional()327 const results = await validator.validate(req)328 expect(results[0].isValid).toBe(true)329 expect(results[0].value).toEqual([false, true, undefined])330 })331})332333describe('Validate with asArray', () => {334 const v = new Validator()335 const json = {336 post: {337 title: ['Hello'],338 flags: [true, false],339 published: [true],340 comments: [341 {342 title: 'abc',343 author: 'John',344 category: 'Heroes',345 flags: [true, false],346 },347 {348 title: 'def',349 author: 'Dave',350 flags: [false, true],351 },352 ],353 },354 pager: {355 prev: true,356 },357 }358359 const req = new Request('http://localhost/', {360 method: 'POST',361 body: JSON.stringify(json),362 })363364 it('Should validate array values', async () => {365 const validator = v.json('post.title').asArray().isAlpha()366 const results = await validator.validate(req)367 expect(results[0].isValid).toBe(true)368 expect(results[1].isValid).toBe(true)369 })370371 it('Should validate array values - specify with `*`', async () => {372 const validator = v.json('post.comments[*].title').asArray().isAlpha()373 const results = await validator.validate(req)374 expect(results[0].isValid).toBe(true)375 expect(results[1].isValid).toBe(true)376 })377378 it('Should return the same result for `.asArray().as{Type}()` and `.as{Type}().asArray()', async () => {379 const validator1 = v.json('post.flags').asArray().asBoolean().isRequired()380 const validator2 = v.json('post.flags').asBoolean().asArray().isRequired()381 const res1 = await validator1.validate(req)382 const res2 = await validator2.validate(req)383384 expect(res1[0].isValid).toBe(true)385 expect(res1[0].message).toBeUndefined()386 expect(res1[0].value).toEqual([true, false])387 expect(res1[1].isValid).toBe(true)388389 // Entire responses should be equal390 expect(res1).toEqual(res2)391 })392393 it('Should fail validation if value is array but `.asArray()` not called', async () => {394 const validator = v.json('post.flags').asBoolean().isRequired()395 const results = await validator.validate(req)396 expect(results[0].isValid).toBe(false)397 const messages = [398 'Invalid Value [true, false]: the JSON body "post.flags" is invalid - should be "boolean"',399 ]400 expect(results[0].message).toBe(messages.join('\n'))401 expect(results[0].value).toEqual([true, false])402 expect(results[1].isValid).toBe(true)403 })404405 it('Should pass validation if `isRequired` and path has no missing entries', async () => {406 const validator = v.json('post.comments[*].author').asArray().isRequired()407 const results = await validator.validate(req)408 expect(results[0].isValid).toBe(true)409 expect(results[1].isValid).toBe(true)410 })411412 it('Should fail validation if `isRequired` and missing entry for path', async () => {413 const validator = v.json('post.comments[*].heroes').asArray().isRequired()414 const results = await validator.validate(req)415 expect(results[0].isValid).toBe(false)416 let messages = [417 'Invalid Value [undefined, undefined]: the JSON body "post.comments[*].heroes" is invalid - should be "string[]"',418 ]419 expect(results[0].message).toBe(messages.join('\n'))420 expect(results[1].isValid).toBe(false)421 messages = [422 'Invalid Value [undefined, undefined]: the JSON body "post.comments[*].heroes" is invalid - isRequired',423 ]424 expect(results[1].message).toBe(messages.join('\n'))425 })426427 it('Should fail validation if value is not array but `asArray` is set', async () => {428 const validator = v.json('pager.prev').asBoolean().asArray()429 const results = await validator.validate(req)430 expect(results[0].isValid).toBe(false)431 const messages = [432 'Invalid Value [true]: the JSON body "pager.prev" is invalid - should be "boolean[]"',433 ]434 expect(results[0].message).toBe(messages.join('\n'))435 })436})437438describe('Invalid HTTP request handling', () => {439 const v = new Validator()440441 it('Should throw malformed error when JSON body absent', async () => {442 const req = new Request('http://localhost/', {443 method: 'POST',444 })445446 let error447 try {448 const validator = v.json('post.title').isRequired()449 await validator.validate(req)450 } catch (e) {451 error = e452 }453 expect(error instanceof Error).toBe(true)454 expect((error as Error).message).toBe('Malformed JSON in request body')455 })456457 it('Should throw malformed error when a JSON body is not valid JSON', async () => {458 const req = new Request('http://localhost/', {459 method: 'POST',460 body: 'Not json!',461 })462463 let error464 try {465 const validator = v.json('post.title').isRequired()466 await validator.validate(req)467 } catch (e) {468 error = e469 }470 expect(error instanceof Error).toBe(true)471 expect((error as Error).message).toBe('Malformed JSON in request body')472 })473})474475describe('Nested objects', () => {476 const json = {477 posts: [478 {479 id: 123,480 title: 'JavaScript',481 authors: [482 {483 name: 'Superman',484 age: 20,485 like: {486 food: 'fish',487 },488 },489 ],490 tags: [491 {492 name: 'Node.js',493 },494 {495 name: 'Deno',496 },497 {498 name: 'Bun',499 },500 ],501 },502 {503 id: 456,504 title: 'Framework',505 tags: [506 {507 name: 'Hono',508 },509 {510 name: 'Express',511 },512 ],513 },514 ],515 pager: {516 prev: true,517 next: false,518 meta: {519 perPage: 10,520 pages: [521 {522 num: 1,523 },524 ],525 },526 },527 }528529 const req = new Request('http://localhost/', {530 method: 'POST',531 body: JSON.stringify(json),532 })533534 it('Should validate nested array values', async () => {535 const v = new Validator()536 const vArray = v.array('posts', (v) => ({537 id: v.json('id').asNumber(),538 title: v.json('title'),539 authors: v540 .array('authors', (v) => ({541 name: v.json('name'),542 age: v.json('age').asNumber(),543 like: v.object('like', (v) => ({544 food: v.json('food').isRequired(),545 })),546 }))547 .isOptional(),548 tags: v549 .array('tags', (v) => ({550 name: v.json('name'),551 }))552 .isOptional(),553 }))554 for (const validator of vArray.getValidators()) {555 const results = await validator.validate(req)556 expect(results[0].isValid).toBe(true)557 expect(results[0].message).toBeUndefined()558 }559 })560561 it('Should validate nested object values', async () => {562 const v = new Validator()563 const vObject = v.object('pager', (v) => ({564 prev: v.json('prev').asBoolean(),565 next: v.json('next').asBoolean(),566 meta: v.object('meta', (v) => ({567 totalCount: v.json('perPage').asNumber(),568 pages: v.array('pages', (v) => ({569 num: v.json('num').asNumber(),570 })),571 })),572 }))573574 for (const validator of vObject.getValidators()) {575 const results = await validator.validate(req)576 expect(results[0].isValid).toBe(true)577 expect(results[0].message).toBeUndefined()578 }579 })580581 it('Should validate nested array values', async () => {582 let v = new Validator()583 const vArray = v.array('posts', (v) => ({584 id: v.json('id'),585 }))586587 for (const validator of vArray.getValidators()) {588 const results = await validator.validate(req)589 expect(results[0].isValid).toBe(false)590 const messages = [591 'Invalid Value [123, 456]: the JSON body "posts.[*].id" is invalid - should be "string[]"',592 ]593 expect(results[0].message).toBe(messages.join('\n'))594 }595596 v = new Validator()597 const vArray2 = v.array('posts', (v) => ({598 optionalProperty: v.json('optional-property').isOptional(),599 }))600 for (const validator of vArray2.getValidators()) {601 const results = await validator.validate(req)602 expect(results[0].isValid).toBe(true)603 expect(results[0].message).toBeUndefined()604 }605 })606607 it('Should validate nested array values with `isOptional`', async () => {608 const v = new Validator()609 const vArray = v.array('posts', (v) => ({610 title: v.json('optional-title').isOptional(),611 comments: v612 .array('comments', (v) => ({613 body: v.json('body'),614 }))615 .isOptional(),616 }))617618 for (const validator of vArray.getValidators()) {619 const results = await validator.validate(req)620 expect(results[0].isValid).toBe(true)621 expect(results[0].message).toBeUndefined()622 }623624 const vArray2 = v625 .array('posts', (v) => ({626 title: v.json('title').asNumber(),627 }))628 .isOptional()629630 for (const validator of vArray2.getValidators()) {631 const results = await validator.validate(req)632 expect(results[0].isValid).toBe(false)633 const messages = [634 'Invalid Value ["JavaScript", "Framework"]: the JSON body "posts.[*].title" is invalid - should be "number[]"',635 ]636 expect(results[0].message).toBe(messages.join('\n'))637 }638 })639640 it('Should validate nested object values with `isOptional`', async () => {641 const v = new Validator()642 const vObject = v.object('pager', (v) => ({643 current: v.json('optional-value').isOptional(),644 method: v645 .object('method', (v) => ({646 name: v.json('name'),647 }))648 .isOptional(),649 }))650651 for (const validator of vObject.getValidators()) {652 const results = await validator.validate(req)653 expect(results[0].isValid).toBe(true)654 expect(results[0].message).toBeUndefined()655 }656 })657658 it('Should only allow `v.json()` in nested array or object', async () => {659 const v = new Validator()660 const vArray = v.array('posts', (v) => ({661 id: v.header('id').asNumber().isRequired(),662 }))663664 for (const validator of vArray.getValidators()) {665 const results = await validator.validate(req)666 expect(results[0].isValid).toBe(false)667 const messages = [668 'Invalid Value [undefined]: the request header "id" is invalid - should be "number"',669 ]670 expect(results[0].message).toBe(messages.join('\n'))671 }672673 const vObject = v.object('pager', (v) => ({674 prev: v.query('prev').asBoolean(),675 next: v.body('next').asBoolean(),676 }))677678 const messages = [679 'Invalid Value [undefined]: the query parameter "prev" is invalid - should be "boolean"',680 'Invalid Value [undefined]: the request body "next" is invalid - should be "boolean"',681 ]682683 for (const [i, validator] of vObject.getValidators().entries()) {684 const results = await validator.validate(req)685 expect(results[0].isValid).toBe(false)686 expect(results[0].message).toBe(`${messages[i]}`)687 }688 })689})690691describe('Custom message', () => {692 const v = new Validator()693694 const json = {695 title: 'foo',696 post: [697 {698 id: 123,699 },700 ],701 }702703 const req = new Request('http://localhost/', {704 method: 'POST',705 body: JSON.stringify(json),706 })707708 it('Should return custom error message - value', async () => {709 const customMessage1 = 'Custom message: not contain!'710 const customMessage2 = 'Custom message: not numeric!'711 const validator = v712 .json('title')713 .contains('bar')714 .message([customMessage1].join('\n'))715 .isNumeric()716 .message([customMessage2].join('\n'))717 const results = await validator.validate(req)718 expect(results[0].isValid).toBe(true)719 expect(results[1].isValid).toBe(false)720 expect(results[1].message).toBe([customMessage1].join('\n'))721 expect(results[2].isValid).toBe(false)722 expect(results[2].message).toBe([customMessage2].join('\n'))723 })724725 it('Should return custom error message - validate type', async () => {726 const customMessage = 'Custom message: not string array!'727 const validator = v.json('post[*].id').message([customMessage].join('\n'))728 const results = await validator.validate(req)729 expect(results[0].isValid).toBe(false)730 expect(results[0].message).toBe([customMessage].join('\n'))731 })732})
added:src/validator/validator.ts+492 added
1import { JSONPathCopy } from './../utils/json'2import type { JSONObject, JSONPrimitive, JSONArray } from './../utils/json'3import { rule } from './rule'4import { sanitizer } from './sanitizer'5import type { Schema } from './schema'67type Target = 'query' | 'header' | 'body' | 'json'8type Type = JSONPrimitive | JSONObject | JSONArray | File9type RuleFunc = (value: Type) => boolean10type Rule = {11 name: string12 func: RuleFunc13 customMessage?: string14 type: 'type' | 'value'15}16type Sanitizer = (value: Type) => Type1718export type ValidateResult = {19 isValid: boolean20 message: string | undefined21 target: Target22 key: string23 value: Type24 ruleName: string25 ruleType: 'type' | 'value'26 jsonData?: JSONObject27}2829export abstract class VObjectBase<T extends Schema> {30 container: T31 keys: string[] = []32 protected _isOptional: boolean = false33 constructor(container: T, key: string) {34 this.container = container35 if (this instanceof VArray) {36 this.keys.push(key, '[*]')37 } else if (this instanceof VObject) {38 this.keys.push(key)39 }40 }4142 isOptional() {43 this._isOptional = true44 return this45 }4647 getValidators = (): VBase[] => {48 const validators: VBase[] = []49 const thisKeys: string[] = []50 Object.assign(thisKeys, this.keys)5152 const walk = (container: T, keys: string[], isOptional: boolean) => {53 for (const v of Object.values(container)) {54 if (v instanceof VArray || v instanceof VObject) {55 // eslint-disable-next-line @typescript-eslint/ban-ts-comment56 // @ts-ignore57 isOptional ||= v._isOptional58 keys.push(...v.keys)59 walk(v.container as T, keys, isOptional)60 const tmp: string[] = []61 Object.assign(tmp, thisKeys)62 keys = tmp63 } else if (v instanceof VBase) {64 if (isOptional) v.isOptional()65 v.baseKeys.push(...keys)66 validators.push(v)67 }68 }69 }7071 walk(this.container, this.keys, this._isOptional)7273 return validators74 }75}7677export class VObject<T extends Schema> extends VObjectBase<T> {78 constructor(container: T, key: string) {79 super(container, key)80 }81}8283export class VArray<T extends Schema> extends VObjectBase<T> {84 type: 'array' = 'array'85 constructor(container: T, key: string) {86 super(container, key)87 }88}8990export class Validator {91 isArray: boolean = false92 query = (key: string): VString => new VString({ target: 'query', key: key })93 header = (key: string): VString => new VString({ target: 'header', key: key })94 body = (key: string): VString => new VString({ target: 'body', key: key })95 json = (key: string) => {96 if (this.isArray) {97 return new VStringArray({ target: 'json', key: key })98 } else {99 return new VString({ target: 'json', key: key })100 }101 }102 array = <T extends Schema>(path: string, validator: (v: Validator) => T): VArray<T> => {103 this.isArray = true104 const res = validator(this)105 const arr = new VArray(res, path)106 return arr107 }108 object = <T extends Schema>(path: string, validator: (v: Validator) => T): VObject<T> => {109 this.isArray = false110 const res = validator(this)111 const obj = new VObject(res, path)112 return obj113 }114}115116type VOptions = {117 target: Target118 key: string119 type?: 'string' | 'number' | 'boolean' | 'object'120 isArray?: boolean121}122123export abstract class VBase {124 type: 'string' | 'number' | 'boolean' | 'object'125 target: Target126 baseKeys: string[] = []127 key: string128 rules: Rule[]129 sanitizers: Sanitizer[]130 isArray: boolean131 private _optional: boolean132 constructor(options: VOptions) {133 this.target = options.target134 this.key = options.key135 this.type = options.type || 'string'136 this.rules = [137 {138 name: this.getTypeRuleName(),139 type: 'type',140 func: this.validateType,141 },142 ]143 this.sanitizers = []144 this._optional = false145 this.isArray = options.isArray || false146 }147148 private _nested = () => (this.baseKeys.length ? true : false)149150 addRule(func: RuleFunc): this151 addRule(name: string, func: RuleFunc): this152 addRule(arg: string | RuleFunc, func?: RuleFunc) {153 if (typeof arg === 'string' && func) {154 this.rules.push({ name: arg, func, type: 'value' })155 } else if (arg instanceof Function) {156 this.rules.push({ name: arg.name, func: arg, type: 'value' })157 }158 return this159 }160161 addSanitizer = (sanitizer: Sanitizer) => {162 this.sanitizers.push(sanitizer)163 return this164 }165166 message = (text: string) => {167 const len = this.rules.length168 if (len >= 1) {169 this.rules[len - 1].customMessage = text170 }171 return this172 }173174 isRequired = () => {175 return this.addRule('isRequired', (value: unknown) => {176 if (value !== undefined && value !== null && value !== '') return true177 return false178 })179 }180181 isOptional = () => {182 this._optional = true183 return this.addRule('isOptional', () => true)184 }185186 isEqual = (comparison: unknown) => {187 return this.addRule('isEqual', (value: unknown) => {188 return value === comparison189 })190 }191192 asNumber = (): VNumber | VNumberArray => {193 const newVNumber = new VNumber({ ...this, type: 'number' })194 if (this.isArray) return newVNumber.asArray()195 return newVNumber196 }197198 asBoolean = (): VBoolean | VBooleanArray => {199 const newVBoolean = new VBoolean({ ...this, type: 'boolean' })200 if (this.isArray) return newVBoolean.asArray()201 return newVBoolean202 }203204 get(value: string) {205 const len = this.rules.length206 if (len > 0) {207 this.rules[this.rules.length - 1].customMessage = value208 }209 return this210 }211212 validate = async <R extends Request>(req: R): Promise<ValidateResult[]> => {213 let value: Type = undefined214 let jsonData: JSONObject | undefined = undefined215216 if (this.target === 'query') {217 value = req.query(this.key)218 }219 if (this.target === 'header') {220 value = req.header(this.key)221 }222 if (this.target === 'body') {223 const body = await req.parseBody()224 value = body[this.key]225 }226 if (this.target === 'json') {227 if (this._nested()) {228 this.key = `${this.baseKeys.join('.')}.${this.key}`229 }230 let obj = {}231 try {232 obj = (await req.json()) as JSONObject233 } catch (e) {234 throw new Error('Malformed JSON in request body')235 }236 const dst = {}237 value = JSONPathCopy(obj, dst, this.key)238 if (this._nested()) jsonData = dst239 }240241 const results: ValidateResult[] = []242243 let typeRule = this.rules.shift()244245 for (const rule of this.rules) {246 if (rule.type === 'type') {247 typeRule = rule248 } else if (rule.type === 'value') {249 const result = this.validateRule(rule, value)250 result.jsonData ||= jsonData251 results.push(result)252 }253 }254255 if (typeRule) {256 const typeResult = this.validateRule(typeRule, value)257 typeResult.jsonData ||= jsonData258 results.unshift(typeResult)259 }260261 return results262 }263264 protected getTypeRuleName(): string {265 const prefix = 'should be'266 return this.isArray ? `${prefix} "${this.type}[]"` : `${prefix} "${this.type}"`267 }268269 private validateRule(rule: Rule, value: Type): ValidateResult {270 let isValid: boolean = false271272 if (this._nested() && this.target != 'json') {273 isValid = false274 } else if (rule.type === 'value') {275 isValid = this.validateValue(rule.func, value)276 } else if (rule.type === 'type') {277 isValid = this.validateType(value)278 }279280 const message = isValid281 ? undefined282 : rule.customMessage || this.getMessage({ ruleName: rule.name, value })283 const result = {284 isValid: isValid,285 message: message,286 target: this.target,287 key: this.key,288 value,289 ruleName: rule.name,290 ruleType: rule.type,291 }292 return result293 }294295 private validateType = (value: Type): boolean => {296 if (this.isArray) {297 if (!Array.isArray(value)) {298 return false299 }300 for (const val of value) {301 if (typeof val === 'undefined' && this._nested()) {302 value.pop()303 }304 for (const val of value) {305 if (typeof val !== this.type) {306 // Value is of wrong type here307 // If it is not optional and not undefined, return false308 if (!this._optional || typeof val !== 'undefined') return false309 }310 }311 }312 } else {313 if (typeof value !== this.type) {314 if (this._optional && (typeof value === 'undefined' || Array.isArray(value))) {315 // Do nothing.316 // If it is optional it's OK to be `undefined` or Array317 } else {318 return false319 }320 }321 }322 return true323 }324325 private validateValue = (func: (value: Type) => boolean, value: Type): boolean => {326 if (this._optional && typeof value === 'undefined') return true327328 if (Array.isArray(value)) {329 // Sanitize330 for (const sanitizer of this.sanitizers) {331 value = value.map((innerVal: any) => sanitizer(innerVal)) as JSONArray332 }333 for (const val of value) {334 if (!func(val)) {335 return false336 }337 }338 return true339 } else {340 // Sanitize341 for (const sanitizer of this.sanitizers) {342 value = sanitizer(value)343 }344 if (!func(value)) {345 return false346 }347 return true348 }349 }350351 private getMessage = (opts: { ruleName: string; value: Type }): string => {352 let keyText: string353 const valueText = Array.isArray(opts.value)354 ? `${opts.value355 .map((val) =>356 val === undefined ? 'undefined' : typeof val === 'string' ? `"${val}"` : val357 )358 .join(', ')}`359 : opts.value360 switch (this.target) {361 case 'query':362 keyText = `the query parameter "${this.key}"`363 break364 case 'header':365 keyText = `the request header "${this.key}"`366 break367 case 'body':368 keyText = `the request body "${this.key}"`369 break370 case 'json':371 keyText = `the JSON body "${this.key}"`372 break373 }374 return `Invalid Value [${valueText}]: ${keyText} is invalid - ${opts.ruleName}`375 }376}377378export class VString extends VBase {379 constructor(options: VOptions) {380 super(options)381 this.type = 'string'382 }383384 asArray = () => {385 return new VStringArray(this)386 }387388 isEmpty = (389 options: {390 ignore_whitespace: boolean391 } = { ignore_whitespace: false }392 ) => {393 return this.addRule('isEmpty', (value) => rule.isEmpty(value as string, options))394 }395396 isLength = (options: Partial<{ min: number; max: number }> | number, arg2?: number) => {397 return this.addRule('isLength', (value) => rule.isLength(value as string, options, arg2))398 }399400 isAlpha = () => {401 return this.addRule('isAlpha', (value) => rule.isAlpha(value as string))402 }403404 isNumeric = () => {405 return this.addRule('isNumeric', (value) => rule.isNumeric(value as string))406 }407408 contains = (409 elem: string,410 options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {411 ignoreCase: false,412 minOccurrences: 1,413 }414 ) => {415 return this.addRule('contains', (value) => rule.contains(value as string, elem, options))416 }417418 isIn = (options: string[]) => {419 return this.addRule('isIn', (value) => rule.isIn(value as string, options))420 }421422 match = (regExp: RegExp) => {423 return this.addRule('match', (value) => rule.match(value as string, regExp))424 }425426 trim = () => {427 return this.addSanitizer((value) => sanitizer.trim(value as string))428 }429}430431export class VNumber extends VBase {432 constructor(options: VOptions) {433 super(options)434 this.type = 'number'435 }436437 asArray = () => {438 return new VNumberArray(this)439 }440441 isGte = (min: number) => {442 return this.addRule('isGte', (value) => rule.isGte(value as number, min))443 }444445 isLte = (min: number) => {446 return this.addRule('isLte', (value) => rule.isLte(value as number, min))447 }448}449450export class VBoolean extends VBase {451 constructor(options: VOptions) {452 super(options)453 this.type = 'boolean'454 }455456 asArray = () => {457 return new VBooleanArray(this)458 }459460 isTrue = () => {461 return this.addRule('isTrue', (value) => rule.isTrue(value as boolean))462 }463464 isFalse = () => {465 return this.addRule('isFalse', (value) => rule.isFalse(value as boolean))466 }467}468469export class VNumberArray extends VNumber {470 isArray: true471 constructor(options: VOptions) {472 super(options)473 this.isArray = true474 this.rules[0].name = this.getTypeRuleName()475 }476}477export class VStringArray extends VString {478 isArray: true479 constructor(options: VOptions) {480 super(options)481 this.isArray = true482 this.rules[0].name = this.getTypeRuleName()483 }484}485export class VBooleanArray extends VBoolean {486 isArray: true487 constructor(options: VOptions) {488 super(options)489 this.isArray = true490 this.rules[0].name = this.getTypeRuleName()491 }492}
modified:src/compose.ts+10 added-4 removed
1import { HonoContext } from './context'2import type { Environment, NotFoundHandler, ErrorHandler } from './hono'3import type { Schema } from './validator/schema'45interface ComposeContext {6 finalized: boolean6 res: any7 res: unknown8}910// Based on the code in the MIT licensed `koa-compose` package.10export const compose = <C extends ComposeContext, E extends Partial<Environment> = Environment>(11export const compose = <12 C extends ComposeContext,13 P extends string = string,14 E extends Partial<Environment> = Environment,15 D extends Partial<Schema> = Schema16>(17 middleware: Function[],12 onNotFound?: NotFoundHandler<E>,13 onError?: ErrorHandler<E>18 onNotFound?: NotFoundHandler<P, E, D>,19 onError?: ErrorHandler<P, E, D>20) => {21 const middlewareLength = middleware.length22 return (context: C, next?: Function) => {23 let index = -1
59 unmodified lines
modified:src/context.ts+21 added-26 removed
1import type {2 Environment,3 NotFoundHandler,4 ContextVariableMap,5 Bindings,6 ValidatedData,7} from './hono'1import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono'2import type { CookieOptions } from './utils/cookie'3import { serialize } from './utils/cookie'4import type { StatusCode } from './utils/http-status'5import type { Schema, SchemaToProp } from './validator/schema'67type HeaderField = [string, string]8type Headers = Record<string, string | string[]>9export type Data = string | ArrayBuffer | ReadableStream1011export interface Context<17 RequestParamKeyType extends string = string,18 E extends Partial<Environment> = any,19 D extends ValidatedData = ValidatedData12 P extends string = string,13 E extends Partial<Environment> = Environment,14 S extends Partial<Schema> = Schema15> {21 req: Request<RequestParamKeyType, D>16 req: Request<P, SchemaToProp<S>>17 env: E['Bindings']18 event: FetchEvent19 executionCtx: ExecutionContext20 finalized: boolean
5 unmodified lines
26 status: (status: StatusCode) => void27 set: {28 <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void29 <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void35 (key: string, value: any): void30 (key: string, value: unknown): void31 }32 get: {33 <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]34 <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]
10 unmodified lines
45 notFound: () => Response | Promise<Response>46}4748export class HonoContext<54 RequestParamKeyType extends string = string,49 P extends string = string,50 E extends Partial<Environment> = Environment,56 D extends ValidatedData = ValidatedData57> implements Context<RequestParamKeyType, E, D>51 S extends Partial<Schema> = Schema52> implements Context<P, E, S>53{59 req: Request<RequestParamKeyType, D>54 req: Request<P, SchemaToProp<S>>55 env: E['Bindings']56 finalized: boolean57 error: Error | undefined = undefined5859 _status: StatusCode = 20060 private _executionCtx: FetchEvent | ExecutionContext | undefined61 private _pretty: boolean = false62 private _prettySpace: number = 268 private _map: Record<string, any> | undefined63 private _map: Record<string, unknown> | undefined64 private _headers: Record<string, string[]> | undefined65 private _res: Response | undefined71 private notFoundHandler: NotFoundHandler<E>66 private notFoundHandler: NotFoundHandler<P, E, S>6768 constructor(74 req: Request<RequestParamKeyType>,75 env: E['Bindings'] | undefined = undefined,69 req: Request<P>,70 env: E['Bindings'] = {},71 executionCtx: FetchEvent | ExecutionContext | undefined = undefined,77 notFoundHandler: NotFoundHandler<E> = () => new Response()72 notFoundHandler: NotFoundHandler<P, E, S> = () => new Response()73 ) {74 this._executionCtx = executionCtx80 this.req = req as Request<RequestParamKeyType, D>75 this.req = req as Request<P, SchemaToProp<S>>76 this.env = env || ({} as Bindings)7778 this.notFoundHandler = notFoundHandler79 this.finalized = false
56 unmodified lines
136 }137138 set<Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void139 set<Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void145 set(key: string, value: any): void146 set(key: string, value: any): void {140 set(key: string, value: unknown): void141 set(key: string, value: unknown): void {142 this._map ||= {}143 this._map[key] = value144 }145146 get<Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]147 get<Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]153 get<T = any>(key: string): T148 get<T>(key: string): T149 get(key: string) {150 if (!this._map) {151 return undefined152 }
74 unmodified lines
227 this.header('set-cookie', cookie, { append: true })228 }229230 notFound(): Response | Promise<Response> {236 return this.notFoundHandler(this as any)231 return this.notFoundHandler(this)232 }233}
modified:src/hono.test.ts+65 added-1 removed
1/* eslint-disable @typescript-eslint/no-unused-vars */2import type { Context } from './context'2import type { Next } from './hono'3import type { Handler, Next } from './hono'4import { Hono } from './hono'5import { logger } from './middleware/logger'6import { poweredBy } from './middleware/powered-by'7import type { Expect, Equal } from './utils/types'89describe('GET Request', () => {10 const app = new Hono()11
1126 unmodified lines
1138 expect(count).toBe(4)1139 expect(log).toMatch(/404/)1140 })1141})11421143describe('Context set/get variables', () => {1144 type Variables = {1145 id: number1146 title: string1147 }11481149 const app = new Hono<{ Variables: Variables }>()11501151 it('Should set and get variables with correct types', async () => {1152 app.use('*', async (c, next) => {1153 c.set('id', 123)1154 c.set('title', 'Hello')1155 await next()1156 })1157 app.get('/', (c) => {1158 const id = c.get('id')1159 const title = c.get('title')1160 type verifyID = Expect<Equal<typeof id, number>>1161 type verifyTitle = Expect<Equal<typeof title, string>>1162 return c.text(`${id} is ${title}`)1163 })1164 const res = await app.request('http://localhost/')1165 expect(res.status).toBe(200)1166 expect(await res.text()).toBe('123 is Hello')1167 })1168})11691170describe('Context binding variables', () => {1171 type Bindings = {1172 USER_ID: number1173 USER_NAME: string1174 }11751176 const app = new Hono<{ Bindings: Bindings }>()11771178 it('Should get binding variables with correct types', async () => {1179 app.get('/', (c) => {1180 type verifyID = Expect<Equal<typeof c.env.USER_ID, number>>1181 type verifyName = Expect<Equal<typeof c.env.USER_NAME, string>>1182 return c.text('These are verified')1183 })1184 const res = await app.request('http://localhost/')1185 expect(res.status).toBe(200)1186 })1187})11881189describe('Handler as variables', () => {1190 const app = new Hono()11911192 it('Should be typed correctly', async () => {1193 const handler: Handler = (c) => {1194 const id = c.req.param('id')1195 return c.text(`Post id is ${id}`)1196 }1197 app.get('/posts/:id', handler)11981199 const res = await app.request('http://localhost/posts/123')1200 expect(res.status).toBe(200)1201 expect(await res.text()).toBe('Post id is 123')1202 })1203})
modified:src/hono.ts+67 added-55 removed
8 unmodified lines
9import { SmartRouter } from './router/smart-router'10import { StaticRouter } from './router/static-router'11import { TrieRouter } from './router/trie-router'12import { getPathFromURL, mergePath } from './utils/url'13import type { Schema } from './validator/schema'1415export interface ContextVariableMap {}1617export type Bindings = Record<string, any> // For Cloudflare Workers
2 unmodified lines
20 Bindings: Bindings21 Variables: Variables22}2323export type ValidatedData = Record<string, any> // For validated data2424export type Handler<26 RequestParamKeyType extends string = string,25 P extends string = string,26 E extends Partial<Environment> = Environment,28 D extends ValidatedData = ValidatedData29> = (30 c: Context<RequestParamKeyType, E, D>,31 next: Next32) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined | void>27 S extends Partial<Schema> = Schema28> = (c: Context<P, E, S>, next: Next) => Response | Promise<Response | undefined | void>2934export type MiddlewareHandler = <E extends Partial<Environment> = Environment>(35 c: Context<string, E>,36 next: Next37) => Promise<void> | Promise<Response | undefined>30export type MiddlewareHandler<31 P extends string = string,32 E extends Partial<Environment> = Environment,33 S extends Partial<Schema> = Schema34> = (c: Context<P, E, S>, next: Next) => Promise<Response | undefined | void>3539export type NotFoundHandler<E extends Partial<Environment> = Environment> = (40 c: Context<string, E>41) => Response | Promise<Response>36export type NotFoundHandler<37 P extends string = string,38 E extends Partial<Environment> = Environment,39 S extends Partial<Schema> = Schema40> = (c: Context<P, E, S>) => Response | Promise<Response>4143export type ErrorHandler<E extends Partial<Environment> = Environment> = (44 err: Error,45 c: Context<string, E>46) => Response42export type ErrorHandler<43 P extends string = string,44 E extends Partial<Environment> = Environment,45 S extends Partial<Schema> = Schema46> = (err: Error, c: Context<P, E, S>) => Response4748export type Next = () => Promise<void>4950// eslint-disable-next-line @typescript-eslint/no-unused-vars
8 unmodified lines
59type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`60 ? ParamKey<Component> | ParamKeys<Rest>61 : ParamKey<Path>6263interface HandlerInterface<T extends string, E extends Partial<Environment>, U = Hono<E, T>> {63interface HandlerInterface<64 P extends string,65 E extends Partial<Environment>,66 S extends Partial<Schema>,67 U = Hono<E, P, S>68> {69 // app.get(handler...)65 <Path extends string, Data extends ValidatedData>(70 <Path extends string, Data extends Schema>(71 ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E, Data>[]72 ): U68 (...handlers: Handler<string, E>[]): U73 (...handlers: Handler<string, E, S>[]): U7475 // app.get('/', handler, handler...)70 <Path extends string, Data extends ValidatedData>(76 <Path extends string, Data extends Partial<Schema> = Schema>(77 path: Path,78 ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E, Data>[]79 ): U80 <Path extends string, Data extends Schema>(path: Path, ...handlers: Handler<string, E, Data>[]): U74 (path: string, ...handlers: Handler<string, E>[]): U81 (path: string, ...handlers: Handler<string, E, S>[]): U82}8384type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE8586function defineDynamicClass(): {80 new <E extends Partial<Environment> = Environment, T extends string = string, U = Hono<E, T>>(): {81 [K in Methods]: HandlerInterface<T, E, U>87 new <88 E extends Partial<Environment> = Environment,89 P extends string = string,90 S extends Partial<Schema> = Schema,91 U = Hono<E, P, S>92 >(): {93 [K in Methods]: HandlerInterface<P, E, S, U>94 }95} {84 return class {} as any96 return class {} as never97}9899interface Route<100 P extends string = string,101 E extends Partial<Environment> = Environment,89 D extends ValidatedData = ValidatedData102 S extends Partial<Schema> = Schema103> {104 path: string105 method: string93 handler: Handler<string, E, D>106 handler: Handler<P, E, S>107}108109export class Hono<110 E extends Partial<Environment> = Environment,111 P extends string = '/',99 D extends ValidatedData = ValidatedData100> extends defineDynamicClass()<E, P, Hono<E, P, D>> {101 readonly router: Router<Handler<string, E, D>> = new SmartRouter({112 S extends Partial<Schema> = Schema113> extends defineDynamicClass()<E, P, S, Hono<E, P, S>> {114 readonly router: Router<Handler<P, E, S>> = new SmartRouter({115 routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],116 })117 readonly strict: boolean = true // strict routing - default is true118 private _tempPath: string = ''119 private path: string = '/'120108 routes: Route<E, D>[] = []121 routes: Route<P, E, S>[] = []122123 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {124 super()125126 extendRequestPrototype()127128 const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]129 allMethods.map((method) => {117 this[method] = <Path extends string = ''>(118 args1: Path | Handler<ParamKeys<Path>, E, D>,119 ...args: [Handler<ParamKeys<Path>, E, D>]130 this[method] = <Path extends string, Env extends Environment, Data extends Schema>(131 args1: Path | Handler<ParamKeys<Path>, Env, Data>,132 ...args: [Handler<ParamKeys<Path>, Env, Data>]133 ): this => {134 if (typeof args1 === 'string') {135 this.path = args1136 } else {124 this.addRoute(method, this.path, args1)137 this.addRoute(method, this.path, args1 as unknown as Handler<P, E, S>)138 }139 args.map((handler) => {140 if (typeof handler !== 'string') {128 this.addRoute(method, this.path, handler)141 this.addRoute(method, this.path, handler as unknown as Handler<P, E, S>)142 }143 })144 return this145 }
1 unmodified line
147148 Object.assign(this, init)149 }150138 private notFoundHandler: NotFoundHandler<E> = (c: Context<string, E>) => {151 private notFoundHandler: NotFoundHandler<P, E, S> = (c: Context<P, E, S>) => {152 return c.text('404 Not Found', 404)153 }154142 private errorHandler: ErrorHandler<E> = (err: Error, c: Context<string, E>) => {155 private errorHandler: ErrorHandler<P, E, S> = (err: Error, c: Context<P, E, S>) => {156 console.trace(err.message)157 const message = 'Internal Server Error'158 return c.text(message, 500)159 }160148 route(path: string, app?: Hono<any>): Hono<E, P, D> {161 route(path: string, app?: Hono<E, P, S>) {162 this._tempPath = path163 if (app) {164 app.routes.map((r) => {165 this.addRoute(r.method, r.path, r.handler)166 })167 this._tempPath = ''168 }156169 return this170 }171160 use<Path extends string = string, Data extends ValidatedData = D>(172 use<Path extends string = string, Data extends Partial<Schema> = Schema>(173 ...middleware: Handler<Path, E, Data>[]162 ): Hono<E, Path, Data>163 use<Path extends string = string, Data extends ValidatedData = D>(174 ): Hono<E, Path, S>175 use<Path extends string = string, Data extends Partial<Schema> = Schema>(176 arg1: string,177 ...middleware: Handler<Path, E, Data>[]166 ): Hono<E, Path, D>167 use(arg1: string | Handler<string, E, D>, ...handlers: Handler<string, E, D>[]): Hono<E, P, D> {178 ): Hono<E, Path, S>179 use(arg1: string | Handler<P, E, S>, ...handlers: Handler<P, E, S>[]) {180 if (typeof arg1 === 'string') {181 this.path = arg1182 } else {183 handlers.unshift(arg1)
3 unmodified lines
187 })188 return this189 }190179 onError(handler: ErrorHandler<E>): Hono<E, P, D> {191 onError(handler: ErrorHandler<P, E, S>) {192 this.errorHandler = handler193 return this194 }195184 notFound(handler: NotFoundHandler<E>): Hono<E, P, D> {196 notFound(handler: NotFoundHandler<P, E, S>) {197 this.notFoundHandler = handler198 return this199 }200189 private addRoute(method: string, path: string, handler: Handler<string, E, D>): void {201 private addRoute(method: string, path: string, handler: Handler<P, E, S>): void {202 method = method.toUpperCase()203 if (this._tempPath) {204 path = mergePath(this._tempPath, path)205 }206 this.router.add(method, path, handler)195 const r: Route<E, D> = { path: path, method: method, handler: handler }207 const r: Route<P, E, S> = { path: path, method: method, handler: handler }208 this.routes.push(r)209 }210211 private matchRoute(method: string, path: string) {212 return this.router.match(method, path)213 }214203 private handleError(err: unknown, c: Context) {215 private handleError(err: unknown, c: Context<P, E, S>) {216 if (err instanceof Error) {217 return this.errorHandler(err, c)218 }219 throw err
9 unmodified lines
229230 const result = this.matchRoute(method, path)231 request.paramData = result?.params232221 const c = new HonoContext<string, E, D>(request, env, eventOrExecutionCtx, this.notFoundHandler)233 const c = new HonoContext<P, E, S>(request, env, eventOrExecutionCtx, this.notFoundHandler)234235 // Do not `compose` if it has only one handler236 if (result && result.handlers.length === 1) {237 const handler = result.handlers[0]226 let res: ReturnType<Handler>238 let res: ReturnType<Handler<P>>239240 try {241 res = handler(c, async () => {})242 if (!res) return this.notFoundHandler(c)
17 unmodified lines
260 })()261 }262263 const handlers = result ? result.handlers : [this.notFoundHandler]252 const composed = compose<HonoContext<string, E>, E>(264 const composed = compose<HonoContext<P, E, S>, P, E, S>(265 handlers,266 this.notFoundHandler,267 this.errorHandler268 )
30 unmodified lines
modified:src/request.ts+6 added-5 removed
34 unmodified lines
35 (): Cookie36 }37 bodyData?: BodyData38 parseBody<BodyType extends BodyData>(): Promise<BodyType>39 // eslint-disable-next-line @typescript-eslint/no-explicit-any40 jsonData?: any40 json<JSONData = any>(): Promise<JSONData>41 json<JSONData = unknown>(): Promise<Partial<JSONData>>42 data: Data43 valid: {43 (key: string | string[], value: any): Data44 (key: string | string[], value: unknown): Data45 (): Data46 }47 }48}
83 unmodified lines
132 }133 return body134 } as InstanceType<typeof Request>['parseBody']135135 Request.prototype.json = async function <JSONData>(this: Request): Promise<JSONData> {136 Request.prototype.json = async function <JSONData = unknown>(this: Request) {137 // Cache the JSON body137 let jsonData: JSONData138 let jsonData: Partial<JSONData>139 if (!this.jsonData) {140 jsonData = JSON.parse(await this.text())141 this.jsonData = jsonData142 } else {
1 unmodified line
144 }145 return jsonData146 } as InstanceType<typeof Request>['jsonData']147147 Request.prototype.valid = function (this: Request, keys?: string | string[], value?: any) {148 Request.prototype.valid = function (this: Request, keys?: string | string[], value?: unknown) {149 if (!this.data) {150 this.data = {}151 }152 if (keys !== undefined) {
12 unmodified lines
modified:tsconfig.build.cjs.json+2 added
3 unmodified lines
4 "module": "CommonJS",5 "declaration": false,6 "rootDir": "./src/",7 "outDir": "./dist/cjs/",8 "noUnusedLocals": true,9 "noUnusedParameters": true,10 },11 "include": [12 "src/**/*.ts"13 ],
8 unmodified lines
modified:tsconfig.build.json+2 added
2 unmodified lines
3 "compilerOptions": {4 "module": "ES2020",5 "rootDir": "./src/",6 "outDir": "./dist/",7 "noUnusedLocals": true,8 "noUnusedParameters": true,9 },10 "include": [11 "src/**/*.ts",12 "src/**/*.mts"
8 unmodified lines
modified:tsconfig.json+2 added-2 removed
8 unmodified lines
9 "strict": true,10 "skipLibCheck": true,11 "strictPropertyInitialization": true,12 "strictNullChecks": true,13 "noUnusedLocals": true,14 "noUnusedParameters": true,13 "noUnusedLocals": false,14 "noUnusedParameters": false,15 "types": [16 "jest",17 "node",18 "@cloudflare/workers-types"
11 unmodified lines